From vincent at visualtrans.de Tue Jan 6 16:52:59 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 6 Jan 2004 22:52:59 +0100 Subject: Finaly found a simple enough task for python, took the plunge, but..... References: <3FFB5312.1030803@connection.com> Message-ID: "Sam" schrieb im Newsbeitrag news:3FFB5312.1030803 at connection.com... | Only 2 weeks messing around with it ( thanks to programs like SYNCHRONEX and | BITORRENT ), and already trying to create windows ( the paths are just too long | for me to want to type them ). | After much trial and error I finaly got the following code to open the 'get dir' | dialog , but I am getting another blank window titled 'tk' and "NOT RESPONDING" | When I kill it (end task), I get reiniit/restart (CTRL+F6) in my shell window | What am I doing wrong? Do I need to do anythink to clean up after using the | dialogs? Take a look at the tkFileDialog module. Or better, use it for convenience. It already provides some "standard" dialogs. You code would then look similar to: #----------------------- import Tkinter import tkFileDialog def me(): root = Tkinter.Tk() root.withdraw() # do this to remove the "blank screen" you mention dirname = tkFileDialog.askdirectory() return dirname print me() #------------------------ HTH Vincent Wehren | | **************************************************************************** ****** | import os | import sys | import tkCommonDialog | | def me(): | dir_name = "" | | getfileDLG = tkCommonDialog.Dialog() | getfileDLG.command = "tk_chooseDirectory" | getfileDLG.__init__() | dir_name = getfileDLG.show( ) | | print dir_name | | **************************************************************************** ****** | | The other think is that the dialog does not get focus. | | Must admit I was little more confortable with the HTML help in Python 2.3 | however less informative ( which I only installed a week before 2.3.3) | The help server in 2.3.3 just produces blank pages (most of the time) and | eventualy locks up. I think it has to do with the loopback, I read about | somewhere, but I can't be dialed to my ISP all the time. | | | Thanks, Sam. | From none at none.com Mon Jan 12 17:35:58 2004 From: none at none.com (Derek) Date: Mon, 12 Jan 2004 17:35:58 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> Message-ID: "Cameron Laird" in message: > I contest the proposition that "Python is less than stellar > at large applications ...", and, in particular, that C++ is > super- ior there. I recognize you're not alone in that; > for me, though, large-scale programming is one of Python's > *strengths*. > > I don't have a good decision mechanism to propose. Trial by > ordeal (and most large-team projects fit in that category) > seems as apt as any. All I know is that there are thousands of extremely large projects written in C++, some consisting of millions of lines of code written by hundreds of developers. C++, while far from perfect, has proven its worth on a huge scale. Python, at the very least, has yet to do so. From graham__fawcett at hotmail.com Wed Jan 14 00:17:28 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 13 Jan 2004 21:17:28 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: Jason Mobarak wrote in message news:... > Graham Fawcett wrote: > > I wouldn't jump at using Twisted's app framework (Woven?) on top of > > Twisted's Web server, though. No disrespect intended to the Twisted > > community or their great body of work; it's just that server and > > app-framework are two separate concerns: one day you might want to or > > need to switch Web servers, and you need to know that your framework > > is portable. I'm no Twisted expert: perhaps Woven is indeed portable, > > and a kindly Twisted person will elaborate here. > > You can use Woven with mod_proxy and Apache. Same with Woven's > successor: Nevow, http://divmod.org/users/slyphon.twistd/nevow/moin.cgi/ . Thanks for clarifying this, Jason. I hereby retract my anti-Twisted statement! ;-) -- G From bart_nessux at hotmail.com Fri Jan 23 14:49:17 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 23 Jan 2004 14:49:17 -0500 Subject: when x process isn't running... do something In-Reply-To: References: Message-ID: Bart Nessux wrote: > Howdy, > > I'm trying to time how long it takes dd to run on a G5, versus how long > it takes to run on a G4 (PATA vs. SATA). Both sytems have Mac OS X > 10.3.2 and Python 2.3. Could someone demonstrate how I might use Python > to monitor for the presense of a process and to do something (in this > case send an email which I know how to do) as soon as that process is no > longer present? Any suggestions on how to monitor? Call top every 5 secs > and read it's output searching for 'dd'??? > > TIA, > Bart > I forgot to mention the fact that I already know when the process began. All I need to know is when it ends and then I can calculate the part in between those two points. From skip at pobox.com Fri Jan 23 17:27:57 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 23 Jan 2004 16:27:57 -0600 Subject: Various strings to dates. In-Reply-To: References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: <16401.40941.538046.350775@montanaro.dyndns.org> Amy> The following three date strings is another example of the various Amy> date formats I will encounter here. Amy> Thursday, 22 January 2004 03:15:06 Amy> Thursday, January 22, 2004, 03:15:06 Amy> 2004, Thursday, 22 January 03:15:06 Assuming you won't have any ambiguous dates (like 1/3/04), just define regular expressions which label the various fields of interest, then match your string against them until you get a hit. For example, the first would be matched by this: >>> import re >>> pat = re.compile(r'(?P[A-Z][a-z]+),\s+(?P[0-9]{1,2})\s+' ... r'(?P[A-Z][a-z]+)\s+(?P[0-9]{4,4})') >>> mat = pat.match('Thursday, 22 January 2004 03:15:06') >>> mat <_sre.SRE_Match object at 0x487498> >>> mat.groups() ('Thursday', '22', 'January', '2004') >>> mat.group('month') 'January' etc. (Extending the regexp to accommodate the time is left as an exercise.) Once you have a match, pull out the relevant bits, maybe tweak them a bit (int()-ify things), then create a datetime instance from the result. I do something like this in my dates module. It's old and ugly though: http://manatee.mojam.com/~skip/python/ Search for "date-parsing module". This was written long before the datetime module was available and was used for for a slightly different purpose. It recognizes a number of different date range formats in addition to individual dates. You might be able to snag some regular expression ideas from it though. Skip From kjdyck at hotmail.com Thu Jan 15 08:35:44 2004 From: kjdyck at hotmail.com (Ken Dyck) Date: Thu, 15 Jan 2004 08:35:44 -0500 Subject: Portable filename comparison Message-ID: Is there a way with Python 2.2 to portably test the equivalence of two filenames? The os.path.samefile function seems to do what I want, but it is only available on Unix and Mac. I need something that works on Windows. The os.path.normcase and os.path.normpath functions are available on all platforms, but don't quite get me there. For example, on Windows >>> os.path.normcase(os.path.normpath("C:\Program Files")) 'c:\\program files' >>> os.path.normcase(os.path.normpath("C:\PROGRA~1")) 'c:\\progra~1' I suppose I could find a way to call into the Win32 API directly, but I'd prefer to use a portable solution if I can find one. Any suggestions? Ken From sombDELETE at pobox.ru Sat Jan 24 11:30:39 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 24 Jan 2004 19:30:39 +0300 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> <871xpp1i8r.fsf@pobox.com> Message-ID: "Ganesan R" wrote in message news:ou4qulnwy0.fsf at andlx-anamika.cisco.com... > >>>>> "John" == John J Lee writes: > > > Ganesan R writes: > >> > Is that all that people mean, though, when they talk about Perl's > >> > superiority for text mangling? Is there more to it? -- > > [...] > >> The perl "built-in" idioms for text processing is not only a syntactic > >> convenience, there are real performance advantages. For example a simple > >> perl loop like > >> > >> while (<>) { } > >> > >> is nearly 6 times slower in python (8 time slower with Python 2.2) using > > [...] > > > Did you try 'for line in file:'? ISTR Tim Peters optimized that (or > > was that fileinput?), precisely because of every hacker and their dog > > running this as a benchmark. > > fileinput is not optimized yet, at least I don't remember any mails about > fileinput in python-devel since python 2.3 was released. I know that it is > slow. for line in file: does seem to be optimized though. The last time I > ran the tests python was definitely twice as slow (which was before python > 2.3 was officially released); now it appears to be only about 40% slower. I > need to revisit these crude benchmarks. Since this problem is not IO bound but rather python internals bound, it makes sense to try psyco. From mksql at yahoo.com Thu Jan 8 15:08:56 2004 From: mksql at yahoo.com (mksql at yahoo.com) Date: Thu, 08 Jan 2004 15:08:56 -0500 Subject: Tkinter button command curiousity Message-ID: New to Tkinter. Initially, I had some code that was executing button commands at creation, rather than waiting for user action. Some research here gave me a solution, but I am not sure why the extra step is necessary. This causes the "graph" function to execute when the button is created: Button(root, text='OK', command=graph(canvas))) However, this waits until the button is pressed (the desired behavior): def doit(): graph(canvas) Button(root, text='OK', command=doit)) Functionally, what is the difference? Why do I need to create a function, to call a function, simply to make a button command wait until pressed? Is there a better method? From arjen.dijkstraNoSpam at hccnet.nl Mon Jan 19 09:24:11 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Mon, 19 Jan 2004 15:24:11 +0100 Subject: Tkinter References: Message-ID: <400be89b$0$127$e4fe514c@dreader13.news.xs4all.nl> http://www.pythonware.com/library/tkinter/introduction/ regards, Arjen "km" schreef in bericht news:mailman.501.1074519339.12720.python-list at python.org... > Hi all, > > Is there any good online tutorial which is a good intro for Tkinter programming in Python ? > > regards, > KM > > > From jikosan83 at yahoo.com Sun Jan 11 01:01:58 2004 From: jikosan83 at yahoo.com (Jikosan) Date: 10 Jan 2004 22:01:58 -0800 Subject: Help with if statement Message-ID: I can't get my "if" statement to work indicated below. What happens is no matter what the value random is, neg gets incremented by 1. This is actually my first time programming in Python. Any help is appreciated. TIA Gene import random uniform = random.uniform neg = 0 N = int(raw_input("Enter number of random generations, N: ")) for x in range(0,N): random = uniform(-1, 1) print random if random < 1.0: <--- Not working neg = neg+1 print neg pi = 4.*(neg/N) print 'The value of Pi is ', pi From g.marshall at nospam.com Mon Jan 26 03:43:42 2004 From: g.marshall at nospam.com (George Marshall) Date: Mon, 26 Jan 2004 08:43:42 GMT Subject: Class returning None ? Message-ID: <2r4Rb.286342$e6.11127748@twister2.libero.it> Hi, I'm wondering, what's the best way to check for success or failure on object initialization ? This is my ugly workaround to do that : class mytest: status=0 def __init__ (self): status=1 _mytest = mytest() def mytest (): if everythingok(): return _mytest() else: return None def everythingok(): return False def main(): a=mytest() if a==None: return 1 if __name__ == "__main__" main() What's the python way to do that ? Thanks. From herrn at gmx.net Fri Jan 9 13:13:43 2004 From: herrn at gmx.net (Marco Herrn) Date: 9 Jan 2004 18:13:43 GMT Subject: error with /usr/lib/python2.3/compileall.py: "Sorry invalid mode: U" Message-ID: Hi, I tried to install a package under debian, where in the postinstall phase some python scripts are called. Then I got the error "Sorry invalid mode: U". I looked what this script does and it is the following: python -O /usr/lib/python2.3/compileall.py /usr/share/woody I looked where exactly in compileall.py the error occurs and it is here: try: print fullname print None print dfile print True ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt except py_compile.PyCompileError,err: print err.msg success = 0 except IOError, e: print "Sorry", e success = 0 So it obviously runs into the IOError. Then I altered the script to see what parameters are given to the method py_compile.compile. Here is one example of it: fullname: /usr/share/woody/woody_xml.py None dfile: None 1 I looked after the permissions on the file /usr/share/woody/woody_xml.py, it is: -rw-r--r-- 1 root root Now I don't have any idea why there is an IOError. Ist it because dfile is None? What is dfile for? Where can here be the error? Bye Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From igor.NOSPAM at obda.net Thu Jan 29 07:04:44 2004 From: igor.NOSPAM at obda.net (Igor Fedorow) Date: Thu, 29 Jan 2004 13:04:44 +0100 Subject: Python & XML & DTD (warning: noob attack!) Message-ID: Hello all, I have an XML file with an internal DTD which looks roughly like this: ]> node 1 node 1-1 node 2 node 2-1 node 2-2 I want to parse this file into my application, modify the data (this includes maybe creating and/or deleting nodes), and write it back into the file -- including the DTD. (It doesn't necessarily need validation, though.) I tried xml.dom.ext.PrettyPrint, but it produces only ... actually lacking the document type definition. Any help is appreciated! Thanks in advance & cheers =) *igor* From aahz at pythoncraft.com Wed Jan 28 11:57:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 28 Jan 2004 11:57:59 -0500 Subject: Cross-version extension modules? References: Message-ID: In article , Peter Astrand wrote: > >Thanks. Is PYTHON_API_VERSION guaranteed to increase only when the >Python major or minor version increases, or can it change between micro >versions as well? Depends whether the micro-version is a pure bugfix release. So far, we've been hewing closely to PEP 6, so no, it won't change. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From john.abel at pa.press.net Wed Jan 21 05:39:42 2004 From: john.abel at pa.press.net (John Abel) Date: Wed, 21 Jan 2004 10:39:42 +0000 Subject: personal document mgmt system idea In-Reply-To: References: Message-ID: <400E56EE.6080700@pa.press.net> Have you looked at the modules available from divmod.org for your text searching? Sandy Norton wrote: >Stephan Diehl wrote: > >[...] > > > >>Just dump your files somewhere in the filesystem and keep a record of it in >>your database. >> >> > >I think I will go with this approach. (see other posting for details) > > > > >>In addition, a real (text) search engine might be of help. I'm using swish-e >>(www.swish-e.org) and are very pleased with it. >> >> > >Just downloaded it... looks good. Now if it also had a python api (-; > > > >>Maybe, before you invest to much time into such a project, you should check >>out the following: >> >>Chandler (http://www.osafoundation.org) >> if it's finished, it will do excactly what you are aiming for (and >> it's written in Python) >> >> > >Still early stages... I see they dropped the ZODB. > > > >>ReiseFS (see www.namesys.com -> Future Vision) >>Gnome Storage (http://www.gnome.org/~seth/storage) >>WinFS >>(http://msdn.microsoft.com/Longhorn/understanding/pillars/WinFS/default.aspx) >> >> > > >Wow! Very exciting stuff... I guess we'll just have to wait and see what develops. > > > > >>Hope that helps >> >> > >Yes. Very informative. Cheers for the help. > > > >>Stephan >> >> > >Sandy > > From fwang2 at yahoo.com Sat Jan 31 16:10:33 2004 From: fwang2 at yahoo.com (oliver) Date: 31 Jan 2004 13:10:33 -0800 Subject: pythonwin woes References: Message-ID: Thanks for your reply, Mark. Yes, I can imagine scenarios where keeping the state around, the way pythonwin is doing is useful. On the other hand, I think there is also a need to restart python process to get a clean start. Maybe an option for both is warranted. oliver > IDLE runs all programs in a new, external Python process, so never sees > this issue. In lots of ways, I like the way Pythonwin does it - keeping > that state around can be very useful - eg, after the program has > terminated, you can still see the objects etc. From jhodges at mit.edu Mon Jan 26 18:30:55 2004 From: jhodges at mit.edu (Jonathan Hodges) Date: 26 Jan 2004 23:30:55 GMT Subject: termios POSIX implementation Message-ID: <4015a32f$0$577$b45e6eb0@senator-bedfellow.mit.edu> Posted with an Unregistered Version of NewsHunter - The Newsgroup Utility for OS X. Get your copy today at: http://www.parkersoftware.com/products/newshunter/ Can anyone provide details on how the python implementation of termios.h differs from the POSIX library? Are there platform specific issues, especially for the Darwin build? It seems that if I make identical function calls in a python script and in some c code, the result on my COM port is very different. Is there something reasonable to explain this? I tried to decipher the source implementation of TERMIOS.py, but I can't seem to make heads or tails of it. Any help would be greater appreciated. Thanks, JH From jmob at nospam__unm.edu Fri Jan 16 05:11:41 2004 From: jmob at nospam__unm.edu (Jason Mobarak) Date: Fri, 16 Jan 2004 03:11:41 -0700 Subject: keeping Python code properly indented In-Reply-To: <3064b51d.0401151125.711ade4c@posting.google.com> References: <3064b51d.0401151125.711ade4c@posting.google.com> Message-ID: The tabnanny module/program is a very good way to make sure python files are properly indented. @ares shtoom --> python -c "import tabnanny; tabnanny.check('.')" ./ui/base.py 9 '\tfrom shtoom import prefs \n' ./test/test_stun.py 18 "\tn1 = NetAddress('10/8')\n" ./audio/__init__.py 21 '\taudio = attempt()\n' ./multicast/unixspec.py 24 '\tgroup = gethostbyname(addr)\n' ./multicast/SAP.py 8 '\tself.dismantlePacket(pack)\n' ./multicast/SDP.py 35 "\tlines = text.split('\\n')\n" ./multicast/netnum.py 10 '\tl = l+[0]*(4-len(l))\n' ./rtp.py 128 '\treturn d\n' beliavsky at aol.com wrote: > How do you keep Python code properly indented as you modify it? I use > an Emacs-type editor that has a Python mode, so the initial indenting > is easy. If I later want to put a 'for' loop (or an 'if' statement) > around a bunch of code, I find myself going through the body of the > loop, manually re-indenting to keep the nested loops correct. There > should be a better way. > > I think that having a 'for' loop end with a matching 'next' statement, > as done in (for example) Basic, is a safer and clearer way of writing > loops, although some Python programmers consider this a 'feature' > rather than a 'bug'. -- (------------------------------( )~~~~~ Jason A. Mobarak ~~~~~~~) (~~ aether_at_gentoo_dot_org ~~( )~~~~ jmob_at_unm_dot_edu ~~~~~) (------------------------------( From sombDELETE at pobox.ru Tue Jan 13 02:45:06 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Tue, 13 Jan 2004 10:45:06 +0300 Subject: Problem with what raw_input() returns References: <56f42e53.0401121746.39b9e4db@posting.google.com> Message-ID: "sebb" wrote in message news:56f42e53.0401121746.39b9e4db at posting.google.com... > If I do the following script: > > # -*- coding: cp1252 -*- > one = "??" > two = one.replace("?","a") > > print two # it prints aa as I expected It's not a good idea anyway, unless you know what you're doing. Use unicode. > > But with the following script: > > # -*- coding: cp1252 -*- > one = raw_input() # When I run the script, I type ?? > two = one.replace("?","a") > > print two # it still prints ?? and I want it to print aa > > > Can someone help me with that problem? > Thanks Use at least 2.3 Python. Then encode stdin like that: import sys, codecs sys.stdin = codecs.getreader(sys.stdout.encoding)(sys.stdin) one = raw_input() two = one.replace(u"?","a") The code above assumes that Python was able to figure out console encoding. If it's absent (sys.stdout.encoding == None) you have to find it out yourself. Besides if it's absent you need to encode stdout using codecs.getwriter as well. -- Serge. From jseale18 at insightbb.com Thu Jan 22 22:14:18 2004 From: jseale18 at insightbb.com (Jeff Seale) Date: Fri, 23 Jan 2004 03:14:18 GMT Subject: Tkinter color names/codes References: Message-ID: Nuff Said wrote in news:pan.2004.01.19.21.06.17.957950 at phreaker.net: > On Mon, 19 Jan 2004 20:39:18 +0000, Jeff Seale wrote: > >> I just happend to notice that there are very FEW colors that you have >> to generate using #hex codes. But I was wondering, how many colors >> have names assigned to them in Tkinter and what are their #hex >> translations? It'd be nice to know these so I don't accidentally >> create a color that already has a name. > > http://wiki.tcl.tk/8606 > - list with all named colors in Tcl/Tk > > http://wiki.tcl.tk/colors > - W3C names, hex codes and Tcl/Tk names for the > 16 HTML 3.2 colors (i.e. the basic VGA set) > > HTH / Nuff > Is it possible to translate all those colors into their #hex combinations? The ones I know about already are Red #FF0000, Yellow #FFFF00, Green # 00FF00, Cyan #00FFFF, Blue #0000FF, Magenta #FF00FF, White #FFFFFF and Black #000000. From Chuck at spears.com Wed Jan 28 11:45:59 2004 From: Chuck at spears.com (Chuck Spears) Date: Wed, 28 Jan 2004 11:45:59 -0500 Subject: id3v2 module References: Message-ID: I too was looking for an ID3V2 tag reader/writer for python but I never did have much luck. Most of the projects are dead in the water. I dropped it for now but will get around at some point to writing it. From tim.golden at viacom-outdoor.co.uk Tue Jan 20 03:56:38 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 20 Jan 2004 08:56:38 -0000 Subject: interface to win job scheduler portable from win98 .. winXP / cmdline or COM ? Message-ID: >-----Original Message----- >From: Robert [mailto:k.robert at gmx.de] > >I found the os.popen("AT /?") way .... >however it works not on Win98 and the "Day" you enter at the >AT are language >dependent. (e.g. Mi(ttwoch) in german, We(dnesday) in english Windows >versions) > >I need a solution work from Win98..WinXP most independent from >internationalization etc. > >is there portable way - or at all a way to manipulate the >Win98/ME scheduler >? >if no simple means, even COM stuff would be ok. >any pointers? > WMI looks like it covers it, but only NT4 / Win2K / XP. Oh, sorry, I've just realised: the Win32_ScheduledJob actually refers to the AT service (despite the name!) If you're really looking for something which will work across every version of Windows, I think you're better off doing something entirely Python from the start. It shouldn't be hard (he says, having not tried it himself). The advantage is: it will work everywhere and you have complete control over it. The disadvantage is: you have to create your own interface and deal with whatever issues the existing mechanisms have already dealt with. 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 mike at triplepc.com Sat Jan 10 12:58:02 2004 From: mike at triplepc.com (Michael T. Babcock) Date: Sat, 10 Jan 2004 12:58:02 -0500 Subject: need help translating a PHP for statement to python In-Reply-To: References: Message-ID: <40003D2A.70806@triplepc.com> > > >If someone could explain to me how one should >translate the multiple increment, evaluations, etc. in the first line >I would appreciate it deeply ... > >for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { > $prd = $q * $y_ar[$y] + $car; > $prd -= ($car = intval($prd / 1E7)) * 1E7; > if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7; > } > > > In all likelihood, you could rewrite the algorithm (if you understand it) in Python in a more Pythonesque kind of way and make it easier to maintain in the future, but this should do it: y = 0 x = cx - cy - 1 while y <= cy: prd = q * y_ar[y] + car # { and so on } x += 1 y += 1 ... that should do it for you, should it not? -- Michael T. Babcock http://www.fibrespeed.net/~mbabcock/code From tweedgeezer at hotmail.com Tue Jan 27 23:00:13 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Jan 2004 20:00:13 -0800 Subject: I support PEP 326 References: <698f09f8.0401271318.21c9ca72@posting.google.com> Message-ID: <698f09f8.0401272000.79704ef0@posting.google.com> Josiah Carlson wrote in message news:... > Unfortunately, I have a feeling that the PEP may be killed because there > doesn't seem to be a location/name that is agreeable to those with > voting power in python-dev. I simply can't understand this aversion to sticking useful things in the builtin namespace. Especially when marginally useful things like reversed (a trivially written 3-line generator) have been put there. Jeremy From mwh at python.net Tue Jan 13 11:17:58 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 16:17:58 GMT Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <400413E0.5C691A56@engcorp.com> Message-ID: Peter Hansen writes: > Tim Rowe wrote: > > > > Well, the documentation for "input()" says "Equivalent to > > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/ > > equivalent...." > > I remember reading that too, and just assumed that at this point > it was in fact *implemented* that way, as a simple alias. Maybe > it should be... http://www.python.org/sf/876178 Ideas on how to write a testcase welcome. Cheers, mwh -- People think I'm a nice guy, and the fact is that I'm a scheming, conniving bastard who doesn't care for any hurt feelings or lost hours of work if it just results in what I consider to be a better system. -- Linus Torvalds From Kyler at news.Lairds.org Mon Jan 19 18:12:07 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Mon, 19 Jan 2004 23:12:07 GMT Subject: Python-based file synchronizer (like Unison)? Message-ID: I've been using Unison http://www.cis.upenn.edu/~bcpierce/unison/ for awhile and it causes me a lot of grief. I'd love to have a Python version which would be vastly easier to modify. Anyone know of anything like this? It doesn't seem like it should take a lot to sit on top of rsync and resolve conflicts. I see that someone implemented rsync in Python and that there's a SWIG wrapper for librsync. http://minkirri.apana.org.au/~abo/projects/pysync/README I might have to take a whack at this on my own, but I'd prefer to use something better that someone has already crafted. Thank you. --kyler From bkelley at wi.mit.edu Sun Jan 11 11:15:01 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Sun, 11 Jan 2004 16:15:01 GMT Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: <40011315.7070000@v.loewis.de> References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> <40011315.7070000@v.loewis.de> Message-ID: <8EeMb.24302$5V2.36981@attbi_s53> Martin v. L?wis wrote: > Brian Kelley wrote: > >> I don't see too much difference between using >> _("STRING") >> >> to indicate a string to be internationalized and >> i"STRING" >> >> Except that the later will be automatically noticed at compile time, >> not run-time. > > > I'm not really sure what "compile time" is in Python. If it is the time > when the .pyc files are generated: What happens if the user using the > pyc files has a language different from the language of the > administrator creating the files? > > Or, what precisely does it mean that it is "noticed"? > > >>> Using what textual domain? >>> >> I am using the same mechanism as gettext but tying it into the "import >> locale" mechanism. > > > That does not answer my question? How precisely do you define the > textual domain? > > In gettext, I typically put a function at the beginning of each module > > def _(msg): > return gettext.dgettext("grep", msg) > > thus defining the textual domain as "grep". In your syntax, I see no > place to define the textual domain. > >> I think this happens fine in both cases. The mechanism for >> internationalizing with wxPython just didn't feel, well, pythonic. It >> felt kind of tacked into place. Of course I feel the same way about >> most C macros :) > > > Can you be more specific? Do you dislike function calls? > >> Perhaps I am optimizing the wrong end of the stick. > > > Why is this an optimization in the first place? Do you make anything run > faster? If so, what and how? > >> Compile-time generation just feels safer to me. The code-analyzer >> might miss special cases and what not, but if it is generated at >> compile time it will work all the time. > > > Please again elaborate: What is compile-time, and what is generation, > in this context? I'll back away for a second to try to explain my previous rationale. Now that it appears to have changed that is. By compile-time I meant essentially, not-run time. For instance if you had a function def foo(...): return i"Message" You wouldn't have to execute foo directly for the parse tree to notice that i"Message" was a string that is supposed to be internationalized. This process gets this string placed in the internationalization table which I would then use various tools to modify and translate. The international string class would then has an internal mechanism to notice what the locale is and what the value of the string should be when printed or used. This is transparent to dictionaries and the like, so all the developer has to do is use i"Message" This should tranparent to Gui Widgets and the like so you can place i"Message" in a list box, it will automatically get internationalized but when you get the result of the user selected, it still can be used to dictionary look ups exactly the same as the original i"Message". > The gettext module provides the GNUTranslation object. You can have > multiple such objects, and need to explicitly use the language's > object on gettext() invocation, e.g. > > print current_language.gettext("This is good") This is the mechanism that I was originally using for the internation string class. > If you can be certain that users will be subsequent, you can do > > def _(msg): > return current_language.gettext(msg) > > print _("This is good") My version of this is message = i"This is good" print message > There might be other ways to determine the current context, e.g. > by looking at thread state. In that case, you still can use > the _ function, but implement it in looking at the thread state. I'll take a look at this. An example of how I am currently using this is as follows: message = i"This is good" or message = international("This is good") lookup = {} print message # -> "This is good" lookup[message] = func locale.set_locale("es") # spanish, this is from memory, might be wrong print message # -> "Esto es bueno" assert lookup[message] == func local.set_locale("it") # italian print message # -> "Ci? ? buona" assert lookup[message] == func My current thinking is as follows, I could get most of this effect by not having a new string type (i"") and just making an internationalization string type. Then I would just use code analyzer tools to generate the translation tables as Serge suggested, heck, they could even use the parse module if I was so inclined. In either case, I far prefer using internation("This is good") over the _("This is good") function call. Mainly because it is more explicit and using _ overrides the interpreters built in for getting last result. >>> 2+2 4 >>> _ 4 Thanks for your inspection of this rambling. Brian From arsanalytica at yahoo.com Thu Jan 22 16:15:20 2004 From: arsanalytica at yahoo.com (Dan) Date: 22 Jan 2004 13:15:20 -0800 Subject: Python Consultants? Message-ID: <8e198b65.0401221315.6d5cb3fe@posting.google.com> I am working on a python/zope web application and could really use some *expert* help on a short term basis. Is there an appropriate forum for trolling for Python Consultants? Here are a pair XML problems that are available: #1) Setup to convert these xml files http://www.gothamanalytics.com/PairTools/geturl?url=http://app.quotemedia.com/data/getHistory.xml&symbol=SUNW http://www.gothamanalytics.com/PairTools/geturl/?url=http://app.quotemedia.com/data/getQuotes.xml?symbols=SUNW into a vector of open,close,volume information suitable for use with a numerical Python module. Doing this quickly is a plus. Here are the dtds of interest: http://app.quotemedia.com/data/dtds/history.dtd http://app.quotemedia.com/data/dtds/quotes.dtd #2) Expose the Salesforce.com SOAP functionality from salesforce.com generated WSDL files, here is an example WSDL http://gothamanalytics.com/Ex/enterprise.wsdl See sforce.com for more info on the salesforce.com API. A Python solution is preferred but a work around which uses Java and the Salesform.com Apache Axis library and an appropriate gateway from python might also be acceptable. Results from an attempt at using ZSI to process the WSDL file is appended to this message. From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 3 12:02:56 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 03 Jan 2004 18:02:56 +0100 Subject: Pass a variable to another python script References: <3ff6ef44$1@clarion.carno.net.au> Message-ID: Steve: >I've written a small cgi python script that collects feedback from a >webform. I need to pass the values to another python script.. how do I >do this? There are many ways (command line, socket, file, database, ...), but the easiest solution is as parameter of a function in the other module. In module a: feedback = "good site" import b b.function(feedback) -- Ren? Pijlman From alisonken1 at juno.com Fri Jan 9 22:24:00 2004 From: alisonken1 at juno.com (Ken Roberts) Date: 9 Jan 2004 19:24:00 -0800 Subject: UPC/EAN barcode script Message-ID: Here's a quick routine that I hacked out to verify UPC-A/E and EAN-13/8 barcodes. Anyone have any suggestions how to improve it? ================== Test script ============== import ean # Below codes taken from http://www.barcodeisland.com examples # UPC-E codes to expand/verify e = { 0: '01278907', 1: '01278916', 2: '01278925', 3: '01238935', 4: '01248934', 5: '01258933', 6: '01268932', 7: '01278931', 8: '01288930', 9: '01298939', 10: '01291944', 11: '01291155', 12: '01291162', 13: '01291179', 14: '01291186' } # UPC-A codes to verify/compress a = { 0: '012000007897', 1: '012100007896', 2: '012200007895', 3: '012300000895', 4: '012400000894', 5: '012500000893', 6: '012600000892', 7: '012700000891', 8: '012800000890', 9: '012900000899', 10: '012910000094', 11: '012911000055', 12: '012911000062', 13: '012911000079', 14: '012911000086' } print 'checking upca2e ...' for i in a.keys(): t1=a[i] t2=ean.upca2e(t1) print 'key ', i, ':', t1, ean.upcaValid(t1) print 'upce', i, ':', t2, ean.upceValid(t2) print print 'Checking upce2a ...' for i in e.keys(): t1=e[i] print 'key', i, ':', t1, ean.upceValid(t1) ================ Barcode script ============== """ ean.py See http://www.barcodeisland.com for UPC/EAN specs Routines for verifying UPC/EAN codes and generating check digit UPC-A is actually EAN13 code with a "0" prepended to it. The Barcode Association has designated that all programs should be converted to EAN by Jan 01, 2005. Routines for UPC-A/UPC-E barcodes. UPC is basically EAN13 with an extra leading '0' to bring the length to 13 characters. Check digit is calculated using ean13CheckDigit('0'+UPCA). UPC-A is 12 characters in length with [12] being the check digit. UPC-E is a compressed (convoluted algorithm) UPC-A with extraneous middle 0 digits removed. """ __version__ = "$Revision: 0.4$" codeLength = { "EAN13": 13, "EAN8": 8, "UPCA": 12, "UPCE": 8 } def __lenCheck(chk, _type='EAN13'): return (len(chk) == codeLength[_type]) or \ (len(chk) == codeLength[_type]-1) def __sumDigits(chk, start=0, end=1, step=2, mult=1): return reduce(lambda x, y: int(x)+int(y), list(chk[start:end:step])) * mult def eanCheckDigit(chk, code='EAN13'): """Returns the checksum digit of an EAN-13/8 code""" if chk.isdigit() and __lenCheck(chk): if code == 'EAN13': m0=1 m1=3 elif code == 'EAN8': m0=3 m1=1 else: return None _len = codeLength[code]-1 t = 10 - (( __sumDigits(chk, start=0, end=_len, mult=m0) + \ __sumDigits(chk, start=1, end=_len, mult=m1) ) %10 ) %10 if t == 10: return 0 else: return t return None def ean13Valid(chk): """Verify if code is valid EAN13 barcode. Returns True|False""" return chk.isdigit() and __lenCheck(chk) and \ (int(chk[-1]) == eanCheckDigit(chk)) def ean8CheckDigit(chk): """Returns the checksum digit of an EAN8 code""" return eanCheckDigit(chk, code='EAN8') def ean8Valid(chk): """Verify if code is valid EAN8 barcode. Returns True|False""" if chk.isdigit() and len(chk) == codeLength["EAN8"]: return int(chk[-1]) == ean8CheckDigit(chk) return False # UPC codes below def upcaCheckDigit(chk): if chk is not None: return eanCheckDigit('0'+chk) return None def upcaValid(chk): if chk is not None: return ean13Valid('0'+chk) return False def upca2e(chk): t = None if chk.isdigit() and __lenCheck(chk, 'UPCA'): if '012'.find(chk[3]) >= 0 and chk[4:8] == '0000': t=chk[:3]+chk[8:11]+chk[3] elif chk[4:9] == '00000': t=chk[:4]+chk[9:11]+'3' elif chk[5:10] == '00000': t = chk[:5]+chk[10]+'4' elif '5678'.find(chk[10]) >= 0 and chk[6:10] == '0000': t=chk[:6]+chk[10] else: t=None # Check digit if t is not None: if upcaValid(chk): t=t+chk[-1] elif len(chk) == codeLength["UPCA"]-1: t=t+str(upcaCheckDigit(chk)) else: t=None return t def upce2a(chk): t=None if chk.isdigit() and __lenCheck(chk, 'UPCE'): if '012'.find(chk[6]) >= 0: t=chk[:3]+chk[6]+'0000'+chk[3:6] elif chk[6] == '3': t=chk[:4]+'00000'+chk[4:6] elif chk[6] == '4': t=chk[:5]+'00000'+chk[5] elif '5678'.find(chk[6]) >= 0: t=chk[:6]+'0000'+chk[6] else: t=None if t is not None: if len(chk) == codeLength["UPCE"] - 1: t=t+str(upcaCheckDigit(t)) elif len(chk) == codeLength['UPCE'] and \ int(chk[-1]) == upcaCheckDigit(t): t=t+chk[-1] else: t=None return t def upceValid(chk): return len(chk) == codeLength["UPCE"] and upcaValid(upce2a(chk)) def upceCheckDigit(chk): if chk is not None: return upcaCheckDigit(upce2a(chk)) return None From bmgx_no_sp at mgleesonprop.co.za Sun Jan 4 12:07:19 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Sun, 04 Jan 2004 19:07:19 +0200 Subject: using cgi form via http and extracting results Message-ID: <3ff84844.0@news1.mweb.co.za> I would like to use an already existing online service (currency converter) basically consisting of a html form with a few options that is submitted and returns the results. I really don't know where to start but I have assumed the following steps need to be taken: 1) Make an http connection to the remote script (http://server/script.cgi) 2) Fill out the html form (1x TEXT and 2x SELECT input fields) 3) Submit the form 4) extract the actual returned result. (using regex or something..) Any help on which modules to use would be much appreciated! From seanl at chaosring.org Sat Jan 3 15:48:00 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 12:48:00 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: Serge Orlov wrote: > "Sean R. Lynch" wrote in message news:LmmdnUn4seDeGWuiXTWc-w at speakeasy.net... > >>I've been playing around with Zope's RestrictedPython, and I think I'm >>on the way to making the modifications necessary to create a >>capabilities-based restricted execution system. The idea is to strip out >>any part of RestrictedPython that's not necessary for doing capabilities >>and do all security using just capabilities. >> >>The basic idea behind capabilities is that you don't give any piece of >>code you don't trust a reference to something you don't want it to have >>access to. You use proxies instead (E calls them "facets"). > > > "Don't give" sounds good in theory but fails in practice. You can't prevent > leakage 100%, so any security system _must_ help programmer to keep > trusted data away from untrusted code. Do you know that rexec failed > exactly because it didn't help to prevent leakage? Hmm, this is good information. I think it will probably change the way I've been looking at this. >>In order to be able to allow untrusted code to create proxy objects, I >>needed to be able to store a reference to the proxied object in a >>private attribute. >> >>To create private attributes, I'm using "name mangling," where names >>beginning with X_ within a class definition get changed to >>__, where the UUID is the same for that class. The UUIDs >>don't need to be secure because it's not actually possible to create >>your own name starting with an underscore in RestrictedPython; they just >>need to be unique across all compiler invocations. > > > This is a problem: you declare private attributes whereas you should be > declaring public attributes and consider all other attributes private. Otherwise > you don't help prevent leakage. What about doing it this way: > > obj.attr means xgetattr(obj,acc_tuple) where acc_tuple = ('attr',UUID) > and xgetattr is > def xgetattr(obj,acc_tuple): > if not has_key(obj.__accdict__,acc_tuple): > raise AccessException > return getattr(obj,acc_tuple[0]) > > __accdict__ is populated at the time class or its subclasses are created. > If an object without __accdict__ is passed to untrusted code it will > just fail. If new attributes are introduced but not declared in __accdict__ > they are also unreachable by default. This is very interesting, and you may convince me to use something similar, but I don't think you're quite correct in saying that the name-mangling scheme declares private attributes; what is the difference between saying "not having X_ in front of the attribute makes it public" and "having X_ in front of the attribute makes it private?" >>The nice thing about using this name mangling is that it's only done at >>compile time and doesn't affect runtime performance. An interesting side >>effect is that code defined on a class can access private attributes on >>all descendants of that class, but only ones that are defined by other >>code on that class, so this isn't a security issue. >> >>I was thinking I needed read-only attributes to be able to avoid >>untrusted code's being able to sabotage the revoke method on a proxy >>object, but I'm thinking that just keeping around a reference to the >>revoke method in the original code may be enough. >> >>Does anyone think I'm going in completely the wrong direction here? Am I >>missing anything obvious? > > > It depends on what type of security do you want. Did you think about DOS > and covert channels? If you don't care about that, yeah, you don't miss > anything obvious. you should worry whether you miss something > non-obvious. I am not (particularly) concerned about DoS because I don't plan to be running anonymous code and having to restart the server isn't that big of a deal. I do plan to make it hard to accidentally DoS the server, but I'm not going to sacrifice a bunch of performance for that purpose. As for covert channels, can you give me an example of what to look for? I am certainly worried about non-obvious things, but my intent wasn't to put up a straw man, because if I ask if I'm missing non-obvious things, the only possible answer is "of course." > By the way, did you think about str.encode? Or you are not worried about > bugs in zlib too? Well, it'll only take *one* problem of that nature to force me to go back to converting all attribute accesses to function calls. On the other hand, as long as any problem that allows a user to access protected data is actually a in (zlib, etc), I think I'm not going to worry about it too much yet. If there is some method somewhere that will allow a user access to protected data that is not considered a bug in that particular subsystem, then I have to fix it in my scheme, which would probably require going back to converting attribute access to method calls. From mcfletch at rogers.com Mon Jan 19 16:31:28 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 19 Jan 2004 16:31:28 -0500 Subject: Simple question from Python newb... What am I doing wrong? For x, y, z in aTuple: In-Reply-To: References: Message-ID: <400C4CB0.2000606@rogers.com> Amy G wrote: >I have a whole bunch of tuples that look something like this, > > ... >for x, y, z in aTuple: > do something with x > do something with y > do something with z > >But I am getting the error that there are too many values to unpack. > > You have one of two problems, most likely: * if you really are doing for x,y,z in aTuple (not a list of aTuples), you're trying to unpack *each* item in aTuple (where each such item is a string, all of which happen to be much longer than three items) into three items. Python right complains that the strings aren't all three characters long. * if you really are doing for x,y,z in aTupleList (a list of aTuples), you've got one non-standard tuple in the list, and can find it pretty easily by doing [ x for x in aTupleList if len(x) != 3 ] and then figure out how it got there. My non-existent money is on the first case. ... >It prints the items from the tuple each on its own line. How can I unpack >these three string values into three different string variables like my >first for loop? > > x,y,z = aTuple Enjoy yourself, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From guettli at thomas-guettler.de Mon Jan 5 10:09:42 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 05 Jan 2004 16:09:42 +0100 Subject: python and LAN References: Message-ID: Am Sat, 03 Jan 2004 20:16:09 +1000 schrieb Egor Bolonev: > Hello, All! > > I wish to write a programs for LAN, but I don't know where to begin. > > For example I have to get a hostlist of my network: > ... > 192.168.1.35 acca > 192.168.3.38 alligator What operating system do you use? Some systems answer ping to the broadcast address, but not all ping 255.255.255.255 If you network is not switched, you can listen to the wire by setting the ethernet card to promiscuous mode. Google for tcpdump. But this has nothing to do with python. thomas From kirk at strauser.com Wed Jan 21 23:35:07 2004 From: kirk at strauser.com (Kirk Strauser) Date: Thu, 22 Jan 2004 04:35:07 GMT Subject: Secure Voting software References: <20040121174434.28446.00000428@mb-m15.aol.com> <7xvfn4lq9m.fsf@ruckus.brouhaha.com> Message-ID: <87zncgy544.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-01-22T01:35:01Z, Paul Rubin writes: > The book "Security Engineering" by Ross Anderson is a good place to start > reading if you're interested in the subject. I just finished "Practical Cryptography" by Niels Ferguson and Bruce Schneier. It was almost enough to make me not want to bother trying. :-/ - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAD1Ke5sRg+Y0CpvERAlquAKCSi28drKEVE3fPC1F9c8SWRBEwWwCdH5pO 3eAxJDSQ3ViaBDmQG7ZWV+w= =sjqt -----END PGP SIGNATURE----- From peter at engcorp.com Mon Jan 19 14:53:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 14:53:38 -0500 Subject: HowTo distinguish between File and Directory References: Message-ID: <400C35C2.2C46EE3C@engcorp.com> Scott F wrote: > > On Win32, is there a function in the standard modules that can take a > pathname and return whether it refers to a File or a Directory? import os os.path.isfile(name) os.path.isdir(name) Is that adequate? -Peter From rainerd at eldwood.com Wed Jan 14 14:47:01 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Wed, 14 Jan 2004 19:47:01 GMT Subject: I come not to bury C++, but to praise it... References: Message-ID: Derek wrote: > I also use C++ and Python as my main languages and I agree with your > comments. However, I don't agree that Python is inherently "safer" > than C++. At best I see it as a tie. For example, C++ let's you > corrupt memory among other "unsafe" things, most of which can be > avoided by using standard containers, smart pointers, etc. Python > lets you do "unsafe" things such as passing an object to a function > when it makes no sense to do so, which can lead to nasty runtime > surprises. What I meant by "safer" is that the worst thing that usually happens in a defective Python program is that it terminates with an exception, complete with traceback. A defective C++ program can do a lot worse. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From jjl at pobox.com Fri Jan 16 14:44:41 2004 From: jjl at pobox.com (John J. Lee) Date: 16 Jan 2004 19:44:41 +0000 Subject: Python COM Server with C++ References: Message-ID: <871xpz7k5y.fsf@pobox.com> andre.bernemann at gmx.de (Andre Bernemann) writes: > I have written a Python COM Server with the help of Mark Hammond's > Book Programming Python on Win32. I used the CreateObjects method in > VB to access the COM Methods and all worked fine. Unfortunately, that [...] Hmm, sorry, I didn't really read the question properly! If you've started with win32all, you probably want to stick with it. I'd guess the python-win32 list is more likely to yield answers (though Mark has been posting here recently, so you might be lucky...). Make sure to search the list archive first, of course. John From ed_zeng at yahoo.com Fri Jan 23 18:06:45 2004 From: ed_zeng at yahoo.com (ex laguna) Date: 23 Jan 2004 15:06:45 -0800 Subject: py2exe with shelve error Message-ID: <53ab57.0401231506.50938738@posting.google.com> Hi, I have ran into a problem with py2exe 0.5.0 and shelve in python 2.3.3. The script works fine standalone, but not with py2exe. Does anyone have a solution of workaround for this? Thanks much. # Begin of setup.py from distutils.core import setup import py2exe setup(console=["test.py"]) # End of setup.py # Begin of test.py import shelve f = shelve.open('test.txt') f['hello'] = 'world' f.close() f = shelve.open('test.txt') print f.keys() print f.values() # End of test.py c:\Python>python -V Python 2.3.3 c:\Python>python test.py ['hello'] ['world'] c:\Python>python setup.py py2exe running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension '_sre' creating python loader for extension 'datetime' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** skipping byte-compilation of C:\Program Files\Python23\lib\__future__.py to __future__.pyc skipping byte-compilation of C:\Program Files\Python23\lib\copy_reg.py to copy_reg.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_compile.py to sre_compile.pyc skipping byte-compilation of C:\Program Files\Python23\lib\locale.py to locale.pyc byte-compiling c:\Python\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc skipping byte-compilation of C:\Program Files\Python23\lib\unittest.py to unittest.pyc skipping byte-compilation of C:\Program Files\Python23\lib\macpath.py to macpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\popen2.py to popen2.pyc skipping byte-compilation of C:\Program Files\Python23\lib\stat.py to stat.pyc byte-compiling c:\Python\build\bdist.win32\winexe\temp\datetime.py to datetime.pyc skipping byte-compilation of C:\Program Files\Python23\lib\atexit.py to atexit.pyc skipping byte-compilation of C:\Program Files\Python23\lib\whichdb.py to whichdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\cmd.py to cmd.pyc skipping byte-compilation of C:\Program Files\Python23\lib\os2emxpath.py to os2emxpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\tempfile.py to tempfile.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pprint.py to pprint.pyc skipping byte-compilation of C:\Program Files\Python23\lib\_strptime.py to _strptime.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_constants.py to sre_constants.pyc skipping byte-compilation of C:\Program Files\Python23\lib\re.py to re.pyc skipping byte-compilation of C:\Program Files\Python23\lib\ntpath.py to ntpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\tokenize.py to tokenize.pyc skipping byte-compilation of C:\Program Files\Python23\lib\getopt.py to getopt.pyc skipping byte-compilation of C:\Program Files\Python23\lib\doctest.py to doctest.pyc skipping byte-compilation of C:\Program Files\Python23\lib\random.py to random.pyc skipping byte-compilation of C:\Program Files\Python23\lib\string.py to string.pyc skipping byte-compilation of C:\Program Files\Python23\lib\warnings.py to warnings.pyc skipping byte-compilation of C:\Program Files\Python23\lib\UserDict.py to UserDict.pyc skipping byte-compilation of C:\Program Files\Python23\lib\inspect.py to inspect.pyc skipping byte-compilation of C:\Program Files\Python23\lib\repr.py to repr.pyc skipping byte-compilation of C:\Program Files\Python23\lib\traceback.py to traceback.pyc skipping byte-compilation of C:\Program Files\Python23\lib\copy.py to copy.pyc skipping byte-compilation of C:\Program Files\Python23\lib\bdb.py to bdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\types.py to types.pyc skipping byte-compilation of C:\Program Files\Python23\lib\anydbm.py to anydbm.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre.py to sre.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pickle.py to pickle.pyc skipping byte-compilation of C:\Program Files\Python23\lib\StringIO.py to StringIO.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pdb.py to pdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\linecache.py to linecache.pyc skipping byte-compilation of C:\Program Files\Python23\lib\token.py to token.pyc skipping byte-compilation of C:\Program Files\Python23\lib\dummy_thread.py to dummy_thread.pyc skipping byte-compilation of C:\Program Files\Python23\lib\opcode.py to opcode.pyc skipping byte-compilation of C:\Program Files\Python23\lib\posixpath.py to posixpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\calendar.py to calendar.pyc skipping byte-compilation of C:\Program Files\Python23\lib\shelve.py to shelve.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_parse.py to sre_parse.pyc skipping byte-compilation of C:\Program Files\Python23\lib\os.py to os.pyc skipping byte-compilation of C:\Program Files\Python23\lib\dis.py to dis.pyc *** copy extensions *** *** copy dlls *** copying C:\Program Files\Python23\Lib\site-packages\py2exe\run.exe -> c:\Python\dist\test.exe c:\Python>cd dist c:\Python\dist>test.exe Traceback (most recent call last): File "test.py", line 3, in ? File "shelve.pyc", line 231, in open File "shelve.pyc", line 211, in __init__ File "anydbm.pyc", line 62, in ? ImportError: no dbm clone found; tried ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in ignored From gandalf at geochemsource.com Wed Jan 7 05:26:09 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 07 Jan 2004 11:26:09 +0100 Subject: Newbie: Python equivalent to Delphi TTable References: Message-ID: <3FFBDEC1.8010702@geochemsource.com> Please try the kinterbasdb module. You can find it here: http://kinterbasdb.sourceforge.net/ Probably you can find all necessary information there. What you want is a cursor. However, the TTable component is buffered. You can go forward and backward in the dataset. AFAIK, cursors in DB API 2.0 are unidirectional. Thus, you must make your own buffering if you want to be able to go forward and backward too. Another note: these cursors do not support updates but you can write a class easily that suit your needs. Best, Laci 1.0 Ashley Lloyd wrote: > Hi all, > > I don't know how many of you are very familiar with Delphi, but we're > looking for anything that offers the user a similar kind of interface > to an Interbase table as Delphi components TTable, TIBOTable, etc > (findkey, etc). If anyone knows of anything allowing us to do this, > I'd be grateful. > > Sorry that this no doubt sounds a little vague, I just can't really > explain it any better! > > TIA > > Ashley > > _________________________________________________________________ > It's fast, it's easy and it's free. Get MSN Messenger today! > http://www.msn.co.uk/messenger > > From aahz at pythoncraft.com Fri Jan 16 13:07:25 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Jan 2004 13:07:25 -0500 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> Message-ID: In article <7934d084.0401152058.164a240c at posting.google.com>, Andrae Muys wrote: > >Found myself needing serialised access to a shared generator from >multiple threads. Came up with the following > >def serialise(gen): > lock = threading.Lock() > while 1: > lock.acquire() > try: > next = gen.next() > finally: > lock.release() > yield next I'm not sure this is generic enough to go in the standard library. Usually, I'd recommend that someone wanting this functionality consider other options in addition to this (such as using Queue.Queue()). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From wrbt at email.com Tue Jan 27 17:43:55 2004 From: wrbt at email.com (Larry) Date: 27 Jan 2004 14:43:55 -0800 Subject: Color count in PIL Message-ID: <2ec1bc1c.0401271443.15f56742@posting.google.com> I've been walking up, down, and around instances in the object model of PIL trying to figure out how to easily calculate how many unique colors are used in an image, specifically a bitmap (mode "P"). Am I missing something? Thanks python friends! From fBechmann at web.de Fri Jan 2 10:32:48 2004 From: fBechmann at web.de (Frank Bechmann) Date: 2 Jan 2004 07:32:48 -0800 Subject: question: Python or Lua for rejuvenation of old PCs? References: <7xisjupq14.fsf@ruckus.brouhaha.com> Message-ID: he was writing about a >> distributed, fault-tolerant home monitoring and control system that >> would be easy to port later to embedded microcontrollers which is not so far from >> embedded controller tasks if my english is not too worse. and whether FORTH is too much of an inconvenience is in the eyes of the beholder - but I have to admit that your statement is true for the vast majority of programmers and that I forgot to add a :). From crap at crud.com Wed Jan 28 23:37:17 2004 From: crap at crud.com (Moosebumps) Date: Thu, 29 Jan 2004 04:37:17 GMT Subject: "static" checking Message-ID: <160Sb.19106$fo1.10783@newssvr25.news.prodigy.com> I'm wondering what kind of checking I can do on a python program before running it (besides reading over every line). I hate running a long python script, only to have it fail at the end because I misspelled a function name, or made some other silly mistake that a compiler would normally catch. Then I have to run it all over again to see what happened or come up with some sort of short test. I usually do try to isolate the new parts of my code, and run them first with some dummy data that will run fast. But that is not always possible because of dependencies, and it would be nice to have some sort of sanity check up front. I noticed there is a "check" function in IDLE, and I've tried running it but it never does anything. Maybe it is not catching the kinds of errors that are biting me. thanks, MB From mesteve_b at hotmail.com Sat Jan 3 18:33:36 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 03 Jan 2004 23:33:36 GMT Subject: Lists are weird when they are instance members References: Message-ID: I didn't say that right. I meant to say that I now finally understood what's going on now, with your replies, but I will take a slight break from the app I'm writing, and do some ingesting of the core Python concepts. "python newbie" wrote in message news:VfIJb.5485$kp4.731 at newssvr29.news.prodigy.com... > thanks for the helpful replies. > I guess I was just in confusion as to why I was able to leave alone the > string variables in class FileGroup, such > as sourceDir and destinDir, and nothing unpredictable happened with those, > but with the list variable, I had to treat differently. > But after I again read closely, Python In a Nutshell, I'm sure I will > understand. > From simonb at NOTTHISBIT.webone.com.au Sat Jan 31 17:11:15 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Sun, 01 Feb 2004 09:11:15 +1100 Subject: numarray and NumarrayType References: Message-ID: On Sat, 31 Jan 2004 16:48:30 +0100, Marco Bubke wrote: > Hi > > I have a little problem mit numarrays type. I want to get the Type but its > noch the right one. If I array.typecode() I get the right one but there is > not a typecode for all types. I geht the same type fer float and double? > > Thats wrong. Its a bug by me or numarray? > I don't know but I used NA_nameToTypeNo on theArray.type().name Seems to work OK. Simon. From tim.golden at viacom-outdoor.co.uk Fri Jan 30 03:49:14 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 30 Jan 2004 08:49:14 -0000 Subject: Pythonwin - breaking out of infinite loop Message-ID: >From: Graham [mailto:gsmith at oxfam.org.uk] >How do I stop a Python program running in PythinWin? I would >expect to be >able to use CTR-C or CTRL-break etc. > Find the Python icon in the systray (next to the clock at the bottom right of the screen). Right-click and select "Break into running code" (or something like that) 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 peterwu at hotmail.com Wed Jan 21 16:25:59 2004 From: peterwu at hotmail.com (Peter Wu) Date: Wed, 21 Jan 2004 16:25:59 -0500 Subject: python mode question References: <87y8s1oxuj.fsf@tulip.whu.ca> Message-ID: <87u12pouxk.fsf@tulip.whu.ca> James Henderson writes: > On Wednesday 21 January 2004 8:23 pm, Peter Wu wrote: >> After firing C-c C-c to execute a python program in Python mode, an >> output buffer will be displayed at the bottom of the window. Also, the >> focus remains in the output buffer. How can I switch the focus from the >> output buffer to the editing buffer? Thanks! > > C-x o That's it! Thanks! > I take it you're talking about Emacs. :) Yeah, GNU Emacs. ^_^ -- ,,, (o o) Peter Wu ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From jason at tishler.net Tue Jan 27 10:04:09 2004 From: jason at tishler.net (Jason Tishler) Date: Tue, 27 Jan 2004 10:04:09 -0500 Subject: Error under Cygwin - threading module In-Reply-To: <20040127144636.GA1204@tishler.net> References: <20040127144636.GA1204@tishler.net> Message-ID: <20040127150408.GB1204@tishler.net> AdSR, On Tue, Jan 27, 2004 at 09:46:36AM -0500, Jason Tishler wrote: > On Thu, Jan 22, 2004 at 02:19:31PM -0800, AdSR wrote: > > Sometimes when I launch my script under Cygwin, I get strange error > > messages like: > > > > 2 [win] python 1912 Winmain: Cannot register window class > > > > Sometimes all of the threads run OK, otherwise after the "correct" > > ones finish the console stops responding anyway. > > FWIW, I cannot reproduce the above problem under: > > $ cygcheck -cd cygwin python > Cygwin Package Information > Package Version > cygwin 1.5.5-1 > python 2.3.2-1 > > and > > Windows 2000 SP4 I "spoke" too soon -- I was able to reproduce the problem after 160 iterations. Please try the latest snapshot: http://cygwin.com/snapshots/ and report back whether or not this solves your problem. Thanks, 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 james at logicalprogression.net Wed Jan 21 15:51:50 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 20:51:50 +0000 Subject: Need help with Python class idioms In-Reply-To: References: Message-ID: <200401212051.50411.james@logicalprogression.net> On Wednesday 21 January 2004 8:43 pm, Tad Marko wrote: > Howdy! > > I'm trying to get my head around Python and I've come to realize that > there are a lot of idioms in Python that are a bit different than in > other languages. I have a class similar to what I've included below. > The only difference is that in the real class, I have even more > mandatory attributes. Too many to specify at once on a constructor and > they don't always exist at construction time anyway, so the accessor > idiom must remain. > > Can anyone suggest a more Pythony way to do the following? > > Thanks, > Tad > > #!/bin/env python > > class A: > def __init__(self): > self.mandatoryVar1 = None > self.mandatoryVar2 = None > > def setMV1(self, mv1): > self.mandatoryVar1 = mv1 > > def setMV2(self, mv2): > self.mandatoryVar2 = mv2 > > def saveToDB(self, db): > if self.mandatoryVar1 == None: > raise Exception, "Mandatory Var 1 not set." > if self.mandatoryVar2 == None: > raise Exception, "Mandatory Var 2 not set." > > # Using db, do whatever saving stuff is needed. What about this: class A: def __init__(self, mandatoryVar1, mandatoryVar2): self.mandatoryVar1 = mandatoryVar1 self.mandatoryVar2 = mandatoryVar2 -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From python at rcn.com Mon Jan 12 04:25:26 2004 From: python at rcn.com (Raymond Hettinger) Date: 12 Jan 2004 01:25:26 -0800 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0401120125.7d186102@posting.google.com> [Tim Rowe] > > If I do from __future__ import division then eval(1/2) gives me 0.5 as > > expected. But if I do print input("enter a sum: ") and enter 1/2 as > > the sum I get 0 as if I hadn't done the import. I thought input was > > supposed to give the same behaviour as an eval on raw input -- why the > > difference here? [Paul Rubin[ > The input function is calling eval from the context of the module > where 'input' itself is defined. If you use "from __future__ import > division" in module A and have "print 3/2" in module B, the value of > 3/2 in module B shouldn't be affected by the input, since module B > may depend on integer division having the old behavior. Right! So, the way to get eval() to respond to the import is to pass along the current environment: >>> from __future__ import division >>> eval('9/2', globals()) 4.5 Raymond Hettinger From firephreek at earthlink.net Thu Jan 29 09:43:36 2004 From: firephreek at earthlink.net (firephreek) Date: Thu, 29 Jan 2004 07:43:36 -0700 Subject: Threads - where to start? Message-ID: <001d01c3e676$46f02ae0$6f01010a@Rachel> A while back I posted asking about a problem I was having with some threads. Somebody responded back with a link to a slide show, but with the little bit of background I have in this subject, I wasn't able to come away with a whole lot, much less a solution to my problem. Where can I go if I want to get a good understanding of threads and how to implement them? I'm not sure what exactly is meant by blocking or locking, or when they should be implemented. Most of the examples I've read through seem to use the 'threading.py' module as a base for their own class of threads. Is this the purpose of threading.py? Or can it be used standalone? What about communicating across threads? Do they have their own namespace? Can they refer to globals in the main program? Why won't some of them just die? I have a lot of questions, but I just don't know where to go! Help! Stryder -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 2004 bytes Desc: not available URL: From tzot at sil-tec.gr Sat Jan 3 10:22:14 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 03 Jan 2004 17:22:14 +0200 Subject: SMTP - Topic & add files References: <1073137983.983243@news.liwest.at> Message-ID: On Sat, 3 Jan 2004 15:19:17 +0100, rumours say that "EsC" might have written: >probably a dummy question, but i don't >know how to set a Topic-Text and add >Files to an email ... > >i use the SMTPLIB module and the >function/method: .sendmail(from,to,msg) > >but how can i set a topic Text? >is there an other function/method, or >must it be encoded within the message-text? To prepare the body of your email message, you need the email package; check it in the documentation. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From gerrit at nl.linux.org Thu Jan 8 08:25:07 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 8 Jan 2004 14:25:07 +0100 Subject: PRE-PEP: new Path class In-Reply-To: <1073567709.3ffd57dda8cb0@mcherm.com> References: <1073567709.3ffd57dda8cb0@mcherm.com> Message-ID: <20040108132507.GA3792@nl.linux.org> Michael Chermside wrote: > I agree... paths should be immutable. > > Instead of .normalize_inplace() which changes the behavior of the > Path, how about .get_normalized_string() (please find a better name) > which allows access to the normalized version without mutating the > Path object? (Or perhaps it should be .get_normalized_Path()... I'm > not sure.) If we make it immutable, we can simply do path.normalize(), which returns the normalized path. Or am I overlooking something? yours, Gerrit. -- 147. If she have not borne him children, then her mistress may sell her for money. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From mksql at yahoo.com Thu Jan 8 12:35:30 2004 From: mksql at yahoo.com (mksql at yahoo.com) Date: Thu, 08 Jan 2004 12:35:30 -0500 Subject: Scrolling graphs in a Tk GUI? References: Message-ID: On Wed, 07 Jan 2004 18:36:49 -0500, John Grayson wrote: >You'll find an example in Python and Tkinter Programming... I can't find any copies to purchase. Every vendor I know is out. From cphsu at zen.com.tw Fri Jan 9 06:24:31 2004 From: cphsu at zen.com.tw (Kent Hsu (Hsu, Chih-Peng)) Date: Fri, 9 Jan 2004 19:24:31 +0800 Subject: Py2Exe and a simple COM Windows Program (can't import pythoncom) References: <982e9537.0401071249.4d75c8fb@posting.google.com> Message-ID: Just include the 'pythoncom23.dll'. (usally can be found in %windir%/system32 -> Windows 2000). Best Regards, Kent Hsu Brian Hlubocky wrote in message news:982e9537.0401071249.4d75c8fb at posting.google.com... > I'm have a fairly simple (in terms of COM) python program that pulls > info from an Access database and creates Outlook contacts from that > information. It uses wxPython for gui and works without problems. > > I want to be able to distribute this program using py2exe, but I am > having some problems. I am using a simple setup.py like in the > documentation for the py2exe tool and everything compiles ok, except > that when I run the exe, I get an exception that says "ImportError: no > module named pythoncom." My program used win32com (which appears to be > loaded fine with the executable) until I needed thread support for the > gui. In order to do this, I needed to import pythoncom and call > CoInitialize() and CoUninitialize() manually for the new thread. I > believe it is this use of the pythoncom module that py2exe is having > trouble with. > > I tried adding "pythoncom" to the import list in the distutils > setup.py but the py2exe tool gave me a warning that said it couldn't > be located. I am able to import this module just fine in python > scripts and at the interpreter. I am relatively new to COM and its use > with python as well as with distutils and py2exe. If anyone could help > me out with this, it would be greatly appreciated! > > Thanks, > Brian From haim at babysnakes.org Sun Jan 18 16:11:51 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Sun, 18 Jan 2004 23:11:51 +0200 Subject: newbie question about compression and ascii References: Message-ID: Serge Orlov wrote: > > "Haim Ashkenazi" wrote in message > news:mailman.470.1074442222.12720.python-list at python.org... >> Hi >> >> I'm a real newbie, so sorry if this is a trivial question. >> >> I'm writing a script that collect a list of files and creates a zipfile >> from these files. when running it on linux everything works fine, but >> when I'm running it on windows I get this error when running the command: >> >> myZip.write(file) >> >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xa8 in position 10: >> ordinal not in range(128) >> >> the file variable contains: u'C:\\Document and Settings\\haim\etc...'. > > A unicode file name... Zip format doesn't support unicode file names. > >> >> is there a way to solve this? > > Only work around. Encode the unicode string using an encoding > of your choice. For windows it's probably "mbcs": > if isinstance(file_name, unicode): > myZip.write(file_name.encode('mbcs')) thanx, this seem to solve the problem. Bye > > -- Serge. -- Haim From eric.brunel at N0SP4M.com Mon Jan 19 09:38:57 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 15:38:57 +0100 Subject: Setting Window Size using Pack Under Tkinter References: <8089854e.0401160134.5674a86c@posting.google.com> <4007de09$0$151$e4fe514c@dreader5.news.xs4all.nl> <4007dedc$0$166$e4fe514c@dreader5.news.xs4all.nl> <8089854e.0401190350.61b3efc@posting.google.com> Message-ID: Fuzzyman wrote: > Short of actually trying it...... (when I get home I *will* try it) > > Would the following work : > > from Tkinter import * > gui=Tk() > Button(gui, text='A button', command=a_function).pack() > > ####code#### > gui.geometry("+%d+%d" %(300, 100)) > gui.resizable(0,0) > gui.mainloop() > > ?? Yes it will. Note however that doing gui.geometry("+300+100") will actually move the window, not resize it. To resize the window, use gui.geometry("300x100") More generally, the syntax for the geometry is "WxH+X+Y" where W and H are the window's width and height resp. and X & Y the coordinates of its top-left corner from the top-left corner of the screen. > If I recall correctly it ought to.... (mixing the pack and geometry > methods in the same GUI)... > > Anyway - thanks. > > Fuzzy > > > "duikboot" wrote in message news:<4007dedc$0$166$e4fe514c at dreader5.news.xs4all.nl>... > >>from Tkinter import * >> gui=Tk() >> >> ####code#### >> gui.geometry("+%d+%d" %(300, 100)) >> gui.resizable(0,0) >> gui.mainloop() >> >>Will work offcourse too.. :-) >> >>cheers, >> >>Arjen >> >> >> >>"duikboot" schreef in bericht >>news:4007de09$0$151$e4fe514c at dreader5.news.xs4all.nl... >> >>>from Tkinter import * >>>gui=Tk() >>> >>>####code#### >>>gui.geometry("+%d+%d" %(300, 100)) >>>gui.resizable(0,0) >>> >>>if __name__=='__main__': >>> gui.mainloop() >>> >>> >>> >>> >>>"Fuzzyman" schreef in bericht >>>news:8089854e.0401160134.5674a86c at posting.google.com... >>> >>>>I'm having trouble implementing my GUI using Tkinter...... >>>>I've been working through the Tkinter tutorials from 'Programming >>>>Python' and am generally happy enough with the functionality and feel >>>>of the results *but* - I can't see how to set the size of the root >>>>window (or any top level window) and to stop it being resized........ >>>> >>>>Thanks for any help. >>>> >>>>Fuzzyman >>>> >>>> >>>>-- >>>> >>>>YAPLP >>>>Yet Another Python Links Page >>>>http://www.voidspace.org.uk/coollinks/python_links.shtml >>>> >>>>Python Utils >>>>http://www.voidspace.org.uk/atlantibots/pythonutils.html >>>> >>>>-- >>>> >>>>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.atlantibots.org.uk >>>>http://groups.yahoo.com/group/atlantis_talk/ >>>>Atlantibots - stomping across the worlds of Atlantis. >>>>--- >>>>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 >>> >>> -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From kim at lignus.dk Fri Jan 23 05:41:37 2004 From: kim at lignus.dk (Kim Petersen) Date: Fri, 23 Jan 2004 11:41:37 +0100 Subject: Help and optimization hints, anyone? Message-ID: I've worked on this table object a bit too long - and seem to have stared too long at the code. Can someone see where it goes wrong in the insertrow function? Also optimization hints and alternatives will be greatly appreciated. #!env python # # created: "15:19 20/01-2004" by Kim Petersen # # $Id$ # import Tkinter class UserDict: defaults={} def __init__(self,inherit=None): if not inherit: self.inherit=[] else: self.inherit=inherit self.dict=self.defaults.copy() def __setitem__(self,name,value): self.dict[name]=value def __getitem__(self,name): if not self.dict.has_key(name): for dict in self.inherit: if dict.has_key(name): return dict[name] raise KeyError,"%s not found" % (name,) return self.dict[name] def haskey(self,name): return self.dict.has_key(name) class Cell(UserDict): defaults={"width": 0,"height": 0,"text": '',"color": "black","background": "white", "widgets": None} def __init__(self,master,row,column,text): UserDict.__init__(self,[row,column]) self.master=master self["text"]=text self.row=row # these are needed for us to find the actual row/col self.column=column self.create() def create(self): """Create the widgets the first time (might inflict up to two resize's)""" x,y=self.column["x"],self.row["y"] w,h=self.column["width"],self.row["height"] r=self.master.create_rectangle((x,y,x+w,y+h),fill=self["background"]) t=self.master.create_text((x+self.master.colpadding,y+h/2), text=self["text"], anchor="w",fill=self["color"]) self["widgets"]=[r,t] bbox=self.master.bbox(t) self["width"]=bbox[2]-bbox[0] self["height"]=bbox[3]-bbox[1] if self["width"]+self.master.colpadding*2>w: self.column.resize(self["width"]+self.master.colpadding*2) self.resize() if self["height"]+self.master.rowpadding*2>h: self.row.resize(self["height"]+self.master.rowpadding*2) self.resize() def resize(self): """Resize according to the width/height given by row,column""" x,y=self.column["x"],self.row["y"] w,h=self.column["width"],self.row["height"] self.master.coords(self["widgets"][0],(x,y,x+w,y+h)) self.master.coords(self["widgets"][1],(x+self.master.colpadding,y+h/2)) def move(self,dx,dy): """Relatively move according to delta's""" self.master.move(self["widgets"][0],dx,dy) self.master.move(self["widgets"][1],dx,dy) class Column(UserDict): """ """ defaults={"x": 0,"width": 0,"label": '',"tag": ''} def __init__(self,master,label='',before=None): UserDict.__init__(self) self.master=master if master.columns: if not before or before>0: if not before: after=(-1) else: after=before-1 self.dict["x"]=master.columns[after]["x"]+master.columns[after]["width"] # since we have a width of 0 there is no need to move the rest of the columns. def calcwidth(self): """Calculate the *actually* needed width of the column (*not* the current one).""" width=0 for row in self.master.rows: width=max(self.master.cells[(row,self)]["width"],width) return width+self.master.colpadding*2 def resize(self,width): # calc delta, set new width dx=width-self["width"] self["width"]=width ci=self.master.columns.index(self) # resize the cells for row in self.master.rows: try: self.master.cells[(row,self)].resize() except KeyError: pass # move columns to the right further to the right for i in range(ci+1,len(self.master.columns)): self.master.columns[i].move(dx) def move(self,dx): self["x"]=self["x"]+dx # move the cells correspondingly for row in self.master.rows: try: self.master.cells[(row,self)].move(dx,0) except KeyError: pass class Row(UserDict): defaults={"y": 0,"height": 0,"label": '',"tag": ''} def __init__(self,master,label,before=None): UserDict.__init__(self) self["label"]=label # now insert it. self.master=master if master.rows: if not before or before>0: if not before: after=(-1) else: after=before-1 self.dict["y"]=master.rows[after]["y"]+master.rows[after]["height"] def calcheight(self): """Calculate the *actually* needed width of the column (*not* the current one).""" height=0 for row in self.master.columns: height=max(self.master.cells[(self,column)]["height"],height) return height+self.master.rowpadding*2 def resize(self,height): dy=height-self.dict["height"] self.dict["height"]=height ri=self.master.rows.index(self) for column in self.master.columns: if self.master.cells.has_key((self,column)): self.master.cells[(self,column)].resize() for i in range(ri+1,len(self.master.rows)): self.master.rows[i].move(dy) def move(self,dy): self.dict["y"]=self.dict["y"]+dy for col in self.master.columns: try: self.master.cells[(self,col)].move(0,dy) except KeyError: pass pass def moveto(self,y): self.move(y-self.dict["y"]) def __setitem__(self,name,value): if name=="height": self.resize(value) elif name=="y": self.move(value-self["y"]) else: self.dict[name]=value class Table(Tkinter.Canvas): """A table object - it consists of a number of cells layed out in rows and columns A row has a specific height A row can have a label A column has a specific width A column can have a label """ def __init__(self,master,**args): Tkinter.Canvas.__init__(self,master,**args) self.colpadding=2 self.rowpadding=2 self.columns=[] # each item contains data about the column self.rows=[] # each item contains data about the row self.cells={} # index: (row,col) def insertrow(self,pos,values): self.rows[pos:pos]=[Row(self,'',pos)] row=self.rows[pos] for i in range(len(values)): if i -- Privat ========================== Kim Petersen ==================== Arbejde Email kim at vindinggaard.dk ===== Jens Gr?ns Vej 11 ===== Email kim at lignus.dk Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51 Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62 From bkelley at wi.mit.edu Fri Jan 16 11:44:57 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 16 Jan 2004 11:44:57 -0500 Subject: Why gmp is not in the standard library? In-Reply-To: References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: <400814a7$0$562$b45e6eb0@senator-bedfellow.mit.edu> Tim Churches wrote: > Of course, someone would need to prepare Python-style docs, and someone > would need to track GMP development and update the version included with > Python at each release (the current gmpy developers perhaps) - thus I > suspect it is more a resourcing issue than anything else. However, if > some dead wood is ever removed from the Python standard library, I would > love to see gmpy take its place. Thanks to the gmpy (and GMP) developer, > BTW. Isn't some of this work done? http://www.lemburg.com/files/python/mxNumber.html Brian From vc_smtp at sikikusa.nims.go.jp Mon Jan 19 01:17:14 2004 From: vc_smtp at sikikusa.nims.go.jp (vc_smtp at sikikusa.nims.go.jp) Date: Mon, 19 Jan 2004 15:17:14 +0900 Subject: Virus Alert Message-ID: <200401190617.i0J6HErX024118@sikikusa.nims.go.jp> Have detected a virus (WORM_BAGLE.A) in your mail traffic on 01/19/2004 15:06:36 with an action quarantined. From noemail at noemail4u.com Tue Jan 27 09:36:27 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Tue, 27 Jan 2004 14:36:27 GMT Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <74cb04cf32d1541b34af7a7e53baaee9@news.teranews.com> On Sat, 24 Jan 2004 04:23:40 GMT, "Moosebumps" wrote: >> Can you give an example of what you mean, in Perl as well as what you >hoped >> would work in Python? I couldn't quite understand what it is that you're >trying >> to do. > >OK, actually on second test, the problem is mostly with IDLE, but not >totally. When I hit F5 under IDLE, it behaves differently with respect to >the command window then if I just run it by double-clicking on the file. > >Here is an example: > >BatchTest.bat: > >set MYVAR=3 >dir >pause >dir >echo %MYVAR% >pause > >BatchTest.py: > ># the intention is to do the same thing as BatchTest.bat, but it doesn't >work under either IDLE or by double-clicking ># in particular the environment variable is not saved, and it doesn't work >if I replace os.system with os.popen > >import os > >os.system("set MYVAR=3") >os.system("dir") >os.system("pause") >os.system("dir") >os.system("echo %MYVAR%") >os.system("pause") > >BatchTest.pl: > ># this actually does the same thing as Python, I was mistaken. I was >mislead by the IDLE behavior. > >system('set MYVAR=3'); >system('dir'); >system('pause'); >system('dir'); >system('echo %MYVAR%'); >system('pause'); > >The general idea is that it would be nice if there weren't any differences >between the batch file and python. From a practical standpoint, it would >encourage a lot of people to switch from nasty batch files to Python scripts >if you could just surround the entire thing with os.batch(' ') or some >similar sort of mechanical textual substitution. Then you could clean it up >gradually. > >I am aware of os.environ and such, and that is useful, but it's not really >the point. > >Of course I could write a function to take a bunch of strings, write a batch >file, save the working directory, execute it, restore the current directory, >then delete the batch file, but that seems like an awful hack. Though I >probably will do that at some point. > >> > What's the deal with that? I thought Python started out as a scripting >> > language. And that seems like the most basic thing that a scripting >> > language should do. >> >> Dunno, although MS-DOS shell scripting is certainly a small subset of >scripting >> in general. Maybe with a concrete example somebody will be able to give >you a >> hand. > >It is a small subset, but an important subset. Shell scripting started >probably when people got sick of typing the same commands into the prompt. >For a language to really support shell scripting, it should provide a way of >automating the process of typing in the commands. As in, there should be no >difference whether you're actually typing, or you're running the script. > >If there is a way and I don't know about it, I would be happy to hear about >it. But I do think it is a pretty big hole. > >MB > If you're looking for more shell-like behavior, look into IPython at http://ipython.scipy.org/. Although it still won't "export" your environment variables, or make your calls to os.system have a unique environment, you can do things like 'ls' (you can probably configure dir to work, but by default it provides access to the python builtin function of that name). Here is an excerpt that does some of the things in Mooosebump's sample: In [15]: import os In [16]: os.environ['MYVAR'] = '3' In [17]: os.system('echo %MYVAR%') 3 Out[17]: 0 In [18]: cd \ C:\ In [19]: ls /w/ad P* Volume in drive C has no label. Volume Serial Number is A096-107C Directory of C:\ [Program Files] [Python23] 0 File(s) 0 bytes 2 Dir(s) 871,232 bytes free Notice the unescaped backslash in line 18, and the "DOS" command line options "/w/ad" and "P*" wildcard on line 19. This still might not be what you're after, but it's a step in the right direction. --dang From missive at frontiernet.net Mon Jan 19 10:52:32 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 19 Jan 2004 15:52:32 GMT Subject: Python 2.3.3 on FreeBSD 4.8 References: Message-ID: On 2004-01-19, Taylor Leese wrote: > I am trying to compile Python 2.3.3 on FreeBSD 4.8 and > I am getting this compiling error. Anybody have any > ideas? > Are you building from ports? ie.. cd /usr/ports/lang/python make ? From michele.simionato at poste.it Mon Jan 19 11:52:10 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Jan 2004 08:52:10 -0800 Subject: YA string interpolation and printing idea References: <7x3caf5mga.fsf_-_@ruckus.brouhaha.com> <4008B9CE.CC140EF@alcyone.com> <7xwu7r6utj.fsf@ruckus.brouhaha.com> Message-ID: <95aa1afa.0401190852.18a939f5@posting.google.com> Christos "TZOTZIOY" Georgiou wrote in message news:... > On 16 Jan 2004 20:52:08 -0800, rumours say that Paul Rubin > might have written: > > >Maybe if type/object > >unification proceeds far enough, we'll someday be able to define our > >own operations on builtin objects like strings. > > I'd like that too, and I believe Ruby does it; however, ISTR that Guido > has specifically said that this won't be allowed, since you can always > subclass the base types. He's the boss :) > > I've also seen a hackish patch (by MWH? can't be sure) that allowed one > to substitute their own classes for the base types (so that integer or > string constants would be instances of the derived subclasses). Don't > know if that would help you in your code. In Python, you cannot change built-in types, but you can always derive a new type with additional methods and give to the new type the name of a built-in type. So, we don't miss much of Ruby functionality, we just miss is a bit of sugar. Also, knowing that the builtins types are fixed, gives me some sense of safety ... Micjele From ian at ibygrave.no-ip.org Fri Jan 9 16:03:54 2004 From: ian at ibygrave.no-ip.org (ian) Date: Fri, 09 Jan 2004 21:03:54 +0000 Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: On Fri, 09 Jan 2004 20:56:26 +0000, JCM wrote: > Assignment rebinds variables to different objects, so b now holds a > reference to the list created by the expression []. As assignment binds but doesn't copy, you might ask http://www.python.org/doc/faq/programming.html#how-do-i-copy-an-object-in-python --IAN From peter at engcorp.com Mon Jan 19 13:46:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 13:46:23 -0500 Subject: Delayed evaluation and setdefault() References: Message-ID: <400C25FF.A76B1FEA@engcorp.com> Leo Breebaart wrote: > > >>> d.setdefault('foo', b()) > then b() *does* get executed regardless of whether or not the > value it returns is actually used ('foo' was not found) or not > ('foo' was found). > > So I guess my question is twofold: one, do people think > differently, and if so why?; and two: is there any elegant (or > other) way in which I can achieve the delayed evaluation I desire > for setdefault, given a side-effect-having b()? def lazysetdefault(dict, key, ref): if not dict.has_key(key): dict[key] = ref() return dict[key] >>> d = {} >>> lazysetdefault(d, 'foo', b) -Peter From k.robert at gmx.de Wed Jan 21 07:25:21 2004 From: k.robert at gmx.de (Robert) Date: 21 Jan 2004 04:25:21 -0800 Subject: interface to win job scheduler portable from win98 .. winXP / cmdline or COM ? References: Message-ID: <19804fd8.0401210425.7130ea85@posting.google.com> this COM interface seems to be right for my problem. but I don't get a handle on it. I am only familiar with things like o=win32com.client.Dispatch("Excel.Application") and navigate. Is it possible this way? I didn't find anywhere a hint for such exported Class Name. I only found a "CLSID" and know little about that. I tried the following. But he says "interface not supported" but seems that he finds anything ... ? >>> from win32com.client import Dispatch >>> Dispatch("{148BD520-A2AB-11CE-B11F-00AA00530503}") Traceback (most recent call last): File "", line 1, in ? File "C:\PYTHON23\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\PYTHON23\lib\site-packages\win32com\client\dynamic.py", line 85, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\PYTHON23\lib\site-packages\win32com\client\dynamic.py", line 73, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147467262, 'Schnittstelle nicht unterst\xfctzt', None, None) Robert Thomas Heller wrote in message news:... > Tim Golden writes: > > >>From: Robert [mailto:k.robert at gmx.de] > >> > >>I found the os.popen("AT /?") way .... however it works not on Win98 > >>and the "Day" you enter at the AT are language dependent. > >>(e.g. Mi(ttwoch) in german, We(dnesday) in english Windows versions) > >> > >>I need a solution work from Win98..WinXP most independent from > >>internationalization etc. > >> > >>is there portable way - or at all a way to manipulate the Win98/ME > >>scheduler ? if no simple means, even COM stuff would be ok. any > >>pointers? > >> > > > > WMI looks like it covers it, but only NT4 / Win2K / XP. > > Oh, sorry, I've just realised: the Win32_ScheduledJob > > actually refers to the AT service (despite the name!) > > > > If you're really looking for something which will work > > across every version of Windows, I think you're better > > off doing something entirely Python from the start. It > > shouldn't be hard (he says, having not tried it himself). > > The advantage is: it will work everywhere and you have > > complete control over it. The disadvantage is: you have > > to create your own interface and deal with whatever > > issues the existing mechanisms have already dealt with. > > I'll second that this is most certainly the easiest solution. > > There seems to be, however, a COM interface to the Task Scheduler, using > all custom interfaces: > > > > As usual, the docs aren't that crystal clear, but I get the impression > that it's even available in win 95, provided that IE4 is installed. > > Thomas From aahz at pythoncraft.com Sat Jan 3 10:26:09 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 Jan 2004 10:26:09 -0500 Subject: Optimized quoting (was Re: Speed?) References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: In article , John Hunter wrote: > >Donald Knuth, God of Computer Science, said "Premature optimization is >the root of all evil". If Knuth is God, then Hoare is God's father: "Premature optimization is the root of all evil in programming." --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." --Knuth restates Hoare -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From serve at detongiser.com Thu Jan 15 14:43:33 2004 From: serve at detongiser.com (Servé Lau) Date: Thu, 15 Jan 2004 20:43:33 +0100 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: <100drb1371jmq67@corp.supernews.com> "Gerry Quinn" wrote in message news:a%uNb.5410$HR.11098 at news.indigo.ie... > As somebody once said, the purpose of paying wages is not to motivate > people to work. It's to motivate them to come in on Monday mornings. > > Think of the boring bits as commercial software's secret weapon ;-) I agree, most open source is not finished or crappy implemented. At some point most people lose interest especially when it's not successful. Yes, there are exceptions. From claird at lairds.com Mon Jan 12 16:33:44 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 12 Jan 2004 21:33:44 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> Message-ID: <10064loqc7sd7e3@corp.supernews.com> In article <7xisjh1e3i.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >I'd say don't bother with C++ unless you're working on a big >multi-person project. Its design will make no sense to you unless >you've faced the problems that come up in those projects. Otherwise >it's a big mess. . . . And if you *are* working on a big multi-person project, and you choose C++, you're likely to end up with ... a big mess. I get to say so. I'm fond of C++, and have seen plenty of pro- jects which rely on it. I've also seen the teams assigned to such projects ... -- Cameron Laird Business: http://www.Phaseit.net From jzgoda at gazeta.usun.pl Wed Jan 21 14:28:53 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 21 Jan 2004 19:28:53 +0000 (UTC) Subject: python As400 References: Message-ID: Enrique pisze: > i checked before this website, http://www.iseriespython.com/, but found no > much information in it (docs) Sorry, I meant "check this site to read documentation for AS/400-specific modules". > worse? how much worse? more worse that can be assumed? I don't know, I never tried to measure it. > and connect python on windows with db2 in as400?? No chance except ODBC (http://www.egenix.com/) or ADO (i.e. adodbapi on SourceForge), anyway you will need Client Access installed. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From jar at netscape.com Mon Jan 19 00:04:13 2004 From: jar at netscape.com (jar at netscape.com) Date: Mon, 19 Jan 2004 14:04:13 +0900 Subject: Hi Message-ID: ------------------ Virus Warning Message (on the network) Found virus WORM_BAGLE.A in file ihm.exe The uncleanable file ihm.exe is moved to /etc/iscan/virus/virSKALqaGMn. --------------------------------------------------------- -------------- next part -------------- Test =) ljbeubmajcklyxfk -- Test, yep. -------------- next part -------------- ------------------ Virus Warning Message (on the network) ihm.exe is removed from here because it contains a virus. --------------------------------------------------------- From spamfilter at macspeno.com Thu Jan 8 09:43:50 2004 From: spamfilter at macspeno.com (John P. Speno) Date: Thu, 8 Jan 2004 14:43:50 +0000 (UTC) Subject: pyserial with Mac and USB converter, possible? References: <88cd63b8.0401071041.2c4d0f9@posting.google.com> Message-ID: In <88cd63b8.0401071041.2c4d0f9 at posting.google.com> jorjun at mac.com (jorjun) writes: >I am getting into RS232 scripting, but would prefer to use my iBook, is this viable? It's hard to say without knowing what you want to do, but most likely it is viable assuming you have a USB to serial adaptor that exposes itself in /dev. :-) You may also want to check in with the Mac Python group: http://www.python.org/sigs/pythonmac-sig/ http://homepages.cwi.nl/~jack/macpython/ Take care. From python at hitmedia.com Fri Jan 30 00:52:51 2004 From: python at hitmedia.com (Python Baby) Date: Thu, 29 Jan 2004 21:52:51 -0800 Subject: easiest transition for a PHP website to move to Python? Message-ID: <20040130055251.GA9734@mail.hitmedia.com> I've got a database-driven website that's written entirely in PHP. It's all pretty MVC : NOT embedded little calls inside HTML, but rather little controller apps in the webroot that merge data with HTML templates on the fly. But for various reasons (mostly fun) I want to rewrite it in Python. There are so many different approaches, though! Zope, Twisted, mod_python, clearsilver, and all the goodies in standard library. What would be the SMOOTHEST TRANSITION for a newbie like me to rewrite my PHP+MySQL website to Python? (The URL is http://www.musicthoughts.com) From Johannes.Nix at web.de Fri Jan 2 12:27:54 2004 From: Johannes.Nix at web.de (Johannes.Nix at web.de) Date: 02 Jan 2004 18:27:54 +0100 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: <67smiy6z1h.fsf@aster.homelinux.net> "Carl Caulkett" writes: > When you have forgotton the 19 theses, but yet carry them out in every > waking moment, then you will have discovered the 20th thesis. > Will this be before or after the forgotten theses are garbage-collected ? "Thirty spokes surround a hub: Where nothing is, lies the usefulness of the wheel" Tao Te King Johannes From dk123456789 at REMOVEhotmail.com Thu Jan 29 19:47:25 2004 From: dk123456789 at REMOVEhotmail.com (Dave K) Date: Fri, 30 Jan 2004 01:47:25 +0100 Subject: conditional expression sought References: Message-ID: <866j101bbuuhtpan29eop9o4mk1mt7nckn@4ax.com> On Thu, 29 Jan 2004 17:58:45 GMT in comp.lang.python, "Elaine Jackson" wrote: >If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, >then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without >evaluating any other B_i. This is such a useful mode of expression that I would >like to be able to use something similar even when there is an i with >bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) >or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious >reasons. Does anybody know a good way to express this? Any help will be mucho >appreciado. > >Peace > I'm not sure if this is what you're looking for, but for i > a very small number, the zip function seems more appropriate: >>> def get_B_i(A, B): for a, b in zip(A, B): if a: return b return A[-1] >>> print get_B_i([False, False, True, False], [0, 1, 2, 3]) 2 >>> print get_B_i([False, False, False, False], [0, 1, 2, 3]) False This has exactly the same effect provided that A and B are the same length, otherwise the return value by failure should be adjusted to whatever suits your purpose. If you really want to write a conditional expression out in full, I can't think of anything non-clumsy that would work for all possible values of B_i, so unfortunately can't help you there. Dave From eltronic at juno.com Sat Jan 3 18:53:54 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Sat, 3 Jan 2004 18:53:54 -0500 Subject: importing Message-ID: <20040103.191552.-3883603.1.eltronic@juno.com> On 3 Jan 2004 12:49:56 -0800 boomer4467 at yahoo.com (Boomer) writes: > trying to import a .csv file(from excel) > into some fields on my company's > software system(which interfaces to > an sql database. Each row in this > .csv file needs to be split into smaller strings import csv #something to the efect of data = file("book1.csv").readlines() p = csv.parser() for ir in data: fields = p.parse(ir) if not fields: # multi-line record continue print fields #you can take it further from here... older than python 2.3 you have to download seperatly the csv module pre compiled version are available. http://www.object-craft.com.au/projects/csv just had the opertunity to use it for the first time yesterday, worked great! e please forward all spam to "me" ________________________________________________________________ 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 jepler at unpythonic.net Tue Jan 6 11:00:36 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 6 Jan 2004 10:00:36 -0600 Subject: Problems with threads and embedding In-Reply-To: <3FFAC395.9080900@poelzi.org> References: <3FFAC395.9080900@poelzi.org> Message-ID: <20040106160036.GJ18443@unpythonic.net> On my system, the attached script shows an expected behavior: at first there are many threads running "daniel.py", then they slowly dwindle back down to one. Using slightly different flags to ps (it doesn't know the "m" flag), I get identical results on redhat 6 (python 1.5.2) and redhat 9 (python 2.2). :r daniel.py import thread, Queue, os l = [] q = Queue.Queue(10) def enqueue(): os.system("ps mT") q.put(thread.get_ident()) for i in range(10): thread.start_new(enqueue, ()) for i in range(10): print q.get() os.system("ps mT") This suggests that the problem may be architecture-specific, thread-library specific, or it may be due to some difference between the normal python executable and the executable with embedded Python. Jeff From g.marshall at nospam.com Fri Jan 9 10:49:26 2004 From: g.marshall at nospam.com (George Marshall) Date: Fri, 09 Jan 2004 15:49:26 GMT Subject: Program return value ? Message-ID: Hi all, I'm trying to get the exit code of a program I want to exec in a python script in a portable manner. I've read that both os.system and os.spawnl are not a portable solution. I tried the os.popen() function and I got the program's exit code with the close() method. p=os.popen("return_a_exit_code.sh") retval=p.close() The only problem is that it doesn't return negative values. What is your experience with that ? Thanks in advance. From kahanpaa at gstar.astro.helsinki.fi Mon Jan 12 15:42:17 2004 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 12 Jan 2004 20:42:17 GMT Subject: Python installation breaks Outlook Express References: Message-ID: Hi. M. Laymon wrote: > Your server has unexpectedly terminated the connection. Possible > causes for > this include server problems, network problems, or a long period of > inactivity. > Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net', > Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F Python is not the source of your problem. The Verizon servers had some problems (they should now be OK, i think): due to an obscure misconfiguration they managed to make flood their own servers with requests - an auto-DOS of sorts. Jere -- Lord, make my words as sweet as honey, for one day I may have to eat them - Daryl Benson From gerrit at nl.linux.org Fri Jan 23 11:50:24 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 23 Jan 2004 17:50:24 +0100 Subject: C compilers In-Reply-To: References: Message-ID: <20040123165024.GA4137@nl.linux.org> Lucas Raab wrote: > I realize that this is a Python newsgroup, but do any of you know any good > C/C++ compilers?? yes From aahz at pythoncraft.com Wed Jan 21 19:34:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jan 2004 19:34:41 -0500 Subject: Do (USA) Python conferences require a coast? References: <6b50e1-goo.ln1@jowls.lairds.org> Message-ID: In article <6b50e1-goo.ln1 at jowls.lairds.org>, Kyler Laird wrote: > >It looks like PyCon > http://pycon.org/ >is always in Washington, DC. I try to avoid DC. It's kind of hard to say "always" about a conference that hasn't had its second iteration yet. ;-) >Python10 > http://www.python10.org/ >is also essentially in DC (Alexandria, VA). "Is"? That was two years ago. The "formal" Python conference is now associated with OSCON, which does tend to be on the west coast. There's absolutely no reason why someone couldn't organize a PyCon somewhere other than D.C. -- that's specifically why it's called "DC 2004" and why we called the last one "DC 2003". However, it's not clear how much of a market there is for additional PyCons; given that the change to PyCon/OSCON is only a year old, and given that the economy hasn't fully recovered, you might want to plan your event for sometime in 2005. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From bart_nessux at hotmail.com Sat Jan 24 16:25:01 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Sat, 24 Jan 2004 16:25:01 -0500 Subject: time.time() In-Reply-To: <7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com> References: <7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com> Message-ID: Terry Carroll wrote: > It sounds like you're thinking time.time() does something else, which > you're trying to do. What is that? There might be another function for > you. I should have been more clear... here's the code: x = time.time() fp = os.popen("some_process", "r") fp.read() fp.close() print (time.time()-x/60)/60 If fp runs for many hours (in my case it does), I want time.time() to return the time it runs in seconds which I would then divide by 60 to get the total amount of minutes which I would then divide by 60 to get the total amount of hours that the process has ran... does that make sense? I don't need to be super precise, just within 1 minute or so of the actual amount of time that the process required to run. From gagenellina at softlab.com.ar Mon Jan 5 18:31:43 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Mon, 05 Jan 2004 20:31:43 -0300 Subject: datetime string to datetime object converter In-Reply-To: Message-ID: <5.2.1.1.0.20040105202350.01e69770@192.168.0.115> At 3/1/2004 23:38, you wrote: >Is there an existing module or script that can convert a datetime string >of unknown format to a python datetime object ? If the format is really unknown the data is ambiguous. 04/03/02 might be April 3rd 2002, March 4th 2002 or even March 2nd 2004; 12-11-2004 might represent two different dates. Gabriel Genellina Softlab SRL From cpl.19.ghum at spamgourmet.com Mon Jan 26 10:26:56 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 26 Jan 2004 16:26:56 +0100 Subject: Py2exe and WMI module References: <697d8a6c.0401260516.40e51096@posting.google.com> Message-ID: Hello Olav, > I have run makepy manually on one all of the above libraries. > Microsoft WMI Scripting Library > WMI ADSI Extension Type Library > WMICntl Type Library > > Traceback (most recent call last): > File "test-fail.py", line 1, in ? > import wmi > File "wmi.pyc", line 132, in ? > File "win32com\client\gencache.pyc", line 527, in EnsureDispatch > File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass > KeyError: '{D2F68443-85DC-427E-91D8-366554CC754C}' Look at: http://starship.python.net/crew/theller/moin.cgi/Py2Exe With py2exe 0.5.0 there is an example with WMI (I think it's the "advanced" one) Also there are some troubles with the name of the zip-file and win32all. Furthermore 0.5.0 got big improvements handlign win32com -Stuff. There is also a "typelib"-directive in 0.5.0, so maybe you can force the inclusion of typelib {D2F68443-85DC-427E-91D8-366554CC754C} HTH Harald From robin at jessikat.fsnet.co.uk Mon Jan 12 19:50:58 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 13 Jan 2004 00:50:58 +0000 Subject: Python is far from a top performer according to benchmarktest... References: Message-ID: In article , Tim Peters writes ....... >That's the magic of Fortran: the F77 standard says (in part): > > If a subprogram reference causes a dummy argument in the > referenced subprogram to become associated with another > dummy argument in the referenced subprogram, neither > dummy argument may become defined during execution of > that subprogram. > >It bascially says you can alias all you want, so long as you only read the >aliased entities and don't modify them. If effect, if you do anything with >aliases that would inhibit optimizations that assume there isn't any >aliasing, then it's your *program* that's not legitimate Fortran. The >Fortran standard has lots of text "like that", imposing (often unenforcable) >restrictions on conforming programs for the benefit of optimizing compilers. >That was the right choice for Fortran's audience. > this was also my understanding, the difficulty is that humans can't do the correct analysis in their heads for all, but the most simple programs. I seem to remember that almost all the compilers I used had mechanisms for turning off the most aggressive optimisations so if the card deck suddenly started working with them off then you could try and figure out what was wrong. Another nastiness was that by putting prints in you often disrupted the optimisations and the values you got printed seemed to indicate everything was fine. -Common blocks are an invention of the Devil-ly yrs- Robin Becker From mcfletch at rogers.com Thu Jan 29 05:18:21 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 29 Jan 2004 05:18:21 -0500 Subject: C API: how to tell if x is a new style instance? In-Reply-To: <20040129095050.GA27902@foof.i3.cz> References: <20040128184040.GD11485@foof.i3.cz> <401821E2.1070106@rogers.com> <20040129095050.GA27902@foof.i3.cz> Message-ID: <4018DDED.2010506@rogers.com> Michal Vitecek wrote: >Mike C. Fletcher wrote: > > >>Well, I don't actually know how to check for the spiritual state of a >>new-style class, but here's how to tell if an instance is an instance of >>a new-style class: >> >> * Note that a new-style class is a sub-class of type, while >> old-style classes are not >> >> Ignore this, it's wrong. Should have read: Note that a new-style class is an *instance* of a sub-class of type, while old-style classes are not. >> * Check if isinstance( instance.__class__, type ) >> >> If the above had been true this would have read issubclass( ... ), trust the code more than the descriptions :) . >> * >> >> > > ahh - it helped. thank you! > > but, so it means that PyType_Check() doesn't work for new style > classes' instances? it returns 0 but i understood from the > documentation that it should return 1: > > Nope, I'm just an idiot :) . The code was saying what I intended, but not the text. The docs you're reading are saying "if it's an instance of the meta-class type, or a sub-class of the meta-class type"... to illustrate: >>> class r( type ): ... pass ... >>> class s: ... __metaclass__ = r ... >>> s >>> s.__class__ >>> isinstance( s, type ) 1 >>> isinstance( s(), type ) 0 You wouldn't want instances of s claiming to be types. But instances of r, (which is a sub-class of type), should claim to be types (s is an instance of r). Hope that resolves any confusion, Mike > """ > int PyType_Check(PyObject *o) > Returns true if the object o is a type object, including instances > of types derived from the standard type object. Returns false in > all other cases. > """ > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From oren-py-l at hishome.net Fri Jan 16 15:40:51 2004 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 16 Jan 2004 15:40:51 -0500 Subject: I come not to bury C++, but to praise it... In-Reply-To: <20040114153516.GA16224@intarweb.us> References: <20040114153516.GA16224@intarweb.us> Message-ID: <20040116204051.GB36773@hishome.net> On Wed, Jan 14, 2004 at 10:35:16AM -0500, Jp Calderone wrote: > On Wed, Jan 14, 2004 at 09:42:52AM -0500, Derek wrote: > > [snip] > > > > I also use C++ and Python as my main languages and I agree with your > > comments. However, I don't agree that Python is inherently "safer" > > than C++. At best I see it as a tie. For example, C++ let's you > > corrupt memory among other "unsafe" things, most of which can be > > avoided by using standard containers, smart pointers, etc. Python > > lets you do "unsafe" things such as passing an object to a function > > when it makes no sense to do so, which can lead to nasty runtime > > surprises. > > > > A traceback is *much* less nasty than memory corruption. A traceback is also much less nasty than deciphering a 1000-character long compiler error message reported in code that uses a heavily templated library. Oren From jjl at pobox.com Mon Jan 19 08:26:51 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Jan 2004 13:26:51 +0000 Subject: secure unpickle? References: Message-ID: <871xpwxe5g.fsf@pobox.com> Gandalf writes: [...] > I'm using this module (based on the documentation you mentioned): [...snip...] What does this have to do with the question? He was worried about security of pickle, not asking how to call dumps() and loads(). John From fisher at energy.uch.net Tue Jan 27 04:56:55 2004 From: fisher at energy.uch.net (Serge A. Ribalchenko) Date: Tue, 27 Jan 2004 11:56:55 +0200 Subject: TELNET instead PING In-Reply-To: References: <5f505344.0401260332.184d4225@posting.google.com> <401571B9.F9DF99D0@engcorp.com> Message-ID: Gandalf wrote: > Note: that reason you talked about is most likely a packet filtering > firewall. A good firewall > can block PING, Telnet, Nbsession and many others. In most cases, the > best policy > is to lock everything by default and permit only the ones you really > want. Firewall > rules can include source addresses too. It is possible that a computer > do not respond > on PING and TELNET ports for you but it does for a similar request from > another > computer. I think there is no universal way to determine if a remote > host is alive or not. If we are talking about IP network segment in the same ethernet layer, can you ignore my ARP request - who-has ? From elainejackson7355 at home.com Sat Jan 10 02:38:31 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 10 Jan 2004 07:38:31 GMT Subject: end of a pickle file Message-ID: How can I tell when I've gotten to the end of a pickle file? TIA Peace From paul at fxtech.com Thu Jan 22 17:52:07 2004 From: paul at fxtech.com (Paul Miller) Date: Thu, 22 Jan 2004 16:52:07 -0600 Subject: Looking for advice: supporting multiple embedded interpreters In-Reply-To: References: Message-ID: <6.0.1.1.2.20040122165118.060feec0@mail.fxtech.com> >I can't address why it doesn't work in 2.3, but just a question - have >you thought of not using independent interpreter states, but just >tracking the contents of sys.modules and clearing out any new modules >at reload time? That would force even nested imports to be reloaded. Hmm - although not as "clean" as having multiple interpreters (since globals would still be visible between modules), it WOULD get around the more pervasive problem, which was the reloading. I'll take a look at this. THANKS! From james at logicalprogression.net Thu Jan 15 05:46:32 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 15 Jan 2004 10:46:32 +0000 Subject: is it possible to create a win binary file from .py files ? In-Reply-To: <200401151125.04886.sancelot@free.fr> References: <200401151125.04886.sancelot@free.fr> Message-ID: <200401151046.32630.james@logicalprogression.net> On Thursday 15 January 2004 10:25 am, stephane ancelot wrote: > Hi, > I am new to python and I would like to know if there are some ways to > provide a binary file as target . Because my projects may contain lot of py > files and I do not want to provide source files . for maintenance puproses > it is too easier for me to send only one file to my customer. > > Best Regards > Steph Try the freeze tool that comes in the Python distribution. I can't say where you will find it exactly because that depends on you platform but there should be a directory somewhere called Tools. An alternative that does not reduce the number of files but does hide the source is to distribute .pyc files. These are created when you import a module, or you can use the compileall module. Note that this is not a real security measure since such files can be disassembled. James From jcarlson at uci.edu Tue Jan 20 02:23:12 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 19 Jan 2004 23:23:12 -0800 Subject: speedy Python strings? References: <20040119185543.ABC7.JCARLSON@uci.edu> <400cc8c4$0$26115$afc38c87@news.optusnet.com.au> Message-ID: <20040119231427.D6BC.JCARLSON@uci.edu> > Note that there's been some very interesting discussions on python-dev > recently that may end up alleviating this issue somewhat in the future - but > no promises - there doesn't appear to be a consensus on the "right way" ... I've been following it. My favorite solution is to not change the structure of the list at all, and to offer a reasonably fast fifo queue in a standard library module with a bunch of other useful data structures. Then you don't need to worry about breaking C modules that rely on the list having that behavior, and get some useful data structures out of the deal. - Josiah From mgoogle at deferran.com Wed Jan 28 04:21:49 2004 From: mgoogle at deferran.com (Manuel de Ferran) Date: 28 Jan 2004 01:21:49 -0800 Subject: pexpect exceptions References: Message-ID: Michael Surette wrote in message news:... > I have been trying to automate the changing of passwords using python and > pexpect. I wrote a script as a test and it works, except that it gives me > an exception when it stops running: > > Exception exceptions.OSError: > (10, 'No child processes') in > ignored > > What is happening and how do I get rid of the exception? > > I am running python 2.3.2 under Slackware linux 9.1 and pexpect 0.99. > Here is the script: > > #!/usr/bin/python > import pexpect > import sys > > if len(sys.argv) != 3: > print 'usage error!' > raise SystemExit > > name= sys.argv[1] > passwd= sys.argv[2] > > a= pexpect.spawn('passwd %s'%name) > > changed= False > while not changed: > i= a.expect(['[Nn]ew password:','[Cc]hanged']) > if i == 0: > a.sendline(passwd) > elif i == 1: > changed= True I have the same issue with the following code : #!/usr/bin/env python '''This runs "ls -l" on a remote host using SSH. At the prompts enter hostname, user, and password. ''' import pexpect import getpass host = raw_input('Hostname: ') user = raw_input('User: ') password = getpass.getpass('Password: ') child = pexpect.spawn("ssh -l %s %s /bin/ls -l"%(user, host)) child.expect('password:') child.sendline(password) child.expect(pexpect.EOF) print child.pid,'middle',child.isalive() print child.before This is a slighty modified version of sshls.py (shipped with pexpect-examples). I've only added "print child.pid,'middle',child.isalive()" and I get the same exception : "exceptions.OSError: (10, 'No child processes')" The weird thing I can't explain is that, I don't get the exception without ",child.alive()" From skip at pobox.com Wed Jan 28 10:11:03 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 09:11:03 -0600 Subject: type() for new style classes - buggy? In-Reply-To: <20040128130204.GA10744@foof.i3.cz> References: <20040128130204.GA10744@foof.i3.cz> Message-ID: <16407.53511.625104.948357@montanaro.dyndns.org> Michal> does the type() command work correctly for new style classes? Yes. Using 2.2: >>> class A(object): pass ... >>> type(A) >>> type(A()) >>> isinstance(A(), A) 1 Using 2.3 or newer: >>> class A(object): ... pass ... >>> type(A) >>> type(A()) >>> isinstance(A(), A) True In general, you shouldn't be using the types module, certainly not for new-style classes. Skip From no at spam.invalid Fri Jan 16 18:32:57 2004 From: no at spam.invalid (Russell E. Owen) Date: Fri, 16 Jan 2004 15:32:57 -0800 Subject: [Ann] RO utility package 2004-01-16 Message-ID: I've put up a new version of my RO utility package at . Highlights include: Tkinter stuff, including: - Nicely wrapped tcp/ip sockets that make connections without blocking the main loop, queue written data as required, return read data via callbacks and also report status changes via callbacks. - An ftp get widget (like a browser transfer window) that handles file transfer and status display. Connection and transfer occurs in a background thread and so cannot block the main loop. - Widgets that support help and input verification - A scrollable frame. - A set of Toplevels that can remember and restore location and size and whether each was visible. - An implementation of preferences, including scalars, colors, fonts, files, directories and sound files. This includes a prefs editor and saving and restoring. Astronomy coordinate system conversions. (Many of these are SLALIB routines that I converted to Python. Commercial use requires a license from Pat Wallace, the author of SLALIB). Basic utilities for sequences, strings and data conversion. Dict subclasses that remember the order in which items were added or store values by appending to a list. A key-value parsing and dispatching system which could be useful for a networked GUI (that's what I use it for). A telescope user interface I am writing relies on them, so they are being maintained. I hope somebody finds them useful. -- Russell From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Jan 30 17:19:51 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 30 Jan 2004 23:19:51 +0100 Subject: python in dreamweaver References: Message-ID: Hi ! I prepare "template" pages with DM ; in "strategic" position (where i think put infos later), i put a key-word ; then i save the page. My web-server (in Python) read the HTML-Page, do multiple search/replace (key-words by data), then send the page. * sorry for my bad english * Michel Claveau From fumanchu at amor.org Tue Jan 6 17:51:44 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 6 Jan 2004 14:51:44 -0800 Subject: help needed with class and method confusion Message-ID: EricN wrote: > Here's one way to do it (undoubtedly there are other ways as well). > Sorry, I couldn't loop the moons. Probably a programmer more clever > than I could write a factory pattern for it. > > class Moon: > def __init__(self, name, diameter = 0.0, planet = "unknown"): > self.NAME = name > self.DIAMETER = diameter > self.HOMEPLANET = planet > > def setMoonName(self, name): > self.NAME = str(name) > > def getMoonName(self): > return self.NAME > > def setMoonDiameter(self, diam): > self.DIAMETER = float(diam) > > def getMoonDiameter(self): > return self.DIAMETER > > def setMoonHomePlanet(self, planet): > self.HOMEPLANET = str(planet) > > def getMoonHomePlanet(self): > return self.HOMEPLANET > > > if __name__ == "__main__": > moons = [] > Io = Moon("Io", 1.0, "Jupiter") > moons.append(Io) > Europa = Moon("Europa", 2.0, "Jupiter") > moons.append(Europa) > Ganymeade = Moon("Ganymeade", 3.0, "Jupiter") > moons.append(Ganymeade) > Titan = Moon("Titan", 3.0, "Saturn") > moons.append(Titan) > > for x in range(len(moons)): > print moons[x].getMoonName() > print moons[x].getMoonDiameter() > print moons[x].getMoonHomePlanet() > print Wow. Someone's spent too much time writing Java. You can achieve the same thing with far less cruft: class Moon: def __init__(self, name, diameter = 0.0, planet = "unknown"): self.name = name self.diameter = diameter self.homeplanet = planet if __name__ == "__main__": moons = [Moon("Io", 1.0, "Jupiter"), Moon("Europa", 2.0, "Jupiter"), Moon("Ganymeade", 3.0, "Jupiter"), Moon("Titan", 3.0, "Saturn"), ] for moon in moons: print moon.name print moon.diameter print moon.homeplanet The biggest two changes stemming from the questions: 1) Why bother with all the setX/getX junk? and 2) Why bother with variable names for each moon? Treat them anonymously. FuManChu From lord_turc at yahoo.com Fri Jan 30 13:27:45 2004 From: lord_turc at yahoo.com (M.Dikmen) Date: Fri, 30 Jan 2004 18:27:45 -0000 Subject: Tcp/ip programs in python Message-ID: Do you now a source about socket programming in python? or some source codes, demo programs? i really need them From no.spam Sun Jan 18 13:21:18 2004 From: no.spam (Christophe Delord) Date: Sun, 18 Jan 2004 19:21:18 +0100 Subject: re question - finiding matching () References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: <20040118192118.61fea23f.no.spam@box> On 18 Jan 2004 07:51:38 -0800, Miki Tebeka wrote: > Hello All, > > To all of you regexp gurus out there... > > I'd like to find all of the sub strings in the form "add(.*)" > The catch is that I might have () in the string (e.g. "add((2 * 2), > 100)"), > > Currently I can only get the "addr((2 *2)" using > re.compile("\w+\([^\)]*\)"). To solve the problem a hand crafted > search is used :-( > > Is there a better way? > > Thanks. > Miki Hello, You may need "recursive patterns" to do this but regular expressions cannot handle this. You can simulate recursive pattern by limiting the recursivity level. For example the expression inside () should be [^\(\)]+ at level 0. At level 1, you can match only zero or one pair: (?:\([^\(\)]+\)|[^\(\)]+)* and so on. You can build such an expression recursively: def make_par_re(level=6): if level < 1: return r'[^\(\)]+' else: return r'(?:\(%s\)|%s)*'%(make_par_re(level-1), make_par_re(0)) par_re = re.compile(r"\w+\(%s\)"%make_par_re()) But in this case you are limited to 6 levels. Now you can try this : for m in par_re.findall("add((2*2), 100) some text sub(a, b*(10-c), f(g(a,b), h(c, d)))"): print m I don't really like this solution because the expressions are ugly (try print make_par_re(6)). Anyway a better solution would be to use a syntactic parser. You can write your own by hand or make your choice here: http://www.python.org/sigs/parser-sig/ Best regards, Christophe. From tjreedy at udel.edu Fri Jan 16 15:46:52 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Jan 2004 15:46:52 -0500 Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> <4006f74a$0$567$b45e6eb0@senator-bedfellow.mit.edu> <87smif64o3.fsf@pobox.com> Message-ID: > > That being said, wasn't there some issue with making the Python > > License GPL compatible for issues like these? > "GPL-compatible" is very different from "GPL", of course. I 'believe' that GPL-compatible means that someone can mix (compile) Python with GPL code and release the mixture -- as a GPL bundle, which the PSF does not want to do with Python itself but which repackagers are free to do. It does not mean that PSF can put GPL code into the core and still release Python with *its* non-GPL license. tjr From syver-en+usenet at online.no Thu Jan 8 10:22:06 2004 From: syver-en+usenet at online.no (Syver Enstad) Date: 08 Jan 2004 16:22:06 +0100 Subject: PRE-PEP: new Path class References: <1073567709.3ffd57dda8cb0@mcherm.com> <3FFD72BD.780554D8@engcorp.com> Message-ID: Peter Hansen writes: > I haven't been following (either discussion) closely, but this > sounds similar to some posts I read about a discussing involved a > .reverse() method, and the apparent conclusion that .reversed() > [note the 'd'] was more appropriate as it didn't imply that the > object was being modified in-place, but that it was returning a > reversed version of itself. Same thing could apply here... Good point, but what about asNormalized() or asReversed()? Or as_reversed() or as_normalized() if that is the coding convention. Doesn't that communicate the intent even better? -- Syver Enstad From michael at foord.net Tue Jan 20 03:31:59 2004 From: michael at foord.net (Fuzzyman) Date: 20 Jan 2004 00:31:59 -0800 Subject: Tk Icon - request to Fredrik Lundh References: <8089854e.0401190436.10f99713@posting.google.com> Message-ID: <8089854e.0401200031.445728d9@posting.google.com> Eric Brunel wrote in message news:... > Fuzzyman wrote: > > There is a very interesting (and potentially useful) program on the > > effbot website - called Tkicon. > > > > http://www.effbot.org/downloads/ > > > > Unfortuantely the last supported version of python is 2.1 > > I've seen a few people asking, but never an answer, on Python 2.3 > > support. > > This utility should not be needed anymore if you're using a recent version of > tcl/tk: the method wm_iconbitmap on toplevel's, that didn't work on earlier > versions of tk on Windows, now works without problem. You should specifiy a .ico > or .icr file name as its argument. See the documentation for the corresponding > tk command at: > http://www.tcl.tk/man/tcl8.3/TkCmd/wm.htm#M15 > Hmmm..... reading the documentation makes things less clear :-) How about : test = tkinter.Toplevel(wm_iconbitmap='test.ico') ???? I'll try that ;-) Anyway - thanks for the help - once I work out the proper Tkinter format then I'm sure it will work......... Fuzzy > HTH From miki.tebeka at zoran.com Sun Jan 4 03:44:39 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 4 Jan 2004 00:44:39 -0800 Subject: Parametrized inheritance References: Message-ID: <4f0a9fdb.0401040044.592a0695@posting.google.com> Hello Dan, > i.e. define Sub as "class Sub(X)", where I can change X at the time of > instantiation. Then I could define MySub as "class MySub(Sub(MyBase))". > (I hope that it's obvious that I'm looking for this effect, not this syntax) >>> class Woof: def say(self): print "woof" >>> class AlsoWoof: pass >>> a = AlsoWoof() >>> a.say() Traceback (most recent call last): File "", line 1, in -toplevel- a.say() AttributeError: AlsoWoof instance has no attribute 'say' >>> AlsoWoof.__bases__ += (Woof,) >>> a = AlsoWoof() >>> a.say() woof >>> > Of course, someone is going to ask "why?" > I need to override a few members in Base. Sub is mostly fine as-is, so if I > could have MySub=Sub(MyMBase), that would be fine. Why don't just override them in the subclass as usuall? >>> class Base: def f(self): print "base" >>> class Sub(Base): def f(self): print "sub" >>> s = Sub() >>> s.f() sub HTH. Miki From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jan 14 17:29:00 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 14 Jan 2004 23:29:00 +0100 Subject: Problems creating mail content using email.MIMEText, non-ASCII encoding Message-ID: <4005c2ab$0$321$e4fe514c@news.xs4all.nl> Hi I'm trying to create e-mail content using the email.MIMEText module. It basically works, until I tried to send mail in non-ascii format. What I did, to test both iso-8859-15 and UTF-8 encodings, was this: ---- from email.MIMEText import MIMEText m=MIMEText(u"body text including an Euro char \u20ac\n", _charset="iso-8859-15") m['From'] = "from at mail.invalid" m['To'] = "to at mail.invalid" m['Subject'] = "iso 8859-15 encoding?" print "FIRST MAIL: [[[%s]]]" % m.as_string() m=MIMEText(u"body text including an Euro char \u20ac\n", _charset="UTF-8") m['From'] = "from at mail.invalid" m['To'] = "to at mail.invalid" m['Subject'] = "UTF-8 encoding?" print "SECOND MAIL: [[[%s]]]" % m.as_string() ---- But that doesn't work. The output is (using Python 2.3.3): ----- [E:\temp]python mail.py FIRST MAIL: [[[Content-Type: text/plain; charset="iso-8859-15" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable From: from at mail.invalid To: to at mail.invalid Subject: iso 8859-15 encoding? body text including an Euro char =20AC ]]] Traceback (most recent call last): File "mail.py", line 12, in ? print "SECOND MAIL: [[[%s]]]" % m.as_string() ......snipped......... File "C:\Python23\lib\email\base64MIME.py", line 148, in encode enc = b2a_base64(s[i:i + max_unencoded]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 33: ordinal not in range(128) ----- The first one in iso-8859-15 format looks okay but is in quoted-printable, and either my mail clients are wrong (unlikely, I've never had this kind of problems with them) or the content is wrong, because what I'm seeing this in Mozilla mail and my webmail client: "body text including an Euro char AC" (a space before 'AC'!) My UTF-8 attempt failed totally as you can see. What am I doing wrong? I'm thinking about ditching email.MIMEText and just create the mail body text myself using regular unicode --> UTF-8 encoding, but then I lose the automatic header creation and some more handy things of email.MimeText... Thanks for help --Irmen de Jong. From tim.one at comcast.net Mon Jan 12 13:19:09 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 12 Jan 2004 13:19:09 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <4002D8CC.4060701@reportlab.com> Message-ID: [Aaron Watters] > re: jeremy's reply... > > I find the Gray and Reuter definition confusing. To my mind > isolation means serializability and if you don't have serializability > (at least as an option) you don't have isolation. Gray and Reuter's "It appears that the system runs one transaction at a time" can be read as implying serializability. Or not. Informal English isn't good for this. > Transactions don't have to be complex to cause serious problems in > read-committed mode: the classic example is a debit of $1000 for > checking account 123 running at the same time as a credit for $4000 > for checking account 123. If both transactions run at the same time > and read the same previous (committed) balance and they both > complete but the first one completes last then the customer is > screwed to the tune of $4000. This one isn't a problem in ZODB. The second transaction that tries to commit will fail, with a ConflictError exception. It's up to the application then to either abort the failed transaction, or retry it. If this is a commonly expected kind of conflict, it's also possible for the object implementing the notion of "checking account" to provide a conflict resolution method. Then instead of raising ConflictError, ZODB will call that method with 3 things: the object state as of the time the transaction began, the object state the transaction is trying to commit, and the object state currently committed. If the method believes it can compute a correct new state from those three, it can return that, and that new state will be committed instead. Or it can give up, letting the ConflictError occur. In this case, a suitable conflict resolution method could compute the delta between the balance as of the time the transaction began, and the balance currently committed, then add that delta to the balance it was trying to commit, and return the result as the balance it "really wants" to commit. > This is only the simplist problem -- for transactions involving > complex data structures the problems can be much more subtle than > that (and more difficult to correct). ZODB's BTrees are probably a good example of that. They resolve some conflicts on their own (for example, two transactions add distinct keys to the same bucket -- then their conflict resolution method returns a bucket with both keys), but punt on others (for example, like before, except the bucket splits -- then changes to the bucket's parent node are also involved, and bucket conflict resolution gives up, letting the ConflictError propagate). I'm not claiming there's no case in which ZODB can yield an "incorrect" database state. For example, it *may* be that when two transactions add distinct new keys to a BTree, one of the transactions did so only because it didn't see the other key in the BTree, and then a final BTree state containing both keys would be incorrect. What the BTree conflict resolution code does is correct for all uses of BTrees made by Zope, though. BTW, there's nothing in ZOBD that *requires* you to run concurrent transactions. If you need them to act always and in all conceivable respects as if one were run at a time, then write your app to do only one at a time. You'll never get a ConflictError then, either. Most people seem much happier getting the benefits of true concurrency and dealing with ConflictErrors. From jcarlson at uci.edu Tue Jan 20 20:30:00 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 17:30:00 -0800 Subject: CD Insert Notification in WinXP References: Message-ID: <20040120172241.0609.JCARLSON@uci.edu> > I'm using Python 2.3 on a Win XP box, and I'm trying to find if there's > a library of some sort that will give you a callback (or something > comparable) when a new disc is inserted into a CD Rom drive. I've done a > little googling and nothing's come up, so I'm not holding my breath. :) > > If not, I'm thinking of implementing a thread to periodically read the > volume serial number using GetVolumeInformation from Mark Hammond's Win > 32 extensions, then doing a compare against the last known value. Does > this sound "sane"? Any recommendations would be useful. Tim, Generally, Windows autoinsert notification can be enabled or disabled for data and audio disks independantly. When autoinsert notification is enabled on data disks, the Windows operating system automatically does what CD:\autorun.inf says. I would imagine that a similar thing occurs on audio cd inserts, except that it automatically calls the program that is associated with .cda files. Certainly there are hooks into the OS that allow one to intercept filesystem read/write calls (it is what virus scanners do), which could be tested to see if the read is from a cdrom drive, but I don't know if Mark Hammond's extensions would be enough, though it is doubtful. I would suggest polling the serial number every 5 seconds or so, making sure to deal with the various exception conditions. - Josiah From hwlgw at hotmail.com Sat Jan 3 05:24:32 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 3 Jan 2004 02:24:32 -0800 Subject: How to control a console based program from Python Message-ID: I never used the popen or popen2 libraries but it is my understanding that they can capture the output of console based programs. Is it also possible to send keystrokes to console base programs? I would like to program a Python program that can play for instance the tty version of nethack 3.4.3 on Windows, simulating a human player: for nethack it would not be possible to know if a human or a computer program is playing it. It is a console based program, it accepts keystrokes and outputs characters on the (Windows) console box. I did see that WConio can read characters from the screen, perhaps I can use that, have to experiment with it some more. But how to send keystrokes? Any help and ideas are much appreciated. And a happy new year of course! From vdebaere at lilly.csoftdotnet.invalid Sun Jan 18 12:04:44 2004 From: vdebaere at lilly.csoftdotnet.invalid (Vincent De Baere) Date: Sun, 18 Jan 2004 18:04:44 +0100 Subject: xml.dom.minidom childnodes Message-ID: <400abcab$0$780$ba620e4c@news.skynet.be> Hi I am playing around a little with python (I've started using python at 1 PM today, so I guess I could be considered a newbie :-)), and have come across a little problem regarding xml.dom.minidom. this code snippet: menudoc = xml.dom.minidom.parse("menu.xml") menurootchildren = menudoc.documentElement.childNodes menunode = menurootchildren[1].cloneNode(1) sys.stdout.write(menunode.toprettyxml(" ")) acts on this file:
  1. test
  2. test2
    1. test3
  1. please don't display this
The thing I got from the manual is that lists (such as menurootchildren) are zerobased. As you can see in the xml file, there is a newline after the (root) documentelement. I guess that's why I need to use menurootchildren[1] instead of menurootchildren[0] to access the first child. I was wondering how I could get the child elements (without the text nodes) instead of the childnodes, thus simply accessing the first child (first occurance of ol) element by using menurootchildren[0]. That's because I would very much like the script to come up with the same result regardless of if there is a newline after the root element or not... TIA Vincent From gerrit at nl.linux.org Thu Jan 8 07:11:34 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 8 Jan 2004 13:11:34 +0100 Subject: PRE-PEP: new Path class In-Reply-To: <3FFC9209.7060703@beyond-thoughts.com> References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <20040108121134.GA2610@nl.linux.org> Christoph Becker-Freyseng wrote: > openwith would be a nice add-on. I see two problems with it: > 1.) it's long. I mean > f(str(path), *args) > is shorter than > path.openwith(f, *args) This is indead a disadvantage. On the other hand, although p.openwith is longer, I do think it is more readable. It occurs often that shorter is not more readable: just think of all those 'obfuscated-oneliners' contests in C and Perl. > path > (f, arg1, arg2, ...) > > (this works by overwriting path.__gt__) I think this is not a good idea. In my opinion, any __gt__ method should always compare, no more, no less. Further, it's very unusal to call something like this. Another possibility is defining __call__: path(f, *args) == f(str(path), *args) which may be unconvinient as well, however. Is it intuitive to let calling mean opening? > 2.) the position of the argument for the path can only be the first one. > (maybe one could misuse even more operators e.g. the __r...__ ones; But > I think this will result in obscure code) Hm, I think almost all file constructors have the path as the first argument. Are there counter-examples? > path.open shouldn't always call the ordinary file-constructor. I mean it > should be changed for special path-classes like FTPPath ... > (Of course for ordinary file-paths the ordinary file-class is the right > one.) Yes... I was planning to define it in a class which is able to 'touch' the filesystem, so an FTPPath could subclass basepath without the need to overload open, or subclass ReadablePath with this need. > Additionaly path-validity is filesystem-dependend. And worse on system > like Linux there can be more than one file system within the same root / > and they all could have different restrictions! > (if I were a viscious guy I could even umount and mount a different fs > making a valid path possibly invalid) I think this makes validating a path essentially impossible to get right. Let's say we can declare path to be invalid, but we can't declare a path to be valid. Is it a good thing to add a method for it then? (I think yes) > So I think the better solution would be to define a > path.isValid() I agree that it's better. We should allow invalid paths after all. > We also need a > path.exists() > method. Sure. > I'm not sure how both should interact ?? Well, if path.exists(), path.isValid(). The question is - should path.isValid() read the filesystem? > Another Point: > Should Path be immutable like string? I have though about this, too. It should certainly not be fully mutable, because if a path changes, it changes. But maybe we could have a .normalise_inplace() which mutates the Path? What consequences would this have for hashability? I like paths to be hashable. so they probably should be immutable. yours, Gerrit. -- 16. If any one receive into his house a runaway male or female slave of the court, or of a freedman, and does not bring it out at the public proclamation of the major domus, the master of the house shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From FBatista at uniFON.com.ar Mon Jan 5 08:01:17 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 5 Jan 2004 10:01:17 -0300 Subject: prePEP "Decimal data type" v0.2 Message-ID: So, it got through! When I posted I received a mail that it was blocked because it's size. I asked to the list administrator and he told me to post it somewhere. So I did: http://www.taniquetil.com.ar/facundo/python/prePEP-Decimal-0.2.html You have the reST version in that directory. By the way, which is the extension for a reST document? (I used .txt). . Facundo -----Mensaje original----- De: Batista, Facundo Enviado el: Lunes 29 de Diciembre de 2003 2:11 PM Para: Python-List (E-mail) CC: Mariano Draghi (E-mail) Asunto: prePEP "Decimal data type" v0.2 Here is the second version of the prePEP for the Decimal data type. Sorry for the delay, but I restructured it to new (thanks list), and changing to a new house and deploying GSM in Argentina are not very time-freeing tasks, :p Anyway, I'll appreciate any suggestion. Thank you! . Facundo ------------------------------------------------------------ PEP: 9999 Title: Decimal data type Version: $Revision: 0.2 $ Last-Modified: $Date: 2003/12/29 13:35:00 $ Author: Facundo Batista Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 17-Oct-2003 Python-Version: 2.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 arjen.dijkstraNoSpam at hccnet.nl Tue Jan 13 04:13:53 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Tue, 13 Jan 2004 10:13:53 +0100 Subject: Oracle to Mysql (dates) Help please References: Message-ID: <4003b6e7$0$142$e4fe514c@dreader4.news.xs4all.nl> Could you please explain that? Cheers, Arjen "Dennis Lee Bieber" schreef in bericht news:t7m8d1-q54.ln1 at beastie.ix.netcom.com... > Dennis Lee Bieber fed this fish to the penguins on Sunday 11 January > 2004 11:02 am: > > > > (you'll need to build a tuple of tuples: ( (tabel1, b1), (tabel2, b2), > > ..., (tabelN, Bn) ) but the rest looks similar) > > > Whoops, slight mistake there -- I hadn't quite noticed that the first > term was the relation itself, and each Bx contained all the values for > one row. > > Someone else has the more correct variation... > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From jdhunter at ace.bsd.uchicago.edu Sat Jan 3 02:27:03 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 03 Jan 2004 01:27:03 -0600 Subject: Speed? In-Reply-To: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> (EP's message of "Fri, 02 Jan 2004 23:01:15 -0800") References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: >>>>> "EP" == EP writes: EP> On questions of the suitability of Python for CGI, embedded EP> apps, etc., execution speed comes to mind. I previously read EP> some comparisons which did not show Python in a good light in EP> this regard: i.e. Python is slow compared to Perl, C++, Java. Donald Knuth, God of Computer Science, said "Premature optimization is the root of all evil". The essence of the quote is that you shouldn't code for performance until the current implementation is hogging a disproportionate chunk of the CPU cycles. In layman's terms: code something that works, and when you hit a performance bottleneck, run a profiler, find the inefficiencies, and refactor looking for a 2-20x performance boost. I write python apps for the hospital I work for, mainly for epilepsy patients. The EEG data files are large, several hundred megabytes each, and in addition we have CT and MRI 3D image data to incorporate. python, with judicious use of Numeric and pygtk, is more than enough to handle the everyday cases. Are you dealing with several hundred megabytes per record or more? If not, my guess is that you can handle your use cases in python with a little careful thought. In a Nut's Hell, write a prototype app. If you are unsatisfied with performance, post here. Otherwise, mark today as the last day you ever coded perl, as I fondly mark that day 5 years ago. JDH From skip at pobox.com Mon Jan 5 09:59:01 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 5 Jan 2004 08:59:01 -0600 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: <1073314318.3ff97a0e68ffe@mcherm.com> References: <1073314318.3ff97a0e68ffe@mcherm.com> Message-ID: <16377.31669.703257.481535@montanaro.dyndns.org> Michael> And I vote +1 on changing the name from "popen5" to something Michael> else. "process" (as suggested in the PEP) isn't too bad, but Michael> I'd certainly be open to another name. If this is to replace Michael> the entire rest of the popenX family for most normal purposes, Michael> a separate, more comprehensible name will help newbies find it. +2. It would be one thing to have a module named "popen". A casual user can easily pop open the docs and see that it stands for "process open". Determining the difference between popen and popenN (for N in range(1,6)) is a bit more challenging. I think it's time to abstract the names (at least) frome their C heritage. Skip From a.neudecker at uni-bonn.de Wed Jan 21 07:41:07 2004 From: a.neudecker at uni-bonn.de (Andreas Neudecker) Date: Wed, 21 Jan 2004 13:41:07 +0100 Subject: Tutorial/Docs on threading with Python? Message-ID: Hi. I would like to learn how to do threading with Python. I have not done threading before can anyone suggest URLs where I could find understandable information on that? (I am using Python for approx. 1 year now, previous programming experiences lie back a long time). Kind regards Andreas From martin at v.loewis.de Sat Jan 24 04:10:19 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 24 Jan 2004 10:10:19 +0100 Subject: Distutils - Program Distribution In-Reply-To: References: Message-ID: Jens Thiede wrote: > Pardon the silly question, but can one use distutils to install > somewhere other than site-packages, or is distutils only ment for this > kind of a job. I'd like to use it to make the distribution of my > programs simpler :) You can achieve nearly anything with distutils by subclassing the commands. The more you deviate from the standard procedures, the more code you have to put into the subclasses. Regards, Martin From rpm at wag.caltech.edu Mon Jan 12 18:58:44 2004 From: rpm at wag.caltech.edu (Rick Muller) Date: 12 Jan 2004 15:58:44 -0800 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <55e9dc4a.0401121558.3d7703c6@posting.google.com> "Bicho Verde" wrote in message news:<40029dad$0$28706$a729d347 at news.telepac.pt>... > And also I don't know exactly why would I learn Python rather than C#, > C++ or Perl. I'd like to take a slightly different perspective on why you should learn Python: it's simply more fun that the other languages. I know lots of programming languages, and many are useful, but python is the only language that I actually look forward to programming in. There is a real elegance to the syntax, and, once you get used to the whole indenting thing, you can use python as a pseudocode or an outlining language. The more you enjoy a language, the more you will use it, and the better you will be at it. From jeremy at alum.mit.edu Tue Jan 27 12:23:28 2004 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: Tue, 27 Jan 2004 12:23:28 -0500 Subject: Call for Participation: PyCon DC 2004 Sprints Message-ID: <1075224208.24805.255.camel@localhost.localdomain> Call for Participation PyCon DC 2004 Sprints March 20-23, 2004 http://www.python.org/cgi-bin/moinmoin/SprintPlan2004 The Python Software Foundation is sponsoring four days of sprints before PyCon -- Saturday through Tuesday. We invite developers to attend the sprints. We will provide space and network connectivity for developers who want to work on open source projects. A sprint is a two or three day focused development session, in which developers pair in a room and focus on building a particular subsystem. A sprint is organized with a coach leading the session. The coach sets the agenda, tracks activities, and keeps the development moving. The developers work in pairs using XP's pair programming approach. We have several sprints already planned, including - Docutils and reStructuredText - Plone - Twisted topics - Zope 2 and Zope 3 - Python core development If you are interested in participating in a sprint, please send mail to the appropriate sprint coach or to me. Developers of all experience levels are welcome. We are also looking for coaches for other sprints topics; if you have an idea, post it in the Wiki or send me an email. The PSF will waive PyCon registration fees for coaches of sprints with at least two attendees. Hope to see you there, Jeremy Hylton PyCon sprint chair From pythonguy at Hotpop.com Thu Jan 29 02:37:15 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 28 Jan 2004 23:37:15 -0800 Subject: wxPython: images from URLs References: <84fc4588.0401280613.771ac07@posting.google.com> Message-ID: <84fc4588.0401282337.79f0e8f8@posting.google.com> This is the straight forward way to do this in wxPython but somehow it always pops up that ugly error window. I remember trying many options to do this purely using wxPython (wxWindows), but I failed. If you use PIL in your program you can conver the wx Image instance to a PIL image of type BMP and then display it by reconverting it back to the wxImage instance. PyWiew has methods to do this. The source code is available somewhere in my Python page at http://members.lycos.co.uk/anandpillai . I no longer maintain that program, but the latest source code should be available there. Regards -Anand Jonathan Daugherty wrote in message news:... > # self._imgstream = urllib2.urlopen(url).read() > # stream=cStringIO.StringIO(self._imgstream) > # > # try: > # img=wxImageFromStream(stream) > # except: > # pass > > I have tried this and it appears to work, but once I have > the image (from wxImageFromStream), I use it as follows: > > try: > bm = wxBitmap(img) > self.bitmap.setBitmap(bm) > except Exception, e: > print e > > And the exception (raised by wxBitmap(img)) is: > > String or Unicode type required > > (The exception is a TypeError exception.) > > Any ideas? No exceptions are raised by the block that > creates the image from the data stream. The image is > a JPG image, and I pass wxBITMAP_TYPE_JPEG to > wxImageFromStream. I have also tried omitting it as > well. From newsgroups at jhrothjr.com Thu Jan 8 08:24:50 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Jan 2004 08:24:50 -0500 Subject: Descriptor puzzlement References: Message-ID: "Michael Hudson" wrote in message news:m34qv6388c.fsf at pc150.maths.bris.ac.uk... > "John Roth" writes: > > [snippety] > > > It doesn't look like the descriptor protocol is getting > > invoked at all. > > > > What's happening here? > > Descriptors need to be attached to classes. Arrrgggh! Of course! John Roth > > Cheers, > mwh > From guettli at thomas-guettler.de Wed Jan 14 06:08:57 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 14 Jan 2004 12:08:57 +0100 Subject: Inserting while itterating References: Message-ID: Am Wed, 14 Jan 2004 09:43:01 +0100 schrieb Thomas Guettler: > Hi, > > Simple excerise: > > You have a sorted list of integers: > l=[1, 2, 4, 7, 8, 12] > > and you should fill all gaps: > > result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > How would you code this? > > Constrain: The original list should be changed, > don't create a copy. No, this is not a homework exerice, I was just interested if you have better solutions. Thank you for your solutions. Mine looks like this: l=[1, 2, 4, 7, 8, 12] i=-1 while 1: i+=1 this=l[i] if i+1==len(l): # End of list break next=l[i+1] assert(this Message-ID: On Mon, 05 Jan 2004 17:39:30 -0800, Tim Roberts wrote: > bmgx wrote: >>1) Make an http connection to the remote script (http://server/script.cgi) >>2) Fill out the html form (1x TEXT and 2x SELECT input fields) >>3) Submit the form >>4) extract the actual returned result. (using regex or something..) > > You don't actually need steps 1 and 2 at all. True. > HTTP transactions are all completely separate. True (ignoring cookies for now). > The results of a form submission are just a URL. Usually false. The result of most form submissions is an HTTP POST request, which contains the URL and form content as separate data. > If the form has fields "FromCurrency", "ToCurrency", and "Amount", all > you have to do is this: > > http://www.currencyservice.com?FromCurrency=dollars&ToCurrency=pounds&Amount=15 This is only true if the form action is an HTTP GET request, which is a rather insecure and ugly way to submit form data, and makes it impossible to submit many kinds of data. HTTP POST is the recommended method for submitting data to a CGI script. > You don't have to HAVE the form source in order to submit a request. True. You just need to construct the HTTP POST request correctly. -- \ "It's a good thing we have gravity or else when birds died | `\ they'd just stay right up there. Hunters would be all | _o__) confused." -- Steven Wright | Ben Finney From mtk at qm.com Wed Jan 14 21:42:43 2004 From: mtk at qm.com (Totte Karlsson) Date: Wed, 14 Jan 2004 18:42:43 -0800 Subject: Printing to console (No Scroll) References: Message-ID: Great, thanks for all help! I'll try these things "Derek" wrote in message news:bu45kp$d99m3$1 at ID-46268.news.uni-berlin.de... > "Diez B. Roggisch" wrote > > > Any alternatives to ncurses? It seems like a overkill for this... > > > > Maybe you can use sys.stdout.write in conjunction with control- > > codes for moving back the cursor to column one. But you'll have > > to lookup these for yourself :) > > I think \r is the control code (at least if you want to go back to the > start of the line): > > import time, sys > for second in range(10): > time.sleep(1) > sys.stdout.write(`10-second` + " seconds \r") > sys.stdout.flush() > > > -- > http://mail.python.org/mailman/listinfo/python-list > From engsolnom at ipns.com Sat Jan 3 17:13:59 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Sat, 03 Jan 2004 14:13:59 -0800 Subject: importing References: <231bc96c.0401031249.12cff6d7@posting.google.com> Message-ID: <6dfevvcfm8a8ojoduvsr1p4u72p4et28al@4ax.com> On 3 Jan 2004 12:49:56 -0800, boomer4467 at yahoo.com (Boomer) wrote: >Hi all, > I'm new to python which explains my problems with this. I'm trying >to import a .csv file(from excel) into some fields on my company's >software system(which interfaces to an sql database. Each row in this >.csv file needs to be split into smaller strings and each respective >string applied to it's field in the software then it's saved and the >next row starts, here's the code I've come up with so far. > >f=open ("book1.csv", "r") >s=f.readline () >while s != "": > print s > l = s.split(s,",",(11)) > PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0]) > PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}") > PlayIt.SetFieldContent ("SY012ADM1", "001bez", l[1]) I'm just a newbie, but I'll take a crack at it any way... split returns a list, and takes either one or two args. If the the first arg is missing, it defaults to setting the separator to while space. In your case, you might try: l = s.split(',', 11) Norm From crawley.storm.dontsendmeemail at ntlworld.com Sat Jan 31 06:21:37 2004 From: crawley.storm.dontsendmeemail at ntlworld.com (Crawley) Date: Sat, 31 Jan 2004 11:21:37 +0000 Subject: win32com support References: Message-ID: Thanks for the reply, Now I think Ive figured out whats going on. Im getting the following error: Traceback (most recent call last): File "E:\Python23\lib\site-packages\win32com\universal.py", line 170, in dispatch retVal = ob._InvokeEx_(meth.dispid, 0, meth.invkind, args, None, None) File "E:\Python23\lib\site-packages\win32com\server\policy.py", line 322, in _InvokeEx_ return self._invokeex_(dispid, lcid, wFlags, args, kwargs, serviceProvider) File "E:\Python23\lib\site-packages\win32com\server\policy.py", line 601, in _invokeex_ return DesignatedWrapPolicy._invokeex_( self, dispid, lcid, wFlags, args, kwArgs, serviceProvider) File "E:\Python23\lib\site-packages\win32com\server\policy.py", line 541, in _invokeex_ return func(*args) File "E:\code\Python\VCAddin.py", line 69, in OnConnection application.SetAddInInfo(None, self._command, -1, -1, addin ) File "E:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) exceptions.AttributeError: .SetAddInInfo Which I believe is because the object I'm calling does not support the SetAddInInfo method. After a bit of investigation, this makes sense as my class extends _IDTExtensibility2 and for that the application parameter is of type 'Object'. I cant see how to cast this into an IApplication instance, which is what I need to call my function. Ive also tried making my object derive from IDSAddin (what VC uses), but when I try the following (GUID found here:http://msdn.microsoft.com/library/default.asp?url=/library/en- us/vcug98/html/_asug_how_add.2d.ins_connect_and_disconnect.asp) universal.RegisterInterfaces('{C0002F81-AE2E-11cf-AD07-00A0C9034965}', 0, 1, 0, ["_IDSAddin"]) I get the following error: Traceback (most recent call last): File "E:\code\Python\VCAddin.py", line 33, in ? universal.RegisterInterfaces('{C0002F81-AE2E-11cf-AD07- 00A0C9034965}', 0, 1, 0, ["_IDSAddin"]) File "E:\Python23\lib\site-packages\win32com\universal.py", line 21, in RegisterInterfaces tlb = pythoncom.LoadRegTypeLib(typelibGUID, major, minor, lcid) pywintypes.com_error: (-2147319779, 'Library not registered.', None, None) Am I using the wrong name ('_IDSAddin') or the wrong GUID or is something more major going wrong. Thanks for your help Rich From jepler at unpythonic.net Thu Jan 8 22:43:11 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 8 Jan 2004 21:43:11 -0600 Subject: Python equivalent of settimeofday()? In-Reply-To: <781faf41.0401081838.10de95c9@posting.google.com> References: <781faf41.0401081838.10de95c9@posting.google.com> Message-ID: <20040109034311.GE24734@unpythonic.net> I don't think anybody's exposed it to Python yet. However, this would be an easy thing to write in C, SWIG, Pyrex, or ctypes. Pick one and get your feet wet! From daniel.dittmar at sap.com Thu Jan 15 09:48:33 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 15 Jan 2004 15:48:33 +0100 Subject: TUPLE & LIST References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: "Yomanium Yoth Taripo?t II" wrote in message news:%7xNb.55 > 1) what are the differences between list and tuple? http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and- list-data-types > 2) how to concatenate tuple and list? no method, no op?rator? listvar + list (tuplevar) tuple (listvar) + tuplevar > 3) im looking the fucking manual, and cant add value in my tuple, when it > already created :/ > how to do it? Try the Python Manual instead: http://www.python.org/doc/current/lib/typesseq-mutable.html I know it's not always easy to locate the documentation for the builtin types. Daniel From phipps.xue at sap.com Fri Jan 9 04:37:03 2004 From: phipps.xue at sap.com (Phipps Xue) Date: Fri, 9 Jan 2004 17:37:03 +0800 Subject: Syntax highlighting in .NET IDE References: <4iPKb.764$K_3.702@newssvr29.news.prodigy.com> Message-ID: "Michael Geary" wrote in message news:vvninrtm2fkaa2 at corp.supernews.com... > Moosebumps wrote: > > Is there a way to have the .NET IDE do syntax highlighting for > > python? I haven't looked into it that much, but perhaps there > > is some config file one can download. > > > > Don't ask why, I know there are better editors, but I have > > special circumstances. : ) > > Visual Python integrates full Python support into VS.NET. It's not cheap but > it's very good: > > http://www.activestate.com/Products/Visual_Python/ It doesn't take full advantage of Visual Studio .NET. I do not know why it creates it's own output window instead of VS.NET's. Anyway, this is not an import tant issue. :-D > > There is also Komodo, which runs separately from VS.NET but feels so much > like VS.NET that it's hard to tell the difference: > > http://www.activestate.com/Products/Komodo/?_x=1 > > -Mike > > From michele.simionato at poste.it Wed Jan 21 07:04:03 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 21 Jan 2004 04:04:03 -0800 Subject: converting base class instance to derived class instance References: <930ba99a.0401200413.5fae6fb9@posting.google.com> Message-ID: <95aa1afa.0401210404.49b65b4b@posting.google.com> sridharinfinity at yahoo.com (Sridhar R) wrote in message news:<930ba99a.0401200413.5fae6fb9 at posting.google.com>... > Consider the code below, > > class Base(object): > pass > > class Derived(object): > > def __new__(cls, *args, **kwds): > # some_factory returns an instance of Base > # and I have to derive from this instance! > inst = some_factory() # this returns instance of Base > return inst # Oops! this isn't an instance of Derived > > def __init__(self): > # This won't be called as __new__ returns Base's instance > pass > > The constrait is there is some factory function that creates an > instance of Base class. So I _can't_ call "Base.__init__(self)" in > Derived.__init__ func, as their will be _two_ instances (one created > by Derived.__init__ and other created by the factory function) > > Simply I want to get a derived class object, but instead of allowing > _automatic_ creation of Base instance, I want to use _existing_ Base's > instance, then use this as a Derived's instance. > > Will metaclass solve this problem? I don't really understand what you want to do (i.e. do you want Derived.__init__ to be called or not?). Moreover, as others pointed out, it is cleaner to use a class factory than to pervert __new__. If you really want to use a metaclass, you could override the __call__ method of the metaclass, in such a way to interfer with the class instantiation. For instance, this is the code to make a singleton class (which is a FAQ ;) class Singleton(type): "Instances of this metaclass are singletons" def __init__(cls,name,bases,dic): super(Singleton,cls).__init__(name,bases,dic) cls.instance=None def __call__(cls,*args,**kw): if cls.instance is None: cls.instance=super(Singleton,cls).__call__(*args,**kw) return cls.instance class C: __metaclass__=Singleton This is not what you want but you can play with __call__ and get the behavior you want. Still, why don't just use a simple factory? Michele Simionato From aaron at reportlab.com Tue Jan 13 19:33:21 2004 From: aaron at reportlab.com (Aaron Watters) Date: 13 Jan 2004 16:33:21 -0800 Subject: Databases: Which one's right for me? References: Message-ID: <9a6d7d9d.0401131633.31ee5a60@posting.google.com> ""Tim Peters" wrote in message news:... > [Aaron Watters]> > > Transactions don't have to be complex to cause serious problems in > > read-committed mode: the classic example is a debit of $1000 for > > checking account 123 running at the same time as a credit for $4000 > > for checking account 123. If both transactions run at the same time > > and read the same previous (committed) balance and they both > > complete but the first one completes last then the customer is > > screwed to the tune of $4000. > > This one isn't a problem in ZODB. The second transaction that tries to > commit will fail, with a ConflictError exception. It's up to the > application then to either abort the failed transaction, or retry it.... Alright, just for yucks. Total blood supply must be kept above 50 except during emergencies. Two transactions notice that there are 40 in bin 1 and 40 in bin two, so one takes 30 units from bin 1 and the other takes 30 units from bin 2. Or even return to the original problem assuming that the balance doesn't change but the debits are entered as separate journal entries, where the current balance is computed on the fly as the old balance less withdrawals... Sorry, I just don't know when to shut up, I know. But when I see ACID I assume these things are not a problem. -- Aaron Watters ps: Tim anticipated this reply in his post somewhat, but wasn't concrete enough for my taste. === It ain't the years, it's the mileage. -- Indiana Jones From salgado at freeshell.org Mon Jan 26 06:07:34 2004 From: salgado at freeshell.org (Guilherme Salgado) Date: Mon, 26 Jan 2004 09:07:34 -0200 Subject: delta time = time stop - time start In-Reply-To: References: Message-ID: <1075115254.21402.5.camel@maluf.alcatraz> On Mon, 2004-01-26 at 04:08, engsol wrote: [...] > The routine I came up with is below, but seems a bit clunky. > Is there a better way of doing this? I think it relies too much on integers rounding off in the proper direction, a la > d_time_hr = d_time / 3600 below. > You can use mx.DateTime (http://www.lemburg.com/files/python/mxDateTime.html). Then, the code will look like this: from mx import DateTime start = DateTime.now() # do something ... stop = DateTime.now() delta = (stop - start).strftime("%H:%M:%S") hope it helps. > Also, this will have to transition to Linux, if that makes a difference. > > START CODE: > > import string > > def deltatime(start, stop): > > t_start = (string.atoi(start[0:2]) * 3600) + (string.atoi(start[3:5]) * 60) + string.atoi(start[6:8]) > t_stop = (string.atoi(stop [0:2]) * 3600) + (string.atoi(stop [3:5]) * 60) + string.atoi(stop [6:8]) > > if t_start < t_stop: > d_time = t_stop - t_start > else: > d_time = (86400 - t_start) + t_stop > > d_time_hr = d_time / 3600 > d_time_min = (d_time - d_time_hr * 3600) / 60 > d_time_sec = (d_time - d_time_hr * 3600) - (d_time_min * 60) > > return str(d_time_hr) + 'hr ' + str(d_time_min) + 'min ' + str(d_time_sec) + 'sec' > > END CODE []'s Salgado -- This email has been inspected by Hans Blix, who has reported that no weapons of mass destruction were used in its construction. Read his report here: From tr at jotsite.com Sun Jan 25 12:37:06 2004 From: tr at jotsite.com (Hoang) Date: Sun, 25 Jan 2004 17:37:06 GMT Subject: Unique ID for CD or DVD Message-ID: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Does anyone know of an existing algorithm/module for generating a unique ID for a given CD or DVD? This would be something akin to CDDB where a CD is recognized based on its content. I could be wrong, but I think CDDB is just based on file size or disk size and this alone is not unique enough. If the solution is in Python, all the better. Hoang Do http://jotsite.com From corey.coughlin at attbi.com Thu Jan 29 19:06:20 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 29 Jan 2004 16:06:20 -0800 Subject: number of arguments a function takes References: Message-ID: "Elaine Jackson" wrote in message news:... > Exactly what I was looking for. Thank you very much. > > "Duncan Booth" wrote in message > news:Xns947FAE6461014duncanrcpcouk at 127.0.0.1... > | "Elaine Jackson" wrote in > | news:CSaSb.329909$ts4.189798 at pd7tw3no: > | > | > Suppose one of the arguments of a function f_1 is another function > | > f_2. Can f_1 access the number of arguments taken by f_2? (I'm > | > writing a little script to automate the construction of logical > | > truth-tables.) Thanks. > | > | Look at the inspect module, in particular you probably want > | inspect.getargspec: > | > | >>> import inspect > | >>> def f(a,b): pass > > | >>> inspect.getargspec(f) > (['a', 'b'], None, None, None) > | >>> help(inspect.getargspec) > | Help on function getargspec in module inspect: > | > | getargspec(func) > | Get the names and default values of a function's arguments. > | > | A tuple of four things is returned: (args, varargs, varkw, defaults). > | 'args' is a list of the argument names (it may contain nested lists). > | 'varargs' and 'varkw' are the names of the * and ** arguments or None. > | 'defaults' is an n-tuple of the default values of the last n arguments. > | > | >>> So you're working on a truth table program? I have a truth table object I did for my own application, more focused on finding input/output transitions in arbitrary truth tables, but if you're interested, let me know. Regardless, are you working on something that will ultimately become public? If so, be sure to announce it when you're done, I'd love to have a look. Especially if you're doing anything with functional simplification, my object can return a simple SOP function for a table (reducing out unused inputs is also an option) but they can get kind of lengthy for complicated functions. And if you need any other help, be sure to let me know! From kenney at netacc.net Wed Jan 28 07:26:07 2004 From: kenney at netacc.net (J. Kenney) Date: 28 Jan 2004 04:26:07 -0800 Subject: Python Importing and modifying print Message-ID: <9742a725.0401280426.329d2178@posting.google.com> Good Morning, Is there a way for a function called within an _imported_ library to call back to _calling_ python program to run a function? (Shown below) Also can you overload the print function to have it do redirect output to an array for a bit, and then switch it back. (for example: right before importing make print append each line to an array vice printing it, then going back to normal after the import is complete.) Many thanks! #first_file.py #!/usr/local/bin/python import newlib def main(): print 'hi' #newlib.py def go(): ???????.main() ???????.main() go() #Desired results % ./first_file.py hi hi % From FBatista at uniFON.com.ar Wed Jan 14 16:15:34 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 14 Jan 2004 18:15:34 -0300 Subject: Quick question..... Message-ID: featherstone80 wrote: #- numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] #- #- How would I get the total, and how would I get the average? Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 ... >>> numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] >>> sum(numberlist) 174 >>> len(numberlist) 10 >>> sum(numberlist)/len(numberlist) 17 >>> from __future__ import division >>> sum(numberlist)/len(numberlist) 17.399999999999999 . Facundo From fumanchu at amor.org Sat Jan 31 01:44:42 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 30 Jan 2004 22:44:42 -0800 Subject: timeit Message-ID: Duncan Smith wrote: > >>> import SDC_table > >>> import subtract > >>> import timeit > >>> t = SDC_table.RandomTable(1, 12, (2,3,4)) > >>> s = """\ > p = subtract.p_risk(t.values, 10) > """ > >>> tim = timeit.Timer(stmt=s) > >>> tim.timeit(10) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > tim.timeit(10) > File "C:\Python23\lib\timeit.py", line 158, in timeit > return self.inner(it, self.timer) > File "", line 6, in inner > NameError: global name 'subtract' is not defined > > # yet > >>> exec(s) > >>> p > 0.242621453769059 I believe you need to put *any* initialization code (like "import subtract") into the "setup" parameter to Timer(). So try something like: > >>> import timeit > >>> s = """p = subtract.p_risk(t.values, 10)""" > >>> tim = timeit.Timer(stmt=s, setup="import SDC_table, subtract; t = SDC_table.RandomTable(1, 12, (2,3,4))") > >>> tim.timeit(10) HTH Robert Brewer MIS Amor Ministries fumanchu at amor.org From marco at bubke.de Mon Jan 5 06:29:00 2004 From: marco at bubke.de (Marco Bubke) Date: Mon, 05 Jan 2004 12:29:00 +0100 Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: Ype Kingma wrote: > Marco Bubke wrote: > >> Hi >> >> There is the Lock object in the threading module. >> But there is no medode there I could aquire a scoped >> lock like: >> >> mutex = threading.Lock() >> my_lock = mutex.scoped_acquire() # maybe scoped_lock() >> #now this stuff is locked >> >> del mylock >> >> #the lock is released. >> >> def do_domething: >> my_lock = mutex.scoped_acquire() >> #now this stuff is locked >> #the lock is released after its out of scope >> >> >> I have written this my own but I'm not sure there is a drawback >> because its looks so convinent. So I wonder why its not in >> the module? > > Some reasons: > - What should happen when an exception happens during the locked stuff? > - It is possible pass a reference to the lock during the locked stuff, > so although the lock goes out of local scope, there still might be > a reference to it. > - The moment that __del__() is called is not guaranteed. > > You can also do it like this: > > mutex = threading.Lock() > mutex.acquire() > try: > # now this stuff is locked > finally: > mutex.release() # explicit is better than implicit This does not look nice to me. There should be something me easily. Maybe that: def do_something() lock(mutex): #this stuff is locked by the mutex So you don't forget to release the lock. best regards Marco From me at privacy.net Thu Jan 29 09:31:33 2004 From: me at privacy.net (Duncan Booth) Date: 29 Jan 2004 14:31:33 GMT Subject: comparing booleans References: <40185112.264898A4@alcyone.com> Message-ID: Dang Griffith wrote in news:eaa90cc908c7a217f0d6475e41c7622d at news.teranews.com: > Interestingly, and I'm not sure why: >>>> (True != True) != True > True >>>> True != (True != True) > True >>>> True != True != True > False You can chain comparison operators in Python. e.g. a < b < c is the same as: (a < b) && (b < c) except that if b is an expression the first form evaluates it exactly once whereas the second form evaluates it either once or twice. You can use any comparison operators in this form, so your True!=True!=True is just shorthand for: (True!=True) && (True!=True) which is in turn equivalent to: False && (True!=True) and 'False && anything' gives False. From dd at guv.ethz.ch Sat Jan 31 06:27:57 2004 From: dd at guv.ethz.ch (=?iso-8859-15?Q?David_D=FCrrenmatt?=) Date: Sat, 31 Jan 2004 12:27:57 +0100 Subject: zlib Message-ID: Hi, I am looking for a zlib implementation (or any other which can handle zip archives) for Python 1.5.2. I only found one for Python >= 2.2 :-( Thanks Dave -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From faizan at jaredweb.com Wed Jan 28 15:42:06 2004 From: faizan at jaredweb.com (Fazer) Date: 28 Jan 2004 12:42:06 -0800 Subject: Best way to compare a list? References: <7b454334.0401271739.59267018@posting.google.com> Message-ID: <7b454334.0401281242.3bd604e6@posting.google.com> John Hunter wrote in message news:... > >>>>> "Fazer" == Fazer writes: > > Fazer> Hello, I was wondering which would be the best way to > Fazer> compare a list? > > Fazer> I was thinking of just using a for loop and testing the > Fazer> condition. > > Fazer> What do you guys think? The best/fastest way of comparing > Fazer> lists. > > What do you want to compare for, equality of all elements? Give a > little more info about what you need to do. > > JDH Sorry about that. Basically, I have to lists. I have to compare them and pick out the difference(s). Maybe the simple/fast approach would be to use a for loop? Thanks, From exarkun at intarweb.us Tue Jan 13 16:44:46 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 13 Jan 2004 16:44:46 -0500 Subject: Why learn Python ?? In-Reply-To: References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> <87d69og2jl.fsf@pobox.com> <873cajafr8.fsf@pobox.com> Message-ID: <20040113214446.GA14438@intarweb.us> On Tue, Jan 13, 2004 at 02:28:38PM -0500, Derek wrote: > "John J. Lee" wrote: > > [...] > > > Point taken. I once worked on a project where we > > > implemented a production system in C++ and then > > > implemented it again in Python for QA purposes. It took > > > about 150k lines of C++ code and 10k lines of Python. > > > Python took less code because so many modules are bundled > > > with the language, but the C++ system ran many times > > > faster. It's all about picking the right tool for the > > > job. > > > > Well, that's a banal truism obscuring the fact that, for the > > great majority of projects, optimisation does not require > > implementation of the *entire* system in a language like > > C++. The sum of C++ and Python is greater than the parts. > > Python and C++ can also be a bigger mess than sum of either part. > Take your pick. > Look at how many modules in the stdlib are not implemented in Python. Look at all the builtin types. It *can* and *does* work, and with very little mess, if you know what you're doing. Jp > > -- > http://mail.python.org/mailman/listinfo/python-list > From dietrich at zdome.net Mon Jan 19 18:47:56 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Mon, 19 Jan 2004 15:47:56 -0800 Subject: Getting a process's output [solved] In-Reply-To: <20040119221350.GB11631@nl.linux.org> References: <82104858-4ACB-11D8-A692-0003934ACDEC@zdome.net> <20040119221350.GB11631@nl.linux.org> Message-ID: On Jan 19, 2004, at 2:13 PM, Gerrit Holl wrote: > Dietrich Epp wrote: >> Is there any easy way to get all the output of a process? Ideally, >> the >> function takes parameters like exec(), calls fork(), wait()s for the >> process to complete, and returns the process's stdout, stderr, and >> exit >> status. By stdout and stderr I don't mean file objects or >> descriptors... I mean strings containing the entire output. >> >> I would try to do it myself, but I'm not sure how to interleave the >> operations. > > Try commands.getstatusoutput() or the various popen functions. Thanks, although getstatusoutput requires arguments to be quoted. I looked at the source code to getstatusoutput() and popen() to come up with a replacement which doesn't need quoted arguments and doesn't create a shell. I don't think it portable, and it will undoubtedly do something very nasty if one of the system calls should fail. I think this would be very cool in the library (the function, not its deficiencies). import os import sys def run_process(path, args): out_r, out_w = os.pipe() pid = os.fork() if pid: os.close(out_w) outf = os.fdopen(out_r) text = outf.read() outf.close() status = os.waitpid(pid, 0)[1] return status, text else: try: if out_w != 1: os.close(1) os.dup2(out_w, 1) if out_w != 2: os.close(2) os.dup2(out_w, 2) os.close(out_w) os.execvp(path, args) finally: # Should be _exit sys.exit(1) Blah blah blah, I hereby release the above code into the public domain. Most of the time I spent trying to get the above code to work I thought that stdout == 0, whoops. From grobinson at transpose.com Thu Jan 22 14:25:55 2004 From: grobinson at transpose.com (Gary Robinson) Date: Thu, 22 Jan 2004 14:25:55 -0500 Subject: I support PEP 326 In-Reply-To: <1074798814.27007.148.camel@localhost.localdomain> Message-ID: > What's PEP 326 again? > Sorry... it's a proposal that Python incorporates two singleton constants that represent top and bottom values: Max and Min might be the names. Max would be bigger than anything it's compared to and Min would be smaller. It would be very convenient -- in code I was writing a week or two ago I was thinking "wouldn't it be great if python had..." exactly what PEP 326 proposes. It would have saved... well... a few minutes. But those add up! The PEP document gives a lot of examples of why it would be good. http://www.python.org/peps/pep-0326.html --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 Company: http://www.transpose.com Blog: http://www.garyrobinson.net > From gerrit at nl.linux.org Mon Jan 26 16:12:34 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 26 Jan 2004 22:12:34 +0100 Subject: Deleting objects In-Reply-To: References: Message-ID: <20040126211234.GA3721@nl.linux.org> user at domain.invalid wrote: > If I want to "reset" the object so that I get > all of my memory back, can I just do: > > del db This may work, if you don't have other references. > or maybe: > > for t in db.tables: > del t > > and expect that I have cleaned up all of my > memory? > > After writing this out, I see that the answer > is clearly yes, but I will post anyway. The answer is no, really :-) 'del' only removes a certain name from the current namespace. An object is only destroyed when *all* references to it have been destroyed. When you are looping over a certain collection, each time the body of the loop is executed, the loop variable (here 't') gets redefined. So if the referencecount to a certain object (db.tables[x]) is N, it will become temporarily N+1 when looping over it: with 'del t', you destroy the local name, so it becomes N again. Conclusion: This aint gonna work. Because of this, it is generally better to explicitly kill/destroy/close something. I don't know anything about databases, but maybe you want to .close() it? 'del db' may work, but can be tricky if other objects, like dicts, lists, sets or others, contain (nameless) references to the object. yours, Gerrit. -- This is my signature. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From ptmcg at users.sourceforge.net Mon Jan 19 08:59:23 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Mon, 19 Jan 2004 13:59:23 GMT Subject: Looking for very simple general purpose tokenizer References: Message-ID: <%oROb.92530$WS1.49742@fe1.texas.rr.com> "Maarten van Reeuwijk" wrote in message news:bug9ij$30k$1 at news.tudelft.nl... > Hi group, > > I need to parse various text files in python. I was wondering if there was a > general purpose tokenizer available. I know about split(), but this > (otherwise very handy method does not allow me to specify a list of > splitting characters, only one at the time and it removes my splitting > operators (OK for spaces and \n's but not for =, / etc. Furthermore I tried > tokenize but this specifically for Python and is way too heavy for me. I am > looking for something like this: > > > splitchars = [' ', '\n', '=', '/', ....] > tokenlist = tokenize(rawfile, splitchars) > > Is there something like this available inside Python or did anyone already > make this? Thank you in advance > > Maarten > -- > =================================================================== > Maarten van Reeuwijk Heat and Fluid Sciences > Phd student dept. of Multiscale Physics > www.ws.tn.tudelft.nl Delft University of Technology Maarten - Please give my pyparsing module a try. You can download it from SourceForge at http://pyparsing.sourceforge.net. I wrote it for just this purpose, it allows you to define your own parsing patterns for any text data file, and the tokenized results are returned in a dictionary or list, as you prefer. The download includes several examples also - one especially difficult file parsing solution is shown in the dictExample.py script. And if you get stuck, send me a sample of what you are trying to parse, and I can try to give you some pointers (or even tell you if pyparsing isn't necessarily the most appropriate tool for your job - it happens sometimes!). -- Paul McGuire Austin, Texas, USA From mirandacascade at yahoo.com Sun Jan 25 16:41:57 2004 From: mirandacascade at yahoo.com (Miranda Evans) Date: 25 Jan 2004 13:41:57 -0800 Subject: progress bar References: <59e5b87.0401231329.6e084d6f@posting.google.com> <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> Message-ID: <59e5b87.0401251341.6a95b17e@posting.google.com> "Hoang" wrote in message news:<9pwQb.5566$vy6.3518 at newssvr29.news.prodigy.com>... > > > > Try Venster: > > http://venster.sourceforge.net > > > > IIRC the test_coolbar.py script includes a progress bar. > > I wonder what possessed someone to start another GUI framework. Aren't > there more than enough existing ones? The reasoning for it wasn't > immediately apparent on the web page. > > Hoang Do > http://jotsite.com Newbie questions...what is meant by the term 'GUI framework'? I'm aware of Tkinter, wxPython and PythonCard (which, I believe builds from a wxPython foundation). Also, it appears as though pywin.mfc has GUI capabilities. Are Tkinter, wxPython, PythonCard and pywin.mfc considered GUI frameworks? Based on the 'more than enough...' remark, it sounds like there are several GUI frameworks out there...what are some others? From claird at lairds.com Wed Jan 14 14:07:04 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 14 Jan 2004 19:07:04 -0000 Subject: what is best for web development?? References: <87oet9grqy.fsf@blakie.riol> <6ee58e07.0401140638.672d50a7@posting.google.com> Message-ID: <100b4qoeeeq7d57@corp.supernews.com> In article <6ee58e07.0401140638.672d50a7 at posting.google.com>, Lothar Scholz wrote: >graham__fawcett at hotmail.com (Graham Fawcett) wrote in message >news:... >> Wilk wrote in message news:<87oet9grqy.fsf at blakie. > >> If it has to be a one-shot install, I would suggest a Web server >> written in Python -- Medusa or Twisted, probably -- that you could >> bundle with your Python app. Find a Web app framework that (a) works >> on Medusa or Twisted and (b) has the templating features you >> require/desire. > >I would not recommend this. A distribution with an own apache server >seems to be the best. It is easy to hide the setup and the customers >know that there is a good working technologie behind the scenes. And >it can be managed by every normal administrator. This is a very >important point for larger customers. > >I would recommend webware+Fun Form Kit+cheeta together with apache. I'm unsure what you're recommending. We're considering a self-contained Web application, including the Web server itself. Are you proposing: 1. An installer which does a conventional Apache installation, except with enough stuff confi- gured so it comes up in a safe state, PLUS a separate installation segment just for the Python-based part; or 2. A custom installer which knows internal details of both Apache and the Python-based application? What advantage do you see for either of these over the pure-Python ap- proach suggested above? Is your point that customers feel more comfortable with "Apache inside"? -- Cameron Laird Business: http://www.Phaseit.net From h.b.furuseth at usit.uio.no Fri Jan 9 11:08:15 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 09 Jan 2004 17:08:15 +0100 Subject: Program return value ? References: Message-ID: George Marshall wrote: > Hi all, I'm trying to get the exit code of a program > I want to exec in a python script in a portable manner. > (...) > The only problem is that it doesn't return negative values. On a Unix system, the exit status from a program is one byte, which on 8-bit systems can have values from 0 to 255. So if the program does exit(-1), the exit status is (unsigned char)-1 == 255. I don't know how this works on other operating system, but in any case I imagine your problem is with the possible range of the exit status, not with python. Maybe your program should write a value to stdout (or some other file) instead, so python could read the number. -- Hallvard From jjl at pobox.com Thu Jan 8 13:33:57 2004 From: jjl at pobox.com (John J. Lee) Date: 08 Jan 2004 18:33:57 +0000 Subject: win32: internet explorer automation problem References: Message-ID: <874qv670iy.fsf@pobox.com> "mic" writes: > I'm currently trying to write an MSIE automation software and have run into > such problem - have no idea how to take control of external popup windows - > I use WebBrowser COM object and am able to catch the NewWindow2 event, but > don't know how to change 'focus' to other than main explorer window. I tried [...] I guess you just need to use the usual browser object model (the one exposed to JavaScript &c.) -- eg. window.focus(), window.blur(). IIRC, it's IHTMLDocument2, or similar, that you want. John From cartermark46 at ukmail.com Mon Jan 19 11:51:46 2004 From: cartermark46 at ukmail.com (Mark Carter) Date: 19 Jan 2004 08:51:46 -0800 Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: > Well, when you think you want a loop and before you know it you've > written: > > (define (my-func arg1 arg2) > (define (inner var) > ... > > it's probably time to come back to a less spartan programming > language. I mean, it's good to know that you *can* write loops that > way, but that doesn't mean it actually *is* a good idea. I'm experimenting with learning a functional language; and I know almost zero about Scheme. I find it very difficult to understand the structure of what's going on. I downloaded Standard ML (the New Jersey offering), and find myself more inclined to dig into ML deeper; rather than Scheme. ML does, at first glance, seem more readable. I suppose that Schemers and Lispers take the attitude that a lack of syntax is an advantage, because you can ultimately program in any paradigm you wish. It's "just" a case of writing code that implements the paradigm. I have also heard claims that the existence of parantheses in s-exprs is a red herring as far as readability is concerned. Non Schemers/Lispers, on the other hand, presumably think that a spoonful of syntactic sugar helps the medicine go down. I suspect that if there really was One Obviously Right Way To Do It, then we'd all be using it. No silver bullet, and all that. I am sure, though, that there will be many people who disagree with my sentiments. From claird at lairds.com Mon Jan 12 20:05:09 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 13 Jan 2004 01:05:09 -0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <877jzwg1v2.fsf@pobox.com> Message-ID: <1006h25r6623m45@corp.supernews.com> In article <877jzwg1v2.fsf at pobox.com>, John J. Lee wrote: . [pages of marvelously precise analysis] . . >Eiffel: Design by contract. The book to read is Meyer's "Object- > Oriented Software Construction". Full of interesting stuff, if you can > stand his self-importance ;-). . . . Mostly I'm writing just to applaud--this post had a lot of value to it. The largest quibble I could find in its scores of lines was the failure to mention that *OOSC* is valuable reading for OO programmers working in *any* language, not just Eiffel. *OOSC* is like *SICP* in that regards; it towers not just over the competition, but also any apparent limit imposed by its language of expression. -- Cameron Laird Business: http://www.Phaseit.net From fumanchu at amor.org Sun Jan 4 01:56:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 3 Jan 2004 22:56:39 -0800 Subject: Recurring dates module [was: Project dream] Message-ID: I offered: > > > first attempt (*very* alpha); feedback/additions appreciated. > > > > > > http://www.aminus.org/rbre/python/recur.py > > > http://www.aminus.org/rbre/python/test_recur.py > > > > I updated this today, including time functions in addition > > to the date functions and generally "filling in the corners". > > I also included > > an interval calculation function for e.g., threading.Timer. and eltronic replied: > rats, datetime IIR is only py2.3 unless it already works in py2* > or some kind soul has backported it ala sets and some of itertools. Yes, sorry about that. Now that I'm fully 2.3 I didn't feel the need (yet) to generalize the date types. I did try, however, to keep all of the calls "method-centric"--that is, I don't ever check type/subclass explicitly. Perhaps for older versions someone might write a wrapper for mxDateTime which makes it behave like the new datetime module. I had that mostly done at one time, then threw it away when datetime made it into the Library. > I envision a timer prog that wakes up every 45 or so seconds > parses an event list and acts on those of the current minute. > but something like recur would be needed for up/down counters. > I guess all counters can derive their data from one main counter. > the thought of starting each alarm in a thread maybe minutes > days or months in advance is not going to survive reboots well. I considered that; it's one of the reasons that I decided to use iteration/generators as the primary mode of operation, and kept the declaration of recurrence in a vocabulary which is "rigorously indeterminate". :) That is, the description of recurrence is ambiguous until you provide a start date/end date to realize it. If your chain of iteration breaks down, you should be able to pick it up again at any point without modifying your description. It's also why the base functionality of recur is available without use the Recurrence class--that's just syntactic sugar over the bare generator functions. I am now using recur with threading.Timer, by the way. You don't set up all your Timers at once (one for each 45 seconds!?)--you code each Timer so that, when it has completed its task, it starts the next Timer. That's where recur.interval() comes in. Example: import threading import recur class Worker(object): """Perform work on a schedule. You must subclass work(), which is called at each interval. """ def __init__(self, recurrence=None): self.recurrence = recurrence if self.recurrence: # Throw away the first occurrence value, # which is almost always .now() self.recurrence.next() def motivate(self): """Start a new timed thread for work.""" if self.recurrence: iv = recur.interval(self.recurrence) threading.Timer(iv, self._run).start() def _run(self): """Prepare for work.""" self.work() self.motivate() def work(self): raise NotImplementedError ...which survives reboots just fine; just call motivate() on app startup. Alternately, you could use a single main thread to calculate the intervals and spawn new threads. That's why I specifically did not embed threading implementations into recur--it's better to leave it simpler and just let it play well with other existing modules which have been written far better than mine. Robert Brewer MIS Amor Ministries fumanchu at amor.org From shaleh at speakeasy.net Sat Jan 10 03:03:39 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat, 10 Jan 2004 00:03:39 -0800 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: <3FFF26A1.943DEA84@engcorp.com> References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <200401100003.39915.shaleh@speakeasy.net> On Friday 09 January 2004 14:09, Peter Hansen wrote: > > Yes or no answers suffice, but feel free to follow up with a paragraph > qualifying your answer (or quantifying it!). :-) > not any longer. As I learned on this and the tutor list, writing code in Pythonic style tends to also result in code being fast enough. Most of my early problems resulted from trying to write C in Python. From tim.golden at viacom-outdoor.co.uk Thu Jan 8 10:43:50 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 8 Jan 2004 15:43:50 -0000 Subject: Calling a function dynamically Message-ID: >-----Original Message----- >From: JoeyTaj at netzero.com [mailto:JoeyTaj at netzero.com] >Sent: 08 January 2004 15:42 >To: python-list at python.org >Subject: Calling a function dynamically > > >I would like to call a function whose name I supply at runtime. >Something like this but it didn't work > >functionName = 'run' >instance = ClassDef() >args = [1, 2] > >#want the dynamic equivalant of >#instance.run(*args) > >#This didn't work cause there was no __call__ attribute. Why? >value = instance.__call__[functionName](*args) The __call__ method of an instance only exists if defined for its class by the developer, typically so that instances of the class can behave as though they were functions. If you're really set on doing what you describe, make use of the getattr function. Something like this should work: >>> >>> class c: ... def f (self, x, y): return x + y ... >>> i = c () >>> print getattr (i, "f") (1, 2) 3 >>> However, perhaps you don't really want to do it this way. A common approach to this in Python is to use a dictionary of functions. Doubtless there are others. If you could paint a wider picture of what you're about, we could probably be of more help. 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 eric.brunel at N0SP4M.com Thu Jan 29 09:06:27 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Thu, 29 Jan 2004 15:06:27 +0100 Subject: popen2 with large input References: Message-ID: cherico wrote: > from popen2 import popen2 > > r, w = popen2 ( 'tr "[A-Z]" "[a-z]"' ) > w.write ( t ) # t is a text file of around 30k bytes > w.close () > text = r.readlines () > print text > r.close () > > This simple script halted on > > w.write ( t ) > > Anyone knows what the problem is? Yep: deadlock... Pipes are synchronized: you can't read from (resp. write to) a pipe if the process at the other end does not write to (resp. read from) it. If you try the command "tr '[A-Z]' '[a-z]'" interactively, you'll see that everytime tr receives a line, it outputs *immediately* the converted line. So if you write a file having several lines to the pipe, on the first \n, tr will try to write to its output, and will be stuck since your program is not reading from it. So it won't read on its input anymore, so your program will be stuck because it can't write to the pipe. And they'll wait for each other until the end of times... If you really want to use the "tr" command for this stuff, you'd better send your text lines by lines and read the result immediatly, like in: text = '' for line in text.splitlines(1): w.write(line) w.flush() # Mandatory because of output bufferization - see below text += r.readline() w.close() r.close() It *may* work better, but you cannot be sure: in fact, you just can't know exactly when tr will actually output the converted text. Even worse: since output is usually buffered, you'll only see the output from tr when its standard output is flushed, and you can't know when that will be... (BTW, the script above does not work on my Linux box: the first r.readline() never returns...) So the conclusion is: don't use pipes unless you're really forced to. They're a hell to use, since you never know how to synchronize them. BTW, if the problem you posted is your real problem, why on earth don't you do: text = t.lower() ??? HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From andymac at bullseye.apana.org.au Wed Jan 7 05:02:46 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 7 Jan 2004 21:02:46 +1100 (EST) Subject: Iterating over a binary file In-Reply-To: References: Message-ID: <20040107205635.W38088@bullseye.apana.org.au> On Tue, 6 Jan 2004, Derek wrote: > f = file(filename, 'rb') > data = f.read(1024) > while len(data) > 0: > someobj.update(data) > data = f.read(1024) > f.close() > > The above code works, but I don't like making two read() calls. Any > way to avoid it, or a more elegant syntax? Thanks. I believe the canonical form is: f = file(filename, 'rb') while 1: data = f.read(1024) if not data: break someobj.update(data) f.close() This was also the canonical form for text files, in the case where f.readlines() wasn't appropriate, prior to the introduction of file iterators and xreadlines(). -- 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 tim.one at comcast.net Fri Jan 30 14:11:28 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 30 Jan 2004 14:11:28 -0500 Subject: NEWLINE character problem In-Reply-To: <013601c3e74c$c34bc780$2f01a8c0@dchirila> Message-ID: [Tim, suggests return s.replace('\r\n', '\n').replace('\r', '\n') ] [Dragos Chirila] > Thanks a LOT !! > > I will give it a try and see how it works... the problem is that I > have realy big strings (more than 50000 characters) Why is that a problem? A 50 megabyte string might be a strain on some modern machines, but 50K isn't much anymore. There are many ways to approach this, but I'm not clear on what you want to do. For example, you can easily enough split on \r, \n and \r\n "in one step": >>> import re >>> bylines = re.compile(r'\r\n?|\n') >>> bylines.split("abc\r\ndef\rghi\njkl\n") ['abc', 'def', 'ghi', 'jkl', ''] # watch out for the trailing ''! >>> Or if you want to pick off a line at a time, use a generator: import re bylines = re.compile(r'\r\n?|\n') def genlines(s): i, n = 0, len(s) while i < n: m = bylines.search(s, i) if m: start, finish = m.span(0) yield s[i:start] i = finish else: break and then >>> for line in genlines("abc\r\ndef\rghi\njkl\n"): ... print "<" + line + ">" Maybe you want a line end character on each piece too -- don't know, but it should be easy to fiddle to taste. From joe at notcharles.ca Sun Jan 25 20:53:31 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 26 Jan 2004 01:53:31 GMT Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: In article , Michele Dondi wrote: > Also, you may have noticed it, but this is a discussion group about > *Perl* and people here is highly likely to be fond of Perl, appreciate > its "nature" and so on... so what did you expect to receive as an > answer to your post? No it's not. This is a newsgroup about Ruby. And that's a newsgroup about Python. And that over there's a newsgroup about Scheme. Only one of these groups is actually about Perl, so I've set the followups there. The troll is actually on-topic there. Please keep your replies there, too. Joe From jepler at unpythonic.net Wed Jan 21 20:25:16 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Jan 2004 19:25:16 -0600 Subject: an example of a singleton design pattern in python? In-Reply-To: References: Message-ID: <20040122012516.GB29212@unpythonic.net> On Wed, Jan 21, 2004 at 07:38:26PM -0500, Aahz wrote: > * Within a single module, use a global class as your singleton object. This is a little bit inconvenient, because you must either mark all methods as staticmethod (and refer to the class by name), or you must mark all methods as classmethod. This metaclass can help. It makes all functions into staticmethods at the time the class is created: from types import FunctionType class SingletonClassMeta(type): def __new__(cls, name, bases, dict): for k, v in dict.iteritems(): if isinstance(v, FunctionType): dict[k] = classmethod(v) return (super(SingletonClassMeta, cls). __new__(cls, name, bases, dict)) class Singleton(object): """All methods in a Singleton object are made class methods""" __metaclass__ = SingletonClassMeta Probably __init__ should be made to raise an exception (RuntimeError, "Singletons cannot be instantiated"))... An example: >>> class C(Singleton): ... x = [] ... def f(self): return self.x ... def g(self, arg): self.x.append(arg) ... >>> C.f() [] >>> C.g(3) >>> C.f() [3] From mcfletch at rogers.com Sat Jan 10 11:48:00 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 10 Jan 2004 11:48:00 -0500 Subject: Debugging Python In-Reply-To: <3fffbe99.486050433@news.blueyonder.co.uk> References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> Message-ID: <40002CC0.3020207@rogers.com> Alan Gauld wrote: >On Fri, 9 Jan 2004 10:29:46 GMT, Harry George > wrote: > > >>>I'm not sure about others, but when I design and code using test-driven >>>development (TDD), I tend not to need to debug almost ever. >>> >>> ... >Interesting comments. How do people generally perform these tests >then? My primary test tool, for low level testing, is usually the >debugger. Batch mode debugging is something I've been doing since >I worked on VAX/VMS systems and its seems as natural as breathing >to me. Its easy to save a test session and run it later etc. How >else do you test code at a low level? > > Standard module unittest, although lots of people like doctest (closer in spirit to your debugger debugging traces). The TDD/Agile people seem generally to use the more formal unittest mechanism (which is more appropriate when you're writing the test first), while doctest encourages you to write something closer to a "regression" test, where you're just testing that what works now isn't going to fail in the future by recording side-effects (debugger/prompt output) and comparing them to the later version's side-effects. unittest testing is a rather involved thing, there's all sorts of test-framework "fixtures", (e.g. MockObjects), that help you run a particular method of a particular object all by its lonesome to test that it does everything it is supposed to do and nothing it's not supposed to do. The entire test-suite is supposed to be run regularly (at least daily & before checkins), with local tests (those for the area on which you are working) being run every 30 seconds or so as you write new tests (and then the code to fix the breakage of those tests (and that only if the test is actually broken with the current code-base)). TDD (test-driven development) tends to reduce/eliminate the use of the debugger because of that (automated) frequency of test-code-runs. You're testing small blocks of code with tests whose very name says what's failed about the block of code, so as soon as you screw something up red lights start flashing telling you what you just did wrong. Given that you're also *working* on very small code blocks, you generally know what you just did (you aren't supposed to be coding large blocks of code at once), and the failed tests' names tell you what went wrong (and where) with what you just wrote. I've only been able to rigorously apply TDD in one or two projects so far. The fit for GUI and graphics code isn't spectacular (IMO). Command-line, library, and network apps (with the appropriate test fixtures (efficient use of which seems to be key to any serious use of TDD)) seem to be a better fit. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jjl at pobox.com Fri Jan 9 09:57:16 2004 From: jjl at pobox.com (John J Lee) Date: Fri, 9 Jan 2004 14:57:16 +0000 (GMT) Subject: win32: internet explorer automation problem In-Reply-To: References: Message-ID: On Fri, 9 Jan 2004, [iso-8859-2] Micha? ?yli?ski wrote: > > Well, it's got to be in there somewhere (not necessarily IHTMLDocument -- > > there are a bunch of interfaces whose names I don't remember). > > Sure, I hope so, but am afraid that WebControl alone doesn't offer it (or at > least not straight from the box). Anyway thx for your help. The "WebBrowser Control" means IWebBrowser2, which is just a little part of SHDOCVW / MSHTML. But I believe JavaScript, VBScript etc. all get their abilities pretty directly via the COM interfaces. That's why it was possible to add Python as a "first-class" scripting language, on a par with JavaScript etc. (or JScript, strictly). So -- IIUC -- it really does have to be in there, and it should be easy to find, too (in some sense of "easy" ;-). John From peter at engcorp.com Thu Jan 15 11:42:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Jan 2004 11:42:35 -0500 Subject: Printing to console, no scroll References: <20040114190350.06766.00000031@mb-m21.aol.com> Message-ID: <4006C2FB.B377BE82@engcorp.com> PiedmontBiz wrote: > > Sorry for my post with all the ansi.py code. > > I forgot the website I got it from. Google is your friend (along with five seconds of effort): http://www.demonseed.net/~jp/code/ansi.py -Peter From sridharinfinity at yahoo.com Sun Jan 18 09:25:10 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 18 Jan 2004 06:25:10 -0800 Subject: Using python for _large_ projects like IDE Message-ID: <930ba99a.0401180625.5863acd4@posting.google.com> Hi, I am a little experienced python programmer (2 months). I am somewhat experienced in C/C++. I am planning (now in design stage) to write an IDE in python. The IDE will not be a simple one. I had an idea of writing the IDE in C/C++, as it is a big project, bcoz of the following 1. if python is used, then the memory required for running the IDE will be high. 2. if pure python is used, the IDE will be slower. I'm not sure whether they are true. Then I thought of using python for 90% of the code and using C for other performance critical part. But the problem is in identifying the performance critical code. People suggest to start with pure python and then _recode_ the performance critical code after profiling the original code. But I fear whether there will be a conflit in say data structures. Not yet expert in extending/embedding python. Are there any ways to forsee the performance critical parts? Also, any suggestions on reducing memory usage of big applications written in python? From swalters_usenet at yahoo.com Thu Jan 8 19:15:47 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 00:15:47 GMT Subject: What psyco is goot at [Was: Rookie Speaks] References: Message-ID: |Thus Spake Delaney, Timothy C (Timothy) On the now historical date of Fri, 09 Jan 2004 09:51:07 +1100| > As an example, check these pystone results (Python 2.3.3, psyco 1.1.1, > Windows 2K SP4). Note I've upped the number of passes ... > > The benchmarks with `from psyco.classes import __metaclass__` are > interesting - they're counter to what one would expect from the docs - > increased memory usage and decreased performance. Is this a known thing > Armin, or is something going screwy on my box? It's happening > consistently. > > Note that psyco.profile() depends heavily on how your code works. I've got > one piece of code that performs approx 5 times better with psyco.full(), > but actually performs worse with psyco.profile() than without psyco at > all! No matter how badly we wish optimization were a theoretical science, I think it will always be mostly empirical. The bottlenecks always seem to show up in the most unintuitive places. You can make some educated guesses based on the Big O nature of your algorithms, but in the end, you just have to field test. > > Unfortunately, I can't make it available, but it's a single pass over a > file (line by line), matching and extracting data using various regexes, > writing lots of other files, then iterating over the other files to > produce even more files. The datasets tend to be very large - 500MB+. > > The main functions only get called one time each (which is probably the > killer) and the bulk of the work is done inside while loops in those > functions. I suspect that if I moved the contents of the main while loops > to their own functions psyco.profile() would do a lot better. It seems you've got two forces pulling in opposite directions here: Function calls are expensive in Python and Psyco only optimizes functions as a whole. I've heard of a tool, I believe it's called HotSpot, that will help you figure out which lines of code, not functions, are the most expensive for you. You could then see if wrapping those lines in a function and binding it with psyco would give you a gain in performance. You might look into it. I haven't researched it, know nothing about it, and it's pretty low on my to-do list ATM, but it might help you with your needs. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From premshree_python at yahoo.co.in Wed Jan 28 12:13:53 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 28 Jan 2004 17:13:53 +0000 (GMT) Subject: Distributing Python programs In-Reply-To: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net> Message-ID: <20040128171353.37596.qmail@web8305.mail.in.yahoo.com> > Can I install Python on a networked server and have > any user run Python > programs without having to go through the 9Mb client > install? Yes. The users will only have to login remotely to the server, and can run Python. > What are my options for distributing Python programs > to my users? If you are creating standalone apps, you could consider distributing them as the py objects or executables (for Windows). See py2exe: http://starship.python.net/crew/theller/py2exe/ Hope this helps. -Premshree --- NEWS wrote: > Can I install Python on a networked server and have > any user run Python > programs without having to go through the 9Mb client > install? > > What are my options for distributing Python programs > to my users? > > Thankyou to anyone who can help. > > Graham > > > > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From http Sat Jan 31 19:29:48 2004 From: http (Paul Rubin) Date: 31 Jan 2004 16:29:48 -0800 Subject: OT: why do web BBS's and blogs get so slow? References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xfzdvej5v.fsf@ruckus.brouhaha.com> y From peter at engcorp.com Fri Jan 9 09:23:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:23:55 -0500 Subject: Python equivalent of settimeofday()? References: <781faf41.0401081838.10de95c9@posting.google.com> Message-ID: <3FFEB97B.9B957AD5@engcorp.com> "Narendra C. Tulpule" wrote: > > do you know how (or if) I can set time on a system using Python? > i.e. is there an equivalent of the shell's 'date -s' or the system > call settimeofday()? Maybe some variation on this? import os,time def settimeofday(tt): ts = time.ctime(tt) os.system("/sbin/hwclock --set '--date=%s'"% ts) os.system("/sbin/hwclock --hctosys") ?? Note the final line, which retrieves the time from the hardware so the system clock is also updated. -Peter From maxm at mxm.dk Wed Jan 14 02:54:42 2004 From: maxm at mxm.dk (Max M) Date: Wed, 14 Jan 2004 08:54:42 +0100 Subject: Does anyone else not find the fun in programming...? In-Reply-To: References: Message-ID: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> Chris Lyon wrote: > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! Perhaps you are working on the wrong projects? I program for work. That isn't fun. Well it's not bad either. But I also have a hobby creating music with algorithmic composition techniques in Python. And that is *fun* Creating basic libraries is also fun. Spending all the time you need to get them "just right" Combining programming with some kind of hobby hardware can also be fun. regards Max M From miki.tebeka at zoran.com Tue Jan 6 02:54:46 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 5 Jan 2004 23:54:46 -0800 Subject: Probles parsing a text file References: Message-ID: <4f0a9fdb.0401052354.549cece4@posting.google.com> Hello, > heres my text file(well the first two lines of it) > > ######################################### > # Default BMUS server CFG file # ... > i heres the script that im using to parse the file ... Try: #!/usr/bin/env python try: fo = open("server.cfg") print "Reading server CFG file" for line in fo: line = line.strip() # Strip white spaces if (not line) or line.startswith("#"): continue eval(line) # *** UNSAFE *** print "line executed" except IOError, e: print "Can't read server CFG (%s)" % e Note that using "eval" is very unsafe. Someone might place 'shutil.rmtree("/")' inside the CFG file. > many thnas for your help No problem. Miki From skip at pobox.com Wed Jan 21 15:32:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 14:32:26 -0600 Subject: SystemError while execing bad code In-Reply-To: References: Message-ID: <16398.57818.351244.255642@montanaro.dyndns.org> Gerrit> exec CodeType(0,0,0,0,"",(),(),(),"","",0,"") ... Gerrit> But I guess this is a case of "so don't do it" :-)? Michael> Definitely. It's easy enought to crash the interpreter this Michael> way (think LOAD_CONST 30000, for just one easy way). In fact, help(types.CodeType) describes it thusly: Create a code object. Not for the faint of heart. Should this sort of stuff be published on the Wiki? Skip From inyeol.lee at siimage.com Tue Jan 27 13:55:55 2004 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 27 Jan 2004 10:55:55 -0800 Subject: Problem with RE matching backslash In-Reply-To: <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> References: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> Message-ID: <20040127185555.GF13453@siliconimage.com> On Tue, Jan 27, 2004 at 03:31:24PM +0000, Ladv?nszky K?roly wrote: > Thanks for your quick and very helpful reply, Peter. > What is still not clear to me is why the search examples work and yield > 'm'. > > K?roly Python and SRE have different convention for handling unrecognized escape sequence, such as "\\m". >From Section 2.4.1 String literals in Python 2.3.3 Reference Manual; """ Unlike Standard , all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) """ >From Section 4.2.1 Regular Expression Syntax in Python 2.3.3 Lib Reference; """ The special sequences consist of "\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character "$". """ So, your 3rd example print re.search('\\m', '\m').group(0) is actually the same as print re.search('m', '\\m').group(0) , thus returns 'm'. -Inyeol Lee From mirko-lists at zeibig.net Thu Jan 8 08:03:47 2004 From: mirko-lists at zeibig.net (Mirko Zeibig) Date: Thu, 08 Jan 2004 14:03:47 +0100 Subject: Descriptor puzzlement In-Reply-To: References: Message-ID: John Roth said the following on 01/08/2004 01:34 PM: > Using Python 2.2.3, I create this script: > > [beginning of script] > > class AnObject(object): > "This might be a descriptor, but so far it doesn't seem like it" > def __init__(self, somedata): > self.it = somedata > def __get__(self, obj, type=None): > print "in get method" > return self.it > def __set__(self, obj, it): > print "in set method" > self.somedata = it > return None > ## def foo(self): > ## return 1 Hm, I don't know __set__ and __get__, there are __getattr__ (or __getattribute__) and __setattr__ for dynamically assigning attributes. Or take a look at properties (http://www.python.org/2.2/descrintro.html#property) > class AnotherObject(object): > def __init__(self): > self.prop = AnObject("snafu") > > myClass = AnotherObject() > print myClass.prop Now just do: print id(myClass.prop) to see the internal reference. > myClass.prop = "foobar" Here you bind an immutable string-object to myClass.prop, the object of type AnObject you have bound before has no further references in the code and will be garbage collected. If you create a destructor for AnObject: def __del__(self): print "%s.__del__" % self you will see that this happens immediately. > print myClass.prop Regards Mirko From mike at mhuffman.com Sat Jan 17 16:13:51 2004 From: mike at mhuffman.com (Mike Huffman) Date: 17 Jan 2004 13:13:51 -0800 Subject: Need to get 8.3 path on Windows References: <100hpmrm74ah548@corp.supernews.com> Message-ID: <3ae9c53d.0401171313.3d49b43@posting.google.com> > >>> import win32api > >>> win32api.GetShortPathName( "C:\Program Files\Internet Explorer" ) > 'C:\\PROGRA~1\\INTERN~1' > >>> Definitely the way to go *IF* you know the user will have Windows Extensions installed. However, if you can only count on a "standard" Python installation you can use the system FOR command on Windows 2K/XP: import sys, os if os.environ['OS'] != 'Windows_NT': print sys.argv[0], 'requires Windows 2000 or Windows XP' sys.exit(1) long_name = 'C:\\Documents and Settings\\All Users\\Start Menu' + '\\Windows Update.lnk' print '%-16s%s' % ('long_name: ', long_name) for_cmd = 'for %I in ("' + long_name + '") do echo %~sI' print '%-16s%s' % ('for_cmd: ', for_cmd) p = os.popen(for_cmd) short_name = p.readlines()[-1] # last line from for command if p.close(): print 'Error calling shell command "for"' else: print '%-16s%s' % ('short_name: ', short_name) If you need to support Windows 98 let me know; I have a script (VBScript) that converts long names to short names using Windows Script Host which I call with popen() as above. Maybe someone has a better way to do it for Win98 without Python Win32 extensions. Mike From swalters_usenet at yahoo.com Mon Jan 5 13:39:00 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 18:39:00 GMT Subject: Progress indicator during FTP upload References: <20040104221012.0cc111a3.no.spam@box> Message-ID: |Thus Spake Christophe Delord On the now historical date of Sun, 04 Jan 2004 22:10:12 +0100| > To update my web site I wrote a script in wich I have overriden ftplib.FTP > to print a dot when a block of bytes is sent. Here is my dot_FTP class : (code snipped) Combine with this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 Salt to taste and serve with red wine. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From eurleif at ecritters.biz Tue Jan 27 21:59:46 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 28 Jan 2004 02:59:46 GMT Subject: Upgrading Python on Red Hat 7.2? Message-ID: I have an ancient server with Red Hat 7.2 and Python 1.5.2. I want to install mod_python, but I'll need a version of python from some time after the stone age to do that. Up2date is broken (missing Python module, go figure), so I can't use that. The latest RPMs seem to be for Red Hat 9, will they work with 7.2? If not, will building from source make versioned binaries only (/usr/bin/pythonX.X instead of /usr/bin/python)? From alan_salmoni at yahoo.com Mon Jan 19 01:11:13 2004 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 18 Jan 2004 22:11:13 -0800 Subject: Python used in Freedom Force References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> <4006911e$0$327$e4fe514c@news.xs4all.nl> Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Alan James Salmoni wrote: > > > >Perhaps all this stuff could be put onto the "Python Success Stories" > >part of the python.org website? It's not public, but if the language > >is clearly being used... > > Currently, due to the load on the webmasters and the available time, > http://www.pythonology.com/ > is better maintained. Send e-mail to the pythonology webmaster to get > something included. Thanks Aahz - I'll get onto it right away! Alan. From rob02omni at vodafone.it Mon Jan 19 04:14:39 2004 From: rob02omni at vodafone.it (Roberto) Date: Mon, 19 Jan 2004 10:14:39 +0100 Subject: How robust is embedding?? References: <874quuthx1.fsf@pobox.com> Message-ID: Thanks for reply and info John. -- Rob "John J. Lee" ha scritto nel messaggio news:874quuthx1.fsf at pobox.com... > "Roberto" writes: > > > I know that surely depend on how robust is my script just wondering if > > anyone is using this in production. > > Yes, people do. Eg., see recent thread on commercial games that embed > Python. Generally, people tent to prefer to extend Python rather than > embed it, though. > > > John From aldo123 at onet.pl Fri Jan 9 04:57:09 2004 From: aldo123 at onet.pl (mic) Date: Fri, 9 Jan 2004 10:57:09 +0100 Subject: win32: internet explorer automation problem References: <874qv670iy.fsf@pobox.com> Message-ID: > I guess you just need to use the usual browser object model (the one > exposed to JavaScript &c.) -- eg. window.focus(), window.blur(). > IIRC, it's IHTMLDocument2, or similar, that you want. I don't think this could work - my piece of code is assumed to be completely separated from the HTML itself. It just 'watches' the MSIE behaviour and simulates the user work. AFAIK opening popup creates another MSIE instance, so I simply loose the context. It'd be perfect if external window will be treated using IHTMLDocument object model, but window object works according to this excerpt from MSDN like this: 'Typically, the browser creates one window object when it opens an HTML document. However, if a document defines one or more frames (that is, contains one or more frame or iframe tags), the browser creates one window object for the original document and one additional window object for each frame' So there is no easy way of doing it like Document.NewWindow.documentelement.outerHTML. There is some ppDisp parameter within OnNewWindow2 event, that looks like some sort of way to go... Michal From rupole at hotmail.com Tue Jan 20 01:29:41 2004 From: rupole at hotmail.com (Roger Upole) Date: Mon, 19 Jan 2004 22:29:41 -0800 Subject: problems with os.path.isdir on windows shares (i've read the FAQ) References: <4489035c.0401161545.75b63ce@posting.google.com> <4489035c.0401190821.bf3ff14@posting.google.com> Message-ID: <400c9cda_3@127.0.0.1> This used to work (1.5.2 maybe ?), and I got bit pretty bad when it stopped. Had a small function to copy a file to either a full path or into a directory, as determined by os.path.isdir. After upgrading, the results weren't pretty the first time I tried to copy a file to a share. I had to replace os.path.isdir(pathname) with win32file.GetFileAttributes(pathname) & win32con.FILE_ATTRIBUTE_DIRECTORY to get around it. Roger "todd smith" wrote in message news:4489035c.0401190821.bf3ff14 at posting.google.com... > "Michel Claveau/Hamster" wrote in message news:... > > Hi ! > > > > \\\\ren\\backup is perhaps no a directory, but the name of a shared > > ressource. > > > > > > > > @-salutations > > > i'm a bit confused as to what you mean by a shared resource. but > \\ren\backup is definately a shared directory, i mkdir'd it myself :) From skip at pobox.com Tue Jan 6 11:34:05 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 6 Jan 2004 10:34:05 -0600 Subject: RELEASED: allout-vim 031229 In-Reply-To: <87d69xawvv.fsf@pobox.com> References: <87d69yqsos.fsf@pobox.com> <95aa1afa.0401060522.630e5cbb@posting.google.com> <87d69xawvv.fsf@pobox.com> Message-ID: <16378.58237.898620.619660@montanaro.dyndns.org> John> michele.simionato at poste.it (Michele Simionato) writes: >> jjl at pobox.com (John J. Lee) wrote in message news:<87d69yqsos.fsf at pobox.com>... >> > Fran?ois Pinard writes: >> > No, actually, a *real* OT comment: I'm pretty sure I've seen two big >> > pieces of code, by two French authors, in which the word "eventually" John> [...] >> "Eventuellement" (or the Italian "eventualmente") >> means "possibly", not "eventually". John> Ah, of course. I was sure I'd looked for a false friend in my John> French dictionary, but I guess I can't have done... Interesting thread I suppose, but in all the messages which have floated by in this thread I never saw a description of what "allout" format is. Can someone describe it or refer me to a URL which does? Thx, Skip From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 16 16:07:27 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 16 Jan 2004 22:07:27 +0100 Subject: Supressing PyChecker warnings References: Message-ID: Jp Calderone: > When using PyChecker on a project which uses bsddb, dozens of messages >like the following are reported: > >warning: couldn't find real module for class > bsddb._db.DBAccessError (module name: bsddb._db) I saw the same thing with PyPgSQL. > I've looked through the PyChecker usage information, documentation, and >browsed some of the source, but I can't find any options for supressing >this. Same here. I'm not even sure if it needs to be supressed, rather than solved. -- Ren? Pijlman From jepler at unpythonic.net Sat Jan 17 18:26:26 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 17 Jan 2004 17:26:26 -0600 Subject: Best way to do this? In-Reply-To: <100jg9er3qak890@corp.supernews.com> References: <100jg9er3qak890@corp.supernews.com> Message-ID: <20040117232625.GA23442@unpythonic.net> def getpass(password, count=3): for i in range(count): p = raw_input("Password: ") if p == password: return 1 return 0 No need to initialize count to 0 and use a while loop, use a "for" loop instead. No need to initialize password above the loop (and if you had to, use None instead of "null"), and no need to set count to 3 when the correct password is entered---just use return or break. Jeff From marco at bubke.de Sun Jan 4 14:19:02 2004 From: marco at bubke.de (Marco Bubke) Date: Sun, 04 Jan 2004 20:19:02 +0100 Subject: Scoped Lock Message-ID: Hi There is the Lock object in the threading module. But there is no medode there I could aquire a scoped lock like: mutex = threading.Lock() my_lock = mutex.scoped_acquire() # maybe scoped_lock() #now this stuff is locked del mylock #the lock is released. def do_domething: my_lock = mutex.scoped_acquire() #now this stuff is locked #the lock is released after its out of scope I have written this my own but I'm not sure there is a drawback because its looks so convinent. So I wonder why its not in the module? thx Marco From jjl at pobox.com Sun Jan 11 09:37:42 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jan 2004 14:37:42 +0000 Subject: OT: Of C, Fortran and pointer aliasing Was: Python if far from a top performer... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: <874qv2lfex.fsf@pobox.com> Samuel Walters writes: > |Thus Spake Rainer Deyke On the now historical date of Sun, 11 Jan 2004 > 06:46:50 +0000| [...] > > The issue with C is that it is too slow for implementing those > > primitives (in part due to pointer aliasing issues). Fortran is > > considerably faster. > > I stand corrected. > > Please help me to understand the situation better. > > I went digging for technical documents, but thus far haven't found many > useful ones. It seems everyone but me already understands pointer > aliasing models, so they might discuss them, but they don't explain them. [...] (haven't read all your post, so sorry if I'm telling you stuff you already know) Pointer aliasing is just the state of affairs where two pointers refer to a single region of memory. Fortran compilers have more information about aliasing than do C compilers, so can make more assumptions at compilation time. Have you tried comp.lang.fortran, comp.lang.c++, comp.lang.c, etc? http://www.google.com/groups?q=pointer+aliasing+FAQ+group:comp.lang.fortran&hl=en&lr=&ie=UTF-8&group=comp.lang.fortran&selm=1992May27.175805.26097%40newshost.lanl.gov&rnum=3 http://tinyurl.com/2v3v5 John From mk at net.mail.penguinista Mon Jan 12 07:57:05 2004 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Mon, 12 Jan 2004 13:57:05 +0100 Subject: xml-rpc for mod_python Message-ID: <400299a1@news.mt.net.mk> Is there any way to make an XML-RPC handler that will work inside mod_python? -- ?????? (jabberID:damjan at bagra.net.mk) The NOC says: echo '16i[q]sa[ln0=aln100%Pln100/snlbx]sbA0D4D465452snlbxq'|dc From d.chirila at bucarest.finsiel.ro Fri Jan 23 04:43:11 2004 From: d.chirila at bucarest.finsiel.ro (Dragos Chirila) Date: Fri, 23 Jan 2004 11:43:11 +0200 Subject: Ordered dictionary? References: Message-ID: <052901c3e195$508b29a0$2f01a8c0@dchirila> Hi Maybe this code will help: import operator def filterList(p_list, p_value): l_len = len(p_list) l_temp = map(None, (p_value,)*l_len, p_list) l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp) return map(operator.getitem, l_temp, (-1,)*len(l_temp)) phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'} names_list = filterList(phones_dict.keys(), 'jan') phones_list = map(phones_dict.get, names_list) print phones_list This extracts from the dictionary the telephone(values) numbers for names(keys) starting with 'jan'... Dragos > Op 2004-01-22, Paul McGuire schreef : > > "Leif K-Brooks" wrote in message > > news:leWPb.231$af7.162835 at newshog.newsread.com... > >> I need to associate a string (key) with an integer (value). A dictionary > >> would do the job, except for the fact that it must be ordered. I also > >> need to look up the value for a specific key easily, so a list of tuples > >> wouldn't work. > >> > > If you really need to access the dictionary in sorted key order, is this so > > difficult? > > > > dKeys = d.keys() > > dKeys.sort() > > for k in dKeys: > > # do stuff with k and d[k], such as: > > print k, "=", d[k] > > > > Or if you are worried about updates to d between the time of key retrieval > > and time of traversal (for instance, if a separate thread were to delete one > > of the keyed entries), take a snapshot as a list: > > > > dItems = d.items() # from here on, you are insulated from changes to > > dictionary 'd' > > dItems.sort() # implicitly sorts by key > > dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer > > for k,v in dItems: > > # do stuff with k and v, such as: > > print k, "=", v # <-- added benefit here of not re-accessing > > the list by key > > Well I too sometimes need the keys in a dictionary to be sorted and your > solutions wouldn't help. The problem is the following. > > I have a number of key value pairs, like names and telephone numbers. > Just more subject to change. Now I want the telephone numbers of everyone > whose name starts with "jan". > > Or I just inserted a name and want to know who is alphabetically next. > Or I want to know who is first or last. > > -- > Antoon Pardon > -- > http://mail.python.org/mailman/listinfo/python-list > From paulpaterson at users.sourceforge.net Sat Jan 31 21:48:49 2004 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Sun, 01 Feb 2004 02:48:49 GMT Subject: ANN: vb2Py 0.2.1 - VB to Python Conversion Message-ID: Version 0.2.1 of vb2py has been released. What is vb2py? ============== vb2py is a toolkit to aid in the conversion of Visual Basic projects to Python. The aim of the conversion is to match, as close as possible, the original VB applications both in terms of code behaviour and form layout. Version 0.2.1 comprises a basic layout converter (converting to PythonCard) with a comprehensive code translation. The project roadmap (http://vb2py.sourceforge.net/roadmap.htm) shows the project's development timeline. Converting VB to Python turns your VB projects into cross platform developments and allows full access to all Python's extensive library of modules. What's new in v0.2.1 ==================== v0.2.1 is a bug fix and minor enhancement version. Quite a large number of Visual Basic functions and keywords were not supported in v0.2 and this is addressed to some extent by this release. The following additional functions were added for this release: Array, ChDir, Choose, Environ, EOF, Erase, FileCopy, FileLen, Filter, FreeFile, IIf, Input, InStrRev, IsArray, Join, Kill, Let, Lof, LSet, LTrim, RTrim, Trim, MkDir, Name, Randomize, Replace, Reset, RGB, RmDir, Rnd, Round, RSet, GetAllSettings, GetSetting, SaveSetting, DeleteSetting, Spc, Split, StrReverse, Switch, Timer. The coverage is still not 100% but if you whave an urgent need for a function it can easily be bumped up the queue! Limitations of v0.2.1 ===================== - Form layout translation is still at the v0.1 level. (target v0.3) - Form event mapping is still primitive (target v0.3) - Error handling, ByRef argument passing, Iterable classes are not currently supported (target v0.4) Getting the Software ==================== * The main website: http://vb2py.sourceforge.net * Download this version: http://vb2py.sourceforge.net/downloads.htm * Documentation: http://vb2py.sourceforge.net/documentation.htm * Online trial: http://vb2py.sourceforge.net/demo.htm Requirements ============ * Python 2.2 or greater * PythonCard (0.7 or greater), wxWindows * simpleparse (2.0.1a3 or greater), mxTextTools * Visual Basic is *not* required (although it would help if you had some VB code ...) Licence ======= vb2py is released under the BSD licence. Release History =============== 0.1 (July 9, 2003) - The first release from the project - a basic form layout translator 0.1.1 (August 1, 2003) - A bugfix release for 0.1 0.2 (September 8, 2003) - The first release with the full VB Parser 0.2.1 (February 1, 2004) - This release Contributors Welcome ==================== This project would not be possible without the help and support of many people. Anyone who wants to get involved is more than welcome to participate in coding, testing, giving advice, etc. Some particular areas of interest right now are, - testing on large VB projects - testing on Mac - testing out with VBScript, VBA In the meantime I would like to thank all those who supported and contributed towards the v0.2.1 release. ---- Paul Paterson vb2py :: A Visual Basic to Python Conversion Toolkit http://vb2py.sourceforge.net From jarausch-remove at igpm.rwth-aachen.de Mon Jan 26 06:12:32 2004 From: jarausch-remove at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 26 Jan 2004 12:12:32 +0100 Subject: raw_input - why doesn't prompt go to stderr Message-ID: Hi when using an interactive Python script, I'd like the prompt given by raw_input to go to stderr since stdout is redirected to a file. How can I change this (and suggest making this the default behaviour) Many thanks for a hint, Helmut Jarausch RWTH Aachen University Germany From igor.NOSPAM at obda.net Thu Jan 29 11:15:17 2004 From: igor.NOSPAM at obda.net (Igor Fedorow) Date: Thu, 29 Jan 2004 17:15:17 +0100 Subject: Python & XML & DTD (warning: noob attack!) References: <40191C49.786AAF89@engcorp.com> Message-ID: On Thu, 29 Jan 2004 15:44:25 +0100, Peter Hansen wrote: > Igor Fedorow wrote: >> >> I have an XML file with an internal DTD which looks roughly like this: >> [snip] >> I want to parse this file into my application, modify the data (this >> includes maybe creating and/or deleting nodes), and write it back into the >> file -- including the DTD. (It doesn't necessarily need validation, >> though.) >> >> I tried xml.dom.ext.PrettyPrint, but it produces only [snip] actually >> lacking the document type definition. >> >> Any help is appreciated! > > Unfortunately I don't know of any way you could generate the DTD again, and > I've never seen a package which supports what you ask for (not that it isn't > possible, mind you). > > On the other hand, are you sure you need the DTD? We use XML in dozens of > ways and absolutely have never benefited from attempts to use DTDs, and > don't appear to suffer from the lack thereof. > > Also, aren't DTDs sort of considered either obsolete or at least vastly > inferior to the newer approaches such as XML Schema, or both? > > So my recommendation is to ditch the DTD and see if any problems arise as a > result. > > -Peter Actually, I don't really *need* it, but I would simply like to have it -- which obviously isn't possible... Anyway, thank you for your help! Cheers =) *igor* From RAV at ns.artphila.com Wed Jan 28 03:31:17 2004 From: RAV at ns.artphila.com (RAV at ns.artphila.com) Date: Wed, 28 Jan 2004 10:31:17 +0200 Subject: RAV AntiVirus scan results Message-ID: <200401280831.i0S8VHLr005586@ns.artphila.com> RAV AntiVirus for Linux i686 version: 8.3.2 (snapshot-20020108) Copyright (c) 1996-2001 GeCAD The Software Company. All rights reserved. Registered version for 2 domain(s). Running on host: ns.artphila.com ----------------------- RAV Antivirus results ----------------------- The infected file was saved to quarantine with name: 1075278677-RAVi0S8VALr005582. The file (part0002:file.zip)->file.pif attached to mail (with subject:MAIL DELIVERY SYSTEM) sent by python-list at python.org to phila at artphila.com, is infected with virus: Win32/Mydoom.A at mm. Cannot clean this file. Cannot delete this file (most probably it's in an archive). The mail was not delivered because it contained dangerous code. ------------------------ this is a copy of the e-mail header: Scan engine 8.11 () for i386. Last update: Tue Jan 27 05:03:51 2004 Scanning for 89279 malwares (viruses, trojans and worms). To get a free 60-days evaluation version of RAV AntiVirus v8 (yet fully functional) please visit: http://www.ravantivirus.com From michael at foord.net Wed Jan 28 11:34:43 2004 From: michael at foord.net (Fuzzyman) Date: 28 Jan 2004 08:34:43 -0800 Subject: Webhosting with Python Message-ID: <8089854e.0401280834.6fd4f972@posting.google.com> I've recently starting using a very cheap web hoster who has python 2.2 installed.... almost free hosting (but not quite)..... Thought some of you guys might be interested.......... http://www.xennos.com 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.voidspace.org.uk/atlantibots/pythonutils.html Pythonutils - home of dateutils, ConfigObj, StandOut, CGI-News and more. From jcarlson at nospam.uci.edu Fri Jan 23 15:07:47 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 12:07:47 -0800 Subject: Server and Client Socket problem In-Reply-To: References: Message-ID: > This code can obviously not run, as its not properly indented. I'm sure that > indentation got somehow lost when you create the posting, but as long as > you don't provide it in a executable fashion, we can't help you. Agreed. > However, as someone beeing recently converted from hand-made socket > programming to twisted, I suggest instead of working with sockets yourself, > you better investigate into the twisted framework. Its very well > documented. After having written both synchronous and asynchronous servers and clients using Python sockets, I've been very happy with the asyncore standard library. I should probably give twisted a shot, but writing with asyncore is so easy that I'm hard-pressed to even bother. I also get a sick satisfaction in implementing protocols...but maybe that is just me. - Josiah From bkc at Murkworks.com Thu Jan 22 09:53:51 2004 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 22 Jan 2004 09:53:51 -0500 Subject: PyCon2004 - Where to stay, which airport? Message-ID: I think this year I might be able to make it to my first Python conference. Cheap flights from Ottawa (2 hour drive), $278 or so to DCA. (but from Massena, 30 minute drive) $1200 to DCA. Thanks FAA Essential Air Service. Anyway, where should I stay that's cheap but not too yucky? I don't mind riding the subway. I might come early for sprints or the Smithsonian. I couldn't find recommended lodgings on the PyCon wiki. Is DCA the correct airport? -- Novell DeveloperNet Sysop #5 _ From lubowiecka at go2.pl Thu Jan 8 10:32:17 2004 From: lubowiecka at go2.pl (Nazgul) Date: Thu, 8 Jan 2004 16:32:17 +0100 Subject: "Interrupted function call" exception while relogging :( References: <4qv6n6ne.fsf@python.net> Message-ID: Uzytkownik "Thomas Heller" napisal w wiadomosci > writes: > Just an idea: you could try to use win32api.Sleep() instead. > > Thomas Thanks! I will try now and let you know if it works for my case... Thanks for reply! Best wishes, Sylwia From james at logicalprogression.net Thu Jan 22 06:37:19 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 22 Jan 2004 11:37:19 +0000 Subject: Converting a string to integer/float In-Reply-To: <2981adb9.0401211943.e1ae272@posting.google.com> References: <2981adb9.0401211943.e1ae272@posting.google.com> Message-ID: <200401221137.19357.james@logicalprogression.net> On Thursday 22 January 2004 3:43 am, Ikot wrote: > Hello, > I am stuck with a problem, might be very trivial, to ask here, but > dont find a way out. I read a string like 12345.678 from a text file, > which will be string for me, but how do I convert it into a float for > my use ? > Thanks > Ikot float is a builtin type that can be constructed from a string: >>> float('12345.678') 12345.678 You'd probably find it helpful to work your way through: http://www.python.org/doc/current/lib/built-in-funcs.html James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From slzatz at hotmail.com Sun Jan 18 18:45:31 2004 From: slzatz at hotmail.com (Steve Zatz) Date: 18 Jan 2004 15:45:31 -0800 Subject: Simple (?) Regular Expression Question Message-ID: <6747bc9d.0401181545.2b4ffb14@posting.google.com> Is '@' a special character in regular expressions? I am asking because I don't understand the following: >>> import re >>> s = ' @' >>> re.sub(r'\b@','*',s) ' @' >>> s = ' a' >>> re.sub(r'\ba','*',s) ' *' Have googled atsign and regular expressions but have not found anything useful. System is Win XP, Python 2.3.3. Any help would be appreciated. From dman at dman13.dyndns.org Fri Jan 2 09:35:03 2004 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Fri, 02 Jan 2004 14:35:03 GMT Subject: Graph in wxPython References: <4f0a9fdb.0312312356.75a4fe15@posting.google.com> Message-ID: On 31 Dec 2003 23:56:09 -0800, Miki Tebeka wrote: > Hello "Oh Kyu Yoon", > >> Does anyone know how to implement plots from scipy, chaco, etc >> into wxPython widget? > > Save them as an image and use wxImage? This works. This past spring I had to implement basic graph generation for a school project I was using wxPython for. I opened a pipe to gnuplot, let it create an image, then displayed the image. -D -- If your life is a hard drive, Christ can be your backup. www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From cygnus at cprogrammer.org Tue Jan 20 16:48:43 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Tue, 20 Jan 2004 16:48:43 -0500 Subject: XML-RPC Message-ID: <20040120214843.GA21585@mail.theserver.ath.cx> I'm using python 2.3.3 (#2, Jan 4 2004, 12:24:16), [GCC 3.3.3 20031229 (prerelease) (Debian)], debian unstable. I have written a client and server program which communicate using the built-in xmlrpclib and SimpleXMLRPCServer. The server starts up fine, and the client can connect to it and issue commands (method calls) just fine. However, after some unknown period of time, the client hangs at the time of the method call, during which time netstat reports: recv send tcp 307 0 127.0.0.1:9000 127.0.0.1:35496 ESTABLISHED Once I break the client and run netstat again, I get: tcp 307 0 127.0.0.1:9000 127.0.0.1:35496 CLOSE_WAIT And lines such as these hang around in netstat's output for quite some time (several are there now, left over from attempts to run the client about 8 hours ago). I haven't been able to identify exactly when this starts to occur or why. Sometimes it happens soon after starting the server; sometimes it takes days. The server is multi-threaded. The XML-RPC thread is the main thread. Proper locking mechanisms are used and I have been able to determine that deadlock is not an issue. Does anyone have any ideas? Thanks! -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 24 06:19:10 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 24 Jan 2004 12:19:10 +0100 Subject: efficient matching of elements a list References: Message-ID: omission9: >Suppose I have a lists of tuples >What is the fastest way in python to get out all the tuples from the >list whose first element is equal to i? A list is not an efficient data structure for this query. Why don't you design another data structure? -- Ren? Pijlman From gerrit at nl.linux.org Thu Jan 15 09:22:48 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 15 Jan 2004 15:22:48 +0100 Subject: super. could there be a simpler super? In-Reply-To: References: Message-ID: <20040115142248.GA4189@nl.linux.org> Kristian Ovaska wrote: > Kerim Borchaev : > > Is it possible that such a "super"(deducing class method declaration > > context) could appear in Python? > > (It seems to me that to implement a simple super something should be > > done during "compilation" of class declaration.) > > The document "Unifying types and classes in Python 2.2" by Guido > probably answers your question. > > Quote from http://www.python.org/2.2.3/descrintro.html#cooperation > regarding super: > > "It would be nice if we didn't have to name the class explicitly, but > this would require more help from Python's parser than we can > currently get. I hope to fix this in a future Python release by making > the parser recognize super." Another quote from the same page :) : --- start quote --- Our second example creates a class, 'autosuper', which will add a private class variable named __super, set to the value super(cls). (Recall the discussion of self.__super above.) Now, __super is a private name (starts with double underscore) but we want it to be a private name of the class to be created, not a private name of autosuper. Thus, we must do the name mangling ourselves, and use setattr() to set the class variable. For the purpose of this example, I'm simplifying the name mangling to "prepend an underscore and the class name". Again, it's sufficient to override __init__ to do what we want, and again, we call the base class __init__ cooperatively. class autosuper(type): def __init__(cls, name, bases, dict): super(autosuper, cls).__init__(name, bases, dict) setattr(cls, "_%s__super" % name, super(cls)) Now let's test autosuper with the classic diamond diagram: class A: __metaclass__ = autosuper def meth(self): return "A" class B(A): def meth(self): return "B" + self.__super.meth() class C(A): def meth(self): return "C" + self.__super.meth() class D(C, B): def meth(self): return "D" + self.__super.meth() assert D().meth() == "DCBA" (Our autosuper metaclass is easily fooled if you define a subclass with the same name as a base class; it should really check for that condition and raise an error if it occurs. But that's more code than feels right for an example, so I'll leave it as an exercise for the reader.) --- end quote --- yours, Gerrit. -- 164. If his father-in-law do not pay back to him the amount of the "purchase price" he may subtract the amount of the "Purchase price" from the dowry, and then pay the remainder to her father's house. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From johnbenson at fairisaac.com Tue Jan 27 21:51:02 2004 From: johnbenson at fairisaac.com (Benson, John) Date: Tue, 27 Jan 2004 18:51:02 -0800 Subject: Oracle beginner problem: can't connect to Oracle using cx_Oracle Message-ID: <1EDE1E01D95DBE48BB06385C08CEFA7604090A34@sdomsg00.corp.fairisaac.com> Hi, I'm a non-Oracle guy just starting to use Python to explore Oracle. I enclose the Python command prompt log for the usage example further down with only the user, password and host names changed to keep me out of trouble. But first, I'd like to point out that I'm able to logon to myhost, and get into the following via SQL*Plus using myuser/mypassword Oracle8i Enterprise Edition Release 8.1.7.3.0 - Production With the Partitioning option JServer Release 8.1.7.3.0 - Production (end quote of Unix box SQL*Plus stuff) so I know that myuser/mypassword works for SQL*Plus on the myhost Unix box. I downloaded the cx_Oracle Python interface to Oracle(r) Version: 4.0 Date: December 17, 2003 Win32 binary for Oracle 8i, Python 2.) and proceeded to exercise the usage example: PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import cx_Oracle >>> connection = cx_Oracle.connect("myuser/mypassword at myhost") Traceback (most recent call last): File "", line 1, in ? DatabaseError: ORA-12514: TNS:listener could not resolve SERVICE_NAME given in connect descriptor >>> (end usage example quote) Any ideas as to what the problem is? Thanks in advance for the usual valuable and pertinent advice I have come to expect from this forum. John Benson jsbenson at bensonsystems.com From pythonguy at Hotpop.com Thu Jan 1 02:01:47 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 31 Dec 2003 23:01:47 -0800 Subject: Graph in wxPython References: Message-ID: <84fc4588.0312312301.68d0a717@posting.google.com> This might be helpful. http://starship.python.net/crew/jhauser/plot-res.html -Anand "Oh Kyu Yoon" wrote in message news:... > Does anyone know how to implement plots from scipy, chaco, etc > into wxPython widget? > > Thank you From bmgx_no_sp at mgleesonprop.co.za Thu Jan 8 05:48:10 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Thu, 08 Jan 2004 12:48:10 +0200 Subject: creating a daemon? Message-ID: <3ffd355c.0@news1.mweb.co.za> This is what I am trying to find out, instruction on how to create a simple daemon on unix systems(Linux), can't find any info on usual sources.. From gulliver at atr.co.jp Sat Jan 24 01:50:28 2004 From: gulliver at atr.co.jp (Roberto Lopez-Gulliver) Date: 23 Jan 2004 22:50:28 -0800 Subject: Psyco on PowerPC? References: <30E0BEC9-4DE7-11D8-B663-000393DB5438@andrew.cmu.edu> Message-ID: <26b7aa41.0401232250.3e6588a8@posting.google.com> Hi Ben, Directly from Armin http://codespeak.net/pipermail/pypy-dev/2003q3/002219.html Haven't try it myself though. Please post here any success/failure you may experience in Mac OSX. Hope this helps. --roberto Han Benjamin wrote in message news:<30E0BEC9-4DE7-11D8-B663-000393DB5438 at andrew.cmu.edu>... > Is anyone aware of any effort in bringing Psyco onto other platforms, > esp. PowerPC (Mac OS X)? I checked the website but it's still stated as > X86 only. > > Thanks, > > Ben From 2002 at weholt.org Thu Jan 15 11:41:08 2004 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 15 Jan 2004 17:41:08 +0100 Subject: Python and CVS: several modules, one namespace Message-ID: This might be slightly off-topic, but I'll ask anyway: I want to import several modules into my cvs-repository, but I want them all to be in the same namespace when they're checked out. For instance, I got these modules foo1.py, foo2.py, foo3.py in the namespace bar, called like so : from bar import foo2, foo3 This matched the folder-structure ../bar/foo2, ../bar/foo3 on the filesystem. But I need to import them as foo1, foo2 and foo3. When checked out they should all be available in the same namespace without having to create the folder, __init__.py first. Is this possible? When I check out foo1 it creates ../bar/foo1, when I check out foo2 in the same folder it creates foo2 etc. without messing up the CVS-folders .... ( Hm ... when I look at the whole thing now, it seems impossible ) Any hints or clues on how to manage different modules in the same namespace when importing them into CVS ??? My main goal is to have one namespace for all my modules. Please tell me if this doesn't make any sense. Thanks in advance, Thomas Weholt From peter at engcorp.com Tue Jan 27 17:47:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Jan 2004 17:47:12 -0500 Subject: Portable /dev/null? References: Message-ID: <4016EA70.7B7C5D67@engcorp.com> Nicolas Fleury wrote: > > Is there an object in some standard library that would be the portable > equivalent of "file('/dev/null','w')" or do I have to create my own > class and object to do it? If it doesn't exist, do you think it would > be a good idea to have such an object in a standard library? Probably considered too simple to bother putting in the standard library. class nullFile: def write(self, data): pass >>> n = nullFile() >>> print >>n, "this goes nowhere" Or something to that effect... -Peter From johnfabel at btinternet.com Sat Jan 31 16:57:47 2004 From: johnfabel at btinternet.com (John Abel) Date: Sat, 31 Jan 2004 21:57:47 +0000 Subject: TCP server as a Windows service using Python? In-Reply-To: References: Message-ID: <401C24DB.1020104@btinternet.com> I don't know if this will be of use to you. Here's a snip of code, that I used to run a web server as a service. It uses my custom module based on SimpleHTTPServer, but you get the idea. HTH J def SvcDoRun( self ): threadEvent = threading.Event() threadEvent.set() webUI = httpWebService( threadEvent ) webUI.start() win32event.WaitForSingleObject( self.hWaitStop, win32event.INFINITE ) threadEvent.clear() webUI.join() class httpWebService( threading.Thread ): def __init__( self, eventNotifyObj ): threading.Thread.__init__( self ) self.notifyEvent = eventNotifyObj def run ( self ): serverPort = 10080 SimpleHTTPServer2.SimpleHTTPRequestHandler.documentRoot = "F:\Temp\HTTPR oot" httpServer = SimpleHTTPServer2.HTTPServer( ('', serverPort), SimpleHTTPS erver2.SimpleHTTPRequestHandler ) httpServerWait = httpServer.fileno() while self.notifyEvent.isSet(): httpReady = select.select( [httpServerWait], [], [], 1) if httpServerWait in httpReady[0]: httpServer.handle_request() David Mitchell wrote: >Hello group, > >I'm trying to create a TCP server using Python, and I want it to run under >Windows as a service. > >Now, I'm fine with building the TCP server using Python - done it lots of >times, and I know there's lots of sample code out there I can grab if I >ever need to. > >Equally, I think I've got the simpler concepts about creating Windows >services using Python clear. I've got the Python Win32 book, worked >through the example code in there and haven't had any real problems with >it. > >Where I'm having trouble is with the overlapped I/O call. When I create a >TCP server, I need to have it sit there waiting for a client >connection. With a Windows service, it has to sit there waiting for >administrative messages such as e.g. a "stop service" message. The >example code in the Python Win32 book uses named pipes to do IO - >I'm constrained to using TCP sockets. > >I can't see how to let the service accept *either* an incoming TCP client >connection *or* an e.g. "stop service" message. If someone could point me >to some sample code, I'd greatly appreciate it - Google hasn't been >helpful. > >Thanks in advance > >Dave M. > > From piedmontbiz at aol.com Fri Jan 9 09:18:30 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 09 Jan 2004 14:18:30 GMT Subject: Bruce Eckel example / CGI server for localhost for Windows XP References: <3ffeaac9$0$321$e4fe514c@news.xs4all.nl> Message-ID: <20040109091830.29446.00002360@mb-m02.aol.com> de Jong website great. I get errors though when I click any link. """""" Exception in server Page "/index2.y" caused an error: session is transported to different remote address Traceback (innermost last): File "/home/promozilla/Server/snakeserver/webapp.py", line 410, in run_Ypage_GET self.pageEngine.addPageVars(page, self, req, resp) File "/home/promozilla/Server/snakeserver/YpageEngine.py", line 123, in addPageVars session=webapp.addSessionCookie(request,response) File "/home/promozilla/Server/snakeserver/webapp.py", line 486, in addSessionCookie session.setRequestData(request,response) File "/home/promozilla/Server/snakeserver/websession.py", line 31, in setRequestData raise ValueError("session is transported to different remote address") ValueError: session is transported to different remote address """ From theller at python.net Tue Jan 13 13:38:27 2004 From: theller at python.net (Thomas Heller) Date: Tue, 13 Jan 2004 19:38:27 +0100 Subject: Py2Exe and Outlook (array bounds change!?) References: <982e9537.0401130858.4d37dae5@posting.google.com> Message-ID: hlubocky at uiuc.edu (Brian Hlubocky) writes: > This one is really puzzling me. I am not that familiar with COM or > py2exe, but I have tested this a fair amount and am pretty sure of > what I am about to explain. The MSDN website says that the item list > in Outlook has array bounds from 1 to length. Using this information, > I wrote a program that adds contacts to outlook using an external > database. When I went to try this out with py2exe however, I got an > exception. > > What I found out is that when using py2exe, the bounds on the items > list changes from 1 to len, to 0 to len-1. Does anyone have any idea > why this might be? It seems goofy that this would happen. Testing is > on the developer machine, so I don't think different dlls could be the > problem. Thanks! Just a wild idea: can it be that you're using makepy generated modules in the script, and late bould com in the py2exe'd file? Thomas From peter at engcorp.com Thu Jan 29 09:41:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Jan 2004 09:41:14 -0500 Subject: "static" checking References: <160Sb.19106$fo1.10783@newssvr25.news.prodigy.com> Message-ID: <40191B89.DE149A45@engcorp.com> Moosebumps wrote: > > I'm wondering what kind of checking I can do on a python program before > running it (besides reading over every line). I hate running a long python > script, only to have it fail at the end because I misspelled a function > name, or made some other silly mistake that a compiler would normally catch. > Then I have to run it all over again to see what happened or come up with > some sort of short test. > > I usually do try to isolate the new parts of my code, and run them first > with some dummy data that will run fast. But that is not always possible > because of dependencies, and it would be nice to have some sort of sanity > check up front. These issues largely go away once you start doing test-driven development. See, for example, Mark Pilgrim's excellent introduction in his book at http://www.diveintopython.org/ (see the link under "unit testing"), or Kent Beck's paper book "Test-Driven Development" (published by Addison Wesley). With this approach, your code generally won't have those dependencies (sometimes the approach has to be tried before someone can really believe that, but it's true) and you find your spelling mistakes, and many other problems that static checking can't find, in seconds without no more effort than it takes to run a batch file. -Peter From lubowiecka at go2.pl Tue Jan 27 14:07:50 2004 From: lubowiecka at go2.pl (Ringwraith) Date: Tue, 27 Jan 2004 20:07:50 +0100 Subject: python service running on Win Xp, but failing on Win NT Workstation :( References: Message-ID: Thanks Mark! From sombDELETE at pobox.ru Sat Jan 3 15:21:05 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 3 Jan 2004 23:21:05 +0300 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Sean R. Lynch" wrote in message news:LmmdnUn4seDeGWuiXTWc-w at speakeasy.net... > I've been playing around with Zope's RestrictedPython, and I think I'm > on the way to making the modifications necessary to create a > capabilities-based restricted execution system. The idea is to strip out > any part of RestrictedPython that's not necessary for doing capabilities > and do all security using just capabilities. > > The basic idea behind capabilities is that you don't give any piece of > code you don't trust a reference to something you don't want it to have > access to. You use proxies instead (E calls them "facets"). "Don't give" sounds good in theory but fails in practice. You can't prevent leakage 100%, so any security system _must_ help programmer to keep trusted data away from untrusted code. Do you know that rexec failed exactly because it didn't help to prevent leakage? > > In order to be able to allow untrusted code to create proxy objects, I > needed to be able to store a reference to the proxied object in a > private attribute. > > To create private attributes, I'm using "name mangling," where names > beginning with X_ within a class definition get changed to > __, where the UUID is the same for that class. The UUIDs > don't need to be secure because it's not actually possible to create > your own name starting with an underscore in RestrictedPython; they just > need to be unique across all compiler invocations. This is a problem: you declare private attributes whereas you should be declaring public attributes and consider all other attributes private. Otherwise you don't help prevent leakage. What about doing it this way: obj.attr means xgetattr(obj,acc_tuple) where acc_tuple = ('attr',UUID) and xgetattr is def xgetattr(obj,acc_tuple): if not has_key(obj.__accdict__,acc_tuple): raise AccessException return getattr(obj,acc_tuple[0]) __accdict__ is populated at the time class or its subclasses are created. If an object without __accdict__ is passed to untrusted code it will just fail. If new attributes are introduced but not declared in __accdict__ they are also unreachable by default. > > The nice thing about using this name mangling is that it's only done at > compile time and doesn't affect runtime performance. An interesting side > effect is that code defined on a class can access private attributes on > all descendants of that class, but only ones that are defined by other > code on that class, so this isn't a security issue. > > I was thinking I needed read-only attributes to be able to avoid > untrusted code's being able to sabotage the revoke method on a proxy > object, but I'm thinking that just keeping around a reference to the > revoke method in the original code may be enough. > > Does anyone think I'm going in completely the wrong direction here? Am I > missing anything obvious? It depends on what type of security do you want. Did you think about DOS and covert channels? If you don't care about that, yeah, you don't miss anything obvious. you should worry whether you miss something non-obvious. By the way, did you think about str.encode? Or you are not worried about bugs in zlib too? -- Serge. From jangseungwook at nate.com Tue Jan 13 21:27:41 2004 From: jangseungwook at nate.com (jang, seungwook) Date: 13 Jan 2004 18:27:41 -0800 Subject: When I installed Silva-0.9.3 and restart Zope, I found ImportError like this - cannot import name ExpatError - Message-ID: [root at orange Zope-2.6.2-linux2-x86]# ./start ------ 2004-01-14T09:12:19 INFO(0) zdaemon Started subprocess: pid 14941 ------ 2004-01-14T09:12:38 ERROR(200) Zope Could not import Products.SilvaDocument Traceback (innermost last): File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/OFS/Application.py, line 522, in impor t_product File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Products/SilvaDocument/__init__.py, li ne 7, in ? File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Products/SilvaDocument/EditorSupportNe sted.py, line 10, in ? ImportError: cannot import name ExpatError ------ 2004-01-14T09:12:38 PANIC(300) z2 Startup exception Traceback (innermost last): File /usr/local/zope/Zope-2.6.2-linux2-x86/z2.py, line 585, in ? File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Zope/__init__.py, line 46, in startup (Object: startup) File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Zope/App/startup.py, line 45, in start up File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/OFS/Application.py, line 500, in impor t_products File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/OFS/Application.py, line 522, in impor t_product File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Products/SilvaDocument/__init__.py, li ne 7, in ? File /usr/local/zope/Zope-2.6.2-linux2-x86/lib/python/Products/SilvaDocument/EditorSupportNe sted.py, line 10, in ? ImportError: cannot import name ExpatError Please Help Me ~ S.W. Jang From Pieter.Claerhout at Creo.com Fri Jan 9 09:51:08 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Fri, 9 Jan 2004 15:51:08 +0100 Subject: Twisted or Medusa or Zope Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D67@cseexch01.cse.creoscitex.com> The right address for Snakelets is: http://snakelets.sourceforge.net Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Peter Hansen [mailto:peter at engcorp.com] Sent: 09 January 2004 15:44 To: python-list at python.org Subject: Re: Twisted or Medusa or Zope Robin Becker wrote: > > In article <3FFEB6D6.BF92551E at engcorp.com>, Peter Hansen > writes > .. > ... > >enlighten me. > > > >Thomas, you're completely ON track here... I just wanted to emphasize that > >Twisted is much more polished and sophisticated. I'd even have to say, > >as a programmer using them, that Twisted does actually provide a simpler and > >cleaner API. It and Medusa are much closer in concept than either is to > >Zope, though, as you say. > > > In another thread http://snakelets.sf.org was mentioned. I get at least a temporary "server not found" error when I try that name. In any case, anything added on top of Twisted and Medusa are, of course, not Twisted and Medusa. Zope is added on top of Medusa, and doubtless there are and will be many things added on top of Twisted, some of which may be similar in purpose to Zope (specifically, content-management systems rather than just frameworks for application writing). -Peter -- http://mail.python.org/mailman/listinfo/python-list From alan.gauld at blueyonder.co.uk Sat Jan 24 12:56:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat, 24 Jan 2004 17:56:10 -0000 Subject: [Tutor] there is no exitfunc in sys module References: <20040124080753.97159.qmail@web61109.mail.yahoo.com> Message-ID: <005501c3e2a3$59bb0040$6401a8c0@xp> > i was reading the manual for sys module. i found a > description for a function known as exitfunc.... > interpreter exits. but when i try to call this > function on Python interactive prompt it says there is > no attribute named exitfunc in sys module. Doing help(sys) yields this: exitfunc -- if sys.exitfunc exists, this routine is called when Python exits Assigning to sys.exitfunc is deprecated; use the atexit module instead. So the note tells us that exitfunc does not exist by default you have to create it. However it also tells us that this is deprecated - ie old fashioned and becoming obsolete - you should use atexit instead However just to illustrate how exitfun can be used: >>> import sys >>> def f(): print "GOOOODBYEEEE!" ... >>> sys.exitfunc = f >>> sys.exit() GOOOODBYEEEE! So you assign a function to sys.exitfunc and when you call sys.exit() to exit it in turn calls your exit function. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From peter at engcorp.com Thu Jan 22 19:10:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Jan 2004 19:10:40 -0500 Subject: strtotime? References: <40105afb$0$319$e4fe514c@news.xs4all.nl> Message-ID: <40106680.849ADEFA@engcorp.com> Leif K-Brooks wrote: > > Irmen de Jong wrote: > >> PHP has a very nice strtotime function (http://php.net/strtotime) > >> which converts a date/time in virtually any format into a timestamp. > >> Does Python have a similar function? > > > > I guess you're looking for: time.strptime > > Thanks, but no. PHP's strtotime() function magically guesses the format > on its own, time.strptime() just uses a fixed format. Perhaps the mx.DateTime package would help: >From http://www.lemburg.com/files/python/mxDateTime.html: ------------------------------ DateTimeFrom(*args,**kws) Constructs a DateTime instance from the arguments. This constructor can parse strings, handle numeric arguments and knows about the keywords year,month,day,hour,minute,second. It uses type inference to find out how to interpret the arguments and makes use of the Parser module. ------------------------------ -Peter From cherico at bonbon.net Thu Jan 29 13:41:51 2004 From: cherico at bonbon.net (cherico) Date: 29 Jan 2004 10:41:51 -0800 Subject: read() on tempfile Message-ID: from tempfile import * f = NamedTemporaryFile () f = write ( 'test' ) print f.read () #here print nothing why is it nothing to read()? I suppose f is of mode 'w+' From mhammond at skippinet.com.au Mon Jan 26 00:01:26 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 26 Jan 2004 16:01:26 +1100 Subject: ReadDirectoryChangesW (windows) In-Reply-To: References: Message-ID: Ognen Duzlevski wrote: > Hi all, > > I am new to win32 programming and was wondring if anyone can enlighten me on a question I have: > > there is a win32file function I would like to use - ReadDirectoryChangesW() and its parameters are, according to > below: > > ---- > ReadDirectoryChangesW(handle, size, bWatchSubtree, dwNotifyFilter, overlapped) > > retrieves information describing the changes occurring within a directory. > > Parameters: > > handle : int > Handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right. > > size : int > Size of the buffer to allocate for the results. > > bWatchSubtree : int > Specifies whether the ReadDirectoryChangesW function will monitor the directory or the directory tree. If TRUE is > specified, the function monitors the directory tree rooted at the specified directory. If FALSE is specified, the > function monitors only the directory specified by the hDirectory parameter. > > dwNotifyFilter : int > Specifies filter criteria the function checks to determine if the wait operation has completed. This parameter can be > one or more of the FILE_NOTIFY_CHANGE_* values. > > overlapped=None : PyOVERLAPPED > Must be None > ------ > > I would like to use this function asynchronously to open a directory using the FILE_FLAG_OVERLAPPED flag so that I can > later on wait for a change to be signalled and so that I can use this in a service waiting with e.g. > WaitForSingleObject(). > > I don't have much experience using pywin32 and I am puzzled by the last line "Must be None". Does this mean > asynchronous access is not supported? Or am I ready to actually RTFM if someone can politely point me to one? :) I'm afraid it is not yet supported. Patches gratefully accepted (and I am willing to help) :) Mark. From carroll at tjc.com Mon Jan 26 15:53:44 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon, 26 Jan 2004 20:53:44 GMT Subject: Newbie Nested Function Problem References: <52d610h685a613ua1tk5k8f11cv1d61q0b@4ax.com> <9%GQb.77000$Su5.22817@twister.nyroc.rr.com> Message-ID: <4kra10pntvn274ilp0mgirfl7tldmh9noe@4ax.com> On Sun, 25 Jan 2004 03:47:17 GMT, "Brian Samek" wrote: >I don't understand what you're saying. I designed the program as three >functions nested within each other. Are you saying I should be designing it >differently? Yes. There are some sometimes good reasons to have a recursive function (i.e., a function that calls itself), but they don't seem applicable here. > I made it a series of nested functions because, for example, I >needed to use the "number" variable from ask_number before it was destroyed. >When a function ends, any variables it has created are destroyed. The standard way to do that is to return the variable to the caller, which then uses it. Here, let me give you an example of how to approach something like this. I'm going to try to re-use as much of your logic code as possible, so we can concentrate on the structure rather than the detail pieces. In practice, I'd code it somewhat differently, but I don't want to go there right now. (We can talk about that after we get the structure down, if you like.) You basically have four elements needed here: 1) an "ask_number" function to find out the number entered by the user; 2) a "countdown" function to do the countdown; 3) a function to ask if the user wants to repeat or leave (One change I made here is the name; I'll discuss that in a second); 4) a main routine that puts these all together. Here's an example of how to do the first function, ask_number: def ask_number(): answerOK = False while not answerOK: number = input("Please enter a number.\n") if number > 500 or number - int(number) != 0 or number < 1: print "Input positive integers less then 501 only, please." else: answerOK = True return number The variable "answerOK" controls whether you have a legitimate answer or not. It starts out false, but goes true when the user answers with a number that meets your requirements. Once it's true, it returns that number to the caller. So the caller can just say: x = ask_number() and he's pretty much assured to get a number meeting your specification, i.e., between 1 and 500. Again, I'd use a different test for the if statement and a few other things, but I wanted to preserve as much of your approach as possible. Now, let's move on to element 2, the countdown. Your code pretty much basically works as is: def countdown (number): while number != 0: print number number = number - 1 There are more Pythonic ways to do this, but let's leave this be. Now, element 3, the function to ask if the user wants to repeat or leave; I've made a trivial but important (I think) change here. You called it "leave", but the user types 'y' if he *doesn't* want to leave, and 'n' if he does want to leave. It makes more sense to describe (and name) the function not in terms of whether the user wants to leave, but rather whether he wants to continue. Also, since the function doesn't actually do the leaving (or continuing) but just asks the question and finds out, t makes sense to name it something that reflects that (as you did with "as_number"). So, I've renamed the function to "ask_continue" instead of "leave". Again, I'd code this a little differently, but leaving as much of your code intact, you can come up with something like this: def ask_continue(): answerOK = False while not answerOK: continue_answer = raw_input ("Type 'y' to start over - type 'n' to exit. ") if continue_answer == "y": answerOK = True elif continue_answer == "n": answerOK = True else: print "Type either 'y' or 'n' please." return continue_answer Same idea here; "answerOK" is a variable that indicates whether you've gotten a legit answer, and once you do, it returns it. Now, to put it all together, you need that fourth element, the main program that uses all of these. Now that you've got the blocks, the main program is pretty straightforward: def main(): repeat = "y" while repeat == "y": limit = ask_number() countdown(limit) repeat = ask_continue() This is basically a big loop that repeats until the value of "repeat" is something other than "y". The end result here is that, when you're working on the main program, you can really forget about how the functions work internally. All you have to remember is what each one returns. And, as you work on each function, you don't have to worry about the other functions at all. When you are writing "ask_number" for example, you can make as many changes to it as you want, and never have to fear that you'll break something in "countdown," or in the main program. And, if you later write another program that needs a prompt for that type of number, you can just copy this function out and use it. These two features, code reuse and code isolation, are the major reasons to use functions. With the approach you originally posted, the code of the functions are so interwoven, that you don't get either. You can't work on that version of your program other than as a big mass. By breaking it down, you've got a bunch of small easy-to-solve problems, which you can approach individually. Now, none of the above is gospel, and for each function, there are a lot of ways to approach it, and Python has some features that would suggest approaching them in certain ways (what we call "pythonic") that I haven't done here (because I don't want to throw that at you right now). For purposes of this post, don't concentrate too much on how each function works; look at how the problem has been broken down and how hote solution has been structured. Hope this helps. From gerrit at nl.linux.org Sun Jan 25 09:49:25 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 25 Jan 2004 15:49:25 +0100 Subject: compress string of data In-Reply-To: References: Message-ID: <20040125144924.GA30813@nl.linux.org> > How i could compress string of data?. >>> import zlib >>> zlib.compress("Hello, world") 'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' http://www.python.org/doc/current/lib/module-zlib.html Gerrit. From jepler at unpythonic.net Thu Jan 1 22:24:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 1 Jan 2004 21:24:06 -0600 Subject: undo and redo ? In-Reply-To: <20040102023847.78427.qmail@web21326.mail.yahoo.com> References: <20040102023847.78427.qmail@web21326.mail.yahoo.com> Message-ID: <20040102032406.GA8304@unpythonic.net> On Thu, Jan 01, 2004 at 06:38:47PM -0800, black wrote: > I'm coding with Tkinter and i wonder whether we could get current OS' clipboard available You're looking for the clipboard_* and selection_* methods of widget objects. I've never worked extensively with this, but instead I usually rely on the way they're handled by the default bindings (which are quite adequate on Unix, but less so on Windows where people are accustomed to having cut/copy/paste on the menu, toolbar, and context-menu) Jeff From andre.bernemann at gmx.de Sun Jan 18 17:50:32 2004 From: andre.bernemann at gmx.de (Andre Bernemann) Date: Sun, 18 Jan 2004 23:50:32 +0100 Subject: Python COM Server with C++ References: Message-ID: <6j2fub.c5d.ln@royal.privat.local> Thank you very much for the help, I got it working with ctypes. Cheers Andr? From mwh at python.net Mon Jan 19 06:05:29 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 19 Jan 2004 11:05:29 GMT Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: Samuel Walters writes: > | Eddie Corns said | > > The next step is to read "Structure and Interpretation of Computer Programs" > > aka SICP and start all over again, in terms of "clearer conceptual vantage > > point" it just can't be beat. It's even availabe online somewhere. > > Here: > http://mitpress.mit.edu/sicp/full-text/book/book.html > > It's the major reason I'm learning scheme. > I just don't stop hearing good things about this book. Well, when you think you want a loop and before you know it you've written: (define (my-func arg1 arg2) (define (inner var) ... it's probably time to come back to a less spartan programming language. I mean, it's good to know that you *can* write loops that way, but that doesn't mean it actually *is* a good idea. Cheers, mwh -- MARVIN: Oh dear, I think you'll find reality's on the blink again. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From computer.problemen at skynet.be Sat Jan 10 14:26:52 2004 From: computer.problemen at skynet.be (broebel) Date: Sat, 10 Jan 2004 20:26:52 +0100 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> <40004743@usenet01.boi.hp.com> Message-ID: <40005064$0$1162$ba620e4c@news.skynet.be> If you look at this as a homework or not is of no interest to me but I like the way you explained which way to go to find the resolution. thanks (i solved it in a jiffy now) "djw" schreef in bericht news:40004743 at usenet01.boi.hp.com... > As this is obviously a class assignment of some sorts, I don't know how much > help you are going to get (or should get) in directly writing the code. > But, what I will say is that you should be able to look at the way the code > works now, how it keeps track of how many bills are needed for each > denomination (200, 100, etc), and apply the same idea to the total number > of bills required using another variable that is initialized before the > loop begins. > > -d > > > broebel wrote: > > > hey, > > > > for the real programmers amongst you, this may be really annoying but I've > > been learning the language for only two days. > > > > this is my problem, > > in this programm,which already works I now have to make a total count of > > how many coins are used. > > this program gives the total per coin. It should be a small peace of code > > (as explained in a tutorial i read, without the answer.)that counts the > > total of all the coins. > > I ve been searching for two days and for this kind of programm it really > > seems kind of long. > > > > thanks in advance > > > > # Een bedrag gepast betalen met zo min mogelijk euromunten > > > > bedrag = input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) > > > > for munt in 200, 100, 50, 20, 10, 5, 2, 1 : > > aantal = 0 > > > > while bedrag >= munt : > > aantal = aantal + 1 > > bedrag = bedrag - munt > > > > if aantal > 0 : > > print aantal, 'x', munt > > > > what i need is: > > for example > > the programm gives > > 68= 50*1 > > 10*1 > > 5*1 > > 2*1 > > 1*1 > > I need an additional code to get the "5" total of all the coins together. > From mhammond at skippinet.com.au Sat Jan 31 21:29:38 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 01 Feb 2004 13:29:38 +1100 Subject: Problems embedding Python In-Reply-To: References: Message-ID: Psymaster wrote: > I've tried running scripts from the embedded interpreter but it doesn't > work. If I try the same scripts as strings to interpret it works. Here > is my program: ... > This compiles and links under MSVC 6 but when run crashes. Any help? You are almost certainly not linking with the correct CRTL. You *must* use the /MD compiler option for release builds, or /MDd for debug builds. Mark. From mwilson at the-wire.com Mon Jan 19 08:31:28 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 19 Jan 2004 08:31:28 -0500 Subject: Best way to do this? References: <100jg9er3qak890@corp.supernews.com> Message-ID: In article <100jg9er3qak890 at corp.supernews.com>, Wil Schultz wrote: >I am reading the "Non-Programmers Tutorial For Python" by Josh Cogliati >http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html > >One of the exercises asks for a program to ask for a password three >times. Surprisingly this took me much longer that it probably should >have so I am curious if the following is the easiest way this is done. > >************************************************* >#!/usr/local/bin/python > >count = 0 >password = "null" > >while count < 3: > count = count + 1 > password = raw_input("what's the pass: ") > if password == "mypass": > print "Access Granted" > count = 3 > else: > if count < 3: > print "Try Again" > else: > print "Too Bad" >************************************************* The "obscure" for/else can help: def get_password (prompt): for i in (1, 2, 3): password = raw_input (prompt) if password == 'mypass': return True else: print "Try Again" else: print "Too Bad" return False Regards. Mel. From ben.m.davies at baesystems.com Wed Jan 14 09:32:34 2004 From: ben.m.davies at baesystems.com (Ben Davies) Date: Wed, 14 Jan 2004 14:32:34 -0000 Subject: pulling set of unique values from a list Message-ID: <400551c0$1@baen1673807.greenlnk.net> I need to get [1,2,3] from [1,1,1,2,2,3,3] with as little effort possible for my CPU (and keyboard). I'd half expected there to be a list.values method to do this, but there isn't so I've have had to use a dictionary object: >>> l=[1,1,1,2,2,2,3,3,3] >>> dict.fromkeys(l).keys() [1, 2, 3] of course another way would be to do it 'by hand' like this: >>> l=[1,1,1,2,2,2,3,3,3] >>> values=[] ... for v in l: ... if not v in values: values.append(v) >>> values [1, 2, 3] personally I prefer the dictionary one-liner, but with the second iterative way it is probably more obvious what the code is doing (and perhaps more efficient?). Is there any better way to do this that I've missed, I was kind of surprised not to find a values() method on the built-in list type? From jepler at unpythonic.net Sat Jan 31 11:14:27 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 31 Jan 2004 10:14:27 -0600 Subject: Python vs. Io In-Reply-To: <711c7390.0401301710.4353274@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> Message-ID: <20040131161426.GA6235@unpythonic.net> On Fri, Jan 30, 2004 at 05:10:16PM -0800, Daniel Ehrenberg wrote: > There's still a difference between types and classes in Python. Try > this in Python: > > >>> x = object() > >>> x.number = 5 > > It raises an error. But the same thing in Io works (which is x := > Object clone; x number := 5). To do it in Python, you have to do > > >>> class goodObject(object): pass > >>> x = goodObject() > >>> x.number = 5 This is because instances of object don't have a __dict__, but instances of goodObject do. Says the new-style objects document: Instances of a class that uses __slots__ don't have a __dict__ (unless a base class defines a __dict__); but instances of derived classes of it do have a __dict__, unless their class also uses __slots__. object has slots=[], effectively. The behavior is much like what you'll see in the example below: class S(object): __slots__ = ['x'] class T(S): pass s = S() s.x = 1 # succeeds s.y = 2 # fails with exception t = T() t.y = 3 # succeeds Now, whether it's good to have __slots__ and __dict__ I can't tell you, but it's this wrinkle that caused the behavior you saw, not a "difference between types and classes". Jeff From jcarlson at nospam.uci.edu Fri Jan 23 19:39:42 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 16:39:42 -0800 Subject: Python & Databases ? In-Reply-To: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> References: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> Message-ID: Peter Moscatt wrote: > Will Python work with any of the databases like MySQL... ? > > Pete There are methods for accessing most every database system through Python. You may want to head to google.com before asking next time. http://sourceforge.net/projects/mysql-python - Josiah From robin at jessikat.fsnet.co.uk Mon Jan 19 08:17:12 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 19 Jan 2004 13:17:12 +0000 Subject: Fw: PDF library for reading PDF files References: <100luvhbh3vr75d@corp.supernews.com> <100nlf2b1qjdae2@corp.supernews.com> Message-ID: In article <100nlf2b1qjdae2 at corp.supernews.com>, Cameron Laird writes ..... >>No, but ReportLab (the company) has a product separate from reportlab >>(the package) called PageCatcher that does exactly what the OP asked >>for. It is not open source, however, and costs a chunk of change. > >Let's take this one step farther. Two posts now have >quite clearly recommended ReportLab's PageCatcher http://reportlab.com/docs/pagecatcher-ds.pdf >. I >completely understand and agree that ReportLab supports >a mix of open-source, no-fee, and for-fee products, and >that PageCatcher carries a significant license fee. I >entirely agree that PageCatcher "read[s] PDF files ... >and ... extract[s] information from the PDF with it." > >HOWEVER, I suspect that what the original questioner >meant by his words was some sort of PDF-to-text "extrac- >tion" (true?) and, unless PageCatcher has changed a lot >since I got my last copy, PDF-to-text is NOT one of its >functions. I suspect Cameron is right. ReportLab does have a product called pageCatcher, but its main function is to grab individual pages for reuse. I believe it could be extended to go deeper and mess about with text streams, but it certainly doesn't do that now and would take some effort to do properly as text can be complicated in PDF (or postscript). -- Robin Becker From ny_r_marquez at yahoo.com Wed Jan 21 12:59:08 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 21 Jan 2004 09:59:08 -0800 Subject: py2exe 0.5.0 (finally) released References: <8a27e309.0401201304.7ee860b0@posting.google.com> <1ebr001fkuq85al2i8c26ejceu8qvedmdb@4ax.com> Message-ID: <8a27e309.0401210959.22a2cacb@posting.google.com> Wolfgang Strobl wrote > icon_resources works for me, like so: > > setup( windows = ["wxKnife.py", > {"script":"wxKnife.py","icon_resources":[(1,"images/app2.ico")]}], > console=["installed_updates.py","installed_sw.py"], > data_files=[("images",["images/app2.ico",]),] > ) That worked. I see that I need to visit the wiki page now. Thank you. -Ruben From claird at lairds.com Sat Jan 3 09:39:19 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Jan 2004 14:39:19 -0000 Subject: Python for Embedded Devices? References: Message-ID: In article , Brandon wrote: >Java seems to have taken off as the platform and language of choice >for many embedded devices. Would it be feasible for Python(perhaps >running on an embedded version of Linux) to act in such a capacity. >Most of my experience with Python has been with Unix-type scripting >tasks and using it when it is an applications built in scripting, but >I know some people try to use to build larger complex applications. Is >the Python interpreter portable and good enough to be used in resource >constrained devices like cell phones? Yes. And no. Yes, Python is certainly feasible for current cellular telephones. I don't see it poised for explo- sive growth there, but neither for technical defects nor because of any lack of good wishes on my part. 'Twould thrill me to write more Python on embedded projects. The one point I'd emphasize when thinking about this is that "embedded devices" covers a wide range, as I believe you already know. Some developers commonly work with hardware that's far, far more constrained than are cellular telephones; others, who also program embedded devices, can't be distinguished from vanilla Linux coders. -- Cameron Laird Business: http://www.Phaseit.net From bkelley at wi.mit.edu Thu Jan 29 10:26:36 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 29 Jan 2004 10:26:36 -0500 Subject: Simple Database Package In-Reply-To: <8089854e.0401290034.4d57a45d@posting.google.com> References: <8089854e.0401290034.4d57a45d@posting.google.com> Message-ID: <401925bb$0$575$b45e6eb0@senator-bedfellow.mit.edu> Fuzzyman wrote: > > Anyway - I couldn't decide between SQLobject and metakit (I'd already > seen sqlite but wanted some advuice before I chose one to dive > into..). > > Anyway - the windows download for SQLobject is zero sized - so I've > gone for metakit and will have a play. To save yourself some headaches, you might want to read my annotated metakit documentation: http://staffa.wi.mit.edu/people/kelley/tutorial/python.html And make sure you join the metakit mailing list, we are here to help :) It includes some common gotchas and has example code for you to play with. Brian From jcarlson at nospam.uci.edu Thu Jan 22 15:27:39 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 12:27:39 -0800 Subject: Ordered dictionary? In-Reply-To: References: Message-ID: Leif K-Brooks wrote: > I need to associate a string (key) with an integer (value). A dictionary > would do the job, except for the fact that it must be ordered. I also > need to look up the value for a specific key easily, so a list of tuples > wouldn't work. How must the dictionary be ordered? Do you need the keys or the values sorted? - Josiah From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jan 9 16:01:42 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 09 Jan 2004 22:01:42 +0100 Subject: Variable Scope 2 -- Thanks for 1. In-Reply-To: References: Message-ID: <3fff16b6$0$315$e4fe514c@news.xs4all.nl> Jens Thiede wrote: > I found the querk in my code: > > a = [1, 2, 3]; > b = a; > b.append(4); First: please remove the ; from the end of your lines... > b == [1, 2, 3, 4]; # As it should. > a == [1, 2, 3, 4]; # - Why? > > One would think that b is a referance to a - however I know it's not. It's not. a and b are both a name (or a reference to) the same list object [1,2,3]. (notice the subtle difference !) > Without changing a thing from above, the following is true: > > b = []; > b.append(5); > a == [1, 2, 3, 4]; > b == [5]; > > How do I avoid accedentaly modifying variables, is this a bug? If not > why not? It's not a bug. It's the way Python works :-) A very important concept with Python is that you don't have variable assignment, but name binding. An "assignment statement" binds a name on an object, and the object can be of any type. A statement like this: age = 29 doesn't assign the value 29 to the variable age. Rather, it labels the integer object 29 with the name age. The exact same object can be given many names, that is, many different "variables" can refer to the same value object: firstName = login = recordName = "phil" All three names now refer to the same string object "phil". Because assignment in Python works this way, there are also no (type)declarations. You can introduce a new name when you want, where you want, and attach it to any object (of any type), and attach it to another object (of any type) when you feel like it. For instance, if the line above has been executed and we then do login=20030405 the name login now refers to an int object 20030405, while firstName and recordName still refer to the old string "phil". That's why b in your second example, is changed. b becomes a name for a different list object (namely, the empty list []). a still refers to the original list. HTH, --Irmen. From nospam-deets at web.de Tue Jan 13 10:49:02 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Tue, 13 Jan 2004 16:49:02 +0100 Subject: newbie list handling question References: <400406F9.40D64EE6@sunpoint.net> Message-ID: > a = [[1, 10], [2, 20], [3, 30]] > av = [] > > for i in a: > av.append(i) > #av = a[:] here you don't store a _copy_ of the contained list, but a reference instead. Change av.append(i) to av.append(list(i)), and you should get a copy of the list. Diez From jjl at pobox.com Fri Jan 16 14:53:03 2004 From: jjl at pobox.com (John J. Lee) Date: 16 Jan 2004 19:53:03 +0000 Subject: traceback as string References: Message-ID: <87wu7r657k.fsf@pobox.com> steve at ferg.org (Stephen Ferg) writes: [...] > try: > main1() > except Exception, e: > print exception_format(e) [...] Just a semi-random warning for anybody as stupid as me: "finally:" blocks do not handle exceptions, so don't expect things like using the traceback module to work there: try: main1() finally: print exception_format(e) # WRONG I spent a long time tracing through the Python source code trying to track down a non-existent bug in a C extension, thanks to this misconception. :-( John From fBechmann at web.de Fri Jan 2 10:48:09 2004 From: fBechmann at web.de (Frank Bechmann) Date: 2 Jan 2004 07:48:09 -0800 Subject: how to receive a WM_COPYDATA message in wxwindows Message-ID: I started to write a SciTe director in python. I had a very basic communication running in Pythonwin but I disliked the strong mixture between Pythonwin's basic functionality and the Pythonwin application. Now I was trying to do the same with wxWindows but I did not find a way to receive the WM_COPYDATA messages sent from SciTe since there is no predefined wx-event for WM_COPYDATA and I got completely lost in the mix of C++/Swig/Python docs and sources. I tried to add my own event handler like this: # wxEVT_COPYDATA = win32con.WM_COPYDATA <== didn't work too wxEVT_COPYDATA = wx.NewEventType() def EVT_COPYDATA(win, func): win.Connect(-1, -1, wxEVT_COPYDATA, func) class CopyDataEvent(wx.PyEvent): def __init__(self, data): wx.PyEvent.__init__(self) self.SetEventType(wxEVT_COPYDATA) ... class SciCtrlFrame(wx.Frame): def __init__(self, logger, scitePath, sciteStartArgs): wx.Frame.__init__(self, None, -1, "title") ... EVT_COPYDATA(self, self.OnCopyData) but that didn't work. Can someone give me a hint where the wxEventType is documented or does someone even have an idea how to solve this? thx in advance. From tjreedy at udel.edu Mon Jan 12 22:48:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Jan 2004 22:48:45 -0500 Subject: Problem with what raw_input() returns References: <56f42e53.0401121746.39b9e4db@posting.google.com> Message-ID: "sebb" wrote in message news:56f42e53.0401121746.39b9e4db at posting.google.com... > # -*- coding: cp1252 -*- > one = "??" > two = one.replace("?","a") > > print two # it prints aa as I expected > > # -*- coding: cp1252 -*- > one = raw_input() # When I run the script, I type ?? > two = one.replace("?","a") > > print two # it still prints ?? and I want it to print aa > > Can someone help me with that problem? > Thanks Learn some basic debugging with print, repr, and ==; or if you know it, use it; or if you did, share results with us ;-) In particular, use different name for second input, print both before replace attempt, and use explicit equality tests. oneb = raw_input() print repr(one), repr(oneb), one == oneb Then draw conclusions and possibly make further test according to results. Terry J. Reedy From guess at askme.com Fri Jan 23 10:21:43 2004 From: guess at askme.com (Carmine Moleti) Date: Fri, 23 Jan 2004 15:21:43 GMT Subject: Ordered dictionary? References: Message-ID: Hi Dragos, > def filterList(p_list, p_value): > l_len = len(p_list) > l_temp = map(None, (p_value,)*l_len, p_list) > l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp) > return map(operator.getitem, l_temp, (-1,)*len(l_temp)) > phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'} > names_list = filterList(phones_dict.keys(), 'jan') > phones_list = map(phones_dict.get, names_list) > This extracts from the dictionary the telephone(values) numbers for > names(keys) starting with 'jan'... Why you didn't used the string.startswith(...) method? I wrote this: d={'carmine':'123456','carmela':'4948399','pippo':'39938303'} for name,number in d.items(): if name.startswith('car'): print name,number This also extract from the dictionay all the (name,number) pairs whose name starts with a given substring ('car' in the example). Thanks for your answer From nid_oizo at yahoo.com_remove_the_ Mon Jan 12 11:15:02 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 12 Jan 2004 11:15:02 -0500 Subject: How to know if a system command doesn't exist? In-Reply-To: References: Message-ID: <8KzMb.1701$PK6.16708@nnrp1.uunet.ca> Nicolas Fleury wrote: > Hi, > How can I know if a system command doesn't exist? All the ways I > have tried behave like if the system command was existing but returning > one. I don't want to sound provocative, but open in Perl returns an > error in a command doesn't exist, so I'm sure we could have an exception > in the same case for popen in Python? Small correction, as far as I can see, Perl's open returns the same error if the command returns 1 or doesn't exist. Same problem there... From francisgavila at yahoo.com Sat Jan 10 23:30:17 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 10 Jan 2004 23:30:17 -0500 Subject: Providing Default Value for User Input References: Message-ID: <1001kcqqk9ic2cc@corp.supernews.com> N?ant Humain wrote in message ... >I have just begun learning Python so that I can write a simple script >to make modification of a file used by another Python script easier. >This file is basically a list of regular expressions. What I want to >do is allow the user to select one of these regular expressions to >modify, but I've realized I know of no way to provide a default value >for user input. I could choose to show the regular expression the user >has chosen and simply allow the user to retype it and modify it from >there, but that is time consuming and error prone. Does Python support >a way to do this? If worse comes to worst, is there a way I could >write such code on my own without having to write a C-based module >(I'd like to stick to Python code only since some users will be >running this script on Windows without a C compiler)? This question is entirely too vague, because the answer depends entirely upon your implementation and has nothing to do with Python per se. I imagine the answer is pretty simple unless your design is horrible. As a shot in the dark, why not just look at what the user types? If it's something you want to interpret as 'use default' (like just an empty line, or the letter 'd' or something), then use a default! E.g.: choices = dict(a=1, b=2, default=100) while True: print 'Please select:' for k,v in choices.items(): print '%-10s%s' % (k,v) input = raw_input('?> ').lower() if input == 'd': input = 'default' try: print 'Value of %s is %s' % (input, choices[input]) except KeyError: print 'Item %r not found.' % input print If you're doing a lot of command-oriented input loops, look at the cmd module, which is pretty handy (I use it quite a bit). -- Francis Avila From exarkun at intarweb.us Fri Jan 9 20:49:01 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 9 Jan 2004 20:49:01 -0500 Subject: Python and Jython are kinda different In-Reply-To: References: <87wu81jjg2.fsf@pobox.com> <8765fkrig3.fsf@pobox.com> Message-ID: <20040110014901.GA4922@intarweb.us> On Fri, Jan 09, 2004 at 11:11:36PM -0000, Dave Benjamin wrote: > In article <8765fkrig3.fsf at pobox.com>, John J. Lee wrote: > > Yes, but it has been specifically noted by GvR (as well as the > > Jythonistas) that Jython is lacking developers ATM. > > I see. > > >> represented in books and tutorials--just two implementations of the Python > >> language, we all ought to be more concerned with unifying them. I never see > >> Jython advertised as a limited subset of Python. > > > > Well, it's *not* a limited subset of CPython 2.1 (apart from tiny > > differences). > > True. I suppose this brings up the following question: What *is* "Python"? > Does the concept of Python *today* fit within Jython's feature set? I'd say > much of it does, but a few things stick out, in order of decreasing > importance (IMHO): > > - generators All generators can be re-written with classes using the iterator protocol. Here's a simple example: # As a generator def foogen(): yield 1 yield 'a' yield [] # As classes using the iterator protocol class _FooGenIterator: counter = 0 def next(self): return getattr(self, 'state_%d' % self.counter)() def state_0(self): return 1 def state_1(self): return 'a' def state_2(self): return [] def state_3(self): raise StopIteration class FooGen: def __iter__(self): return _FooGenIterator() # Used exactly the same for i in foogen(): print i for j in FooGen(): print j > - properties This is getting closer, I think. More generator, descriptors are pretty honkin' fundamental these days. On the other hand, most behavior acheivable with properties can be achieved with __g/setattr__, albeit it quite as conveniently. > - getattr/getitem behavior (which is even different from CPython 2.1) I guess I haven't used Jython enough to know what's going on here. > - type factories being classes This seems pretty important to me, probably the most important on the list. Metaclasses existed before 2.2, but not without writing an extension module. > - dictionary support for "in" keyword This seems pretty trivial to me. It's just a transformation of dict.has_key(). > [snip] > > > I believe GvR said that PyPy might (might!) become a sort of > > executable standard for Python in the future, though. > > I think that's an impressive idea, but it almost seems like the resources > spent in keeping PyPy and CPython in parallel could be better spent keeping > Jython and CPython in parallel, seeing as nobody is calling PyPy "Python" > currently. > Can't say I agree here, probably because I don't much care about Java ;) I think PyPy has a lot more bang for the buck for your average Python programmer. Jython might be nice to bring in some of the Java people, or make some of that Java work easier when you absolutely have to use it, but for your average Python application, it hardly enters into the picture. PyPy, on the other hand opens up a lot of possibilities for future improvements to the language (because it is easier to prototype new features in Python than in C) as well as improvements to existing features. Jp From jmob at nospam__unm.edu Thu Jan 15 21:58:48 2004 From: jmob at nospam__unm.edu (Jason Mobarak) Date: Thu, 15 Jan 2004 19:58:48 -0700 Subject: Redefining __call__ in an instance In-Reply-To: References: Message-ID: class SomeThing(object): def __call__ (self): print 'gnihtemos' # get a reference to ourself M = __import__(__name__) ''' Return the requested class but don't instantiate it, leaves open the possibilty that class reference may be need to be stored and instantiate later. ''' def factory(S): return getattr(M, S, None) # A class version that instantiates. class FactoryError (TypeError): pass class Factory (object): def __new__(cls, name): C = getattr(cls, '_call_%s' % (name,), None) if C is None: raise FactoryError('Nothing know about %s' % (name,)) cls.__call__ = C return object.__new__(cls) def _call_SomeThing (self): print 'something' def __init__(self, n): pass ''' Also, the point of doing this is to make getting a factory class more convenient. If you need *args and **kwargs in your factory-lookup functionality there's no point in using it because it's no longer anonymous. Consider the following: ''' def init_factory (S, *args, **kwargs): return getattr(M, S, None)(*args, **kwargs) class Foo: def __init__ (self, need, to, know): pass class ooF: def __init__ (self, still, need, to, know): pass # So doing: init_factory('Foo', 'a', 'b', 'c') init_factory('ooF', 'a', 'b', 'c', 'd') # Is no different than: target = None # ... do stuff with target here ... if target == 'Foo': f = Foo('a', 'b', 'c') elif target == 'ooF': o = ooF('a', 'b', 'c', 'd') """ Okay, so a class could have it's __init__ define *args, **kwargs cull it's own data. But that's only useful for **kwargs, since otherwise you still need to know in the requesting code what kind class is needed, unless *args is just an arbitrary tuple of data in which case you could just pass a tuple to the class. Still this is a a bit past the point because the dictionary data in kwargs could just be passed as a dictory """ class Bar: def __init__ (self, *args, **kwargs): self.arbData = args self.sil = None self.i = None self.con = None for (key, val,) in kwargs.items(): setter = getattr(self, key, None) if setter is None: setattr(self, key, val) else: setter(self, val) def set_sil (self, d): # check sil here self.sil = d def set_i (self, d): # check i here self.i = d def set_con (self, d): # check con here self.con = d def __call__ (self): print self.sil, self.i, self.con DATA = """sil = foo i = bar con = baz """ if __name__ == '__main__': factory('SomeThing')()() Factory('SomeThing')() import cStringIO fp = cStringIO.StringIO(DATA) def g_ki (fp): while True: L = fp.readline() if L == '': break T = [I.strip() for I in L.split('=', 1)] if len(T) != 2: yield (T[0], None) else: yield tuple(T) g = g_ki(fp) data_dict = {} for (key, val,) in g: data_dict[key] = val init_factory('Bar', **data_dict)() output = """ gnihtemos something foo bar baz """ Robert Brewer wrote: > Robert Ferrell wrote: > >>I'd like to have a factory class that takes a string argument >>and returns >>the appropriate factory method based on that string. I'd like the >>instances to be callable. Like this: >> >>fact = Factory('SomeThing') >>aSomeThing = fact(some args) >> >>anotherFact = Factory('SomeThingElse') >>anotherThing = anotherFact(some other args) > > > Perhaps this will give you some ideas: > > >>>>class SomeThing(object): > > ... pass > ... > >>>>def Factory(classname, *args, **kwargs): > > ... return globals()[classname](*args, **kwargs) > ... > >>>>st = Factory('SomeThing') >>>>st > > <__main__.SomeThing object at 0x010C0F10> > > > If you still want to package that into a class instead of a function > (and then override __call__), feel free. Obviously, more exception > checking could be done. > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > -- (------------------------------( )~~~~~ Jason A. Mobarak ~~~~~~~) (~~ aether_at_gentoo_dot_org ~~( )~~~~ jmob_at_unm_dot_edu ~~~~~) (------------------------------( From hameedkhaan at yahoo.com Thu Jan 22 10:44:20 2004 From: hameedkhaan at yahoo.com (Hameed Khan) Date: Thu, 22 Jan 2004 07:44:20 -0800 (PST) Subject: What is object() Message-ID: <20040122154420.6597.qmail@web61110.mail.yahoo.com> hi, i was reading library refrence manual. there i found object() function. they says in library refrence that "Return a new featureless object. object() is a base for all new style classes. It has the methods that are common to all instances of new style classes." My questions are whats the use of this function and the object returned by it? and what are new style classes?. Thanks, Hameed Khan __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From jmob at unm.edu Tue Jan 13 12:53:42 2004 From: jmob at unm.edu (Jason Mobarak) Date: Tue, 13 Jan 2004 10:53:42 -0700 Subject: what is best for web development?? In-Reply-To: References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: Graham Fawcett wrote: > Wilk wrote in message news:<87oet9grqy.fsf at blakie.riol>... > >>ketulp_baroda at yahoo.com writes: >> >> >>>The problem i am facing here is i dont know what to use for >>>development of the application. I came across many ways to develop web >>>application in python which I already specified like >>>i)the cgi module in python >>>ii)Python Server Pages >>>iii)Quixote >>>iv)WebWare >>>v)Zope etc. >>>I want to choose such an environment so that i dont have to install >>>other softwares to run my application.For eg. I think if I develop >>>using zope then the client also has to install zope to run my software >>>and i dont want this. >> >>When you use one of theses servers, you don't need to install anything >>else than a classic browser on the client side. >>On the server side, most of the servers will not need anything else, you >>can even start without server with the batterie include : >>BasicHTTPServer (it was somes examples on this list somes days ago). > > > Just a guess, but I suspect the OP is using the term "client" in the > business sense, not the client/server sense; that is, he's trying to > write a Web application that is easy to deploy on his clients' > (customers') servers. > > If it has to be a one-shot install, I would suggest a Web server > written in Python -- Medusa or Twisted, probably -- that you could > bundle with your Python app. Find a Web app framework that (a) works > on Medusa or Twisted and (b) has the templating features you > require/desire. > > I wouldn't jump at using Twisted's app framework (Woven?) on top of > Twisted's Web server, though. No disrespect intended to the Twisted > community or their great body of work; it's just that server and > app-framework are two separate concerns: one day you might want to or > need to switch Web servers, and you need to know that your framework > is portable. I'm no Twisted expert: perhaps Woven is indeed portable, > and a kindly Twisted person will elaborate here. > > -- Graham You can use Woven with mod_proxy and Apache. Same with Woven's successor: Nevow, http://divmod.org/users/slyphon.twistd/nevow/moin.cgi/ . From user at domain.invalid Wed Jan 14 18:23:40 2004 From: user at domain.invalid (user at domain.invalid) Date: Wed, 14 Jan 2004 23:23:40 GMT Subject: Deleting objects Message-ID: Say I have an object (foo), that contains an array (bar) of references to other objects. Now I want to puff some of the objects from the array so that I remove the array element, and destroy the oject. but when I do: del foo.bar[0] Python says: object doesn't support item deletion So do I need to define __del__? And what would I put there? What if I wanted to remove the array element but still have the object exist? What happens if I succeed in destroying an object that other objects still think they are referencing? Thanks, Toby From __peter__ at web.de Sun Jan 4 04:54:06 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jan 2004 10:54:06 +0100 Subject: Filename type (Was: Re: finding file size) References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <20040103165041.GA31412@nl.linux.org> <3FF740ED.9020909@rogers.com> Message-ID: > [Peter Otten] >> >>I think both filename class and os.path functions can peacefully >> >>coexist. > > [Gerrit Holl (me)] >> >Thanks for the links. >> >(I think they don't, by the way) > > [Mike C. Fletcher] >> Is that peaceful? I don't know. If there's a war, let's be honest, >> os.path is going to take a good long while to defeat because it's there >> and embedded directly into thousands upon thousands of scripts and [Gerrit Holl] > Sure, I don't think os.path would die soon, it will surely take longer > than the string module to die. But I think there is a number of places > where Python could be more object-oriented than it is, and this is one > of them. The first step in making those modules more object-oriented is > providing a OO-alternative: the second step is deprecating the old way, > and the third step is providing only the OO-way. The third step will > surely not be made until Python 3.0. I don't think OO is a goal in itself. In addition to the os.path functions' ubiquity there are practical differences between a path and the general str class. While a string is the default that you read from files and GUI widgets, a filename will never be. So expect to replace e. g. os.path.exists(somestring) with os.filename(somestring).exists() which is slightly less compelling than somefile.exists(). Are unicode filenames something we should care about? Should filename really be a subclass of str? I think somepath[-1] could return the name as well. Should files and directories really be of the same class? These to me all seem real questions and at that point I'm not sure whether a filename class that looks like a light wrapper around os.path (even if you expect os.path to be implemented in terms of filename later) is the best possible answer. Peter From pythonguy at Hotpop.com Mon Jan 5 01:09:05 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 4 Jan 2004 22:09:05 -0800 Subject: Why does this fail? References: Message-ID: <84fc4588.0401042209.60cdb724@posting.google.com> I could not help replying to this thread... There are already quite a lot of spider programs existing in Python. I am the author of one of the first programs of the kind, called HarvestMan. It is multithreaded and has many features for downloading websites, checking links etc. You can get it from the HarvestMan homepage at http://harvestman.freezope.org. HarvestMan is quite comprehensive and is a bit more than a link checker or web crawler. My feeling is that it is not easy to understand for a Python beginner though the program is distributed as source code in true Python tradition. If you want something simpler, try spider.py. You can get information on it from the PyPi pages. My point was that, there is nothing to gain from re-inventing the wheel again and again. Spider programs have been written in Python, so you should try to use them rather than writing code from scratch. If you think that you are having new ideas, then take the code of HarvestMan(or spider) and customize it or improve on it. I will be happy to merge the changes back in the code if I think they improve the program, if it is for HarvestMan. This is the main reason why developers release programs as opensource. Help the community, and help yourselves. Re-inventing the wheel is perhaps not the way to go. best regards -Anand "Dave Murray" wrote in message news:... > Thank you all, this is a hell of a news group. The diversity of answers > helped me with some unasked questions, and provided more elegant solutions > to what I thought that I had figured out on my own. I appreciate it. > > It's part of a spider that I'm working on to verify my own (and friends) web > page and check for broken links. Looks like making it follow robot rules > (robots.txt and meta field exclusions) is what's left. > > I have found the library for html/sgml to be not very robust. Big .php and > .html with lot's of cascades and external references break it very > ungracefully (sgmllib.SGMLParseError: expected name token). I'd like to be > able to trap that stuff and just move on to the next file, accepting the > error. I'm reading in the external links and printing the title as a sanity > check in addition to collecting href anchors. This problem that I asked > about reared it's head when I started testing for a robots.txt file, which > may or may not exist. > > The real point is to learn the language. When a new grad wrote a useful > utility at work in Python faster than I could have written it in C I decided > that I needed to learn Python. He's very sharp but he sold me on the > language too. Since I often must write utilities, Python seems to be a very > good thing since I normally don't have much time to kill on them. > > Dave From exarkun at intarweb.us Sun Jan 4 22:44:02 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 4 Jan 2004 22:44:02 -0500 Subject: problem with async chat client in windows In-Reply-To: References: Message-ID: <20040105034402.GA4135@intarweb.us> On Mon, Jan 05, 2004 at 03:02:29AM +0100, Jonas wrote: > Hi, > I'm writing a small chat client to learn some python and networking. No > problem with the network stuff tho, the problem is when the user should be > able to interact and type messages to send. Since I work with windows I > can't use the select function Why not? select works perfectly well on Windows. See http://www.twistedmatrix.com/ Jp From michael at foord.net Thu Jan 29 03:22:26 2004 From: michael at foord.net (Fuzzyman) Date: 29 Jan 2004 00:22:26 -0800 Subject: Cross Platform Browser Launcher References: Message-ID: <8089854e.0401290022.67ce3cae@posting.google.com> Stephan Deibel wrote in message news:... > Hi, > > On Wed, 28 Jan 2004, Pieter Claerhout wrote: > > Take a look at the webbrowser module... > > http://www.python.org/doc/current/lib/module-webbrowser.html > > I submitted a patched webbrowser module with substantial improvements > a while back. I'm hoping this can make it into Python 2.4 so please > try it out: > > http://python.org/sf/728278 > > Thanks! > > Stephan Deibel > Thanks for all your help guys - I've downloaded the updated module to have a look at it. Certainly using the standard module : from webrowser import open as openbrow openbrow('help.html') works under windows ! 'm a bit worried about not being able to supply an absolute path... am wondering if the current working directory will always get set correctly on other platforms..... Hmmm... to be fair - I'm not sure how likely my application is to be run on anything other than windows. Thanks. Fuzzy > -- > Wing IDE for Python > Archaeopteryx Software, Inc > Take Flight! > > www.wingide.com > > > > > Cheers, [snip..] From francisgavila at yahoo.com Fri Jan 9 15:30:17 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 9 Jan 2004 15:30:17 -0500 Subject: convert a list to a string References: <3FFE1E29.20801@hotmail.com> <7xwu81dcr7.fsf@ruckus.brouhaha.com> <3FFE21A4.7040208@hotmail.com> Message-ID: Bart Nessux wrote in message <3FFE21A4.7040208 at hotmail.com>... >Forgot to say thanks! the number[0] thing is great! Here's something a bit more mysterious, but sometimes convenient, e.g. with struct (which always returns a tuple): >>> a, = [1] #note trailing comma >>> a 1 -- Francis Avila From haim at babysnakes.org Wed Jan 21 09:40:02 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Wed, 21 Jan 2004 16:40:02 +0200 Subject: py2exe error Message-ID: Hi (complete newbie warning...:) ) I've written a script that uses pickle to store data to a file. here's the code that stored the data: ------------- def put(self, conf): """ dump the preferences to a file""" # TODO: make a backup copy of the prefs !!!! try: f = open(self.bacFile, "w") except: raise 'BadFileError', "couldn't write file" pickle.dump(conf, f) f.close() --------------------------------- when running from regular python interperter, it works fine. I need this script to run without python installed, so I've created a stand-alone binary with py2exe. I used the following simple setup.py: from distutils.core import setup import py2exe setup(name = 'default', version = '0.1.0', console = ["CLI_Backup.py"], windows = ["Configurator.py"] ) ------------------------- when running from this binary I get this error: Traceback (most recent call last): File "MainFrame.pyc", line 140, in OnSaveMenuEvent File "MainFrame.pyc", line 174, in dumpPrefs File "NS_Backup.pyc", line 64, in put File "pickle.pyc", line 1382, in dump File "pickle.pyc", line 231, in dump File "pickle.pyc", line 293, in save File "pickle.pyc", line 663, in save_dict File "pickle.pyc", line 677, in _batch_setitems File "pickle.pyc", line 293, in save File "pickle.pyc", line 514, in save_unicode LookupError: no codec search functions registered: can't find encoding ----------------------------- I guess I should add some custom module to the setup.py but I don't know which (or am I completely off track here...). can someone help? thanx -- Haim From bolo at coco.ro Mon Jan 19 07:38:45 2004 From: bolo at coco.ro (Florian Preknya) Date: Mon, 19 Jan 2004 14:38:45 +0200 Subject: overwrite private method... (of wxColumnSorterMixin class) Message-ID: Is there a posibility to overwrite a private method (one that starts with __ ) ? I read that they are just formely private, they are prefixed with the class name to have an obtured visibility, so maybe it's a trick here... More details... I use wxPython, more specifically the wxColumnSorterMixin class. I want to overwrite the __OnColClick event handler to behave on my way: I want the sorting feature will affect only some columns, not all columns and that event handler is the key. The problem is that the event chain is skiped in the __OnColClick method, so I cannot receive the event anymore. So, my idea was to overwrite the __OnColClick method in the mixin subclass. Is this possible? Or, are they other solutions for this ? Thanks, Florian. From missive at frontiernet.net Mon Jan 19 10:44:42 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 19 Jan 2004 15:44:42 GMT Subject: FreeBSD 4.8 and Python-2.2.3 compiling error References: Message-ID: On 2004-01-18, Taylor Leese wrote: > I'm hoping somebody can point me in the right > direction. I am getting this error when trying to > compile Python-2.2.3 on FreeBSD 4.8: > Are you building from ports? ie.. cd /usr/ports/lang/python22 make ? From donald.welch.nospam at hp.com Fri Jan 9 15:42:14 2004 From: donald.welch.nospam at hp.com (djw) Date: Fri, 09 Jan 2004 12:42:14 -0800 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> Message-ID: <3fff1245@usenet01.boi.hp.com> Joe Francia wrote: > d wrote: >> Worked fine for me on Linux... made two suggested changes: 1) use >> raw_input(), not input(), 2) check user input for errors. Sorry, I don't >> know how to say "Enter a number between 0 and 500" in whatever language >> this is in (German?) >> > > You're a Python user and you don't recognize Dutch?!?! For shame... ;>) Well, I was only off by one country - not too bad for someone who took 4 years of high school Spanish and can hardly speak a word of it. I was looking at the code that I proposed to the OP, and wondered if this wasn't better: #!/usr/bin/env python while 1: bedrag = raw_input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) try: bedrag = int( bedrag ) if bedrag < 0 or bedrag > 500: raise ValueError except ValueError: print "Enter a number between 0 and 500" # In DUTCH, of course! else: break # ... etc. Is this good style, that is, to put multiple items inside a single try: except: else: block? Seems more compact and tidy than my first try. -d From max at alcyone.com Mon Jan 19 06:32:26 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 19 Jan 2004 03:32:26 -0800 Subject: adding elements to python tuples References: Message-ID: <400BC04A.C7FA9E9E@alcyone.com> Uwe Mayer wrote: > is it possible to append new elements to a tuple? I know tuples are > immutable and that this would mean to create a new tuple with one more > element, but how do you do it? Just use the + operator: >>> a = (1, 2, 3) >>> a + (4,) (1, 2, 3, 4) >>> a (1, 2, 3) >>> a += (4, 5) >>> a (1, 2, 3, 4, 5) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Here day fights with night. -- (the last words of Victor Hugo) From davidb at mcs.st-and.ac.uk Sat Jan 24 14:25:04 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 24 Jan 2004 11:25:04 -0800 Subject: any news client in Python? References: <2b4c49e0.0401230915.3438810f@posting.google.com> Message-ID: <4de76ee2.0401241125.45e77f9e@posting.google.com> pygeek at yahoo.com (Daniel Han) wrote in message news:<2b4c49e0.0401230915.3438810f at posting.google.com>... > hello everybody. > > i've been looking around for a decent newsreader (not rss) > that's written in Python. Strange, but i found none so far, > i've been to sf.net, freshmeat.net, and even googled that, > still nothing interesting. I don't know exactly what you mean by "decent" so it's difficult to be confident that you'll like what's available. To start with, there's the NewsFlash (tknf) newsreader: http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/ I wrote my own newsreader for a minority platform, too: http://www-solar.mcs.st-and.ac.uk/~davidb/Software/Python/NewsRead/ There are probably others lurking in FTP archives. I have to admit that my own attempt isn't exactly the best example you could hope for. My excuse is that I had to create my own widget set at the same time as writing the application. If I still had to use it, I would probably rewrite it, or at least refactor it severely. David From tad at tadland.net Wed Jan 21 15:43:28 2004 From: tad at tadland.net (Tad Marko) Date: 21 Jan 2004 12:43:28 -0800 Subject: Need help with Python class idioms Message-ID: Howdy! I'm trying to get my head around Python and I've come to realize that there are a lot of idioms in Python that are a bit different than in other languages. I have a class similar to what I've included below. The only difference is that in the real class, I have even more mandatory attributes. Too many to specify at once on a constructor and they don't always exist at construction time anyway, so the accessor idiom must remain. Can anyone suggest a more Pythony way to do the following? Thanks, Tad #!/bin/env python class A: def __init__(self): self.mandatoryVar1 = None self.mandatoryVar2 = None def setMV1(self, mv1): self.mandatoryVar1 = mv1 def setMV2(self, mv2): self.mandatoryVar2 = mv2 def saveToDB(self, db): if self.mandatoryVar1 == None: raise Exception, "Mandatory Var 1 not set." if self.mandatoryVar2 == None: raise Exception, "Mandatory Var 2 not set." # Using db, do whatever saving stuff is needed. From devrim at machsim.com Sat Jan 17 14:32:31 2004 From: devrim at machsim.com (Devrim Erdem) Date: 17 Jan 2004 11:32:31 -0800 Subject: Python class derived from a C++ base class Message-ID: Hello, [Warning-Python beginner] My application has a c++ plugin interface. To create a plugin, a class is derived from the Plugin class and compiled into a shared object ( so or dll ). I would like to allow writing plugins also in python. It is very comfortable if the plugin developer could derive a python class from the C++ base class. I am not well educated to think an elegant and a robust way to do this. I would appreciate any hints. Thanks in advance, Devrim. From marco at bubke.de Sat Jan 31 10:48:30 2004 From: marco at bubke.de (Marco Bubke) Date: Sat, 31 Jan 2004 16:48:30 +0100 Subject: numarray and NumarrayType Message-ID: Hi I have a little problem mit numarrays type. I want to get the Type but its noch the right one. If I array.typecode() I get the right one but there is not a typecode for all types. I geht the same type fer float and double? Thats wrong. Its a bug by me or numarray? Here is the code. The array is of type 'Float32" but I get tFloat64. cdef int numarray_type numarray_type = NA_NumarrayType(flat_array) if numarray_type == tFloat32: self.type = GL_FLOAT elif numarray_type == tFloat64: self.type = GL_DOUBLE elif numarray_type == tUInt32: self.type = GL_UNSIGNED_INT elif numarray_type == tInt32: self.type = GL_INT elif numarray_type == tUInt16: self.type = GL_UNSIGNED_SHORT elif numarray_type == tInt16: self.type = GL_SHORT elif numarray_type == tUInt8: self.type = GL_UNSIGNED_BYTE elif numarray_type == tInt8: self.type = GL_BYTE else: assert 0, "can't convert numarray type to opengl type" regards Marco From fumanchu at amor.org Mon Jan 19 12:13:32 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 19 Jan 2004 09:13:32 -0800 Subject: A lazy-committing database object with curry? Message-ID: Tim Lesher wrote: > I'm writing a database helper class that represents records in a SQL > database as objects. I want to be able to instantiate the objects > (from the database), play with their values locally, then lazily > commit the changes all at once (via an explicit commit call). Other > than the call to Commit(), I don't want clients of this class to have > to think about the fact that there's a database behind it all--there are > some interesting and non-obvious dependencies on the particular values > that are committed together, and I want to hide that in the Commit() call. > > 8< curry code snipped >8 > > Are there any pitfalls to doing this? Am I being dazzled by the shiny > new toy that is currying? Is there another simple solution, or a > refinement of this one, that I'm not seeing? I have to admit I've never thought of using currying for that. My usual approach in such a situation is to have an additional object attribute which acts as a flag for whether or not the object is "finished". Commit() could then be called at any time, but it won't actually do anything if instance.finished is False. It reads clearer to me than all the currying: class SomeRecordType(object): def __init__(self, title, description): self.title = title self.description = description self.finished = False def Commit(self): if self.finished: Do_database_commit(self) foo = myDb.LookupTitleRecord('some title') foo.description = 'bar' foo.Commit() # not updated in the DB yet foo.finished = True foo.Commit() # now updated in the DB Incidentally, this allows other threads to do the Commit calls for you, on a schedule. So your client code wouldn't need to call Commit() at all if the app is persistent. Robert Brewer MIS Amor Ministries fumanchu at amor.org From thelastmohiccan at yahoo.com Mon Jan 26 03:27:46 2004 From: thelastmohiccan at yahoo.com (lenk) Date: Mon, 26 Jan 2004 10:27:46 +0200 Subject: Zope Message-ID: Hi I installed zope in suse 9.0(own package).but i can t find start to start the server . /opt/zope/ ... is it a right path ? second problem Can you give an web example for python (forum,gueastbook ...) links pls:) thanks for all From arjen.dijkstraNoSpam at hccnet.nl Mon Jan 19 06:35:57 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Mon, 19 Jan 2004 12:35:57 +0100 Subject: adding elements to python tuples References: Message-ID: <400bc126$0$137$e4fe514c@dreader8.news.xs4all.nl> Maybe you could use this? >>> d=(1,2,3,4) >>> e=5, >>> d=d+e >>> d (1, 2, 3, 4, 5) Regards, Arjen "Uwe Mayer" schreef in bericht news:bugels$6u$1 at news.rz.uni-karlsruhe.de... > Hi, > > is it possible to append new elements to a tuple? I know tuples are > immutable and that this would mean to create a new tuple with one more > element, but how do you do it? > > i.e. i have (1,2,3) and want to append 4: > (1,2,3,4) instead of ((1,2,3),4) > > I wanted to use it as a return value of a function and an assignment, but: > > (a,b,c),d = myfunc() > > doesn't look nice to me. I intended to have > > a,b,c,d = myfunc() > > Thanks for any suggestions. > Ciao > Uwe > -- > From bik.mido at tiscalinet.it Tue Jan 27 03:20:05 2004 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Tue, 27 Jan 2004 09:20:05 +0100 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: <31va10lja5i7nqggpigd7c92676ua9m7h3@4ax.com> On Mon, 26 Jan 2004 20:45:19 +0100, I wrote: [OT, slightly edited] >>you'll see that it shouldn't be so. AND, the writting as usuall is >>fantastic incompetent. To illustrate, i quote: > >Haha, thanks! I'll make that a .sig! I guess it is fair to point out my own errors: >Also, you may have noticed it, but this is a discussion group about ^^^^^^^^^^^^^^^^^^^^^^^ This should be "you may *not* have noticed it". >*Perl* and people here is highly likely to be fond of Perl, appreciate ^^ *are* Michele From tim.one at comcast.net Fri Jan 30 23:30:28 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 30 Jan 2004 23:30:28 -0500 Subject: NEWLINE character problem In-Reply-To: <20040130144254.GA29356@intarweb.us> Message-ID: [Dragos Chirila] >> I have a string and I want to split it by NEWLINE character. >> >> It is knowned that "Microsoft Windows, Apple's Macintosh OS and >> various UNIX, all use different characters to mark the ends of lines >> in text files. Unix uses the linefeed (ASCII character 10), MacOS >> uses the carriage return (ASCII character 13), and Windows uses a >> two-character sequence of a carriage return plus a newline". So, >> PLEASE don't tell me to use 'split' by '\n' because it won't work. [Jp Calderone] > s.splitlines() Woo hoo! Jp is right, and I never realized that splitlines() looks for all of \n, \r\n, and \r line endings. >>> 'a\nb\rc\r\n'.splitlines() ['a', 'b', 'c'] >>> 'a\nb\rc\r\n'.splitlines(True) ['a\n', 'b\r', 'c\r\n'] >>> That's certainly Pythonic . From mwh at python.net Wed Jan 14 06:34:38 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 14 Jan 2004 11:34:38 GMT Subject: Parsing c-code References: Message-ID: "tm" writes: > are there recommended modules for parsing c-code. I think the most sane way is to use gccxml (google for it) and parse the output of that. This still leaves you with quite a lot of work to do, but is probably less terrifying (caveat: I haven't done this myself). Cheers, mwh -- [3] Modem speeds being what they are, large .avi files were generally downloaded to the shell server instead[4]. [4] Where they were usually found by the technical staff, and burned to CD. -- Carlfish, asr From pythongnome at hotmail.com Fri Jan 30 16:51:37 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 30 Jan 2004 21:51:37 GMT Subject: pythonwin woes References: Message-ID: "oliver" wrote in message news:a7c2c93c.0401301309.4e61c606 at posting.google.com... > Hi, > > I am trying my hands on the latest verion of pythonwin extension with > python 2.3.3 , and run into *semi-fatal* problem: the run command > ignores the modifications I made to the source code, and *always* > show me results given by that outdated source: it feels like it just > use that cached .pyc!!! > > I wonder if the other pythonwin users had experienced the same > problem, or did I miss anything here. There is no such problem in IDLE > though. > > Thanks > > oliver A while ago, I had the same exact problem. It always ran the outdated file. I had to delete the old .pyc file to get it to run correctly. I'm running Python 2.3.3 like you only I'm using build 157 and it seems to work just fine. I had to go through a few versions before it went away with build 157. Try emailing Mark Hammond and see if he had any suggestions. -- "Victorious warriors win first and then go to war, while defeated warriors go to war first and then seek to win." Sun-tzu, The Art of War. Strategic Assessments From max at alcyone.com Wed Jan 7 07:43:57 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 07 Jan 2004 04:43:57 -0800 Subject: Why " ".some_string is often used ? References: Message-ID: <3FFBFF0D.696FA6DC@alcyone.com> "St?phane Ninin" wrote: > Is there a reason to do instead of just returning join(text.split()) ? > why concatenate " " to the string and not just returning the string > instead ? Because they're not the same thing unless you've already done from string import join first. join is not a builtin function. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I get my kicks above the wasteline, sunshine -- The American, _Chess_ From gerrit at nl.linux.org Sun Jan 4 10:10:33 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 16:10:33 +0100 Subject: Find out username and UID/GID In-Reply-To: References: Message-ID: <20040104151033.GA15726@nl.linux.org> Florian Lindner wrote: > how can I find out the username and it's UID and GID on a linux system, > using the most recent python version? If possible, without the use of extra > libraries. >>> import os >>> import pwd >>> os.getuid() 500 >>> os.getgid() 500 >>> pwd.getpwuid(500) ('gerrit', 'x', 500, 500, 'Gerrit Holl', '/home/gerrit', '/bin/bash') I think there is a simpler way for the last one in the docs, but I'm not entirely sure. yours, Gerrit. -- 188. If an artizan has undertaken to rear a child and teaches him his craft, he can not be demanded back. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From none at none.com Tue Jan 13 14:28:38 2004 From: none at none.com (Derek) Date: Tue, 13 Jan 2004 14:28:38 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> <87d69og2jl.fsf@pobox.com> <873cajafr8.fsf@pobox.com> Message-ID: "John J. Lee" wrote: > [...] > > Point taken. I once worked on a project where we > > implemented a production system in C++ and then > > implemented it again in Python for QA purposes. It took > > about 150k lines of C++ code and 10k lines of Python. > > Python took less code because so many modules are bundled > > with the language, but the C++ system ran many times > > faster. It's all about picking the right tool for the > > job. > > Well, that's a banal truism obscuring the fact that, for the > great majority of projects, optimisation does not require > implementation of the *entire* system in a language like > C++. The sum of C++ and Python is greater than the parts. Python and C++ can also be a bigger mess than sum of either part. Take your pick. From __peter__ at web.de Sun Jan 11 04:18:52 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Jan 2004 10:18:52 +0100 Subject: Problem in directory working References: <92ed2954.0401102257.565dd6f4@posting.google.com> Message-ID: Gyoung-Yoon Noh wrote: > I've written Unix's find-like function using recursive os.listdir() > call and generator expression. It seems that error happens in > generator expression. > Below codes do not work. walk.next() generates StopIteration. > When I replace 'yield' with 'print', it works fine. > > Why this does not work? > I've had successively implemented unix-find using os.path.walk(). > But I want to combine recursive call and generator expressions. > > Any comments are welcome. > > > [snip] > import os > > def find(path): > if not os.path.exists(path): > raise StopIteration > if os.path.isdir(path): > for l in os.listdir(path): > fullpath = os.sep.join((path, l)) for p in find(fullpath): yield p > else: > yield path > > if __name__=='__main__': > #find('/home/myhome'); raise SystemExit() > walk = find('/home/myhome') > for i in walk: > print i.next() Just writing find(somepath) will create a new generator but only yield a value when its next() method is called. This is done implicitly by the for loop I inserted into your code. Do you know about 2.3's new os.walk()? It would make a good building block for routines scanning the file system. Peter From squirrel at WPI.EDU Thu Jan 8 20:26:55 2004 From: squirrel at WPI.EDU (Christopher T King) Date: Thu, 8 Jan 2004 20:26:55 -0500 Subject: xrange() syntactic sugar Message-ID: Okay, so this is really two requests in one, and they're both kinda outlandish, but I'm gonna post them nonetheless: I've always thought xrange() to be ugly; it looks to be a lot of typing just to get an efficient loop over some numbers. Since it uses the same 'parameters' as the slice operator, I was thinking it would be neat if the slice operator were to be syntactic sugar for the xrange operator. Example: for i in xrange(0,8,2): pass is equivalent to for i in 0:8:2: pass Being the syntactic sugar it is, it does nothing but save typing (and those extra colons do look slightly messy), but it does help unify the syntax a bit. Now part two: xrange() objects become an acceptable list index, operating as a slice operator does. Example: a[0:8:2] is equivalent to a[xrange(0,8,2)] Since (correct me if I'm wrong) xrange()s just hold the three numbers given them, this part (at least) shouldn't be too difficult to implement. This would then allow the unification to be complete, so a[0:8:2] is really the list 'a' being indexed by an xrange() object. Therefore a change in the implementation would be fully backward compatible. This type of indexing is slightly reminiscent of that of Matlab. I'm not sure if the new xrange syntax would cause parsing problems; it might in a statement such as: for a in 0:8: 2: pass But I doubt that would be a problem, so long as the parser gobbles up as much as it can. Just a humble RFC. Don't reject me too harshly, I know it's a kinda silly feature to request :) I just wanna give it a try. From sross at connectmail.carleton.ca Thu Jan 8 21:33:22 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 8 Jan 2004 21:33:22 -0500 Subject: Pesky reverse() References: <3t3svvs7ni8l8jnn1l1v60oogirqoaa85f@4ax.com> Message-ID: <_noLb.81639$BA6.1706329@news20.bellglobal.com> wrote in message news:3t3svvs7ni8l8jnn1l1v60oogirqoaa85f at 4ax.com... > I need to use the built-in method 'reverse', but notice strange behavior. [snip] > new_list = my+list # should save a 'forward' copy, right? Nope > my_list.reverse() actually reverses both copies, since Python is a bit too > helpful sometimes, and I understand why. > > So the question is, how do I get a forward and reverse list? >>> forward = range(10) >>> reverse = forward[:] # copy >>> reverse.reverse() >>> print forward [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print reverse [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> HTH Sean From fumanchu at amor.org Fri Jan 2 13:31:19 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 2 Jan 2004 10:31:19 -0800 Subject: undo and redo ? Message-ID: Somebody asked: > > anyone can inspires me how we can > > achieve undo and redo function ? Diez B. Roggisch replied: > When working with a MVC-approach, the actions you the user > can invoke on the > model could be created as objects that know how to undo/invert their > effects. Then you store a list of these actions and > performing undo takes > the last action and apply its inverted action to your model. An excellent point of inspiration can be found via the GoF: http://www.amazon.com/exec/obidos/ASIN/0201633612 Synopsis/discussion at: http://c2.com/cgi/wiki?CommandPattern FuManChu From philh at invalid.email.address Sun Jan 4 00:19:43 2004 From: philh at invalid.email.address (phil hunt) Date: Sun, 4 Jan 2004 05:19:43 +0000 Subject: Text-to-HTML processing program References: Message-ID: On Sat, 03 Jan 2004 11:05:54 -0500, Jeff Schwab wrote: >phil hunt wrote: >> Does anyone know of a text-to-HTML processing program, ideally >> written in Python because I'll probably be wanting to make small >> modifications to it, which is simple and straightforward to use >> and which uses a simple markup language (something like Wikipedia >> markup would be ideal)? > >How about troff? Or if you really want to keep it simple, why not use >the
 tag in HTML?

I wasn't aware troff did HTML output.

>Or if you really want to keep it simple, why not use
>the 
 tag in HTML? 

Yuk. 

-- 
"It's easier to find people online who openly support the KKK than 
people who openly support the RIAA" -- comment on Wikipedia
(Email: , but first subtract 275 and reverse 
the last two letters).  




From nhodgson at bigpond.net.au  Sat Jan 17 17:59:27 2004
From: nhodgson at bigpond.net.au (Neil Hodgson)
Date: Sat, 17 Jan 2004 22:59:27 GMT
Subject: Retrive unicode keys from the registry
References: 
	
	<1xpzaa8i.fsf@python.net>
	<69ZNb.15222$Wa.2798@news-server.bigpond.net.au>
	<40086EE5.7020708@v.loewis.de>
Message-ID: 

Martin v. L?wis:

> I believe the story would be completely different for the registry: the
> wide registry functions are available on all Windows versions, AFAIK.

   The documentation for RegQueryValue says:
""" Unicode: Implemented as Unicode and ANSI versions. Note that Unicode
support on Windows Me/98/95 requires Microsoft Layer for Unicode. """

   Neil




From carroll at tjc.com  Fri Jan  9 14:30:42 2004
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 09 Jan 2004 19:30:42 GMT
Subject: urllib - changing the user agent
References: <8089854e.0401090509.3dd74859@posting.google.com>
Message-ID: 

On 9 Jan 2004 05:09:41 -0800, michael at foord.net (Fuzzyman) wrote:

 [ wants to change the user-agent in HTTP request from urllib ]

Fuzzy --

I take the easy way out, and use urllib2, instead:

    url = "http//www.spam.com/eggs.html"
    req_headers = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
        }
    req = urllib2.Request(url, None, req_headers)




From mwh at python.net  Thu Jan  8 15:47:32 2004
From: mwh at python.net (Michael Hudson)
Date: Thu, 8 Jan 2004 20:47:32 GMT
Subject: books
References: <3FFDC029.AB0A4097@unet.univie.ac.at>
Message-ID: 

Thomas Mang  writes:

> Hello,
> 
> I have programmed mostly in C++ lately, and I want to start learning
> Python now.
> 
> Which books would you recommend to buy?

Well, maybe, none.  Have you tried the online material? 

    http://www.python.org/topics/learn

and in particular

    http://www.python.org/topics/learn/prog.html

> I am both looking for an introduction into the language, as well as
> complete guides.

For the "complete guide", what I've seen of Python in a Nutshell is
pretty good.  But I actually don't own any books on Python (well apart
from the one I tech reviewed).

Cheers,
mwh

-- 
  For their next act, they'll no doubt be buying a firewall 
  running under NT, which makes about as much sense as 
  building a prison out of meringue.                     -- -:Tanuki:-
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html


From jmvw at wwwcomm.com  Thu Jan 22 10:49:49 2004
From: jmvw at wwwcomm.com (Michiel)
Date: 22 Jan 2004 07:49:49 -0800
Subject: Problems using ZSI web service from .NET
Message-ID: <1c9f633a.0401220749.29755bea@posting.google.com>

Hello,

I am not sure this is the right place to ask. I tried the ZSI mailing
list, but got no response there.

My goal is to write some web services with ZSI to be used by a client
written in .NET. I'm using ZSI 1.2.7 (this was easy to install on my
Debian system).

I have no problem with functions with parameters and return values
with simple types, but I am having a hell of a time moving a simple
array.

My web service is taken from the zsi examples:

______________________________
#!/usr/bin/python

def echo(s):
    return s

from ZSI import dispatch
dispatch.AsCGI()
______________________________


I want to invoke the echo function with an array of strings as a
parameter and I want it to give me an array back. I had a lot of
trouble putting together a WSDL file that was properly imported by
Visual Studio (without turning my string arrays into single strings),
but with the help of many google searches, I finally came to a
description with the following schema:

______________________________
        
           
              
                
                   
                     
                   
                  
               
             
           
        
______________________

For brevity, I've left out the rest of the wsdl file. Messages for
parameters and return value of echo are defined as having the above
type ArrayOfString.

Now, it seems that ZSI doesn't like what my .NET client is sending it.

Request from .NET app:

______________________________________________



  
    
      
    
    
      s1
      s2
    
  


_______________________________________________

The response from the ZSI cgi:

_______________________________________________



SOAP-ENV:Client
Unparseable message


Any cannot parse untyped element
/soap:Envelope/soap:Body/soapenc:Array/Item[1]






_________________________________________________


For comparison, a simple ZSI client works fine and this is the dialog:

_________________________________ Tue Jan 20 13:38:34 2004 REQUEST:




1
2
3





_________________________________ Tue Jan 20 13:38:36 2004 RESPONSE:
Date: Tue, 20 Jan 2004 18:38:35 GMT
Server: Apache/1.3.26 Ben-SSL/1.48 (Unix) Debian GNU/Linux PHP/4.1.2
mod_perl/1.26
Content-Length: 664
Content-Type: text/xml; charset="utf-8"





1
2
3





_____________________________________


It seems the arguments to echo have types here. 

Can I get .NET to do the same? Can this be done through the WSDL file?
Or else, how can I send arrays back and forth?

Thank you,

Michiel van Wessem


From sebb at linuxcult.com  Tue Jan  6 20:04:19 2004
From: sebb at linuxcult.com (sebb)
Date: 6 Jan 2004 17:04:19 -0800
Subject: Getting strange characters in the command prompt
Message-ID: <56f42e53.0401061704.523f394@posting.google.com>

For information, I have windows xp (english edition).

When I use special non-english characters (like ? ? ? ...) in my
python code, IDLE tells me to add a line like:

# -*- coding: cp1252 -*-

... because of the presence of non-ASCII characters.

When I write a script like the folowing:

# -*- coding: cp1252 -*-
print "? ? ?"

... and I run it in the windows command prompt, I get strange
characters I didn't ask for.

And when I write those non-English characters (? ? ?) directly in the
command prompt, I get the correct characters.

Can anyone help we with that problem?


From exarkun at intarweb.us  Thu Jan 15 18:17:04 2004
From: exarkun at intarweb.us (Jp Calderone)
Date: Thu, 15 Jan 2004 18:17:04 -0500
Subject: Binary strings, unicode and encodings
In-Reply-To: <265368cb.0401151138.37a3a47b@posting.google.com>
References: <265368cb.0401151138.37a3a47b@posting.google.com>
Message-ID: <20040115231704.GA23935@intarweb.us>

On Thu, Jan 15, 2004 at 11:38:39AM -0800, Laurent Therond wrote:
> Maybe you have a minute to clarify the following matter...
> 
> Consider:
> 
> ---
> 
> from cStringIO import StringIO
> 
> def bencode_rec(x, b):
>     t = type(x)
> 
>     if t is str:
>         b.write('%d:%s' % (len(x), x))
>     else:
>         assert 0
> 
> def bencode(x):
>     b = StringIO()
> 
>     bencode_rec(x, b)
> 
>     return b.getvalue()
> 
> ---
> 
> Now, if I write bencode('failure reason') into a socket, what will I get
> on the other side of the connection?
> 
> a) A sequence of bytes where each byte represents an ASCII character

  Yes.

> 
> b) A sequence of bytes where each byte represents the UTF-8 encoding of a
> Unicode character

  Coincidentally, yes.  This is not because the unicode you wrote to the
socket is encoded as UTF-8 before it is sent, but because the *non*-unicode
you wrote to the socket *happened* to be a valid UTF-8 byte string (All
ASCII byte strings fall into this coincidental case).

> 
> c) It depends on the system locale/it depends on what the site module
> specifies using setdefaultencoding(name)

  Not at all.  'failure reason' isn't unicode, there are no unicode
transformations going on in the example program, the default encoding is
never used and has no effect on the program's behavior.

  bencode_rec has an assert in it for a reason.  *Only* byte strings can be
sent using it.  If you want to send unicode, you'll have to encode it
yourself and send the encoded bytes, then decode it on the other end.  If
you choose to depend on the default system encoding, you'll probably end up
with problems, but if you explicitly select an encoding yourself, you won't.

  Jp



From fumanchu at amor.org  Wed Jan  7 01:57:44 2004
From: fumanchu at amor.org (Robert Brewer)
Date: Tue, 6 Jan 2004 22:57:44 -0800
Subject: Problem: 'Threads' in Python?
Message-ID: 

Ralph Sluiters wrote:
> You did everything, but not answer my question. I know what 
> cookies are, but
> I don't need cookies here. And you said in your answer "start 
> background
> process", that was my question. How can I start a background process.
> 
> But I've solved it now,

And the answer was...? <:O


FuManChu, who doesn't know how long he can hold his breath... :)



From alert at notification.messagelabs.com  Tue Jan 27 09:38:42 2004
From: alert at notification.messagelabs.com (alert at notification.messagelabs.com)
Date: 27 Jan 2004 14:38:42 -0000
Subject: WARNING. You sent a potential virus or unauthorised code
Message-ID: <20040127143842.15430.qmail@server-23.tower-27.messagelabs.com>

For English instructions please scroll down.

ISION MailScan hat einen potenziellen Virus 
oder eine verd?chtige Datenstruktur in einer 
von Ihnen verschickten oder an Sie 
gesendeten Nachricht entdeckt. 
____________________________________________________________

Einige Informationen zu der infizierten eMail
____________________________________________________________
Zur besseren Identifikation der Nachricht:

Der Absender der Nachricht war: 
    python-list at python.org

Der Empf?nger der Nachricht war: 
    alice at spiegel.de

Der Betreff war: 'Hi'
Die Nachricht wurde verschickt am Tue, 27 Jan 2004 14:31:22 +0100
Um die Nachricht genauer zu identifizieren:

Scanner 7 (Unpacker) berichtet folgendes:
>>> W32/MyDoom.A in '510178_3X_AZ-S_PA2__message.doc=R46.scr'


Die Originalnachricht ist in den ISION Quarant?ne_Server umgeleitet 
worden, in 
mail server server-23.tower-27.messagelabs.com (id 510178_1075214322)
und wird dort f?r 30 Tage gespeichert bevor sie endg?ltig gel?scht wird.
____________________________________________________________

Weitere Hilfe
____________________________________________________________
Lesen Sie bitte die haeufig gestellten Fragen (
FAQ)  fuer eine solche Situation unter
http://www.ision.net/mailscan/faq
Hier werden die meisten Ihrer Fragen 
beantwortet. 
Wenn Sie weitere Informationen ben?tigen 
oder glauben, dass es sich um einen falschen 
Alarm handelt, kontaktieren Sie bitte das 
ISION Customer Interaction Center unter

support at ision.net

Sollten Sie mit dem Support in Kontakt treten, 
geben Sie bitte immer die nachfolgende Virus 
Identifikationsnummer an:
{{{ mail server server-23.tower-27.messagelabs.com (id 510178_1075214322) }}}
______________________________________

Diese Nachricht wurde von ISION MailScan 
unter Nutzung des MesssageLabs Virus Control 
Centers auf  alle bekannten Viren untersucht. 
Wenn Sie mehr ?ber diese Dienstleistung 
erfahren m?chten, besuchen Sie
http://www.ision.net/mailscan/faq
_________________________________________________________________

*************************ENGLISH*********************************
ISION Mailscan discovered a possible
virus or unauthorised code (such as a joke program or trojan)
in an email sent by you.

Please read this whole email carefully. It explains what has
happened to your email, which suspected virus has been caught,
and what to do if you need help.

____________________________________________________________

Some details about the infected message
____________________________________________________________

To help identify the email:

The message was titled 'Hi'
The message date was Tue, 27 Jan 2004 14:31:22 +0100
The message identifier was (empty)
The message recipients were 
    alice at spiegel.de


To help identify the virus:

Scanner 7 (Unpacker) reported the following:

>>> W32/MyDoom.A in '510178_3X_AZ-S_PA2__message.doc=R46.scr'


The message was diverted into the virus holding pen on
mail server server-23.tower-27.messagelabs.com (id 510178_1075214322)
and will be held for 30 days before being destroyed.


____________________________________________________________

What should you do now?
____________________________________________________________

If you sent the email from a corporate network, you should first
contact your local Helpdesk or System Administrator for advice.
They will be able to help you disinfect your workstation.

If you sent the email from a personal or home account, you will
need to disinfect your computer yourself. To do this you will
need an anti_virus program. We suggest using one of the leading
industry anti_virus packages such as McAfee, F_Secure or Cybersoft,
which cost ?15_?30 per copy.
____________________________________________________________

Getting more help
____________________________________________________________

You may like to read the Support FAQs at
http://www.ision.net/english/mailscan/faq 
These will answer many of the most common queries.

If you believe this message to be a false alarm or you require
further assistance, you can email ISION UK Support at:_

   	support at ision.net.uk

or contact ISION Internet by telephone on:_

	+44 (0) 208 293 73 00 

Please quote the following Virus Pen ID when contacting Support.
{{{ mail server server-23.tower-27.messagelabs.com (id 510178_1075214322) }}}

________________________________________________________________________
This email has been scanned for all viruses by the MessageLabs Email
Security System. For more information on a proactive email security
service working around the clock, around the globe, visit
http://www.messagelabs.com
________________________________________________________________________



From nhodgson at bigpond.net.au  Wed Jan 21 14:57:45 2004
From: nhodgson at bigpond.net.au (Neil Hodgson)
Date: Wed, 21 Jan 2004 19:57:45 GMT
Subject: Jython and SciTE
References: 
Message-ID: 

rt lange:

> I'm trying to get SciTE to run and compile my jython scripts.
> This is what I have in my python.properties file:
>
> command.name.1.*.py=Go Jython
> command.1.*.py=jython $(FileNameExt)
> command.1.subsystem.*.py=1
> command.name.2.*.py=Jython -> jar
> command.2.*.py=jythonc --core --jar $(FileName).jar $(FileNameExt)
> command.2.subsystem.*.py=1
>
> I keep getting as output:
>
> >jython DiceRoll.py
> >The system cannot find the file specified.

   Depending on the OS and the type of command (batch, exe, python script)
"jython" is you may need to execute through the command interpreter which is
cmd on NT:

command.1.*.py=cmd /c jython $(FileNameExt)

   Neil




From antonmuhin at rambler.ru  Mon Jan 19 13:39:40 2004
From: antonmuhin at rambler.ru (anton muhin)
Date: Mon, 19 Jan 2004 21:39:40 +0300
Subject: Delayed evaluation and setdefault()
In-Reply-To: 
References: 
Message-ID: 

Leo Breebaart wrote:

> Hi all,
> 
> I have a question about Python and delayed evaluation.
> 
> Short-circuiting of Boolean expressions implies that in:
> 
>    >>> if a() and b():
> 
> any possible side-effects the call to b() might have will not
> happen of a() returns true, because then b() will never be
> executed.
> 
> However, if I go looking for dictionary keys like this:
> 
>    >>> d = {}
>    >>> d.setdefault('foo', b())
> 
> then b() *does* get executed regardless of whether or not the
> value it returns is actually used ('foo' was not found) or not
> ('foo' was found). 
> 
> If b() has side-effects, this may not be what you want at all. It
> would seem to me not too exotic to expect Python to have some
> sort of construct or syntax for dealing with this, just as it
> supports Boolean short-circuiting.
> 
> So I guess my question is twofold: one, do people think
> differently, and if so why?; and two: is there any elegant (or
> other) way in which I can achieve the delayed evaluation I desire
> for setdefault, given a side-effect-having b()?
> 

It's normal---setdefault is just a method and its parameters get 
evaluted before the call occur. If you want this kind of lazy 
evaluation, I'd suggest something like this ('foo' in d) or 
(d.setdefault('foo', b()). If you want your value too, it gets even 
trickier.

Actually, if you really need this kind of functionality, it might be 
worth defining a function.

def lazysetdefault(d, key, func):
   if key not in d:
     d[key] = func()()
   return d[key]

lazysetdefault(d, 'foo', lambda: b())

However, are you real sure you need it?

regards,
anton.



From noemail at noemail4u.com  Mon Jan 12 07:56:36 2004
From: noemail at noemail4u.com (Dang Griffith)
Date: Mon, 12 Jan 2004 12:56:36 GMT
Subject: need help translating a PHP for statement to python
References: 
	
Message-ID: <944baf3371667ab5b21f6020c57ad385@news.teranews.com>

On Sat, 10 Jan 2004 20:22:18 +1100, "Eli Pollak" 
wrote:

>Haha ... you must be originally a perl coder. Who else writes attricious
>code like this
>    if ($bar = (($x_ar[$x] -= $prd + $bar) < 0))

Any C programmer worth his salt.  I miss those days.  Sort of.
    --dang


From pmagic at snet.net  Wed Jan 14 21:39:04 2004
From: pmagic at snet.net (paul m)
Date: Wed, 14 Jan 2004 21:39:04 -0500
Subject: ProtoCiv: porting Freeciv to Python CANNED
In-Reply-To: 
References: 
	
	
	
	
Message-ID: 

JanC wrote:
> 
> You think "cross-platform" means "it runs out-of-the-box on all possible 
> platforms that ever existed, now exist, and will ever exist"?
> 
> Please go searching and come back when you find 1 (one) program which fits 
> that definition...  :-p
> 

vi might come close... ;-)

--Paul M



From jjl at pobox.com  Wed Jan 14 15:08:37 2004
From: jjl at pobox.com (John J. Lee)
Date: 14 Jan 2004 20:08:37 +0000
Subject: C++ bad-mouthing (was: Why learn Python ??)
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	<7xisjh1e3i.fsf@ruckus.brouhaha.com>
	<10064loqc7sd7e3@corp.supernews.com>
	<7xeku496wx.fsf@ruckus.brouhaha.com>
	
	<7xhdz08xgy.fsf@ruckus.brouhaha.com> <1073978329.887910@yasure>
	<87brp7agl7.fsf@pobox.com> <7xvfnfmzy8.fsf@ruckus.brouhaha.com>
Message-ID: <878yka2sze.fsf@pobox.com>

Paul Rubin  writes:

> jjl at pobox.com (John J. Lee) writes:
> > > But at any rate, I thought we were talking about huge projects
> > > involving many programmers, and I don't think Grail was of that
> > > sort at all.
> > 
> > Right.  Wasn't it a research project?  In any case, hardly a
> > large-scale programming effort along the lines of Mozilla!
> 
> Grail wasn't huge but I think any serious browser qualifies as
> substantial.

True, though not on the same scale as Zope, for example (or the others
I list below).


> If you're saying it didn't really fail but actually
> wasn't even seriously attempted,

Not sure what the goals were, but I'm not sure they were to compete
with Netscape and IE.  CNRI funding -- "R" for research -- seems to
imply I do remember correctly (one of us should really check the facts
here... oh well, it's USENET ;-).

Do correct me if I'm wrong, but you seem to imply, in saying "wasn't
even seriously attempted", that if Grail wasn't intended to be a
Netscape-replacement, it must have had no purpose at all.  That's
certainly not obvious to me.


> ok, that's even fewer substantial
> programs that have even been tried in Python.

The project stopped, according to the tarball, because CNRI didn't
want to allocate more money to it because of low usage compared to,
the big two of the day.  Given that, what do we learn from Grail?

Well, what does the *existence* of Grail tell us (along with
similar-size projects like Mailman)?  It tells us that projects at
least that large are feasible.  What does the *ending* of Grail
development tell us about Python's suitability for development of
large projects?  Not a lot: all we know is that it *didn't* run into
the problems that afflict large-scale projects (if you believe the
tarball README, anyway).

Others provided (in a different bit of the thread) at least one
example of a much larger system, solving a problem that would take a
best-estimate of on the order of a million lines of C++ code if solved
in C++.  Other people posted examples in an thread last year:
eg. Peter Hansen with another project the same size as Zope (there
have been lots of other threads too, by the look of it -- but I
haven't scoured those for examples).  Twisted is at least that big,
too (according to pycount.py run on the old version of Twisted that's
sitting on my hard drive -- again, it seems to spit out multiple total
lines, so I hope it's working right...!).

Of course, the above two paragraphs (implicitly) points out the big
joke here: it seems hard to dispute that reducing the number of lines
of code needed by an order of magnitude is a good way of reducing risk
on big projects.  Now, what sort of language would you pick to achieve
that?  C++ or Java?  Or Lisp or Python?

not-holding-my-breath-for-your-answer--ly y'rs,


John


From ajsiegel at optonline.com  Wed Jan 21 15:20:17 2004
From: ajsiegel at optonline.com (Arthur)
Date: Wed, 21 Jan 2004 20:20:17 GMT
Subject: [Numpy-discussion] Status of Numeric
References: 
	
	
Message-ID: 

On Wed, 21 Jan 2004 13:31:01 -0500, "Humpty Dumpty"
 wrote:

>
>"Paul Dubois"  wrote in message
>news:mailman.533.1074574795.12720.python-list at python.org...
>> Having two array classes around is a terrible idea. Once you have two
>> popular array classes the entire world bifurcates. This plot package
>
>I second that vehemently.
>
>> I only suggested we do numarray because Numeric was, by general
>> agreement, unmaintainable.  It was hard to work on and lacked the kind
>> of robustness necessary to get permission to put it in the core. We all
>> agreed Numeric would cease. Let's stick to the plan.
>
>However, I think experience has shown that users tend to go for better
>performance rather than better design.
>
>So why couldn't Numeric be redesigned for maintainability, but keep the
>algorithms that make it more performant than numarray?  Does the interface
>need to change?
>
>Oliver
>

>From where I sit, these look like very important questions in regard
to Python's future.

I certainly have no answers.

Paul seems to mention that one of the goals of numarray was to achieve
something clean and maintainable enough to move to a module of the
Python core distrtibution..  

Which, to me, seems like a worthy goal. 

On the other hand, it would seem that the goal of something to move
into the core would be performance optimized at the range of array
size most commonly encountered.  Rather than for the extraodrinary,
which seems to be the goal of numarray, responding to specific needs
of the numarray development team's applications.

Has the core Python development team given out clues about their
feelings/requirements for a move of either Numeric or numarray into
the core? 

It concerns me that this thread isn't trafficked.

Is it that folks feel that the stauts quo: an actively maintained 3rd
party package for numerical operations on multidimensional arrays, is
adequate.  With numarray to replace Numeric as the standard. And
performance nuances relatively unimportant.

I see nothing terrible about that position, and hope that that is the
tacit measage of the lack of respoonse to the thread.

Certainly folks can't be considering the global issues here simply
unimportant.

Art


From bcd at pvv.ntnu.no  Wed Jan 14 09:16:02 2004
From: bcd at pvv.ntnu.no (Bent C Dalager)
Date: Wed, 14 Jan 2004 14:16:02 +0000 (UTC)
Subject: ProtoCiv: porting Freeciv to Python CANNED
References: 
	
	
	<4004EC9E.1E2E2893@alcyone.com>
Message-ID: 

In article <4004EC9E.1E2E2893 at alcyone.com>,
Erik Max Francis   wrote:
>
>If you're saying that you've come to the realization that volunteer
>programers on a project with which you only have a passing interest
>won't follow your orders and do whatever you say, I'd say pointing that
>out is less like "denigration" and more like "common goddamn sense."

It is, never the less, worth pointing out. It would seem that Brandon
entered the scene with an idea that OSS developers might be incredibly
useful to him for some reason or other. Other game developers might
very well have the same idea. When Brandon finds out that this is not
the case and describes in some detail why OSS won't do the job for
him, than this can certainly be useful for other game developers to
learn so that don't have to spend 6 months figuring out the exact same
thing themselves.

The conclusion may seem obvious to _you_ but this is no guarantee that
everyone else also possesses this knowledge. OSS is being hailed as
the second coming, and it comes as no surprise therefore that some
people might be deluded into thinking they could harness this power to
cure cancer overnight or land a man on Mars by 2005.

Cheers
	Bent D
-- 
Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd
                                    powered by emacs


From jcribbs at twmi.rr.com  Thu Jan 29 23:33:24 2004
From: jcribbs at twmi.rr.com (Jamey Cribbs)
Date: Fri, 30 Jan 2004 04:33:24 GMT
Subject: Printing From Python
In-Reply-To: <8089854e.0401290555.501f0695@posting.google.com>
References: <8089854e.0401290555.501f0695@posting.google.com>
Message-ID: 

Fuzzyman wrote:

> Any 'print' modules out there - that implement cross platform printing
> interfaces ?

Well, this solution isn't cross platform, it isn't written in Python, 
and it isn't free, but I have used it quite a bit and it works great (on 
Windows, at least).

Rpv (http://www.rpvreport.com) is a report generator that is totally 
unlike Crystal Reports or other products.  To me, it fills a great niche 
between complex, gui-designer report writers like Crystal, and the other 
end of the spectrum such as trying to format text as an html document 
and then doing an external call to your web browser.

Basically, Rpv is a program that will read a text file that your program 
creates that will have all of the data that you want to print.  It then 
reads a template file (another text file) that you create beforehand, 
which tells it how to format the report, where to place the data from 
the text file, where the headers go, etc.

So, basically the steps I use in a program to let the user print data are:

1).  Create the text file containing the data.
2).  Do an external call to Rpv, passing it the name of the text file 
and the name of the template file.
3).  Rpv then opens up a nice print preview window that shows the user 
what the report will look like with all of the data included.
4).  The user can then press the print button in the preview window and 
print the report.

Combined with pygtk (or wxPython), it makes your application look 
professional.

And Rpv is pretty cheap.  I think I paid something like $40 for an 
royalty free version that lets me use it and distribute the runtime to 
all my customers.

Also, I have absolutely no connection to the makers of Rpv, I just 
really like their product.

Hope this helps.

Jamey


From cookedm+news at physics.mcmaster.ca  Mon Jan 12 21:51:00 2004
From: cookedm+news at physics.mcmaster.ca (David M. Cooke)
Date: Mon, 12 Jan 2004 21:51:00 -0500
Subject: building strings with variable input
References: 
	<400273B8.E991F41D@alcyone.com>
	
	<4002F93D.298A2394@alcyone.com>
Message-ID: 

At some point, Erik Max Francis  wrote:

> "David M. Cooke" wrote:
>
>> In which case he's probably better off with his original format
>> (almost):
>> 
>> cmd = '"$executable" -start "$startTime" -end "$endTime" -dir \
>> "$directory"'
>> os.environ['executable'] = 'blah'
>> os.environ['startTime'] = '12'
>> os.environ['endTime'] = '18'
>> os.environ['directory'] = './'
>> os.system(cmd)
>
> This doesn't resolve the underlying possibility for mailicious people in
> control of the contents of those variables to get it to execute
> arbitrary shell code.  (In his case he says it isn't an issue, but
> still.)

Do you mean something like
os.environ['startTime'] = '`rm -rf /`'
?
That 'rm -rf /' *won't* be executed: the shell will expand
"$startTime" to "`rm -rf /`", and that's it. Of course, if the
executable you're calling is a shell script that doesn't handle it's
arguments correctly, then you're in trouble. That means $executable is
bad practice -- you're allowing arbitrary commands to be called.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca


From serve at detongiser.com  Wed Jan 14 15:58:18 2004
From: serve at detongiser.com (Servé Lau)
Date: Wed, 14 Jan 2004 21:58:18 +0100
Subject: ProtoCiv: porting Freeciv to Python CANNED
References: 
	
	
	
	
	
	<4004EC9E.1E2E2893@alcyone.com>
	<23891c90.0401140223.344b22af@posting.google.com>
Message-ID: <100bbb6kj9m03a4@corp.supernews.com>

"Paul Boddie"  wrote in message
news:23891c90.0401140223.344b22af at posting.google.com...
> Erik Max Francis  wrote in message
news:<4004EC9E.1E2E2893 at alcyone.com>...
> >
> > There are plenty of things you can get out of starting, getting involved
> > with, and approaching open source projects.  A legion of personal
> > servants is not going to be one of them, and only a crass idiot would
> > think otherwise.
>
> As far as I've been able to discover, life is just one long cocktail
> party in Brandon's honour. So it isn't exactly surprising that
> everyone appears to him as just another waiter with a tray of drinks.

Well said, that's just how he sounds.
I think I'm gonna create a new sig

"I won't stop denigrating OS people for being incapable of fulfillng the
kinds of projects I have in mind
Brandon J. Van Every"




From sdeibel at wingide.com  Tue Jan 13 16:49:50 2004
From: sdeibel at wingide.com (Stephan Deibel)
Date: Tue, 13 Jan 2004 16:49:50 -0500 (EST)
Subject: Support for docutils/ReST sprint at PyCon?
Message-ID: 

Hi,

This is probably only of interest to docutils/ReST users:

I'm trying to help get David Goodger, author of docutils, to PyCon 2004 so
he can lead a docutils/ReST sprint there.  Since he's currently looking
for work (*) and can't make it w/o support, I've taken it upon myself to
try to get enough pledges of $ from interested people to make this
possible.

(*) http://starship.python.net/~goodger/cv/resume_David_Goodger.html).

If you would like to make a donation pledge, please email me with the
amount you'ld be willing to give, and whether or not you want to remain
anonymous.  If there are enough donations in all, we'll figure out ways to
get the money to David.  If we end up falling short, then nobody has to
pay.

The total needed is $500 (US) w/o lodging, more if no free overnight
option is found.  I've currently got $287 in pledges, so hope I might 
find a few more donations here on the general Python list.

More information on the conference is here:

http://pycon.org/dc2004/

Note that the sprints are March 20-23, before the main conference dates
of March 24-26.

Thanks very much!

Stephan Deibel

--
Wing IDE for Python
Archaeopteryx Software, Inc
Take Flight!

www.wingide.com





From a_kabaila at yahoo.com.au  Sat Jan  3 04:19:05 2004
From: a_kabaila at yahoo.com.au (Al Kabaila)
Date: Sat, 03 Jan 2004 20:19:05 +1100
Subject: Starting a script interactively?
References: <37d5fe8f.0401021305.349a440@posting.google.com>
Message-ID: 

David Klaffenbach wrote:

> Is there a way from within a python script to cause the interpreter to
> be in interactive mode after the script finishes?
> 
> so that if I run:
> 
> myscript.py
> 
> it will always execute as if I had run:
> 
> python23.exe -i myscript.py
> 

In Linux OS, add first line in myscript.py as follows:

#! //python

and make sure that myscript.py is executable.  I don't know if this works
under dos, but there should be some equivalent.

Regards,
-- 
Al Kabaila, a_kabaila at yahoo.com.au


From gsmith at oxfam.org.uk  Thu Jan 29 04:28:02 2004
From: gsmith at oxfam.org.uk (Graham)
Date: Thu, 29 Jan 2004 09:28:02 -0000
Subject: Distributing Python programs
References: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net>
	<4017C6EE.E7F1B27@engcorp.com>
	<4017cd62$0$9388$ed9e5944@reading.news.pipex.net>
	<40180790.FED25AB8@engcorp.com>
Message-ID: <4018d298$0$9387$ed9e5944@reading.news.pipex.net>

Thank you to Peter, Skip and Premshree for your help.  I got my network
install of Python up and running and all is well !!!

regards
Graham Smith

PeopleSoft Technical Team Leader
OXFAM GB
+44 (1865) 313255
gsmith at oxfam.org.uk




From yaipa at yahoo.com  Tue Jan  6 22:50:23 2004
From: yaipa at yahoo.com (yaipa h.)
Date: 6 Jan 2004 19:50:23 -0800
Subject: ASCII characters in my hex output
References: 
Message-ID: <6e07b825.0401061950.680bc643@posting.google.com>

Kelia,

Google,
  " binascii.hexlify " 

at 

  http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.python


If your converting a Basic program, I did the same and you can
find it by googling 'Eurotherm'.

  --yaipa

"nuvodido"  wrote in message news:...
> I am using pyserial to work with a device on my serial port.  the 
> output is a mixture of ASCII and hex: 
> 
> Ex.	'\x10\x00*'
> 
> 
> I need conver the \x00* nuber in to decimal.  Is there way to 
> convter this value striat forward?
> 
> 
> Thanks in advance
> Kelia Nichols
> ______________________________________
> No trees were killed in the sending of this message. However a large 
> number of electrons were terribly inconvenienced.


From amy-g-art at cox.net  Fri Jan 23 17:02:27 2004
From: amy-g-art at cox.net (Amy G)
Date: Fri, 23 Jan 2004 14:02:27 -0800
Subject: Various strings to dates.
References: <4GfQb.16187$AA6.14368@fed1read03>
	
Message-ID: 

No it won't.  Unfortunatly I don't necessarily have a comma delimited date
string.  Thanks for the input though.

The following three date strings is another example of the various date
formats I will encounter here.

Thursday, 22 January 2004 03:15:06
Thursday, January 22, 2004, 03:15:06
2004, Thursday, 22 January 03:15:06

All of these are essentially the same date... just in various formats.  I
would like to parse through them and get a comparable format so that I can
display them in chronological order.


"wes weston"  wrote in message
news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net...
> Amy,
>     I hope there is a better way but, if you go here:
>
> http://www.python.org/doc/current/lib/datetime-date.html
>
> The new datetime module may help. This and the time mod
> should get you where you want to go.
>
> list     = strdate.split(", ")
> daystr   = list[0]
> daynum   = int(list[1])
> monthstr = list[2]
> year     = int(list[3])
> #funct to get a month int is needed
>
> d = datetime.Date(y,m,d)
>
> wes
>
> ---------------------------------------
>
> Amy G wrote:
> > I have seen something about this beofore on this forum, but my google
search
> > didn't come up with the answer I am looking for.
> >
> > I have a list of tuples.  Each tuple is in the following format:
> >
> > ("data", "moredata", "evenmoredata", "date string")
> >
> > The date string is my concern.  This is the date stamp from an email.
> > The problem is that I have a whole bunch of variations when it comes to
the
> > format that the date string is in.  For example I could have the
following
> > two tuples:
> >
> > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15")
> > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004
03:15:06")
> >
> > I know there is some way to use the date string from each of these to
get a
> > date usable by python, but I cannot figure it out.
> > I was trying to use time.strptime but have been unsuccesful thus far.
> >
> > Any help is appreciated.
> >
> >
>




From erwin+usenet at andreasen.org  Tue Jan 13 08:12:39 2004
From: erwin+usenet at andreasen.org (Erwin S. Andreasen)
Date: Tue, 13 Jan 2004 14:12:39 +0100
Subject: error with /usr/lib/python2.3/compileall.py: "Sorry invalid
 mode: U"
References: 
Message-ID: <877jzwouuw.fsf@andreasen.org>

Marco Herrn  writes:

> I tried to install a package under debian, where in the postinstall
> phase some python scripts are called. Then I got the error
> "Sorry invalid mode: U".

> I looked what this script does and it is the following:
>
> 	python -O /usr/lib/python2.3/compileall.py /usr/share/woody

I think this happens because your "python" is really a link to a
pre-2.3 python. The 'U' option to open appeared in 2.3.


-- 
===============================================================
                           Herlev, Denmark     
                             <*>   
===============================================================



From yet-another at no-domain.cn  Fri Jan  2 02:33:47 2004
From: yet-another at no-domain.cn (Jules Dubois)
Date: Fri, 2 Jan 2004 00:33:47 -0700
Subject: Where to go from here? newbee
References: 
	<1koon5kaqkghf.211m8yj2j32t$.dlg@40tude.net>
	
Message-ID: <1qjsrabfr90m7.1rrmuiqe42xpb.dlg@40tude.net>

On Thu, 1 Jan 2004 09:45:00 -0600, in article
, Richard wrote:

>  Jules Dubois wrote:
> 
>  > Go to http://www.cs.unm.edu/~ej and click on these links.
> 
>  >   Python Hacking I (Just do it!)
>  >   Python Hacking II (types, functions, exceptions)
>  >   Python Hacking III
> 
>  > Type the commands and see what happens.
> 
> Ok. Now I'm slowly understanding.

In an earlier article, you said "It's like teaching 1st grade stuff to a
college grad."  These files were created by a university senior and were
intended as quick-and-dirty "tutorials", introducing Python to a
senior-level engineering class.  All were new to Python.

What I liked about the tutorials was they were instructive but required the
user to determine the correspondence between the input and output.  If you
or anyone else wants the tutorials, download them now before the account is
removed.  I believe the author graduated in December.

> I guess you could say that python is
> similar to visual basic and c++ in coding.

It's not much like Visual Basic and is perhaps somewhat similar to C++.  As
I learn Smalltalk, what I'm noticing more and more is how similar they are
-- less Smalltalk's integrated environment.

Further, if you're an experienced programmer, I recommend _Python in a
Nutshell_ by Alex Martelli.  I've read it cover to cover about a dozen
times now and my conclusion is that it's one of the very best programming
language books I've read (and I've read many in the last 25 years.)

Finally, download the Python documentation from Python.org.

> I have a program written in python which has several "py" files included.
> How do I view these for the coding examples?

.py files are source code, so load them into your favorite text editor.  I
use XEmacs.


From na  Fri Jan  9 15:10:28 2004
From: na (Andrew)
Date: Fri, 9 Jan 2004 12:10:28 -0800
Subject: How to insert into listbox using wxPython
References: 
	<3ffda907$0$572$b45e6eb0@senator-bedfellow.mit.edu>
Message-ID: 

Hi thanks for your help but I am still having problems basically I am using
a button to connect to a Database and I want to display the data from the
database into the listbox
Here is the code I am using for the button

    def OnB2Button(self, event):
        self.db = MySQLdb.connect("localhost", "", "", "guestbook")
        global db
        self.c = self.db.cursor()
        self.c.execute("SELECT * FROM guests;")
        self.results = self.c.fetchall()
        # Here is where I don't know what to do I want to be able to get the
data from self.results and display it in the listbox
        self.listbox.Append('')
        self.listbox.Set([''])
        self.listbox.Delete(0)
        print self.listbox.GetSelections()
        self.sizer.Add(self.listbox, 0, wxEXPAND)
        self.Set.Sizer(self.sizer)

Thank you again for your help

Cheers

Andrew




From swalters_usenet at yahoo.com  Sun Jan 11 02:47:26 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Sun, 11 Jan 2004 07:47:26 GMT
Subject: readling newlines
References: 
Message-ID: 

|Thus Spake Alessandro Crugnola *sephiroth* On the now historical date of
Sat, 10 Jan 2004 14:25:44 +0000|

> Hi, I'm trying to detect the newlines method of a file opened. I'm using
> the 'U' mode as parameter when opening a file, but for every file opened
> the result is always "\r\n", even if the file has been saved with the
> "\n" newline method. Is there i'm missing?
> 
> I'm on Windows with python 2.3.3

Not quite sure what "U" mode is, but try adding the "b" mode when opening
the file.  Windows makes a distinction between binary and text files. 
Python defaults to text mode, and since newlines for windows text is \r\n,
that's what Python puts there.

HTH

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From pinard at iro.umontreal.ca  Tue Jan 20 19:18:15 2004
From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard)
Date: Tue, 20 Jan 2004 19:18:15 -0500
Subject: calling Pyrex results from C
In-Reply-To: <20040120234855.GV22782@jowls>
References: 
	<20040120172733.GA7666@titan.progiciels-bpi.ca>
	<20040120234855.GV22782@jowls>
Message-ID: <20040121001815.GA22127@alcyon.progiciels-bpi.ca>

[Kyler Laird]
> On Tue, Jan 20, 2004 at 12:27:33PM -0500, Fran?ois Pinard wrote:

> > There is some magic needed to establish Python context, not much.
> > Hoping that it will help, here is a template I use when generating
> > Pyrex main programs.

> Paul started me on this path and you've given me exactly what I need to
> keep going.

Good. :-)

There is also some linking magic, which differs from system to system,
it might be documented in the Python Embedding API, I'm not sure.  If
you do not stumble on the proper recipe, I'll share what I use on Linux.
Just ask if you want me to go search into some of my Makefiles :-).

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



From ramen at lackingtalent.com  Thu Jan 22 02:12:02 2004
From: ramen at lackingtalent.com (Dave Benjamin)
Date: Thu, 22 Jan 2004 07:12:02 -0000
Subject: Do (USA) Python conferences require a coast?
References: <6b50e1-goo.ln1@jowls.lairds.org> 
Message-ID: 

In article , Aahz wrote:
> In article <6b50e1-goo.ln1 at jowls.lairds.org>,
> Kyler Laird   wrote:
>>
>>It looks like PyCon
>>	http://pycon.org/
>>is always in Washington, DC.  I try to avoid DC.
> 
> It's kind of hard to say "always" about a conference that hasn't had its
> second iteration yet.  ;-)

Well, it does make it particularly hard to find a counterexample. ;)

How about Phoenix, Arizona? The only time we have a coast is if there's
enough money in it for lakefront real estate.

Effortlessly avoiding DC,
Dave

-- 
.:[ dave benjamin (rameny sp00) -:- spoomusic.com -:- ramenfest.com ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :


From xpythonist at yahoo.com.br  Tue Jan 20 06:27:00 2004
From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=)
Date: Tue, 20 Jan 2004 08:27:00 -0300 (ART)
Subject: Escaping slashes (double backslash plague)
In-Reply-To: <20040119202933.GA10765@nl.linux.org>
Message-ID: <20040120112700.98379.qmail@web21508.mail.yahoo.com>

 --- Peter Hansen  escreveu: 

> If this isn't what you're trying to do, please
> explain more thoroughly
> what your goal is, because it seems very unnecessary
> to be putting 
> \/ into a string for any reason (whether as a path
> or not) ...
> 
> -Peter

Yes, that is what I was trying to do, and five minutes
after posting I realized that it was a very stupid
idea. I apologize for bothering you and the others
asking things I should have figured out myself. But
thanks anyway, because your explanation helped me to
clarify some misconceptions I had about strings in
python!

Aloysio

______________________________________________________________________

Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis!
http://br.geocities.yahoo.com/



From swalters_usenet at yahoo.com  Sun Jan 18 22:44:49 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Mon, 19 Jan 2004 03:44:49 GMT
Subject: re question - finiding matching ()
References: <4f0a9fdb.0401180751.4b66d974@posting.google.com>
	<7xr7xwyhws.fsf@ruckus.brouhaha.com>
Message-ID: 

| Paul Rubin said |

> miki.tebeka at zoran.com (Miki Tebeka) writes:
>> I'd like to find all of the sub strings in the form "add(.*)"
>> The catch is that I might have () in the string (e.g. "add((2 * 2), 100)"), 
> 
> You can't do that with classic regexps.  You need a parser, not a scanner.

Or, to put it slightly differently:

Regexps are a type of system that is not mathematically powerful enough to
handle this type of identification.  The next step up in power are
parsers.

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From jsbenson at bensonsystems.com  Thu Jan 15 14:01:19 2004
From: jsbenson at bensonsystems.com (John Benson)
Date: Thu, 15 Jan 2004 11:01:19 -0800
Subject: the thread that refused to die: I come not to bury C++,
	but to praise it...
Message-ID: <0bf101c3db99$f64fa5c0$8d09500a@jsbwxp3>

Regarding the post below, I'm not against anything that helps you get work
done. There are just a lot of tradeoffs, and the rather spirited discussion
of C++ over the last few days has highlighted a lot of them. My spiritual
master Dogbert once said, "Assume that everybody has had the same
experiences as you; then, if they disagree, they must be stupid." In my
experience, C++ was only a short detour between C and Python due to the
vagaries of my job history. It's dawning on me, however, that not everyone
had the same experiences, that there is a lot of valuable C++ expertise out
there, and that C++ may well be around for longer than I initially thought.

My initial purpose in this thread was to try to help people "let go" of C++,
static typing (and maybe even Java!) by putting some historical perspective
on it. I suppose the exercise was hypocritical, because I'm still holding
onto my Commodore 64, Kaypro PC, and, of course, the C language. Go figure.
I am happy, however, that the thread dislodged some interesting comments
from the convolutions of various contributors.

Message: 4
Date: Thu, 15 Jan 2004 03:03:53 GMT
From: "python newbie" 
Subject: Re: I come not to bury C++, but to praise it...
To: python-list at python.org
Message-ID: 

Are you against using C++ wrapped in a library such as wxWindows?  This
library makes it pretty easy painless to write cross-platform stuff, but
even on Windows alone, it beats MFC or the going price of Delphi.







From swalters_usenet at yahoo.com  Thu Jan 15 00:30:12 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Thu, 15 Jan 2004 05:30:12 GMT
Subject: Printing to console (No Scroll)
References: 
Message-ID: 

The cheesy dirt simple way:

 print "Closing window in :"
 for second in range(10):
     time.sleep(1)
     #print enough spaces to cover up the last message.
     print " "*20 + "\r",
     print `10-second` +" seconds",

Note the comma at the end of each print statement.
That causes python not to output a newline.

HTH

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From llothar at web.de  Sat Jan 31 23:51:53 2004
From: llothar at web.de (Lothar Scholz)
Date: 31 Jan 2004 20:51:53 -0800
Subject: OT: why do web BBS's and blogs get so slow?
References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com>
Message-ID: <6ee58e07.0401312051.5688006c@posting.google.com>

Paul Rubin  wrote in message news:<7xbrojk9rk.fsf_-_ at ruckus.brouhaha.com>...
> Lots of times, when a blog (that supports user comments) or a web BBS
> gets heavily loaded, it slows down horribly, even when it's hosted at
> an ISP on a fast computer with plenty of net bandwidth.  I'm wondering
> what those programs are doing, that makes them bog down so badly.
> Anyone know what the main bottlenecks are?  I'm just imagining them
> doing a bunch of really dumb things.

The problem is that most of them don't use an application server and
that most of them uses databases very unoptimized, for example PhpBB
runs about 50 SQL queries per page for medium size thread views.

The www.asp-shareware.org has a nice framework that let you view the
messages in an nntp server. It's amazing fast, because everything is
hold in memory. Optimizing this by a factor 10 is not difficult.

The problem may come with slashdot or for example the german website
"www.heise.de" which gets upto 100 requests per second (it's among the
top ten in germany). They also use a NNTP backend. For sites like this
you need multiple server and then its not so easy to maintain cache
coherence. But there are only very few websites that have this
traffic.

At the moment there seems to be absolute no evolution in the area of
BBS's. PHPBB has set a standart an it seems that nobody is able to
think about more/other functionality. Maybe if more and more people
get virtual servers and have more control over what they can install
then it may become better. We shall see.


From edcjones at erols.com  Sun Jan 25 22:33:41 2004
From: edcjones at erols.com (Edward C. Jones)
Date: Sun, 25 Jan 2004 22:33:41 -0500
Subject: efficient updating of nested dictionaries
In-Reply-To: 
References: 
Message-ID: <40148b8d$0$7336$61fed72c@news.rcn.com>

omission9 wrote:
> I have a dictionary that looks like this
> MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO
> 
> I am having a problem updating this with a simple 
> MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting 
> into the inner dicts.
> Getting the keys of each and iterating through and updating each one is 
> terribly slow as the number of keys gets bigger and bigger.
> What is the bst way to update my nested dicts?

Make a table whose rows are (KEY_X, KEY_Y, KEY_Z, FOO). If the table is 
large use MySQL or some other database. For small or medium sized tables 
try "http://members.tripod.com/~edcjones/MultiDict.py".


From peter at engcorp.com  Tue Jan 13 14:21:16 2004
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 13 Jan 2004 14:21:16 -0500
Subject: Division oddity
References: 
	<7xeku5vrn8.fsf@ruckus.brouhaha.com>
	
	<400413E0.5C691A56@engcorp.com>
	
Message-ID: <4004452C.47DB4C4@engcorp.com>

Michael Hudson wrote:
> 
> Peter Hansen  writes:
> 
> > Tim Rowe wrote:
> > >
> > > Well, the documentation for "input()" says "Equivalent to
> > > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/
> > > equivalent...."
> >
> > I remember reading that too, and just assumed that at this point
> > it was in fact *implemented* that way, as a simple alias.  Maybe
> > it should be...
> 
> http://www.python.org/sf/876178
> 
> Ideas on how to write a testcase welcome.

Are there any test cases which verify behaviour both in the presence
and absence of certain "from __future__ import" statements?

My first thought would have been simply to write two test files,
one of which imports from __future__ and the other which does not,
and check that in both cases input(x) == eval(raw_input(x)).  

Or is the issue how to test when the input comes from stdin?  In
that case, doesn't faking sys.stdin work as usual?

-Peter


From skip at pobox.com  Wed Jan 28 11:07:21 2004
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 28 Jan 2004 10:07:21 -0600
Subject: isinstance() bug
In-Reply-To: <20040128154119.GA11485@foof.i3.cz>
References: <20040128132225.GA10842@foof.i3.cz>
	<16407.54576.283608.505067@montanaro.dyndns.org>
	<20040128154119.GA11485@foof.i3.cz>
Message-ID: <16407.56889.446921.416710@montanaro.dyndns.org>


    >> You imported the module twice (look at sys.modules) so you have two
    >> different A classes.

    Michal>  i think that if absolute path was somehow put into the classes
    Michal>  internal information this inconsistency would be put away.

Perhaps.  Try it and see.  Patches are welcome... ;-)
 
    Michal>  and as to the sys.modules thing: this could be considered as
    Michal>  just two references to the same module (again its absolute path
    Michal>  would be taken into account), not two different modules.

    Michal>  does it make sense?

Yup.  Patches are welcome. 

Skip



From bkelley at wi.mit.edu  Thu Jan 29 16:57:00 2004
From: bkelley at wi.mit.edu (Brian Kelley)
Date: Thu, 29 Jan 2004 16:57:00 -0500
Subject: Python vs. Io
In-Reply-To: <101iv0ri062ag22@news.supernews.com>
References: <711c7390.0401291301.3f95794@posting.google.com>
	<101iv0ri062ag22@news.supernews.com>
Message-ID: <4019813c$0$559$b45e6eb0@senator-bedfellow.mit.edu>

John Roth wrote:
> "Daniel Ehrenberg"  wrote in message
> news:711c7390.0401291301.3f95794 at posting.google.com...
> 
> 
>>Can anyone show me how to so much as alias "for" to "each" in Python
> 
> 
> Without getting into the language wars, I think what you're looking
> for is called the Visitor Pattern (Design Patterns: GOF). It's actually
> trivial to implement as long as you're not looking for built-in support.

I think Daniel's example is a little bit more complicated than that.  It 
resembles more closly the lisp-ish macros that were discussed to death a 
while ago.

Note that in his code:
each((key, value) in map(x=1, y=2, z=3),
     write(key, ": ", value, "\n")
)

key and value are variable names that get used inside the function call.

Here is my pythonic(?) version, however it requries a lambda to bind the 
variable names.

def map(**kw):
     return kw.items()

def each(seq, func):
     for v in seq:
         apply(func, v)

from sys import stdout
write = stdout.write

each(map(x=1,y=2,z=3),
      lambda key, value: write("%s: %s\n"%(key, value)))

Brian



From wfolta at netmail.to  Sun Jan 18 22:47:26 2004
From: wfolta at netmail.to (Wayne Folta)
Date: Sun, 18 Jan 2004 22:47:26 -0500
Subject: New to Python: my impression v. Perl/Ruby
Message-ID: <3296C411-4A32-11D8-9496-000A959CB2EC@netmail.to>

I've been a long-time Perl programmer, though I've not used a boatload 
of packages nor much of the tacky OO.

A couple of years ago, I decided to look into Python and Ruby. Python 
looked OK, but not that different. I did like the indent-as-group idea, 
which was different. Ruby looked very cool. But it was impossible to 
get good documentation. It seemed like a Japanese cult with a few 
western initiates.

Well, MacOS X ships with Perl, Python, and Ruby (and PHP, and ...) so I 
recently figured I'd try them again. I still find Ruby more intriguing, 
but I've settled on Python. Why?

Well, Perl is an expedient measure that (for me) doesn't scale up and 
has that horrible OO syntax. (So I never used it much.) If you're going 
to read someone else's Perl, you had better be "in the zone".

A couple of months ago, I'd written a quick Perl script that would 
"unstick" a co-worker's POP email. The problem is the Windows-based POP 
server is too stupid to realize a message does not end in CRLF, so it 
just appends a period then CRLF thinking it's doing well. But the 
period ends up not being alone on a line, so it's not a valid 
termination to the message. So their email program hangs waiting for a 
proper termination. Sigh.

A week ago, the script broke because I hadn't properly accounted for 
the fact that the user might have hundreds of messages queued up. (I 
hadn't used a Perl POP package, which might've handled it, but just 
threw it together myself. Yes, that would've made the Perl code more 
competitive with the other two solutions.)

So I decided this might be a nice exercise to try Python. And it went 
together very quickly using Python's POP3 package. Then I decided to 
try it in Ruby. I think one little portion of the code shows the 
difference between the two cultures.

The problem is that the message is not properly terminated, so you need 
to time out and catch that timeout to realize, "hmmm, malformed". In 
Python I had:

M = poplib.POP3 ('172.16.30.1') ;
M.user ('foo') ;
M.pass_ ('bar')

num_mesgs = len (M.list ()[1])
bad_mesgs = 0

for msg in range (num_mesgs):
	try:
		M.retr (msg + 1)
... blah blah...

How do I get it to time out after 5 seconds and how do I catch that? 
The online docs are pretty good, but I had to guess that POP3 was built 
on the socket package. Looking at socket's docs I found the proper 
command and exception. I had to include:

socket.setdefaulttimeout (5.0)

before the POP3 commands to set the default socket timeout to 5 
seconds. And

except socket.timeout:

is the proper way to catch the timeout. Both of these things are in the 
socket documentation.

Contrast this with Ruby. The Ruby docs are less complete, but they did 
mention that POP was subclassed from protocol and you'd have to look at 
protocol's source to see how it works. Looking through protocol, I 
figured out what to do and it was more elegant.

The protocol class had a read_timeout, but since Ruby's mantra might be 
said to be "Real OO", the POP code had been written such that you could 
say

pop.read_timeout = 5

after the POP open and it set the timeout for that pop connection to 5 
seconds. Almost as if POP passed the read_timeout upstream to socket 
automatically. (I don't think Ruby does, but it's coded to look that 
way.)

My experience is limited, but it feels like this example gives a good 
feel for the two languages. Python was better documented and things 
came together quickly. Ruby ultimately had a more elegant solution, but 
was more poorly documented. This echoes the mantras: Python's is 
"Batteries Included", while Ruby's might be "Real OO".

On a personal note, I usually prefer an elegant solution, but when the 
language goes so far as to consider

0.step(360, 45)

to be reasonable, my head hurts. I know there's syntactic sugar so I 
don't have to code like that. I know everything's an object. But, 
dammit, a constant integer is an integer with constant value and 
causing it to iterate is a step too far.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 4917 bytes
Desc: not available
URL: 

From asterix5 at tiscali.fr  Mon Jan 26 04:16:23 2004
From: asterix5 at tiscali.fr (asterix5 at tiscali.fr)
Date: Mon, 26 Jan 2004 09:16:23 GMT
Subject: any news client in Python?
Message-ID: <4014db58$0$7162$626a54ce@news.free.fr>


Had you tried Naja? It's a newsreader with a csv filter.

http://www.keyphrene.com/products/naja


From carroll at tjc.com  Sat Jan 24 22:17:06 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sun, 25 Jan 2004 03:17:06 GMT
Subject: Newbie Nested Function Problem
References: 
Message-ID: <52d610h685a613ua1tk5k8f11cv1d61q0b@4ax.com>

On Sun, 25 Jan 2004 02:45:02 GMT, "Brian Samek"
 wrote:

>I began learning python a few days ago and just wrote the following program.
>I have nested three functions together.  For some reason, the leave function
>works fine when 'y' or 'n' are inputted, but it does not restart itself when
>other things are inputted.  Why is this?

I haven't tried running this, but...

># This program counts down from a user-defined integer less than or equal
># to 500.
>
>print "This program counts down from any number less than or equal to 500"
>print
>
># ask_number gets the number from the user and then puts it into countdown
>
>def ask_number():
>    number = input("Please enter a number.\n")
>    if number > 500 or number - int(number) != 0 or number < 1:
>        print "Input positive integers less then 501 only, please."

Okay, ask_number doesn't do what you're saying.  It's asking for a number,
placed into variable number, and if it gets something out of range, prints
an error message.

And then ends.  It doesn't either a) repeat until it gets a valid number
or b) do anything with the number it gets, like pass it back to the caller
in a return statement, i.e.:

  return number

> ask_number()

Okay, you invoked ask_number, but didn't even try to get anything from it.
Normally, this would read something like:

number_in = asknumber()

>    else:

Um.. it looks like you're inadvertably making this a deeply recursive
call, probably something you want to stay away from until you have regular
stuff down pat.




From eurleif at ecritters.biz  Thu Jan 22 16:21:00 2004
From: eurleif at ecritters.biz (Leif K-Brooks)
Date: Thu, 22 Jan 2004 21:21:00 GMT
Subject: Ordered dictionary?
In-Reply-To: 
References: 
	
Message-ID: <09XPb.234$af7.167008@newshog.newsread.com>

Josiah Carlson wrote:
>> I need to associate a string (key) with an integer (value). A 
>> dictionary would do the job, except for the fact that it must be 
>> ordered. I also need to look up the value for a specific key easily, 
>> so a list of tuples wouldn't work.
> 
> 
> How must the dictionary be ordered?  Do you need the keys or the values 
> sorted?

Sorry for not making that clear, I need it sorted by the order of 
insertion. Looks like 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 might do 
what I want...



From http  Wed Jan 28 00:04:42 2004
From: http (Paul Rubin)
Date: 27 Jan 2004 21:04:42 -0800
Subject: little client + server app : has this been done?
References: 
Message-ID: <7x1xpkk6j9.fsf@ruckus.brouhaha.com>

Python Baby  writes:
> Should I do it from scratch or is this just some well-known library I
> don't know about?   (I searched around, of course, but couldn't find one.)
> 
> Thanks!

Use a web server.


From OlafMeding at compuserve.com  Thu Jan  8 14:03:10 2004
From: OlafMeding at compuserve.com (Olaf Meding)
Date: 8 Jan 2004 11:03:10 -0800
Subject: Name of the function
References: <9e5ea2c4.0401080640.64ef5d58@posting.google.com>
	
Message-ID: <9e5ea2c4.0401081103.6fa93bf9@posting.google.com>

Is there a way to do this w/o importing another module?

Yes this is what I was looking for except the code below requires
importing module inspect.

> def foo():
>      print inspect.currentframe().f_code.co_name

Thanks much for your reply.


Olaf


From guettli at thomas-guettler.de  Tue Jan  6 09:18:22 2004
From: guettli at thomas-guettler.de (Thomas Guettler)
Date: Tue, 06 Jan 2004 15:18:22 +0100
Subject: tuple.__hash__()
References: 
	
	
Message-ID: 

Am Tue, 06 Jan 2004 04:04:01 -0500 schrieb Mike C. Fletcher:

> Just wrote:
> AFAIK, the dictionary class simply uses the hash to sort into buckets, 
> providing fast indexing, before using equality to check whether the two 
> keys are equal. 

Thank you, that what I was asking for.

Here is a sample script which checks this:

from types import *

class MyHash:
    def __init__(self, id):
        assert(type(id)==IntType)
        self.id=id

    def __hash__(self):
        # All objects have the same hash value
        return 1

    def __cmp__(self, b):
        return cmp(self.id, b.id)

    def __repr__(self):
        return "" % self.id
    
def main():
    d={}
    i1=MyHash(1)
    d[i1]=1
    i2=MyHash(2)
    d[i2]=1
    i3=MyHash(3)
    d[i3]=1
    print d.items()

    # id=1 twice
    d[MyHash(1)]=1

    print d.items()
    # All right there are only three elements in the dict
    # Dictionaries use __cmp__ if __hash__ is equal.
    
if __name__=="__main__":
    main()
    
    	


From bokr at oz.net  Thu Jan  8 13:53:10 2004
From: bokr at oz.net (Bengt Richter)
Date: 8 Jan 2004 18:53:10 GMT
Subject: Integer math question
References: <3987e01c.0401030832.114c6f2a@posting.google.com>
Message-ID: 

On 3 Jan 2004 08:32:07 -0800, mersmann at szut.uni-bremen.de (Frank) wrote:

>Hi,
>
>can anybody help with the following problem?
>
>In C++
>
>i = 5 / 10 	and
>i = -5 / 10 	both have the same result 0.
>
>In python
>
>i = 5 / 10 	gives me 0 as expected, but
>i = -5 / 10 	gives -1 as result.
>
>Is this a feature or a bug? I remember Delphi gave me the same result as
>C++.
It is a feature. Python does the more useful thing IMO.
If you look on / (or now //) as a denominator-defined mapping
of integer intervals to integers, it is clearer.

I.e., the mappings that python implements are

    [denom*k, denom*k+denom) => k for denom >0
and
    [denom*k+denom, denom*k) => k for denom <0


The C version is ugly, because it maps a unique extra-sized interval
around zero to zero, i.e., for denom>0

    [-denom+1, denom) => 0

which contains 2*denom-1 source integers, and all the rest of the
intervals go symmetrically in both directions from there, containing
denom integers. Python's source intervals are all the same size.


====< showintdiv.cpp >=====================================
#include 
#include 
void main(int argc, char* argv[]){
    if(argc<4){ printf("Usage: %s xlo xhi den\n", argv[0]); return; }
    int xlo = atoi(argv[1]);
    int xhi = atoi(argv[2]);
    int den = atoi(argv[3]);
    int x;
    for(x=xlo; x======================================
printf = (lambda wso, fmt, *args: wso(fmt%args)).__get__(
            __import__('sys').stdout.write)

def main(argv):
    if len(argv)<4: printf("Usage: %s xlo xhi den\n" % argv[0]); return
    xlo = int(argv[1])
    xhi = int(argv[2])
    den = int(argv[3])
    for x in xrange(xlo, xhi): printf("%3d", x)
    printf("\n");
    for x in xrange(xlo, xhi): printf("%3d", x/den)
    printf("\n");

if __name__== '__main__':
    import sys
    main(sys.argv)
===========================================================


Python maps successive equal sized intervals to successive integers from -inf to +inf

[10:38] C:\pywk\clp>showintdiv.py   -15 16  5
-15-14-13-12-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
 -3 -3 -3 -3 -3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1  0  0  0  0  0  1  1  1  1  1  2  2  2  2  2  3

But C maps symmetrically across zero, causing 2*denom-1 points to map to zero

[10:38] C:\pywk\clp>showintdiv.exe  -15 16  5
-15-14-13-12-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
 -3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1  0  0  0  0  0  0  0  0  0  1  1  1  1  1  2  2  2  2  2  3

With a negative denominator, python still maps successive intervals, but going the other
direction from (and including) zero.

[10:38] C:\pywk\clp>showintdiv.py   -15 16 -5
-15-14-13-12-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
  3  2  2  2  2  2  1  1  1  1  1  0  0  0  0  0 -1 -1 -1 -1 -1 -2 -2 -2 -2 -2 -3 -3 -3 -3 -3

Whereas C is still symmetric with the 2n-1 points going to zero:

[10:38] C:\pywk\clp>showintdiv.exe  -15 16 -5
-15-14-13-12-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
  3  2  2  2  2  2  1  1  1  1  1  0  0  0  0  0  0  0  0  0 -1 -1 -1 -1 -1 -2 -2 -2 -2 -2 -3

The extra-sized interval across zero makes for a hiccup in the use of the mapping as a function.
E.g., you can't translate the input by k*denom and get a uniformly translated (by k) output
unless you stay away from the zero interval.

Ok, back to the grind...

Regards,
Bengt Richter


From swalters_usenet at yahoo.com  Tue Jan  6 01:20:20 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Tue, 06 Jan 2004 06:20:20 GMT
Subject: Python/C and PYTHONPATH
References: 
	
	
	
	
	
	
Message-ID: 

Ack...  definitely not pep-7 compliant code

And to think...  A co-worker once called me "obsessive" about indention.
(They say "obsessive," I say "consistent and legible.")

Well, It seems PAN likes to perform a stealth word-wrap when you edit from
the non-attached editor. (I used vim because I'm comfy hammering out code
there)  Nope, on second look, I must have accidentally mashed some keys
while in vim.  That extraneous "else" block is just a copy of the "else"
block.

If you run it through indent, and clean up a couple of oddball line-wraps
it will at least be legible. Remove the unneeded prototypes, embarrassing
extra else block, and it will compile. Remove the whole block about
searching for the = and fix the typo in the second setenv call (extrapath
should be eventual_path) and it will run without segfault.  Then replace
the ";" with ":" and it will run properly on a linux system.  For myself,
I made the snippet a little more general and added the option of choosing
which pathlist env variable and changed the function name to
envPathAppend. Then it's not a bad little snippet.


|Thus Spake Tero Pihlajakoski On the now historical date of Tue, 06 Jan
2004 01:04:31 +0000|

> Here. I might not want to add ';' or ':', depending on the OS (probably
> not)? I can solve this with #ifdefs for WIN32 and Linux, but everytime I
> want to run it on a new system, I'd have to find out the delimiter... It
> also needs a buffer underrun check on that [1024]. I'll stick with the
> PyRun_... for now, but I'll definitely save this code, so thanks. Again.

That buffer overrun is not the only bit of braindead logic in that
snippet.  The "success/failure" condition testing leaves a couple of loose
ends.

> Also, found this piece from sys.path docs (now that my net is up and
> running):
>   ... "A program is free to modify this (sys.path) list for its own
> purposes." ...

Hmmm...  I suppose it's a matter of aesthetics and scope of the project
you're working on.  If you're writing a big program for which the python
interpretor is only one small or medium part of the functionality and the
majority is c/c++, then you're opening up a whole big realm of
cross-platform issues.  However, if the bulk of your code is python, then
perhaps you should have the main program be in python with your extra c
code as a module. That would be cleaner and probably more portable.

I suspect that at this point you're just trying to tinker with the
interface, then use what's most comfortable.  Now at least, you have an
option.  Besides, it seems that someone already posted a cleaner fix than
I could have given you.

HTH

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From eastier at free.fr  Sat Jan 31 21:21:57 2004
From: eastier at free.fr (Emmanuel)
Date: Sun, 01 Feb 2004 03:21:57 +0100
Subject: How to optimised with embedded Python ?
Message-ID: <401C62C5.C5ECABF7@free.fr>

Hi,

I would like to use optimised python scripts ( *.pyo ), in order to gain
space.
But I use an embedded python. The compiler can only be run from my
application.
How do I set the compiler, from the C api, to create optimised files ?

Thanks by advance,

Emmanuel



From dan.ng at bullok.com  Sat Jan  3 19:59:42 2004
From: dan.ng at bullok.com (Dan Bullok)
Date: Sun, 04 Jan 2004 00:59:42 GMT
Subject: Parametrized inheritance
Message-ID: <2AJJb.725692$HS4.5422608@attbi_s01>

I have a couple of classes:
    class Base:
        ...

    class Sub(Base):
        ...


I want to subclass Base and Sub, i.e. define classes:
    class MyBase(Base):
        ...

    class MySub(Sub):
        ... 

The inheritance looks like this: 
    Base->MyBase
        ->Sub->MySub

But I'd really like it to look like this:
    Base->MyBase->Sub->MySub

i.e. define Sub as "class Sub(X)", where I can change X at the time of
instantiation.  Then I could define MySub as "class MySub(Sub(MyBase))".
(I hope that it's obvious that I'm looking for this effect, not this syntax)


Of course, someone is going to ask "why?"

I need to override a few members in Base.  Sub is mostly fine as-is, so if I
could have MySub=Sub(MyMBase), that would be fine.



    

                


From martin at v.loewis.de  Sat Jan 24 03:26:40 2004
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sat, 24 Jan 2004 09:26:40 +0100
Subject: utf8 encoding problem
In-Reply-To: 
References: <20040122103549.GA5620@wiggy.net>	
	
Message-ID: 

Wichert Akkerman wrote:


>>P.S. According to HTML standard, with
>>application/x-www-form-urlencoded content type form data are
>>resricted to ASCII codes:
[...]
> Luckily that is not true, otherwise it would be completely impossible to
> have websites using non-ascii input. To be specific, the encoding used
> for HTML forms is determined by:  [algorithm omitted]

As Denis explains, it is true. See 17.13.4

application/x-www-form-urlencoded
... Non-alphanumeric characters are replaced by `%HH', a percent sign 
and two hexadecimal digits representing the ASCII code of the character.

So this form is restricted only to characters which have an ASCII code,
i.e. ASCII characters.

To have non-ASCII input, use multipart/form-data:

multipart/form-data
...
The content type "multipart/form-data" should be used for submitting 
forms that contain files, non-ASCII data, and binary data.

This reconfirms that you should use it for non-ASCII.

Regards,
Martin



From baas at ira.uka.de  Sun Jan 18 13:49:55 2004
From: baas at ira.uka.de (Matthias Baas)
Date: Sun, 18 Jan 2004 19:49:55 +0100
Subject: ANN: Python Computer Graphics Kit v1.1.0
Message-ID: 

Release 1.1.0 of the Python Computer Graphics Kit is available at
http://cgkit.sourceforge.net

What is it?
-----------

The kit is a collection of Python modules that contain the basic types
and functions required for creating 3D computer graphics images. The
kit includes several new types such as vectors, matrices and
quaternions. It contains a binding for Pixar's RenderMan interface
which is a renderer independent API to communicate 3D data to
renderers which will finally produce a 2D image. There are already
several RenderMan compliant renderers freely available (they are not
part of the kit). The kit also includes some of the functionality from
the RenderMan Shading Language which enables you to create procedural
models or textures from within Python.

Even though the kit focuses on RenderMan, the new types or the Shading
Language functionality can also be used for other rendering mechanism
such as OpenGL or other renderers such as POV-Ray.

The kit should run on any platform where Python (and a C/C++ compiler)
is available. Windows users can download a binary version for Python
2.2 and Python 2.3.


What's new?
-----------

There are two new modules:

- cgkitinfo: Retrieve version information
- slparams: Extract RenderMan shader parameters from shader source

Other changes:

- The quaternion class has some new methods such as slerp() and
squad() (thanks to Max Rheiner)
- The RenderMan binding supports string handles and the (corrected)
version number can be suppressed (thanks to Moritz M?ller)

For a full list of changes see the changelog.


For more information, visit:

http://cgkit.sourceforge.net


- Matthias -



From jjl at pobox.com  Wed Jan 14 15:40:16 2004
From: jjl at pobox.com (John J. Lee)
Date: 14 Jan 2004 20:40:16 +0000
Subject: Why learn Python ??
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	
	<100655fo84c2211@corp.supernews.com>
	
	<87d69og2jl.fsf@pobox.com>
	
	<873cajafr8.fsf@pobox.com>
	
Message-ID: <873cai2rin.fsf@pobox.com>

"Derek"  writes:

> "John J. Lee" wrote:
[...]
> > for the
> > great majority of projects, optimisation does not require
> > implementation of the *entire* system in a language like
> > C++.  The sum of C++ and Python is greater than the parts.
> 
> Python and C++ can also be a bigger mess than sum of either part.
> Take your pick.

Not entirely sure what you mean, so I'll try and restate it:

You're saying that the C++ code for a Python extension is uglier than
the equivalent C++ code you'd write for a pure-C++ solution, where the
C++ code in question is that used to solve the *small part* of the
*whole* problem that you've farmed out to C++.  Right?

Actually, I think that's only true if you're writing wrappers in C on
the C API level.  Leaving that important point aside, though, the
choice we're discussing here is between:

1. Most code in Python, plus small amount (say 10 percent) of C/C++
   code plus ugly code to wrap it (or the latter two mixed up
   together, if you prefer).

2. All code in C++.


For cases where it meets the performance requirements, 1 is preferable
to 2 because, even given an overhead of ugliness (which I dispute,
thanks to SWIG and Boost Python) in that 10 percent of the problem
recoded in C++, you make a saving on the other 90 percent that (far!)
more than compensates.  A ratio of 5-10 in terms of lines of code is
often quoted, and that ratio applies to 90% of the project.


John


From swalters_usenet at yahoo.com  Mon Jan 12 15:22:18 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Mon, 12 Jan 2004 20:22:18 GMT
Subject: How to intercept a keypress using python?
References: 
Message-ID: 

|Thus Spake Ticachua On the now historical date of Mon, 12 Jan 2004
09:50:38 -0800|

> Hello all,
> 
> Does anyone know how to intercept user's keypress or mouseclick in Python?
> I'd like to write a small tool (Python-based preferrably) running on
> Windows to capture the user's keypresses and mouseclicks and write them to
> a file.
> 
> Thanks for your help.

Some people in alt.2600 and alt.crackers will certainly know where to find
such tools.  Have you asked there?

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From jjl at pobox.com  Mon Jan 26 14:48:45 2004
From: jjl at pobox.com (John J. Lee)
Date: 26 Jan 2004 19:48:45 +0000
Subject: Guardian: open source is a throwback says Jack Schofield
References: <64cff82f.0401251143.328388bd@posting.google.com>
Message-ID: <87oesq5w4i.fsf@pobox.com>

malcolmny_1 at lycos.com (malcolm) writes:

> Why you can't get something for nothing
> Jack Schofield Jan 22 2004

Having bought the Guardian's Thursday edition (with the "online"
section) a few times, I know they get frequent letters complaining
about Schofield's anti-open source "bias" (which doesn't alter the
correctness of otherwise of what he says, of course).

Another quote from the article:

> Finally, a couple of weeks ago, I mentioned that the movement did not
> have any way of creating software architectures. A reader disputed
> this in Feedback, citing three programs: Perl, Python and
> Apache. These are excellent programs, but not what I'd call a software
> architecture.

I guess we have to wait, with bated breath, for Jack to define
"software architecture", then .  STOP PRESS, software industry
revolutionized by IT journalist's definition of software architecture!

Why is there so much empty name-calling in the software industry?

> Curiously, also, none of them was developed by the open source
> movement, though they have of course been adopted and improved by
> it. Larry Wall developed Perl while working at Unisys; both Python and
> Apache came out of academia.

More empty name-calling.  Academics are barred from being part of the
open source movement, apparently.


> [..]
> 
> "There are also undoubted benefits from running open source software,
> though the financial ones can be small or even negative. Companies are
> bound to be tempted by the idea of getting something for nothing .."
> 
> "The facility to fix bugs yourself and to modify programs also sounds
> attractive. However, fixing bugs is not practical for most companies,
> and modifications can be positively dangerous.

Perfectly sensible points (as is the point about "TCO", which is of
course crucially important), though he conspicuously fails to draw any
sensible conclusions from them.


> If you are really going to do these things, you need to hire several
> reliable programmers with kernel-level skills"

Hard to come up with an interpretation of that that makes sense...


> "Indeed, the whole progress of commercial computing has been from
> expensive hand-written, bug-ridden, company-specific programs to
> cheaper but more powerful off-the-shelf packages. From that point of
> view, open source is a throwback."

Eh?

It appears Schofield got employed as a columnist for "ask Jack", in
which people ask questions about why their Windows machine is broken
(no dig at MS here, if linux had achieved world domination, I imagine
they'd still be asking similar questions about that; things would
still be broken, but broken on a higher level).

No great fascination to be had from observing people's "special"
reasoning when rooting for their home side, I guess .

It's a shame, when there are perfectly good arguments to be made
against open source, that this kind of third-rate excuse for analysis
gets published.  Don't give up the day job, Jack!


> - http://www.guardian.co.uk/online/story/0,3605,1127802,00.html


John


From __peter__ at web.de  Mon Jan 26 17:24:04 2004
From: __peter__ at web.de (Peter Otten)
Date: Mon, 26 Jan 2004 23:24:04 +0100
Subject: Single and double asterisks preceding variables in function
	arguments
References: 
	
	
Message-ID: 

Stephen Boulet wrote:

> <<
> a={'c1':'red','c2':'blue','c3':'fusia'}
> def bar(**params):
> ....for k in params.keys():
> ........print k, params[k]
> bar(a)
> Traceback (most recent call last):
>    File "", line 1, in ?
> TypeError: bar() takes exactly 0 arguments (1 given)
>  >>
> 
> Why does bar take zero arguments?

The error message is not as clear as it should should be. bar() takes 0
mandatory, 0 positional and an arbitrary number of keyword arguments, e.
g.:

>>> def bar(**params):
...     print params
...
>>> bar(color="blue", rgb=(0,0,1), name="sky")
{'color': 'blue', 'rgb': (0, 0, 1), 'name': 'sky'}

That's the standard way of passing optional keyword arguments, but you can
also pass them as a dictionary preceded by **:

>>> adict = {'color': 'blue', 'rgb': (0, 0, 1), 'name': 'sky'}
>>> bar(**adict)
{'color': 'blue', 'rgb': (0, 0, 1), 'name': 'sky'}

This is useful, if you want to compose the argument dict at runtime, or pass
it through to a nested function.

> 
> Hmm, but:
> 
> <<
> def bar2(*params,**moreparams):
> ....print "params are ", params,'\n'
> ....for k in moreparams.keys():
> ........print k, moreparams[k]
> ....print "moreparams are ", moreparams

bar2() accepts 0 mandatory, as many positional and keyword arguments as you
like. For the expected result, try 

>>> def bar2(*args, **kwd):
...     print args
...     print kwd
...
>>> bar2(1,2,3)
(1, 2, 3)
{}
>>> bar2(1, name="sky", color="blue")
(1,) # tuple of optional positional args
{'color': 'blue', 'name': 'sky'} # dict of optional keyword args
>>>

And now a bogus example that shows how to compose the arguments:

>>> def bar3(x, *args, **kwd):
...     print "x=", x
...     print "args=", args
...     print "kwd=", kwd
...     if "terminate" not in kwd:
...             kwd["terminate"] = None # avoid infinite recursion
...             bar3(x*x, *args + ("alpha",), **kwd)
...
>>> bar3(2, "beta", color="blue")
x= 2
args= ('beta',)
kwd= {'color': 'blue'}
x= 4
args= ('beta', 'alpha')
kwd= {'color': 'blue', 'terminate': None}
>>>

To further complicate the matter, a mandatory arg may also be passed as a
keyword argument:

bar3(x=2, color="blue") # will work, args is empty
bar("beta", # will not work; both "beta" and 2 would be bound to x
            # and thus create a conflict                
    x=2, color="blue")


Peter



From no.spam  Sun Jan 18 15:09:17 2004
From: no.spam (Christophe Delord)
Date: Sun, 18 Jan 2004 21:09:17 +0100
Subject: Determining a replacement dictionary from scratch
References: <4b805376.0401181116.3b0adb41@posting.google.com>
Message-ID: <20040118210917.4e046a24.no.spam@box>

On 18 Jan 2004 11:16:31 -0800, Dan wrote:

> Hello,
> 
> I'd like to be able to take a formatted string and determine the
> replacement dictionary necessary to do string interpolation with it. 
> For example:
> 
> >>> str = 'his name was %(name)s and i saw him %(years)s ago.'
> >>> createdict( str )
> {'name':'', 'years':''}
> >>>
> 
> Notice how it would automatically fill in default values based on
> type.  I figure since python does this automatically maybe there is a
> clever way to solve the problem.  Otherwise I will just have to parse
> the string myself.  Any clever solutions to this?
> 
> Thanks 
> -dan

You can use the % operator to look for such constructions. You just
need to define the __getitem__ method of a class to store the
variable names. What about this function:

def createdict(format):
    class grab_variables:
        def __init__(self):
            self.variables = {}
        def __getitem__(self, item):
            self.variables[item] = ''
    g = grab_variables()
    format%g
    return g.variables

print createdict('his name was %(name)s and i saw him %(years)s ago.')

{'name': '', 'years': ''}


Best regards,
Christophe.


From tjreedy at udel.edu  Tue Jan 27 21:47:33 2004
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 27 Jan 2004 21:47:33 -0500
Subject: Confused about a list.sort()
References: 
Message-ID: 


"Amy G"  wrote in message
news:S6FRb.2098$P17.1139 at fed1read03...
> I have a list of numbers... actully I have two lists, List 1 is a list of
> number strings and List2 is one of numbers.
>
> List 1 example:
> List1 = [ '20040124123000', '20040124123001', '20040125012456']
>
> List 2 example:
> List2 = [ 20040124123000L, 20040124123001L, '20040125012456L]
>
> When I try either:
> List1 = List1.sort ... or
> List2 = List2.sirt
>
> and then...
> print List1... or
> print List2
>
> I get None.
>
> Why is this?
> How do I remedy this problem?

Read the library reference manual on builtin objects - sequences -  lists -
methods.

Seriously.

TJR






From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Fri Jan  9 08:21:12 2004
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Fri, 09 Jan 2004 14:21:12 +0100
Subject: Bruce Eckel example / CGI server for localhost for Windows XP
 possible?
In-Reply-To: 
References: 
Message-ID: <3ffeaac9$0$321$e4fe514c@news.xs4all.nl>

Will Stuyvesant wrote:
> Is there anybody who can provide simple example code like found in
> Fredrik Lundh's Python Standard Library book for setting up a CGI
> server for localhost with Python? 

Not sure if this helps, but do you require a CGI style server?
Does it need to be extremely small and simple (though that's relative)?
If not, and servlet-style intelligent web applications also suit
your needs, you might be able to pick one of Python's web frameworks
and just run that on your local machine. Most won't need Apache.

At least, mine doesn't: Snakelets http://snakelets.sourceforge.net

I've heard from one user that he's using Snakelets to run a
web application off a CD-ROM...
(try an older Snakelets version <1.20 for that).

Good luck
--Irmen de Jong.


From steveb428pleaseremovethis at hotmail.com  Sun Jan 18 12:06:06 2004
From: steveb428pleaseremovethis at hotmail.com (DilbertFan)
Date: Sun, 18 Jan 2004 17:06:06 GMT
Subject: Using python for _large_ projects like IDE
References: <930ba99a.0401180625.5863acd4@posting.google.com>
Message-ID: <22zOb.2835$Zk3.135@newssvr29.news.prodigy.com>

If you do write this  IDE, please include a compiler warning that catches
the missing () at the end of a function that doesn't have arguments.  I've
sunk into a dark world of a diabolically mind-destroying hysteria while
trying to troubleshoot some scripts, and then realizing that a python
function was not executing because I was calling it without '()'.  But
Python doesn't complain, or give you a message or anything,... it simply
doesn't execute that function!

Big reason I forget the empty parenthesis: I do Delphi also, and it doesn't
require it.

(Meanwhile, for Python I'm using Komodo, which is really good.  Funny how I
keep upgrading UltraEdit when I go ahead and register more language-specific
tools anyway )

"Sridhar R"  wrote in message
news:930ba99a.0401180625.5863acd4 at posting.google.com...
> Hi,
>
> I am a little experienced python programmer (2 months).  I am somewhat
> experienced in C/C++.  I am planning (now in design stage) to write an
> IDE in python.  The IDE will not be a simple one.  I had an idea of
> writing the IDE in C/C++, as it is a big project, bcoz of the
> following
>
> 1. if python is used, then the memory required for running the IDE
> will be high.
> 2. if pure python is used, the IDE will be slower.
>
> I'm not sure whether they are true.
>
> Then I thought of using python for 90% of the code and using C for
> other performance critical part.  But the problem is in identifying
> the performance critical code.  People suggest to start with pure
> python and then _recode_ the performance critical code after profiling
> the original code.  But I fear whether there will be a conflit in say
> data structures.  Not yet expert in extending/embedding python.
> Are there any ways to forsee the performance critical parts?
>
> Also, any suggestions on reducing memory usage of big applications
> written in python?




From ark at acm.org  Fri Jan 23 09:46:53 2004
From: ark at acm.org (Andrew Koenig)
Date: Fri, 23 Jan 2004 09:46:53 -0500
Subject: I support PEP 326
In-Reply-To: <4010C5D3.9060702@prescod.net>
Message-ID: <001301c3e1bf$be53ec40$6402a8c0@arkdesktop>

> Calling min with no arguments need not be the same as calling it with an
> empty sequence argument. That is not necessarily an argument for making
> the empty function call return something arguably strange...

I agree with you that it's strange, but it's right.  It might interest you
to know that APL has behaved the same way for more than 35 years.  In APL,
the usual way of obtaining the largest positive value is to ask for the
lowest element of an empty sequence.

In Python, if you give min or max a single argument, it is assumed to be a
sequence, and if that sequence is empty, you get an exception.  If you give
it more than one argument, those arguments are treated as elements of a
sequence, and you get an exception if there are no arguments (i.e. if the
sequence is empty).

Therefore, if min([]) were to return Max (which, although surprising, I
still think is reasonable), then min() should also return Max.





From nomail at edu  Sun Jan 18 11:16:36 2004
From: nomail at edu (Izzie)
Date: Sun, 18 Jan 2004 11:16:36 -0500
Subject: Using python for _large_ projects like IDE
In-Reply-To: <930ba99a.0401180625.5863acd4@posting.google.com>
References: <930ba99a.0401180625.5863acd4@posting.google.com>
Message-ID: 

Sridhar R wrote:

> I am a little experienced python programmer (2 months).  I am somewhat
> experienced in C/C++.  I am planning (now in design stage) to write an
> IDE in python.  The IDE will not be a simple one.  I had an idea of
> writing the IDE in C/C++, as it is a big project, bcoz of the
> following

Don't bother, there are many good IDEs that can be used with python,
there are even more excellent text editors that (IMO) are better
than all IDEs that I tried. Why waste you time?

i.




From jcarlson at uci.edu  Wed Jan 21 16:09:52 2004
From: jcarlson at uci.edu (Josiah Carlson)
Date: Wed, 21 Jan 2004 13:09:52 -0800
Subject: Assignment to slice
References: 
Message-ID: <20040121130236.D8E3.JCARLSON@uci.edu>

> Instead python will just tack stuff on to the front of
> the array. Which, I still believe, is totally
> inconsistent. But what do I know? I have about 5
> minutes of python experience.

> Oh well. Maybe my problem is that I'm using perl as my
> model of consistency. Plus, it's a minor issue anyway.
> I just need to be aware of it, and not try to write
> perl code in python. I need to learn to write python
> code in python.

There are a few choices that one can make when allowing slice reading
and writing in sequences.  Python made one: never cause an exception for
integer arguments, and certain indices map to the same location.  Perl
made another: extend the sequence if necessary to fill it out.

Both are consistant and predictable.  Python does it one way, Perl does
it another.  Heck, Python has variable definitions that are done one way,
Perl has variable definitions that are done another.  They were choices
made during the creation that fit a paradigm.

Expecting Python to behave like Perl is like expecting your mother to
pee standing up; without alteration, it's not gonna happen.

 - Josiah



From ville.spamstermeister.vainio at thisisspamprotectiontut.finland  Thu Jan 22 01:31:07 2004
From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio)
Date: 22 Jan 2004 08:31:07 +0200
Subject: Nokia prefers Python
References: 
	
Message-ID: 

>>>>> "Mike" == Mike C Fletcher  writes:

    >> This might be the start of a success story. Says Nokia prefers
    >> Python!

    Mike> Oh, neat.  Someone was looking for a series 60 developer a

"Neat". That has got to be the understatement of the year. 

My job is w/ Symbian OS, and this definitely made my day. We'll see
how they are carrying it through, and how people could help.

-- 
Ville Vainio   http://tinyurl.com/2prnb


From fnord at u.washington.edu  Sat Jan  3 21:53:19 2004
From: fnord at u.washington.edu (Lonnie Princehouse)
Date: 3 Jan 2004 18:53:19 -0800
Subject: Abstract Syntax Tree conundrum
References: 
	
Message-ID: 

Andrew Dalke wrote in message 

> Does this help?
> >>> compiler.pycodegen.ModuleCodeGenerator(x).getCode()

Yes!  It's exactly what I was looking for.  Thanks very much =)



-ljp


From paradisejourney at hotmail.com  Thu Jan 15 07:15:52 2004
From: paradisejourney at hotmail.com (aj)
Date: 15 Jan 2004 04:15:52 -0800
Subject: what is best for web development??
References: 
	<87wu80559x.fsf@blakie.riol>
	
	<87oet9grqy.fsf@blakie.riol>
Message-ID: <14ba0c0.0401150415.121f31f2@posting.google.com>

hi 
i am a newbi to python and developing a web application
what do u all think is the best application framework for developing
web application in python. I want a framework that supports
templates,database connectivity, is available for both unix and
windows.
Zope
Quixote
Draco or others
I read some stuff about all these frameworks and i think zope is a good one
But wanna know what you all think


Wilk  wrote in message news:<87oet9grqy.fsf at blakie.riol>...
> ketulp_baroda at yahoo.com writes:
> 
> > Wilk  wrote in message news:<87wu80559x.fsf at blakie.riol>...
> >> ketulp_baroda at yahoo.com writes:
> >> 
> >> > i am developing a web application and i am really confused on what should i use.
> >> > should i use just python and use the cgi module availabe.
> >> > Or should i use application like WebWare.Also there is PSP available.
> >> > I am really confused and need help
> >> 
> >> It depends of the kind of application you want to do exactly, there are
> >> many possibilities from cgi to zope...
> >> 
> >> Look into the archive of the list, you'll find a lot of answer to this
> >> question. Or describe more what you need.
> >> 
> >> bye
> >
> >
> > hey thanks for ur reply
> > i am developing an issue tracking system 
> 
> There is one that you can look at : http://roundup.sf.net
> I think it can be used in standalone server or cgi.
> 
> > the primary requirements are
> > 1)it should be platform independent which i think python will take
> > care of
> > 2)it should have customizable gui .I am thinking of using templates
> > for this like Cheetah. Is there any other better solution to Cheetah?
> 
> There is no better solution than Cheetah : there is others solutions...
> 
> > The problem i am facing here is i dont know what to use for
> > development of the application. I came across many ways to develop web
> > application in python which I already specified like
> > i)the cgi module in python
> > ii)Python Server Pages
> > iii)Quixote
> > iv)WebWare
> > v)Zope etc.
> > I want to choose such an environment so that i dont have to install
> > other softwares to run my application.For eg. I think if I develop
> > using zope then the client also has to install zope to run my software
> > and i dont want this.
> 
> When you use one of theses servers, you don't need to install anything
> else than a classic browser on the client side.
> On the server side, most of the servers will not need anything else, you
> can even start without server with the batterie include :
> BasicHTTPServer (it was somes examples on this list somes days ago).
> 
> bye


From theller at python.net  Fri Jan 16 14:40:08 2004
From: theller at python.net (Thomas Heller)
Date: Fri, 16 Jan 2004 20:40:08 +0100
Subject: ctypes 0.6.3 released
Message-ID: 

It's release day ;-)

ctypes 0.6.3 released
=====================

Overview

    'ctypes' is a Python package to create and manipulate C data types
    in Python, and to call functions in dynamic link libraries/shared
    dlls. It allows wrapping these libraries in pure Python.

    It works on Windows, Linux and MacOS X (the latter require that
    your machine is supported by libffi).


Changes

    A critical bug with pointer instances was fixed, this makes the
    'incomplete types' sample code in the tutorial actually work.

    All ctypes objects are now correctly garbarge collected.  This
    *may* lead to crashes in your program (especially with callback
    functions, or pointers handed out to longer running C code).  You
    must keep a reference in Python to any object as long as it is
    used in foreign C code.

    All other known bugs have been fixed.

    Again, a lot of changes to the COM package, but all this is still work in
    progress and unstable, and it has to be properly documented.

Homepage

    

Enjoy,

Thomas


From claird at lairds.com  Wed Jan 14 13:21:58 2004
From: claird at lairds.com (Cameron Laird)
Date: Wed, 14 Jan 2004 18:21:58 -0000
Subject: I come not to bury C++, but to praise it...
References: 
	
	<100aq779r2h2c9e@corp.supernews.com>
	
Message-ID: <100b266i0r70g86@corp.supernews.com>

In article ,
Donn Cave   wrote:
>In article <100aq779r2h2c9e at corp.supernews.com>,
> claird at lairds.com (Cameron Laird) wrote:
>
>> In article ,
>> Derek  wrote:
>> 			.
>> 			.
>> 			.
>> reliability, I very much want to understand it.  Are you alluding
>> precisely to Python's dynamic typing, and observing that, as earlier
>> is better, C++'s compile-type checks beat Python's run-time checks?
>
>Your wording is precise enough that your question could have
>been better.  Note "compile type checks" vs. "run-time checks" -
>a difference not only in when, but what.  There's more to it
>than "earlier is better".
			.
			.
			.
Great!  *What* more?  When I look at Python and C++, I see the
former as having *stricter*, if more dynamic, typing, so I don't
understand what advantage C++ has in this one regard apart from
time-of-detection.

I apologize, by the way, for writing "compile-type" where I 
intended "compile-time".
-- 

Cameron Laird 
Business:  http://www.Phaseit.net


From jjl at pobox.com  Fri Jan 16 14:42:06 2004
From: jjl at pobox.com (John J. Lee)
Date: 16 Jan 2004 19:42:06 +0000
Subject: Python COM Server with C++
References: 
Message-ID: <8765fb7ka9.fsf@pobox.com>

andre.bernemann at gmx.de (Andre Bernemann) writes:
> I have written a Python COM Server with the help of Mark Hammond's
> Book Programming Python on Win32. I used the CreateObjects method in
> VB to access the COM Methods and all worked fine. Unfortunately, that
> is not what i really want. First I'd like to make the COM Server
> accessible from C++ and as a beside product I want to use early

I'd do this in ctypes, although its COM support is still quite new.
win32com (from win32all, aka Python for Windows Extensions, which is
what you're probably using ATM) has recently grown support for
implementing vtable interfaces (but not calling them, IIRC), but I
suspect one is less likely to get stuck when using ctypes, since
everything is pretty close to the way you'd do in in C (COM makes that
quite complicated, of course, but I think the ctypes COM support is
fairly 'thin' -- probably a good thing, IMHO -- but also elegant).


> binding within VB with the NEW operator. I've googled around alot, but
> I still have not the complete picture of what to do.

Take at look at win32/com/samples/server in the ctypes package -- an
example of implementing a dual interface.  I haven't tried a dual
interface myself, but, as COM goes, it all looks very simple and
elegant.


> So far I think I have to create an IDL file to describe the interface
> and compile it with the MIDL Compiler. There ist my first question.
> What do I have to create first, the IDL file or the Python COM Server?

IDL first.  This is explained in the little comment at the top of the
sample.


> I'm a little bit confused about dispid's, the GUID's and naming
> conventions. Do i need to make use of the makepy Utility in any way?

I don't know how one implements vtable/dual interfaces in win32com.


> Do I have to modify the Python COM Server Source Code in any way or
> can I use it as it is? (I can post the code here on request)
[...]

ditto


John


From fowlertrainer at anonym.hu  Mon Jan  5 10:40:50 2004
From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu)
Date: Mon, 5 Jan 2004 16:40:50 +0100
Subject: Python-list Digest, Vol 4, Issue 38
In-Reply-To: 
References: 
Message-ID: <16129653189.20040105164050@anonym.hu>

Hello !

I have used mod_python. But it is don't reload my modules when I
editing them.

I try with this:
--------------------
# Module importer
import os
import traceback
import kinterbasdb
import sys
import time
import threading
import imp
import stat

ImpLock=threading.Lock()
IModuleDir="C:/bhaweb/modules"
IModules={}

def LoadModule(ModName):
    fp, pathname, description = imp.find_module(ModName)
    try:
      mod=imp.load_module(ModName, fp, pathname, description)
      print mod
      sys.modules[ModName]=mod
    finally:
      # Since we may exit via an exception, close fp explicitly.
      if fp: fp.close()

def ImportModules(Modules):
    ImpLock.acquire()
    try:
        if not (IModuleDir in sys.path): sys.path.append(IModuleDir)
        # Do imports, if needed
        print Modules
        for m in Modules:
            sf=IModuleDir+"/"+m+".py"
            if sys.modules.has_key(m):
               sd=os.stat(sf)
               lm=sd[stat.ST_MTIME]
               if IModules.has_key(m):
                  dd=IModules[m]
                  if (dd<>lm):
                     print "ReLoad"
                     reload(sys.modules[m])
               IModules[m]=lm
            else:
               print "Load"
               LoadModule(m)
               sd=os.stat(sf)
               lm=sd[stat.ST_MTIME]
               IModules[m]=lm
            '''
            import s
            sf=IModuleDir+"/"+s


            '''
        print IModules
    finally:
        ImpLock.release()

#for k in sys.modules.keys(): print k,sys.modules[k]
'''
f=file(IModuleDir+"/test.py","w")
f.write("print 1")
f.close()
'''
#print os.stat(IModuleDir+"/test.py")[stat.ST_MTIME]
#sys.exit()
'''
ImportModules(["test"])
f=file(IModuleDir+"/test.py","w")
f.write("print 2")
f.close()
time.sleep(2)
ImportModules(["test"])
'''
ImportModules(["test"])
BHASession.test()
--------------------
test.py is this:
def test():
    print 1
--------------------
But python is say:

> Executing: C:\Program Files\ConTEXT\ConExec.exe "C:\Python\python.exe" "C:\bhaweb\modules\ModImport.py"

['test']
Load

{'test': 1073316581}
Traceback (most recent call last):
  File "C:\bhaweb\modules\ModImport.py", line 75, in ?
    BHASession.test()
NameError: name 'BHASession' is not defined
> Execution finished.

I run this in native mode, but do this in under mod_apache also.

Why ? What I do wrong ?
Plase send the email in private also, because I'm in digest mode.

Thanx:
 KK




From ville.spamstermeister.vainio at thisisspamprotectiontut.finland  Sat Jan 24 05:15:22 2004
From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio)
Date: 24 Jan 2004 12:15:22 +0200
Subject: [OPINION] - does language really matter if they all do the
	samething?
References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com>
	
Message-ID: 

>>>>> "Dietrich" == Dietrich Epp  writes:

    Dietrich> Example: I wrote a project in Python which reads some
    Dietrich> data files and uses them to make a decision (sort of).
    Dietrich> I got it to about 90% functionality, and realized that
    Dietrich> the last 10% was extremely difficult to do with Python.
    Dietrich> After writing one Lisp macro of exactly 13 lines, I
    Dietrich> rewrote the entire program, incorporating the data into
    Dietrich> Lisp files which were not only much shorter, but much
    Dietrich> clearer, easier to read, etc.  I just couldn't think of
    Dietrich> a way to write this program in Python without a lot of
    Dietrich> code replication.

Soon you can, with projects like
http://www.caddr.com/code/lython/.

I can imagine problems like yours can be fixed by writing a teensy bit
of Lisp to process the data, and then throw the results back to good
old Python to do the rest. Lisp-like stuff can be integrated and
implemented quite easily in Python, even if we lose the native
compilation aspect of Lisp.

    Dietrich> never consider doing in anything but Python, except the
    Dietrich> occasional hardcore text processor which causes physical
    Dietrich> pain to write in anything but Perl or Ruby.

Any examples? Off the top of my head I can't think of anything...

-- 
Ville Vainio   http://tinyurl.com/2prnb


From zensunni at rochester.rr.com  Sat Jan 24 22:47:17 2004
From: zensunni at rochester.rr.com (Brian Samek)
Date: Sun, 25 Jan 2004 03:47:17 GMT
Subject: Newbie Nested Function Problem
References: 
	<52d610h685a613ua1tk5k8f11cv1d61q0b@4ax.com>
Message-ID: <9%GQb.77000$Su5.22817@twister.nyroc.rr.com>

> Okay, ask_number doesn't do what you're saying.  It's asking for a number,
> placed into variable number, and if it gets something out of range, prints
> an error message.
>
> And then ends.  It doesn't either a) repeat until it gets a valid number
> or b) do anything with the number it gets, like pass it back to the caller
> in a return statement, i.e.:
>

It does repeat if it doesn't get a valid number.  The function calls itself
after printing an error mesage.  For some reason the original message
formatted itself differently when I pasted it into my mail program.  The
line just before the first else statement should be indented to the same
level as the line before it so it reads:

def ask_number():
    number = input("Please enter a number.\n")
    if number > 500 or number - int(number) != 0 or number < 1:
        print "Input positive integers less then 501 only, please."
        ask_number()
    else:



>   return number
>
> > ask_number()
>
> Okay, you invoked ask_number, but didn't even try to get anything from it.
> Normally, this would read something like:
>
> number_in = asknumber()
>

What do you mean by I "didn't even try to get anything from it."  I get a
variable called "number" from it from which the countdown(number) function
counts down.

> >    else:
>
> Um.. it looks like you're inadvertably making this a deeply recursive
> call, probably something you want to stay away from until you have regular
> stuff down pat.

I don't understand what you're saying.  I designed the program as three
functions nested within each other.  Are you saying I should be designing it
differently?  I made it a series of nested functions because, for example, I
needed to use the "number" variable from ask_number before it was destroyed.
When a function ends, any variables it has created are destroyed.

Thanks,

Brian




From jjl at pobox.com  Tue Jan  6 11:02:12 2004
From: jjl at pobox.com (John J. Lee)
Date: 06 Jan 2004 16:02:12 +0000
Subject: RELEASED: allout-vim 031229
References: 
	
	
	
	
	
	
	<87d69yqsos.fsf@pobox.com>
	<95aa1afa.0401060522.630e5cbb@posting.google.com>
Message-ID: <87d69xawvv.fsf@pobox.com>

michele.simionato at poste.it (Michele Simionato) writes:

> jjl at pobox.com (John J. Lee) wrote in message news:<87d69yqsos.fsf at pobox.com>...
> > Fran?ois Pinard  writes:
> > No, actually, a *real* OT comment: I'm pretty sure I've seen two big
> > pieces of code, by two French authors, in which the word "eventually"
[...]
> "Eventuellement" (or the Italian "eventualmente")
> means "possibly", not "eventually".

Ah, of course.  I was sure I'd looked for a false friend in my French
dictionary, but I guess I can't have done...


John


From tim.golden at viacom-outdoor.co.uk  Fri Jan 30 09:27:47 2004
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Fri, 30 Jan 2004 14:27:47 -0000
Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain
Message-ID: 

>-----Original Message-----
>From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com]
>Sent: 30 January 2004 12:45
>To: python-list at python.org
>Subject: Re: NetGetAnyDCName() - get PDC of a foreign WinNT-domain
>
>
>Tim Golden  wrote in message 
>news:...
>> [... snip my suggestion of pdc = win32net.NetGetAnyDCName (None,
>> "name_of_other_domain") ...]
>> 
>> >From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com]
>> >
>> >Thanks for your help, but that does not work. I get an error message
>> >which sais it can't reach the domain.
>> >But I'm sure did not make an syntax-error, because if I enter my own
>> >domain it works.
>> >
>> >Any other idea?
>> >
>> >Dirk
>> >
>> >
>> 
>> To ask the obvious question: do you definitely have all
>> the necessary security / connectivity in place to reach
>> the domain controller on that domain?
>
>
>I can reach the other domains and I have all rights. That's no 
>the problem.
>
>Dirk

Could you dump a cut-and-paste of the interpreter, so
we can see what's happening? This is what I get, altho'
as I say, I don't have another domain. Is yours the same?



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.
>>> import win32net
>>> win32net.NetGetAnyDCName ()
u'\\\\VOBDC1'
>>> win32net.NetGetAnyDCName (None, "VOUK")
u'\\\\VOBDC1'
>>> win32net.NetGetAnyDCName (None, "non-existent")
Traceback (most recent call last):
  File "", line 1, in ?
pywintypes.error: (1355, 'NetGetAnyDCName', 'The specified domain either
does not exist or could not be contacted.')
>>>



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 gandalf at geochemsource.com  Tue Jan 27 05:47:04 2004
From: gandalf at geochemsource.com (Gandalf)
Date: Tue, 27 Jan 2004 11:47:04 +0100
Subject: TELNET instead PING
References: <5f505344.0401260332.184d4225@posting.google.com>	<401571B9.F9DF99D0@engcorp.com>	
	
Message-ID: <401641A8.508@geochemsource.com>

>
>> Note: that reason you talked about is most likely a packet filtering 
>> firewall. A good firewall
>> can block PING, Telnet, Nbsession and many others. In most cases, the 
>> best policy
>> is to lock everything by default and permit only the ones you really 
>> want. Firewall
>> rules can include source addresses too. It is possible that a 
>> computer do not respond
>> on PING and TELNET ports for you but it does for a similar request 
>> from another
>> computer. I think there is no universal way to determine if a remote 
>> host is alive or not.
>
>
> If we are talking about IP network segment in the same ethernet layer, 
> can you ignore my ARP request - who-has  ?
>
Probably I cannot. :-)
But this applies only when you are in the same segment.
By the way, is it possible to send an ARP request from pure Python? ;-)
AFAIK Python provides tools for level 3 and above only.




From rainerd at eldwood.com  Sat Jan  3 14:38:57 2004
From: rainerd at eldwood.com (Rainer Deyke)
Date: Sat, 03 Jan 2004 19:38:57 GMT
Subject: Integer math question
References: <3987e01c.0401030832.114c6f2a@posting.google.com>
	<11EJb.20461$Vl6.3782481@news20.bellglobal.com>
Message-ID: 

Sean Ross wrote:
> a = bq + r       and  0<=r

Anyone has a hint how else to get faster results?
(This is to find out what was bold in the document, in order to grab
documents ptoduced in word and generate html (web pages) and xml
(straight data) versions)

# START ========================
import win32com.client
import tkFileDialog, time

# Launch Word
MSWord = win32com.client.Dispatch("Word.Application")

myWordDoc = tkFileDialog.askopenfilename()

MSWord.Documents.Open(myWordDoc)

boldRanges=[]  #list of bold ranges
boldStart = -1
boldEnd = -1
t1= time.clock()
for i in range(len(MSWord.Documents[0].Content.Text)):
    if MSWord.Documents[0].Range(i,i+1).Bold  : # testing for bold
property
        if boldStart == -1:
            boldStart=i
        else:
            boldEnd= i
    else:
        if boldEnd != -1:
            boldRanges.append((boldStart,boldEnd))
            boldStart= -1
            boldEnd = -1          
t2 = time.clock()
MSWord.Quit()

print boldRanges  #see what we got
print "Analysed in ",t2-t1
# END =====================================

Thanks in advance


From antonmuhin at rambler.ru  Wed Jan 14 05:46:48 2004
From: antonmuhin at rambler.ru (anton muhin)
Date: Wed, 14 Jan 2004 13:46:48 +0300
Subject: Inserting while itterating
In-Reply-To: 
References: 
Message-ID: 

Thomas Guettler wrote:

> Hi,
> 
> Simple excerise:
> 
> You have a sorted list of integers:
> l=[1, 2, 4, 7, 8, 12]
> 
> and you should fill all gaps:
> 
> result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> 
> How would you code this?
> 
> Constrain: The original list should be changed,
> don't create a copy.
> 
>   thomas
> 

1:

previous = l[0]
current = 1

while current < len(l):
     for e in range(previous + 1, l[current]):
         l.insert(current, e)
         current += 1
     previous = l[current]
     current += 1


2:

first, last = l[0], l[-1]
for _ in range(len(l)): l.pop()
l.extend(range(first, last + 1))

:)

hth,
anton.


From tdelaney at avaya.com  Tue Jan  6 21:27:35 2004
From: tdelaney at avaya.com (Delaney, Timothy C (Timothy))
Date: Wed, 7 Jan 2004 13:27:35 +1100
Subject: Pre-PEP: Dynamically evaluating default function arguments
Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE010633FF@au3010avexu1.global.avaya.com>

> From: Daniel Ehrenberg
> 
> I'm sorry I wasted your time, everyone.

IMO it's not a waste of time for this PEP to be written. Unfortunately, not many people are willing to formally document something that they would like to see when the guaranteed result is that it will be rejected.

Tim Delaney



From jcarlson at uci.edu  Tue Jan 20 17:09:01 2004
From: jcarlson at uci.edu (Josiah Carlson)
Date: Tue, 20 Jan 2004 14:09:01 -0800
Subject: Error with Shelve from a frozen application
References: <4378fa6f.0401201055.384a057d@posting.google.com>
Message-ID: <20040120140619.1C45.JCARLSON@uci.edu>

> Hello all,
> 
> I have searched and experimented but can't find a way to make this
> work. I have an application that I froze using py2exe which uses
> Shelve to store data for me. This is the error I am getting:
> 
> Traceback (most recent call last):
>   File "", line 14, in ?
>   File "imputil.pyc", line 103, in _import_hook
>   File "", line 52, in _import_top_module
>   File "imputil.pyc", line 216, in import_top
>   File "imputil.pyc", line 271, in _import_one
>   File "", line 128, in _process_result
>   File "anydbm.pyc", line 62, in ?
> ImportError: no dbm clone found; tried ['dbhash', 'gdbm', 'dbm',
> 'dumbdbm']
> 
> A couple of places mentioned forcing the compiler to import the anydbm
> module. I've tried this both from within the main program and from the
> compiler options. Neither of them worked. Can someone please tell me
> how to fix this?
> 
> Thanks ahead of time,
> Marc

I've had similar problems with attempting to force encodings imports.

At the beginning of your script, give the following a try:

for i in ['dbhash', 'gdbm', 'dbm', 'dumbdbm']:
    try: eval('import '+i)
    except: pass

Send it through py2exe, and give it a shot.

 - Josiah



From peter at engcorp.com  Tue Jan 13 14:18:56 2004
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 13 Jan 2004 14:18:56 -0500
Subject: Division oddity
References: 
	<7xeku5vrn8.fsf@ruckus.brouhaha.com>
	
	<400413E0.5C691A56@engcorp.com>
	<7xr7y3mzsl.fsf@ruckus.brouhaha.com>
Message-ID: <400444A0.717BA7A3@engcorp.com>

Paul Rubin wrote:
> 
> Peter Hansen  writes:
> > > Well, the documentation for "input()" says "Equivalent to
> > > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/
> > > equivalent...."
> >
> > I remember reading that too, and just assumed that at this point
> > it was in fact *implemented* that way, as a simple alias.  Maybe
> > it should be...
> 
> Python has no support for macros or aliases, and it would be silly
> to add some special kludge for input().  The user needs to be able
> to redefine the function and so forth too.

Sure it does:

def input(*args):
    return eval(raw_input(*args))

That's what I mean by "alias", anyway.... same as the implementation
which I understand is used for string.methodx(s) nowadays, which is
apparently just passed on to s.methodx().

-Peter


From rajarshi at presidency.com  Mon Jan 12 20:17:28 2004
From: rajarshi at presidency.com (Rajarshi Guha)
Date: Mon, 12 Jan 2004 20:17:28 -0500
Subject: how can I execute a function string
Message-ID: 

Hi ,
 I have some code that generates a function on the fly in a string. 
At a later point in time I want to execute this function (which also
requires a parameters to be passed to it). So the code is something like
this:

def generate_func():
	s = """ def function(x):
	print x
	return 2
"""
	return s

funcstring = generate_func()
retval = ....

That is, retval should have the value returned from the evaluation of the
function in the string funcstring.

Is this possible by means of simple function calls or does this involve
some sort of black magic?

Thanks,


From akhavr at kds.com.ua  Mon Jan 12 15:40:12 2004
From: akhavr at kds.com.ua (Andrey Khavryuchenko)
Date: Mon, 12 Jan 2004 22:40:12 +0200
Subject: script to translate from compiler AST
References: 
	
	
	
Message-ID: 

Michael,

"MH" == Michael Hudson wrote:

 MH> Andrey Khavryuchenko  writes:
 >> Imagine, I've built an AST that I want to run.  I've not found an
 >> easy (read library) way to do that, hence the question.

 MH> Ah!  Try

 MH> http://groups.google.com/groups?th=f3f7a7f6fac16ca2

Wow, thanks!  Exactly what I need.  Unfortunately pycodegen is not yet
documented :)

-- 
Andrey V Khavryuchenko            http://www.kds.com.ua/
Silver Bullet Software Solutions  http://www.kds.com.ua/training/


From http  Sun Jan 11 01:13:07 2004
From: http (Paul Rubin)
Date: 10 Jan 2004 22:13:07 -0800
Subject: Help with if statement
References: 
Message-ID: <7xeku7qah8.fsf@ruckus.brouhaha.com>

jikosan83 at yahoo.com (Jikosan) writes:
> for x in range(0,N):
>     random = uniform(-1, 1)

random is a number between -1 and +1.  It's always < 1.

>     print random
>     if random < 1.0: <--- Not working
>         neg = neg+1

You mean "if random < 0.0:".


From Mike at DeleteThis.Geary.com  Sat Jan 17 02:40:11 2004
From: Mike at DeleteThis.Geary.com (Michael Geary)
Date: Fri, 16 Jan 2004 23:40:11 -0800
Subject: Need to get 8.3 path on Windows
References: 
Message-ID: <100hpmrm74ah548@corp.supernews.com>

Patrick L. Nolan wrote:
> Our python script uses popen to run an application on Windows XP.
> The application chokes if the filename given as a command line
> argument contains any spaces.  It's happy with the 8.3 shortname
> notation, though.  So given a file with a name like
>  c:\Documents and Settings\Joe User\Desktop\My Files\foo.dat
> I would like to be able to convert this to
>  c:\DOCUME~1\JOEUSE~1\Desktop\MYFILE~1\foo.dat
>
> This would be a fairly simple exercise in text manipulation
> except that the number may not always be 1.  If the directory
> names are not unique in the first 6 characters, there may
> be ~2 etc.

You're looking for the Windows API function GetShortPathName, which is
supported by the win32api module in Mark Hammond's Windows extensions:

>>> import win32api
>>> win32api.GetShortPathName( "C:\Program Files\Internet Explorer" )
'C:\\PROGRA~1\\INTERN~1'
>>>

This function returns the actual short name for a file or directory; it
doesn't just do a string manipulation.

-Mike




From tim.one at comcast.net  Wed Jan 14 20:24:40 2004
From: tim.one at comcast.net (Tim Peters)
Date: Wed, 14 Jan 2004 20:24:40 -0500
Subject: Cyclic garbage collection and segfaults...
In-Reply-To: 
Message-ID: 

[Simon Burton]
> In my extensions python seems to segfault in the GC most of all...

That's quite likely:  gc is the only part of the system that routinely
crawls over every container in existence, so is supremely sensitive to all
manner of common C coding errors (wild stores, buffer overruns,
uninitialized memory, mixing calls to different memory subsystems on a
single object, and failure to follow the GC protocols).

> Just yesterday I removed a malloc that was (why??) causing a segfault.

Well, you certainly can't use the system malloc to obtain memory and expect
Python's garbage collection to manage it -- for gc'ed extension types, the
memory must be gotten via PyObject_GC_New() or PyObject_GC_NewVar(), and you
have to follow all the other rules too.  If you haven't read and understood
the "Supporting Cyclic Garbage Collection" section of the Python/C API
manual, you're going to get lots of segfaults.  But if you follow the rules,
you shouldn't get any.  Remember too that this is C code, not Python code,
so the result of not following a rule is more likely to be a nasty crash
than a friendly exception.




From cjw at sympatico.ca  Sun Jan  4 17:35:18 2004
From: cjw at sympatico.ca (Colin J. Williams)
Date: Sun, 04 Jan 2004 17:35:18 -0500
Subject: PythonWin problems
In-Reply-To: <9Z1Jb.15438$lo3.12939@newsread2.news.pas.earthlink.net>
References: 
	<9Z1Jb.15438$lo3.12939@newsread2.news.pas.earthlink.net>
Message-ID: 

r.e.s. wrote:
> "Colin J. Williams"  wrote ...
> 
>>PythonWin has been my favourite IDE for quite a while.
>>
>>When one right clicks on a .py file in the Windows Explorer, among the 
>>options are Open and Edit.  The former is the default and executes 
>>Python, with the selected script.  The latter activates the PythonWin 
>>editor, with the selected script.
>>
>>Since, most frequently, I wish to edit the script, or execute it with 
>>the debugger, I tried changing the default to Edit, using the Edit File 
>>Type menu.
> 
> 
> FWIW ...
> 
> I'm not sure what you mean by "Edit File Type menu".
> Using WinXP Pro, in Windows Explorer I went to 
> Tools/Folder Options/File Types
> selected PY, clicked Advanced, and set the default to Edit.
I thought of this activity as editing.
> Now double-clicking a .py file brings it up in PythonWin,
> and I've experienced neither of the problems that you report below.
> 
> 
>>Unfortunately, this leads to a couple of problems:
>>
>>1. Any activity becomes horrendously slow, and
>>2. The following message appears:
>>    LoadBarState failed - LoadBarState failed (with win32 exception!)
>>[Dbg]>>>
> 
Many thanks to those who responded.

I used the ideas of John Roth and modified my XP registry, using 
Registrar-Lite, to read:

REGEDIT4

[HKEY_CLASSES_ROOT\Python.File]
@="Python File"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008

[HKEY_CLASSES_ROOT\Python.File\AutoRegister]
@="C:\\WINDOWS\\System32\\PythonCOM23.dll"

[HKEY_CLASSES_ROOT\Python.File\DefaultIcon]
@="C:\\PYTHON23\\Py.ico"

[HKEY_CLASSES_ROOT\Python.File\shell]
@="Edit"

[HKEY_CLASSES_ROOT\Python.File\shell\Edit]

[HKEY_CLASSES_ROOT\Python.File\shell\Edit\command]
@="C:\\Python23\\pythonwin.exe /edit \"%1\""

[HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE]

[HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command]
@="C:\\Python23\\Pythonw.exe C:\\Python23\\Lib\\idlelib\\idle.pyw -e \"%1\""

[HKEY_CLASSES_ROOT\Python.File\shell\open]

[HKEY_CLASSES_ROOT\Python.File\shell\open\command]
@="C:\\PYTHON23\\python.exe \"%1\" %*"

All functions well now.

Thanks.

Colin W.





From scottdog at nospam.com  Tue Jan 20 17:40:09 2004
From: scottdog at nospam.com (Dog@will.hunt)
Date: Tue, 20 Jan 2004 14:40:09 -0800
Subject: Installing SpamBayes
References: <400c399b_2@newsfeed.slurp.net>
	
	<400c451a_1@newsfeed.slurp.net>
	<20040120135921.1C3F.JCARLSON@uci.edu>
Message-ID: <400c5790_1@newsfeed.slurp.net>

That didnt work either and the file assoc. are correct.

"Josiah Carlson"  wrote in message
news:20040120135921.1C3F.JCARLSON at uci.edu...
> > The instructions that came with SpamBayes says it.  THey say to either
run
> > the setup.py file in the Python GUI (IDLE) or froma command prompt.  I
have
> > tried both to no avail...
>
> If you are in windows and your associations are correct, try:
> setup.py install
>
>  - Josiah




From maketo at vinland.freeshell.org  Tue Jan 13 10:44:08 2004
From: maketo at vinland.freeshell.org (Ognen Duzlevski)
Date: Tue, 13 Jan 2004 15:44:08 +0000 (UTC)
Subject: Inlined C code and a TypeError
Message-ID: 

Hi all,

I have a nested loop that is written using PyInline for speed reasons. It modifies three matrices (lists of lists 
containing integer numbers).

Upon return from this function I run min() on values from the matrices. Below is the puzzling output:

--
time in nested loop: 0.250000
403
394
402



Traceback (most recent call last):
  File "./primegens_old.py", line 1656, in ?
    GetSegment()
  File "./primegens_old.py", line 1499, in GetSegment
    tmp_score,sim = SeqMapping(seq[ndx1],seq[0],seqmapping,inversemapping,length[ndx1],length[0])
  File "./primegens_old.py", line 678, in SeqMapping
    minscore = min(delmat[tlen][qlen], insertmat[tlen][qlen], scoremat[tlen][qlen])
TypeError: an integer is required
--

I do not understand - the numbers 403, 394 and 402 are results of printing the delmat, insertmat and 
scoremat[tlen][qlen] each. The " is a result of calling type on each of these. Yet, when min is called, ot 
dies with the TypeError. Can anyone shed some light on this?

Thank you,
Ognen


From swalters_usenet at yahoo.com  Thu Jan  8 20:05:33 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Fri, 09 Jan 2004 01:05:33 GMT
Subject: What psyco is goot at [Was: Rookie Speaks]
References: 
Message-ID: 

|Thus Spake Delaney, Timothy C (Timothy) On the now historical date of
Fri, 09 Jan 2004 11:51:23 +1100|
> Anyway, when the non-psyco code takes an hour, and the psyco.full()
> version takes 10 minutes, you know you're onto a winner :)
*chuckle*

That could be a good hint.

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From guettli at thomas-guettler.de  Wed Jan 14 03:43:01 2004
From: guettli at thomas-guettler.de (Thomas Guettler)
Date: Wed, 14 Jan 2004 09:43:01 +0100
Subject: Inserting while itterating
Message-ID: 

Hi,

Simple excerise:

You have a sorted list of integers:
l=[1, 2, 4, 7, 8, 12]

and you should fill all gaps:

result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

How would you code this?

Constrain: The original list should be changed,
don't create a copy.

  thomas



From gerrit at nl.linux.org  Thu Jan 15 11:28:33 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Thu, 15 Jan 2004 17:28:33 +0100
Subject: [HUMOUR] indoctrination starts at an early age
Message-ID: <20040115162833.GA4748@nl.linux.org>

Hi,

1 November 1985, indoctrination does start at an early age indeed:

http://people.nl.linux.org/~gerrit/basic1.png
http://people.nl.linux.org/~gerrit/basic2.png

Broadcasted in a yearly children's program, in a song. Accompying text: 
BIEP BIEP TUUT TUUT
BIEP BIEP TUUT TUUT
BIEP
GO TO
FOR I IS ONE TO HUNDRED
PRINT
GO TO
FOUR
IF NOT
FIFTEEN
NEXT
GET A

translation: s/BIEP/BEEP/g
 text: http://www.omroep.nl/vara/tv/kvk/songteksten/album06/papa_papa.html
music: http://home.student.utwente.nl/g.holl/papa%20papa.mp3

:)

yours,
Gerrit.

-- 
214. If this maid-servant die, he shall pay one-third of a mina.
          -- 1780 BC, Hammurabi, Code of Law
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/



From swalters_usenet at yahoo.com  Thu Jan 15 20:23:20 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Fri, 16 Jan 2004 01:23:20 GMT
Subject: Printing to console (No Scroll)
References: 
	
	
Message-ID: 

| Dennis Lee Bieber said |
>         Don't you need a \r on the second print line also? Otherwise the
> spaces will be printed at the end of the previous counter value?

Um, yeah.  You do.

> 
> 
>         Though would \r even work if this was to be run on a Mac -- I
>         thought
> Macs used to use \r for line ending (maybe OS-X has gone to \n).

I don't know.  I've never owned a mac, and haven't ever worked on one.
Thus, mac nuances rarely enter my mind even when I know about them.

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From stephan.diehlNOSPAM at gmx.net  Wed Jan 14 09:43:18 2004
From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl)
Date: Wed, 14 Jan 2004 15:43:18 +0100
Subject: pulling set of unique values from a list
References: <400551c0$1@baen1673807.greenlnk.net>
Message-ID: 

Ben Davies wrote:

> I need to get [1,2,3] from [1,1,1,2,2,3,3] with as little effort possible
> for my CPU (and keyboard).
> I'd half expected there to be a list.values method to do this, but there
> isn't so I've have had to use a dictionary object:
>
 
I'd use a set for that:

>>> from sets import Set
>>> l = [1,1,1,2,2,3,3]
>>> [x for x in Set(l)]
[1, 2, 3]
>>>

By the way, in a lot of cases where I used lists, I'm now using sets because
they seem more natural in some situations.

Stephan


From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Sun Jan 25 11:45:29 2004
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Sun, 25 Jan 2004 17:45:29 +0100
Subject: xrange not hashable - why not?
In-Reply-To: 
References: 
	
	
Message-ID: <4013f2a9$0$327$e4fe514c@news.xs4all.nl>

Sean Ross wrote:

>>xrange(100, sys.maxint),
>>since you have to walk through the items in that range to see if n is in
>>there, and that's a large range.
> 
> 
> Hmm, I don't think what I said there is correct, please disregard.


I think you're right though:

90000000 in xrange(1,sys.maxint)   takes a long time to complete....

--Irmen


From jensthiede at webgear.co.za  Fri Jan 23 13:45:51 2004
From: jensthiede at webgear.co.za (Jens Thiede)
Date: 23 Jan 2004 10:45:51 -0800
Subject: Distutils - Program Distribution
Message-ID: 

Pardon the silly question, but can one use distutils to install
somewhere other than site-packages, or is distutils only ment for this
kind of a job. I'd like to use it to make the distribution of my
programs simpler :)

Thanks for any good replies,

Jens.


From francisgavila at yahoo.com  Mon Jan  5 16:42:33 2004
From: francisgavila at yahoo.com (Francis Avila)
Date: Mon, 5 Jan 2004 16:42:33 -0500
Subject: Problem: 'Threads' in Python?
References: 
Message-ID: 


Ralph Sluiters wrote in message ...
>Hi,
>i've got a small problem with my python-script. It is a cgi-script, which
is
>called regulary (e.g. every 5 minutes) and returns a xml-data-structure.
>This script calls a very slow function, with a duration of 10-40 seconds.
To
>avoid delays, i inserted a cache for the data. So, if the script is called,
>it returns the last caculated data-structure and then the function is
called
>again and the new data is stored in the cache. (There is no problem to use
>older but faster data)
>
>My problem is, that the client (A Java program (or browser, command line))
>waits, until the whole script has ended and so the cache is worthless. How
>can I tell the client/browser/... that after the last print line there is
no
>more data and it can proceed? Or how can I tell the python script, that
>everything after the return of the data (the retieval of the new data and
>the storage in a file) can be done in an other thread or in the background?

Wouldn't a better approach be to decouple the cache mechanism from the cgi
script?  Have a long-running Python process act as a memoizing cache and
delegate requests to the slow function.  The cgi scripts then connect to
this cache process (via your favorite IPC mechanism).  If the cache process
has a record of the call/request, it returns the previous value immediately,
and updates its cache in the meantime.  If it doesn't have a record, then it
blocks the cgi script until it gets a result.

How can threading help you if the cgi-process dies after each request unless
you store the value somewhere else?  And if you store the value somewhere,
why not have another process manage that storage?  If it's possible to
output a complete page before the cgi script terminates (I don't know if the
server blocks until the script terminates), then you could do the cache
updating afterwards.  In this case I guess you could use a pickled
dictionary or something as your cache, and you don't need a separate
process.  But even here you wouldn't necessarily use threads.

Threads are up there with regexps: powerful, but avoid as much as possible.
--
Francis Avila



From pod at internode.on.net  Sat Jan  3 19:51:19 2004
From: pod at internode.on.net (PoD)
Date: Sun, 04 Jan 2004 10:51:19 +1000
Subject: Speed?
References: 
Message-ID: 

On Fri, 02 Jan 2004 23:01:15 -0800, EP wrote:

> 
> On questions of the suitability of Python for CGI, embedded apps, etc., 

Most of the time taken by that test is outputting to the screen.
I tried you script in various environments

90x45 xterm     54.5 seconds
80x10 xterm     35.6
text console    26.2
minimised xterm 25.0

Run in Idle, the output goes to a TkInter text widget so I'm not surprised
it's so slow.



From wweston at att.net  Fri Jan 23 16:49:32 2004
From: wweston at att.net (wes weston)
Date: Fri, 23 Jan 2004 21:49:32 GMT
Subject: Various strings to dates.
In-Reply-To: <4GfQb.16187$AA6.14368@fed1read03>
References: <4GfQb.16187$AA6.14368@fed1read03>
Message-ID: 

Amy,
    I hope there is a better way but, if you go here:

http://www.python.org/doc/current/lib/datetime-date.html

The new datetime module may help. This and the time mod
should get you where you want to go.

list     = strdate.split(", ")
daystr   = list[0]
daynum   = int(list[1])
monthstr = list[2]
year     = int(list[3])
#funct to get a month int is needed

d = datetime.Date(y,m,d)

wes

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

Amy G wrote:
> I have seen something about this beofore on this forum, but my google search
> didn't come up with the answer I am looking for.
> 
> I have a list of tuples.  Each tuple is in the following format:
> 
> ("data", "moredata", "evenmoredata", "date string")
> 
> The date string is my concern.  This is the date stamp from an email.
> The problem is that I have a whole bunch of variations when it comes to the
> format that the date string is in.  For example I could have the following
> two tuples:
> 
> ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15")
> ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 03:15:06")
> 
> I know there is some way to use the date string from each of these to get a
> date usable by python, but I cannot figure it out.
> I was trying to use time.strptime but have been unsuccesful thus far.
> 
> Any help is appreciated.
> 
> 



From corey.coughlin at attbi.com  Thu Jan 29 19:25:54 2004
From: corey.coughlin at attbi.com (Corey Coughlin)
Date: 29 Jan 2004 16:25:54 -0800
Subject: conditional expression sought
References: 
Message-ID: 

"Elaine Jackson"  wrote in message news:...
> If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True,
> then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without
> evaluating any other B_i. This is such a useful mode of expression that I would
> like to be able to use something similar even when there is an i with
> bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1])
> or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious
> reasons. Does anybody know a good way to express this? Any help will be mucho
> appreciado.
> 
> Peace

Oh, this must be part of your truth table script.  Interesting,
looking for something like a fast SOP evaluator, or more like a
function evaluation mechanism?  It would probably be most useful to
share your containers for A and B.  Are you really going to have
variables named A_1 to A_n, or will you just have a vector A[0:n]? 
The vector would probably be easier to deal with.  Using integer
representations for your boolean vectors is a good idea, and will
probably buy you enough speed that you won't need a more serious form
of short circuit evaluation, I imagine.  Unless your vectors are very
large indeed.  Hmm...


From cookedm+news at physics.mcmaster.ca  Thu Jan 15 20:15:11 2004
From: cookedm+news at physics.mcmaster.ca (David M. Cooke)
Date: Thu, 15 Jan 2004 20:15:11 -0500
Subject: Quick question.....
References: 
	<379178f1.0401151634.556bb405@posting.google.com>
Message-ID: 

At some point, featherstone80 at hotmail.com (Narsil) wrote:

> I tried that.  I get the following error message
>
> Traceback (most recent call last):
>   File "E:\python\fun4b.py", line 80, in ?
>     menu()
>   File "E:\University\python\assign4b.py", line 49, in menu
>     print sum(weektotlist)
> NameError: global name 'sum' is not defined
>
> What did I do wrong?

'sum' as a builtin was introduced in python 2.3. You're using an older
version.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca


From Tobias.Windeln at gmx.de  Fri Jan  9 08:33:59 2004
From: Tobias.Windeln at gmx.de (Tobias Windeln)
Date: Fri, 09 Jan 2004 14:33:59 +0100
Subject: Object-based inheritance in Python
In-Reply-To: 
References: 
	
Message-ID: 

Stephan Diehl wrote:
> Tobias Windeln wrote:
> 
> 
>>Hi!
>>
>>I'm looking for suggestions on object-based inheritance
>>in Python. Automatic forwarding (often called delegation)
>>in Python is easy:
>>
> 
> 
> Have a look at Hans Nowaks 'selfish' implementation:
> http://zephyrfalcon.org/download/selfish-0.4.2.zip

Thanks, this was exactly what I was looking for.



From skip at pobox.com  Wed Jan 28 10:05:56 2004
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 28 Jan 2004 09:05:56 -0600
Subject: Distributing Python programs
In-Reply-To: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net>
References: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net>
Message-ID: <16407.53204.465653.73259@montanaro.dyndns.org>


    Graham> Can I install Python on a networked server and have any user run
    Graham> Python programs without having to go through the 9Mb client
    Graham> install?

Are you talking about Windows?  I think that as long as you copy
Python23.dll to the same directory as python.exe you will be okay.  For
Unix-y systems as long as everyone is on the same architecture you should be
okay.

    Graham> What are my options for distributing Python programs to my users?

Distutils is probably the way to go assuming they already have access to
Python proper.  Check the distutils docs:

    http://www.python.org/doc/current/lib/module-distutils.html

Otherwise, take a look at py2exe (Windows only) or Gordon MacMillan's
installer (cross-platform?).

Skip



From zunbeltz at wm.lc.ehu.es.XXX  Tue Jan 27 02:24:35 2004
From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola)
Date: 27 Jan 2004 08:24:35 +0100
Subject: unittest
References: 
	
	
	
Message-ID: 

David Goodger  writes:

> Zunbeltz Izaola wrote:
>  > Tnaks, why is this so?
> 
>  From the fine manual
> (http://www.python.org/doc/current/lib/minimal-example.html):
> 
>      A testcase is created by subclassing unittest.TestCase. The three
>      individual tests are defined with methods whose names start with
>      the letters "test". This naming convention informs the test runner
>      about which methods represent tests.

I have to read the manuals at full :-)

Zunbeltz

> 
> The convention is necessary because you might want methods that are
> *not* tests.
> 
> -- David Goodger


From francisgavila at yahoo.com  Fri Jan 16 09:03:06 2004
From: francisgavila at yahoo.com (Francis Avila)
Date: Fri, 16 Jan 2004 09:03:06 -0500
Subject: do loop
References: <3064b51d.0401160536.5d80fa97@posting.google.com>
Message-ID: <100frr2i3ulhf3d@corp.supernews.com>

beliavsky at aol.com wrote in message
<3064b51d.0401160536.5d80fa97 at posting.google.com>...
>In a Python 'for' loop, one can change the value of looping variable,
>so that
>
>for i in range(3):
>    i = i*5
>    print i
>
>is legal code
>
...
>Is there a way to write a loop in Python that enforces this
>constraint? Should such functionality be added to the language?

Note: I haven't done a search of the archives for possible past discussions
of this, which I really should do before responding.

First, I think this is simply not a problem in practice.  Even much more
common errors, such as binding to a misspelled attribute name, are not
checked for.  Python leans very heavily on regression testing, even as a
design methodology, and thus is unconcerned with having these sort of
bondage-and-discipline language features.

Second, PyChecker (which is a static code checker, providing many of the
kinds of checks that people from staticly-typed languages tend to miss)
could probably easily be extended to check for this sort of behavior, if it
doesn't already have it.

Finally, Fortran is often subject to very agressive optimization by the
compiler.  Python optimization, by comparison, is pretty rudamentary (and
there wouldn't be any speed advantage in this case, anyway, given the
bytecodes Python uses).  Thus there may be a very significant incentive for
Fortran to disallow assignment to loop variables, whereas Python has no such
incentive.

--
Francis Avila



From jjhuang at cm.nctu.edu.tw  Tue Jan  6 10:26:14 2004
From: jjhuang at cm.nctu.edu.tw (Chun-Chieh Huang)
Date: Tue, 06 Jan 2004 23:26:14 +0800
Subject: Embedding python problem, related to PyObject_Print.
References: 
Message-ID: 

Chun-Chieh Huang  writes:

> Dear all,
>
> I carefully lookup PyObject_Print in the API manual, but I can't find
> the resolution. And the problem is described below:
>
> I embed python into C++ code as follows:

Sorry I didn't specify the platform. Below is my python version and
platform, but I use g++-2.96 to compile the C++ code, which embeds
python. Is it a problem of different compiler versions?

Python 2.3.3 (#1, Jan  5 2004, 14:18:28) 
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2
-- 
Chun-Chieh Huang, aka Albert    E-mail: jjhuang AT cm.nctu.edu.tw
???                         
Department of Computer Science  
National Tsing Hua University   MIME/ASCII/PDF/PostScript are welcome!
HsinChu, Taiwan                 NO MS WORD DOC FILE, PLEASE!


From mirko-lists at zeibig.net  Mon Jan 19 05:20:52 2004
From: mirko-lists at zeibig.net (Mirko Zeibig)
Date: Mon, 19 Jan 2004 11:20:52 +0100
Subject: C++ bad-mouthing
In-Reply-To: 
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	<7xisjh1e3i.fsf@ruckus.brouhaha.com>
	<10064loqc7sd7e3@corp.supernews.com>
	
	<3064b51d.0401160539.49fc5893@posting.google.com>
	
Message-ID: 

Rainer Deyke said the following on 01/16/2004 07:23 PM:
> beliavsky at aol.com wrote:
> 
>>What is so dangerous about the STL in C++?
> 
> 
> One thing is that iterators can get invalidated when the container is
> modified.

Hm, I think there are similar problems in Python:
--- snip ---
adict = {'foo': 'bar', 'spam': 'ham'}

for key in adict: # has to be adict.keys()
   del adict[key]
--- snap ---

This snippet leads to a RuntimeError but the first item will be gone.

Of course, you may use the "older" syntax in this case. ".keys()" will 
generate the list of keys once in advance, while the upper example will 
call next() each time AFAIK.

Regards
Mirko
-- 


From http  Thu Jan  8 18:31:46 2004
From: http (Paul Rubin)
Date: 08 Jan 2004 15:31:46 -0800
Subject: count objects in a list and random numb gen
References: 
Message-ID: <7xekuaxbj1.fsf@ruckus.brouhaha.com>

Bart Nessux  writes:
> New to Python... trying to figure out how to count the objects in a
> list and then map the count to the objects or convert the list to a
> dict... I think the latter would be better as I need a number
> associated with each entry. Any pointers?

I'm sorry but I just can't understand the above description.  To count
the objects in a list L, use len(L).  To find the k'th element of L,
list, use L[k].  

> Also, does this bit of code look to be truely random?
> 
> def random_number_gen():
>     winner = []	
>     winner.append(random.sample(xrange(100000), 1))	
>     print winner	

If you want to choose one random winner out of a list, you can say
print random.randint(100000).  

Note that Python's random function doesn't try to be really seriously
random, but only to have reasonable statistical properties.  If you
need random numbers that can stand up to an adversary (e.g. you're
using it in an online game where the winners get substantial prizes),
you shouldn't generate them with the random module.


From dk123456789 at hotmail.com  Fri Jan  2 19:51:04 2004
From: dk123456789 at hotmail.com (Dave K)
Date: Sat, 03 Jan 2004 01:51:04 +0100
Subject: Can this be reversed (Tkinter)?
References: 
Message-ID: 

On Fri, 2 Jan 2004 12:49:08 -0800 in comp.lang.python, "mark"
 wrote:

>I am looking at the format used by root.geometry().  The string returned
>from root.geometry() is "%dx%d+%d+%d".  Is there a quick and painless
>way to extract the values from that string (i.e., "100x150+25+25" =>
>(100,150,25,25))?
> 
>- Mark

For that particular string, I can think of 2 one-liners:

>>> s='100x150+25+25'
>>> print tuple([int(x) for x in s.replace('x', '+').split('+')])
(100, 150, 25, 25)
>>> print tuple([int(x) for y in s.split('x') for x in y.split('+')])
(100, 150, 25, 25)


For more general use, the regular expression "\d+" will match positive
integers:

>>> s='100x150+25+25/(34*7);12-34*(56%78/9)'
>>> import re
>>> print tuple([int(x) for x in re.findall('\d+', s)])
(100, 150, 25, 25, 34, 7, 12, 34, 56, 78, 9)

Dave


From __peter__ at web.de  Mon Jan 12 05:20:35 2004
From: __peter__ at web.de (Peter Otten)
Date: Mon, 12 Jan 2004 11:20:35 +0100
Subject: building strings with variable input
References: 
Message-ID: 

Olaf Meyer wrote:

> Sometimes if find it clumsy unsing the following approach building
> strings:
> 
> cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime,
> directory)
> 
> Especially if you have a lot of variable input it makes it hard to match
> the variables to the proper fields. From other scripting languanges I'm
> used to something like:
> 
>   $cmd = "$executable -start $startTime -end $endTime -dir $directory"
> 
> This makes it very easy to see how the string is actually built. You
> dont't have to worry where which variables go.
> 
> Is there a similar way to do this in python?

>>> "from %(org)s to %(dest)s" % dict(org="X", dest="Y")
'from X to Y'

or even

>>> org = "A"
>>> dest = "B"
>>> "from %(org)s to %(dest)s" % locals()
'from A to B'

Peter


From aahz at pythoncraft.com  Sat Jan 17 11:00:26 2004
From: aahz at pythoncraft.com (Aahz)
Date: 17 Jan 2004 11:00:26 -0500
Subject: Does anyone else not find the fun in programming...?
References: 
Message-ID: 

In article ,
Chris Lyon  wrote:
>
>I find python very effective as a language and can generally project
>most of my hazy thoughts into it. But FUN !!! This is work dammit,
>I have now ground my teeth down from the number of times I read that
>programming is fun. Football (association) is fun, walking along
>canals is fun, Arguing about quite how useless the British Government
>is fun but programming  ?

When I learned Python, I'd been programming for more than twenty years,
but I didn't call myself a programmer because I hated programming.  I
still don't think that programming is fun, but Python is enough fun for
me to call myself a programmer.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From na  Mon Jan  5 18:33:27 2004
From: na (Andrew)
Date: Mon, 5 Jan 2004 15:33:27 -0800
Subject: Need Help Optomizing Code
Message-ID: 

Hi I am fairly new to python

and was wondering if anyone out there could help me optomize this code.

It is a simple Tkinter program that connects to a database and deletes
records

Some of this code was borrowed from a book learning python

Anyhelp would be cool thank you in advance

Andrew

"""""Below is the code"""""

import MySQLdb
from Tkinter import *

class FormEditor:

    def __init__(self):


        self.row = 0
        self.current = None

        self.root = root = Tk()
        root.minsize(300, 200)


        root.rowconfigure(0, weight=1)
        root.columnconfigure(0, weight=1)
        root.columnconfigure(1, weight=2)


        Label(root, text='Form Editor App', font='bold').grid(columnspan=2)
        self.row = self.row + 1
        self.listbox = Listbox(root, selectmode=SINGLE)
        self.listbox.grid(columnspan=2, sticky=E+W+N+S)
        self.listbox.bind('')
        self.row = self.row + 1

        self.add_button(self.root, self.row, 0, 'Delete Entry',
self.delentry)
        self.add_button(self.root, self.row, 1, 'Reload', self.load_data)

        self.load_data()


    def add_button(self, root, row, column, text, command):
        button = Button(root, text=text, command=command)
        button.grid(row=row, column=column, sticky=E+W, padx=5, pady=5)

    def load_data(self):
        self.db = MySQLdb.connect("localhost", "", "", "guestbook")
        self.c = self.db.cursor()
        self.c.execute("select * from guests;")
        self.results = self.c.fetchall()
        self.listbox.delete(0, END)
        for item in self.results:
            self.listbox.insert(END, item)

    def delentry(self):
        self.db = MySQLdb.connect("localhost", "", "", "guestbook")
        self.c = self.db.cursor()
        self.c.execute("DELETE FROM guests WHERE id LIMIT 1;")
        self.results = self.c.fetchall()
        print "Please press reload to see your results"


app = FormEditor()
app.mainloop()




From stephendotboulet at motorola_._com  Mon Jan 26 15:47:16 2004
From: stephendotboulet at motorola_._com (Stephen Boulet)
Date: Mon, 26 Jan 2004 14:47:16 -0600
Subject: Single and double asterisks preceding variables in function
	arguments
In-Reply-To: 
References: 
	
Message-ID: 

anton muhin wrote:

> Stephen Boulet wrote:
> 
>> I've run across code like "myfunction(x, *someargs, **someotherargs)", 
>> but haven't seen documentation for this.
>>
>> Can someone fill me in on what the leading * and ** do? Thanks.
>>
>> Stephen
> 
> 
> See item 7.5 in Language Reference. In short: * declaries list of 
> additional parameters, while ** declares map of additional parameters. 
> Try somehting like:
> 
>     def foo(*params): print params
> 
> and
> 
>     def bar(**params): print params
> 
> to find out details.
> 
> regards,
> anton.

<<
a={'c1':'red','c2':'blue','c3':'fusia'}
def bar(**params):
....for k in params.keys():
........print k, params[k]
bar(a)
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: bar() takes exactly 0 arguments (1 given)
 >>

Why does bar take zero arguments?

Hmm, but:

<<
def bar2(*params,**moreparams):
....print "params are ", params,'\n'
....for k in moreparams.keys():
........print k, moreparams[k]
....print "moreparams are ", moreparams

bar2(range(3),a,)
params are  ([0, 1, 2], {'c3': 'fusia', 'c2': 'blue', 'c1': 'red'})

moreparams are  {}
 >>

I think I've got the *params argument down (you just get the whole 
argument list), but I'm still not getting the **moreparams ...

Stephen


From jjl at pobox.com  Mon Jan 19 08:21:15 2004
From: jjl at pobox.com (John J. Lee)
Date: 19 Jan 2004 13:21:15 +0000
Subject: New to Python: my impression v. Perl/Ruby
References: 
Message-ID: <87ad4kxees.fsf@pobox.com>

Wayne Folta  writes:
[...]
> So I decided this might be a nice exercise to try Python. And it went
> together very quickly using Python's POP3 package. Then I decided to
> try it in Ruby. I think one little portion of the code shows the
> difference between the two cultures.
> 
> The problem is that the message is not properly terminated, so you
> need to time out and catch that timeout to realize, "hmmm, malformed".
> In Python I had:
> 
> M = poplib.POP3 ('172.16.30.1') ;
> M.user ('foo') ;
> M.pass_ ('bar')
> 
> num_mesgs = len (M.list ()[1])
> bad_mesgs = 0
> 
> for msg in range (num_mesgs):
> 	try:
> 		M.retr (msg + 1)
> ... blah blah...
> 
> How do I get it to time out after 5 seconds and how do I catch that?
> The online docs are pretty good, but I had to guess that POP3 was
> built on the socket package. Looking at socket's docs I found the

Well, that's not exactly a huge leap given any knowledge of how the
internet works.  I'm not sure that Python's docs should be in the
business of educating people about that...


> proper command and exception. I had to include:
> 
> socket.setdefaulttimeout (5.0)
> 
> before the POP3 commands to set the default socket timeout to 5
> seconds. And
> 
> except socket.timeout:
> 
> is the proper way to catch the timeout. Both of these things are in
> the socket documentation.

...but the fact that there is no timeout support in client modules of
the socket module is a known bug:

http://www.python.org/peps/pep-0042.html
http://www.python.org/sf/723287

It's likely to be fixed in 2.4.  Timeouts on sockets were only
introduced in Python 2.3 (though there was a third party library
around for a long time before that that retrofitted timeouts into
the standard library).


> Contrast this with Ruby. The Ruby docs are less complete, but they did
> mention that POP was subclassed from protocol and you'd have to look
> at protocol's source to see how it works. Looking through protocol, I
> figured out what to do and it was more elegant.

Well, if Python's standard library had decided to subclass everything
from some 'protocol' base class, the docs would indeed mention that
fact, since that's would be a fact about the Python standard library
rather than about networking in general.  It didn't, so it doesn't.


> The protocol class had a read_timeout, but since Ruby's mantra might
> be said to be "Real OO", the POP code had been written such that you
[...]

In the absence of some explanation of what you mean by "Real OO", that
sounds trollish.

I don't see how a missing feature in Python reveals any difference in
culture between Python and Ruby, other than perhaps that the Ruby
people like implementation inheritance more than the people who
designed the Python standard library.


John


From mwh at python.net  Mon Jan 19 06:07:30 2004
From: mwh at python.net (Michael Hudson)
Date: Mon, 19 Jan 2004 11:07:30 GMT
Subject: viewcvs install error on solaris
References: <4007e92d$0$325$ba620e4c@news.skynet.be>
Message-ID: 

bva  writes:

> Hello,
> 
> While trying to install viewcvs on a solaris 5.9 machine I get the
> following error message:
> 
> Traceback (most recent call last):
>    File "./viewcvs-install", line 35, in ?
>      import compat
>    File "./lib/compat.py", line 20, in ?
>      import urllib
>    File "/usr/local/lib/python2.2/urllib.py", line 26, in ?
>      import socket
>    File "/usr/local/lib/python2.2/socket.py", line 41, in ?
>      from _socket import *
> ImportError: No module named _socket
> 
> Python is installed on the machine.  Can anybody tell me what I'm
> doing wrong or what I've forgotten?

Your python install lacks the socket module.  On Solaris this usually
means something exciting to do with your SSL install.  Who installed
Python?  Complain at them.

Cheers,
mwh

-- 
  In many ways, it's a dull language, borrowing solid old concepts
  from many other languages & styles:  boring syntax, unsurprising
  semantics, few  automatic coercions, etc etc.  But that's one of
  the things I like about it.                 -- Tim Peters, 16 Sep 93


From klappnase at web.de  Wed Jan 21 12:14:51 2004
From: klappnase at web.de (klappnase)
Date: 21 Jan 2004 09:14:51 -0800
Subject: Tkinter bitmap bug ?
Message-ID: 

Hello everyone,

I have seen several threads here on this problem, but still cannot figure out
the solution. I want to create a window icon for a Tkinter application and tried
several things that are supposed to work. Here is a little demo of what I tried:

#################################from Tkinter import *

icon1 = ('''#define im_width 26
#define im_height 25
static char im_bits[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x7e,
0x00,0x00,0xe0,0x7f,0x00,0x00,0xff,0x63,0x00,0x00,0x3f,0x70,0x00,0x00,0x03,
0x7e,0x00,0x00,0xe3,0x7f,0x00,0x00,0xff,0x63,0x00,0x00,0x3f,0x60,0x00,0x00,
0x03,0x60,0x00,0x00,0x03,0x60,0x00,0x00,0x03,0x78,0x00,0x00,0x03,0x7c,0x00,
0x00,0x03,0x7e,0x00,0xc0,0x03,0x7e,0x00,0xe0,0x03,0x3c,0x00,0xf0,0x03,0x18,
0x00,0xf0,0x03,0x00,0x00,0xe0,0x01,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };''')

icon2 = ('R0lGODlhEAAMAKEAAAAAAAC18////////yH5BAEAAAIALAAAAAAQAAwAAAI'
        'glIFgyxcfVFsAQtmS3rjaH1Hg141WaT5ouprt2HHcUgAAOw==')

def test0():
    root = Tk()
    root.iconbitmap('@/somepath/window_icon.xbm')
    root.mainloop()

def test1():
    root = Tk()
    root.bit = BitmapImage(data=icon1)
    root.iconbitmap(root.bit)
    root.mainloop()

def test2():
    root = Tk()
    bit = BitmapImage(data=icon1)
    img = PhotoImage(data=icon2)
    try:
        b1 = Button(root, bitmap=bit)
        b1.icon_ref = bit
        b1.pack()
    except:
        pass
    try:
        b2 = Button(root, image=img)
        b2.icon_ref = img
        b2.pack()
    except:
        pass
    root.mainloop()

def test3():
    root = Tk()
    img = PhotoImage(data=icon2)
    top = Toplevel(root)
    l = Label(top, image=img)
    l.icon_ref = img
    l.pack()
    root.iconwindow(top)
    root.mainloop()

if __name__=='__main__':
    test0()
   
#############################################

Running the test0() function works fine, however I wanted to not to carry an
external bitmap file around, so I tried to pass the bitmap data to a BitmapImage
object.
Running test1() returns following error message:

Traceback (most recent call last):
  File "/usr/local/share/test.py", line 52, in ?
    test1()
  File "/usr/local/share/test.py", line 20, in test1
    root.iconbitmap(root.bit)
  File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1448, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "pyimage1" not defined

No surprise - the image gets garbage collected as soon as it is created, I know.
So I tried test2() to avoid this. Unfortunately it is quite the same here,
and this is the point where it begins to look like a bug to me. Running test2()
returns a window with only one button with the PhotoImage correctly displayed.
Obviously the PhotoImage does not get garbage collected, so why does the 
BitmapImage ???

I thought then if this all would not work I might use a PhotoImage as window
icon using the iconwindow() method - see test3().
However the icon does not show up.

Any help on this would be greatly appreciated.

Thanks in advance

Michael


From CGStartup at earthlink.net  Sat Jan 31 20:02:47 2004
From: CGStartup at earthlink.net (Stan Schwartz)
Date: 31 Jan 2004 17:02:47 -0800
Subject: Programmers Wanted for Computer Graphics Startup Near
	Philadelphia
References: <2da21d6c.0401310807.671be3b7@posting.google.com>
	
Message-ID: <2da21d6c.0401311702.1fd5c019@posting.google.com>

"Mikl?s"  wrote in message news:...
> Software patents are evil.
> Hell to them.

At one point I would have agreed with you, and I
agree that a fair number of software patents unfairly
take credit for work that was already in the public
domain.  Do you think patents are ever justified?
Stan


From aahz at pythoncraft.com  Wed Jan 14 14:24:13 2004
From: aahz at pythoncraft.com (Aahz)
Date: 14 Jan 2004 14:24:13 -0500
Subject: Myth or Urban Legend? Python => Google [ was: Why learn Python
	??]
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	
	
	<1009fum3evnc96a@corp.supernews.com>
Message-ID: 

In article <1009fum3evnc96a at corp.supernews.com>,
Francis Avila  wrote:
>EP wrote in message ...
>>
>>Is it true that the original Google spider was written in Python?
>
>I don't know *what* Google uses Python for, but it uses Python.

How about http://www.python.org/Jobs.html
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From ark at acm.org  Mon Jan 26 10:57:31 2004
From: ark at acm.org (Andrew Koenig)
Date: Mon, 26 Jan 2004 15:57:31 GMT
Subject: I support PEP 326
References: 	<401081A1.E4C34F00@alcyone.com>	
	
Message-ID: 

> Calling min with no arguments need not be the same as calling it with an
> empty sequence argument. That is not necessarily an argument for making
> the empty function call return something arguably strange...

Having min() and min([]) return different values is also arguably strange.




From jcarlson at uci.edu  Wed Jan 21 16:49:21 2004
From: jcarlson at uci.edu (Josiah Carlson)
Date: Wed, 21 Jan 2004 13:49:21 -0800
Subject: newbie: "File Buffered" Text widget
References: 
Message-ID: <20040121134515.D8EC.JCARLSON@uci.edu>

> I need a "File Buffered" Text widget (in Tkinter), that
> is a window over a buffered text file which would behave
> as if the entire file was loaded in memory (permitting
> the user to browse huge corpora text files).
> 
> Before writing one from scratch, I would like to be sure
> that there is no such thing available somewhere.

Creating your own read-only widget shouldn't be too difficult.  Creating
your own read-write widget would be a bit more difficult.  I would offer
to write a wxPython read-only one (it would take like 10 minutes), but
you're looking for Tkinter, so nevermind.

 - Josiah



From ldwhitley.remove.this at charter.net  Sat Jan  3 14:25:49 2004
From: ldwhitley.remove.this at charter.net (LD Whitley)
Date: Sat, 03 Jan 2004 13:25:49 -0600
Subject: Simulation library in Python
In-Reply-To: 
References: 
Message-ID: 

Samir Patel wrote:

> I am interested in creating a professional level
> simulation model in Python, so any help regarding this
> will be very much appriciated.


I think Simpy is about as close as you're going to come - it's the best 
I've seen in Python.  I haven't tracked it lately but if you send a note 
to the developers I think that you'll find they're still active.

Personally, I (and the group of which I'm a member) are doing our 
modeling in C++/CSim.  It's mostly a speed of simulation issue but I 
have to admit that I haven't done any comparisons between the C++/CSim 
and Simpy.  I'm just assuming that the compiled nature of C++ and the 
interpreted nature of Python will give the edge to C++. Our models can 
run for a long time so speed of execution is important.  If anyone has 
information to the contrary, I'm all ears.  (or eyeballs, or something)

Larry

-- 
LD Whitley
http://webpages.charter.net/ldwhitley



From rmkrauter at yahoo.com  Fri Jan 30 23:38:52 2004
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Fri, 30 Jan 2004 23:38:52 -0500
Subject: timeit
In-Reply-To: 
References: 
Message-ID: <1075523932.4239.22.camel@vaio>

Did you try enclosing arg to Timer in quotes? It is enclosed in quotes
in the python tutorial:
http://www.python.org/doc/current/tut/node12.html#SECTION00121000000000000000000

Rich

On Fri, 2004-01-30 at 23:21, Duncan Smith wrote:
> This is possibly a stupid question, but I need to get this working quickly,
> and I guess I'm just too tired / pressured to see what I'm doing wrong.
> Clearly (from the output below) I can't pass the statement to an instance of
> timeit.Timer, but I can execute it using exec().  Any idea what I need to do
> to get this timed (using timeit).  Cheers.
> 
> >>> import SDC_table
> >>> import subtract
> >>> import timeit
> >>> t = SDC_table.RandomTable(1, 12, (2,3,4))
> >>> s = """\
> p = subtract.p_risk(t.values, 10)
> """
> >>> tim = timeit.Timer(stmt=s)
> >>> tim.timeit(10)
> 
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
>     tim.timeit(10)
>   File "C:\Python23\lib\timeit.py", line 158, in timeit
>     return self.inner(it, self.timer)
>   File "", line 6, in inner
> NameError: global name 'subtract' is not defined
> 
> # yet
> >>> exec(s)
> >>> p
> 0.242621453769059
> 



From alan.gauld at btinternet.com  Thu Jan  1 17:34:12 2004
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 01 Jan 2004 22:34:12 GMT
Subject: Test if IDLE is a mature program
References: 
	<7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com>
	
	<99dce321.0312311130.5b7c7c8a@posting.google.com>
	
Message-ID: <3ff49f0e.776954150@news.blueyonder.co.uk>

On Wed, 31 Dec 2003 14:48:59 -0500, "Aubrey Hutchison"
 wrote:
> I understand the problem of using the names of common modules...
> 
> But why do we need to work around that problem..

For the same reason you have to do it in any development tool.
Name clashes are the programmers responsibility not the tool
makers, there is no sane way for a tool maker to avoid user
stupidity.

> My position still stands
> This program does not really provide a credit to PYYHON.

On your general point that IDLE is not a mature product you are
correct, it is only at version 1.0 with Python 2.3. Name me any
product (except maybe TeX) that was mature at version 1.0.
I remember using Visual Basic at v1.0 and it definitely wasn't
mature...

However your test of maturity is completely bogus, it is an issue
of user error not IDLE error. How do you think IDLE should handle
the case you describe? How would it know whether you intended a
name clash or not?

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld


From gerrit at nl.linux.org  Fri Jan  9 15:39:44 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Fri, 9 Jan 2004 21:39:44 +0100
Subject: PRE-PEP: new Path class
In-Reply-To: <3FFEFB7C.6030802@beyond-thoughts.com>
References: 
	
	<3FFEFB7C.6030802@beyond-thoughts.com>
Message-ID: <20040109203944.GA5405@nl.linux.org>

Christoph Becker-Freyseng wrote:
> Gerrit Holl wrote:
> >John Roth wrote:
> >
> >>I'm adding a thread for comments on Gerrit Holl's pre-pep, which
> [...]
> >Shall I submit this as an official PEP? Or shall I first fill in more
> >open issues and perhaps give the possibility to change "closed" issues?
> >
> 
> I think there are still a lot of issues. I think letting settle things 
> down at first is wiser. And then present a PEP where many (even better 
> all) contributors agree. (I didn't like the result of PEP308 very much ...)

Yes. But of course, a PEP being an official PEP does not mean there
can't be any more changes to it. So the question is, at what point does
a pre-PEP become a PEP? Some PEPs have a $Revision: 1.20$, after all.

> In additions there are still good points in the older discussions and 
> existing modules that should be integrated (You linked in the prePEP).

Yes, that's true. I'll do that.

yours,
Gerrit.

-- 
49. If any one take money from a merchant, and give the merchant a
field tillable for corn or sesame and order him to plant corn or sesame in
the field, and to harvest the crop; if the cultivator plant corn or sesame
in the field, at the harvest the corn or sesame that is in the field shall
belong to the owner of the field and he shall pay corn as rent, for the
money he received from the merchant, and the livelihood of the cultivator
shall he give to the merchant.
          -- 1780 BC, Hammurabi, Code of Law
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/



From none at none.com  Mon Jan 12 09:45:53 2004
From: none at none.com (Derek)
Date: Mon, 12 Jan 2004 09:45:53 -0500
Subject: Why learn Python ??
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	
Message-ID: 

I guess I didn't really answer the main question: Why learn Python
over Perl, C/C++, C#, etc.

In short, because it's easier to program, isn't tied to a platform,
and has lots of high-level functionality right out of the box.




From newsgroups at jhrothjr.com  Sat Jan  3 18:55:11 2004
From: newsgroups at jhrothjr.com (John Roth)
Date: Sat, 3 Jan 2004 18:55:11 -0500
Subject: pickling lambdas?
References: <9abf3a27.0401031446.4d73cfb2@posting.google.com>
	
	<7x65fs38cg.fsf@ruckus.brouhaha.com>
Message-ID: 


"Paul Rubin"  wrote in message
news:7x65fs38cg.fsf at ruckus.brouhaha.com...
> "John Roth"  writes:
> > > however, upon google searching for "python lambda pickle" i find 2
> > > posts, one including gvr, which apparently demonstrate that this was
> > > being attempted and even suggest that it is feasible.  has this become
> > > available yet, or will it be soon?
> >
> > Why do you want to do this? According to the docs, all that
> > is saved for a function or a class is the name. Code, data and
> > so forth is not saved, so it makes no sense to try to pickle
> > a lambda unless you've bound it to a name at the module level.
>
> I think the idea may be to pickle a closure, to save the data inside
> it.  I do remember some mention about pickling generators.  Anyway, in
> Python 2.x the closest you can come to that is pickling class
> instances.

That ought to work as long as you unpickle it into the same module
so you can get the original class definition.

John Roth




From ian at ibygrave.no-ip.org  Mon Jan 12 15:33:31 2004
From: ian at ibygrave.no-ip.org (ian)
Date: Mon, 12 Jan 2004 20:33:31 +0000
Subject: Why learn Python ??
References: <40029dad$0$28706$a729d347@news.telepac.pt>
Message-ID: 

On Mon, 12 Jan 2004 13:05:19 +0000, Bicho Verde wrote:

>     And also I don't know exactly why would I learn Python rather than C#,
> C++ or Perl.

As usual, someone else already said it better than I can:

"Why Python?" by Eric S. Raymond
http://www.linuxjournal.com/article.php?sid=3882

--IAN



From gandalf at geochemsource.com  Thu Jan 29 17:32:45 2004
From: gandalf at geochemsource.com (Gandalf)
Date: Thu, 29 Jan 2004 23:32:45 +0100
Subject: wxNotebook question
Message-ID: <40198A0D.70704@geochemsource.com>

How can I hide/show a page (wxNotebookPage) invisible of a wx.wxNotebook 
instance?
There is a GetPage() method which returns a wxNotebookPage but I could 
not find
any documentation in the help about this class. I thought there will be 
a 'SetVisible'
or 'SetTabvisible' method but it seems to be a proxy for the root 
control on that page.
So I cannot even get method names by dir(self.notebook.GetPage(0)).

Thanks in advance





From jsbenson at bensonsystems.com  Thu Jan  8 22:54:12 2004
From: jsbenson at bensonsystems.com (John Benson)
Date: Thu, 8 Jan 2004 19:54:12 -0800
Subject: Lua: further investigation and comparisons with Python and Forth
Message-ID: <02ef01c3d664$3ead3c00$e50a500a@jsbwxp3>

Since I've seen some Forth expertise/interest in evidence here, so I'll
permit myself some observations on Lua/Python/Forth.

Lua's scripting command syntax is pretty simple, though different from
Python's. It is reference- and not variable-oriented (that is, "variables"
are merely holders for references, not values) and smacks of Python in this
regard. Functions are first-class objects; again, very similar to Python.

The big differences (for me) are two:

1) Lua is designed to be driven "from the outside" by an embedding host
program and needs to be extended via C to fulfill its stated purpose of
providing an embeddable, extendable scripting language, so the Lua C API is
much more important to me as a Lua programmer than the Python API has been
to me as a Python programmer.

2) The Lua API is stack-based, so your C extension code pushes, pops and
otherwise manipulates values on the Lua stack. These values aren't simple
processor scalars; you can push a table onto the stack, whose elements can
be tables containing tables and so on and so forth. Speaking of forth, the
Lua C API has very much the flavor of Forth on steroids. You play the same
kind of stack games, but the command prompt on the other side of Lua can be
used like an object-oriented scripting language.

One very cool aspect of Lua is that the entire state of a "Lua virtual
machine" is encapsulated in the "Lua state" data structure. This means no
hidden global variable sharing at the C language level, so you can easily
instantiate a new Lua "session" to handle each concurrent incoming socket
session in a server if you wish, and keep them all perfectly separate. To
me, that means that I can extend Lua with the appropriate C routines and
then script socket sessions in an object-oriented fashion without leaving
the comfort of my C compiler (old habits die hard). While this would be a
useless tour de force on the PC or Unix, it's actually very useful on my old
Tandem K100 4-CPU fault-tolerant system. The file system has only one level
of directory per disk volume (ack!) and so a port of Python or Java would
only be an exercise in masochism. Later Tandems sport a POSIX personality
(called OSS, or Open Systems Services), but my K100 dates from an earlier
time when mainframes still roamed the earth. Flattening the Lua source tree
to fit on the K100 wasn't too hard, and there isn't anything in Lua's
operation that requires directory nesting in the filesystem.

Aside:

It was kind of fun to draw on my previous experience with Forth in grokking
the Lua C API. For a real blast from the past, check out the Open Firmware
initiative, which has adopted Forth as the language of it's BIOS code
loader. In the future, you may be able to buy some hardware, talk to a
little Forth kernel in ROM somewhere, decide how to load a real machine
BIOS, and then set it going prior to the actual OS boot.

Before reading about Open Firmware, I had assumed that Forth had completely
dropped out of sight. Anyone else aware of counterexamples?






From adalke at mindspring.com  Mon Jan 12 01:35:13 2004
From: adalke at mindspring.com (Andrew Dalke)
Date: Mon, 12 Jan 2004 06:35:13 GMT
Subject: Simple Python Speed Benchmark
References: 
Message-ID: 

engsolnom at ipns.com:
> I was curious how long Python takes just to read and display time.clock()
  ...
> I was amazed at the difference in speed depending on when/how the clock
times were converted to
> milliseconds....almost 4 to 1...as indicated in the RESULTS below. I
understand the variation in the
> times is probably due to other running processes.
>
> Any explanation?

There are quite a few things here.

First, if you look at the "Test 3:" and "Test 4:" numbers you'll see it's
only
2 times slower, not 4.  Let's start with that case, where the tests you make
are in a function.  You can see the PVM op codes generated by using
the dis module

>>> def spam():
... t1 = time.clock()
...
>>> import dis
>>> dis.dis(spam)
  2           0 LOAD_GLOBAL              0 (time)
              3 LOAD_ATTR                1 (clock)
              6 CALL_FUNCTION            0
              9 STORE_FAST               0 (t1)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE
>>> def spam2():
... t1 = time.clock() * 1000
...
>>> dis.dis(spam2)
  2           0 LOAD_GLOBAL              0 (time)
              3 LOAD_ATTR                1 (clock)
              6 CALL_FUNCTION            0
              9 LOAD_CONST               1 (1000)
             12 BINARY_MULTIPLY
             13 STORE_FAST               0 (t1)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE
>>>

This shows that the "* 1000" is doing two more things; load the
constant "1000" and then do a binary multiply.  The obvious
conclusion is that the factor of 2 slowdown comes from this step.
(That actually surprises me.  Function call overhead should be
much more than a simple multiply.)

The next is the precision of the clock.  The numbers generated
are pretty well quantized.  For example, '0.014527' comes up
quite frequently as does '0.005867'.  It appears that your clock
has a resolution of about 0.0003, which is 5% of the smaller
numbers or 2% of the bigger ones.  If the time slices are just
at the wrong point then you may get a systematic error of up
to about 6% (ie, if the time.clock is done in just under an
integral time quantum while the time.clock()*1000 is just over
a quantum).

To get around that, you should do more tests, and not have
the results of one test strongly correlated with the other.
(You do because get_time_1() is always followed with a
get_time_2().)  The easiest way is to use the timeit module,
either on the command-line or interactively, as

>>> import timeit
>>> timeit.Timer("time.clock", "import time").repeat(3, 10000)
[0.0063276180834463958, 0.0066243037524600368, 0.0078663607060889262]
>>> timeit.Timer("time.clock()", "import time").repeat(3, 10000)
[0.054394886949353349, 0.053860182268920198, 0.05341180138486834]
>>> timeit.Timer("time.clock()*1000", "import time").repeat(3, 10000)
[0.057691115018485561, 0.059368981429486212, 0.058075800674146194]
>>>

As you can see, on my box it takes 0.06 microseconds to do
'time.clock', 0.48 microseconds to make the call, and 0.03
microseconds to do the *1000.

Try those on your machine.

                    Andrew
                    dalke at dalkescientific.com




From ville.vainio at spamster_tut_remove.fi  Mon Jan  5 02:34:14 2004
From: ville.vainio at spamster_tut_remove.fi (Ville Vainio)
Date: 05 Jan 2004 09:34:14 +0200
Subject: Cheetah best for templating?
References: 
	<3FF74DFF.6BE7AC7D@alcyone.com>
Message-ID: 

Erik Max Francis  writes:

> I tend to think highly of EmPy, but that's not exactly a surprise :-):

Me too!

> 	http://www.alcyone.com/software/empy/
> 
> I do know that there are several people on the EmPy mailing list using
> EmPy for exactly the purpose you're considering.

Including yours truly. Also, the source code generation problem might
be solved trivially by checking out

http://www.students.tut.fi/~vainio24/pywiz/

> What's going to be best for you is really going to depend on your
> aesthetic sensibilities; pretty much all of templating systems' base
> features are universal, just expressed in different ways.  The only

Also, there is very little to lose by taking a cursory glance at each
one and choosing what seems easiest (assuming they have the same level
of power).

Short EmPy tutorial:

---------- myfile.em -------------------

@{
# statements
import time
var1 = 12
var2 = "Hello"
}

@var2 World! @var1 plus one is @(var1+1)
------------------------------------------

python em.py myfile.em > output.txt

-- 
Ville Vainio   http://www.students.tut.fi/~vainio24


From crap at crud.com  Sat Jan 10 04:36:06 2004
From: crap at crud.com (Moosebumps)
Date: Sat, 10 Jan 2004 09:36:06 GMT
Subject: Setting up test for XML-RPC
References: 
Message-ID: 

OK, I tried the obvious and it worked.  : )  I just changed the call to
server.pow(3,5) and it returns the correct result.  I wonder why they aren't
set up that way in the first place.

But the second question still stands.  I am running both the client and
server on my own machine now (Windows 2000).  Would I just need Python and
web server if they were different machines?  I would like to avoid
installing a bunch of software on the 20 machines if possible.

thanks,
MB

"Moosebumps"  wrote in message
news:cDPLb.2260$nl3.2178 at newssvr29.news.prodigy.com...
> I'm trying to test out Python XML-RPC for the first time, and can't find
> anything that executes a call end to end.
>
> I thought that I would use SimpleXMLRPCServer to run a simple server on
> localhost, and xmlrpclib to run a client that connects to it, but they
don't
> seem to register the same functions.  The server test code registers 'pow'
> and 'add' (in the Python 2.3 distribution) but the client seems to call
> "print server.examples.getStateName(41)".  It doesn't seem like they were
> meant to work together as a unit test, although that would seem logical.
>
> Can anyone help me just get a single XML-RPC call to execute (and I want
to
> see both the client and server code)?  I have googled extensively and
> haven't come up with anything.
>
> Also -- I'm investigating this for a nightly build process involving many
> machines.  There is going to be a master machine that sends requests to 20
> other machines to build things.  They're just a bunch of Windows XP
> machines, with almost no software on them.  What software would I need to
> install to run XML-RPC servers on them to receive requests?  Just Python
and
> a web server like Apache?
>
> If there are any other _very_ lightweight RPC mechanisms, I would
appreciate
> hearing about them.  I am writing some build scripts in Python, and while
I
> could for example schedule a task on 20 machines separately, it would be
> nicer to have a master machine control when the build happened, etc. and
be
> able to manage dependencies by waiting for a return result, etc.  All I
want
> to do is execute a python function on a remote machine and get a result
> back.  It is all done in a local, secure environment.
>
> Thanks for all the previous responses to my questions -- this newsgroup
has
> been very helpful.
>
> MB
>
>




From sidharthk at hotmail.com  Thu Jan 29 13:59:35 2004
From: sidharthk at hotmail.com (Sidharth Kuruvila)
Date: Fri, 30 Jan 2004 00:29:35 +0530
Subject: read() on tempfile
References: 
Message-ID: 


"cherico"  wrote in message
news:afc115ec.0401291041.155b51ee at posting.google.com...
> from tempfile import *
>
> f = NamedTemporaryFile ()
> f = write ( 'test' )
> print f.read () #here print nothing
>
> why is it nothing to read()?
> I suppose f is of mode 'w+'

the rpoblem is probably that your file pointer is sitting at the end of the
file after you write something
try f.seek(0) before you read, might work





From aahz at pythoncraft.com  Mon Jan 19 14:52:17 2004
From: aahz at pythoncraft.com (Aahz)
Date: 19 Jan 2004 14:52:17 -0500
Subject: Delayed evaluation and setdefault()
References:  <400C25FF.A76B1FEA@engcorp.com>
Message-ID: 

In article <400C25FF.A76B1FEA at engcorp.com>,
Peter Hansen   wrote:
>Leo Breebaart wrote:
>> 
>>    >>> d.setdefault('foo', b())
>> then b() *does* get executed regardless of whether or not the
>> value it returns is actually used ('foo' was not found) or not
>> ('foo' was found).
>> 
>> So I guess my question is twofold: one, do people think
>> differently, and if so why?; and two: is there any elegant (or
>> other) way in which I can achieve the delayed evaluation I desire
>> for setdefault, given a side-effect-having b()?
>
>def lazysetdefault(dict, key, ref):
>    if not dict.has_key(key):
>        dict[key] = ref()
>    return dict[key]

First of all, Peter made a boo-boo in naming a parameter ``dict``.

If the key will be in the dict more than 90% (*very* roughly) of the time
you call this, you can do this instead:

def lazysetdefault(d, key, ref):
    try:
        return d[key]
    except KeyError:
        d[key] = ref()
        return d[key]

That minimizes the bytecode and function calls.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From premshree_python at yahoo.co.in  Tue Jan 27 23:17:03 2004
From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=)
Date: Wed, 28 Jan 2004 04:17:03 +0000 (GMT)
Subject: Manipulating MIDI
Message-ID: <20040128041703.13351.qmail@web8304.mail.in.yahoo.com>

Hello,

I am in need of a module using which I could
manipulate musical information from MIDI files. What I
need is some module that could extract the frequency
components of the various instruments in the musical
piece. Any suggestions?

If there isn't such a module, could you suggest a
similar module in C/C++, so that I could then write
bindings for it in Python.

-Premshree Pillai
[http://www.qiksearch.com/]

=====
-Premshree
[http://www.qiksearch.com/]

________________________________________________________________________
Yahoo! India Mobile: Download the latest polyphonic ringtones.
Go to http://in.mobile.yahoo.com



From cavada at irst.itc.it  Thu Jan 15 07:25:36 2004
From: cavada at irst.itc.it (Roberto Cavada)
Date: Thu, 15 Jan 2004 13:25:36 +0100
Subject: [ANNOUNCE] gtkmvc-0.9.0
Message-ID: <1074169536.26364.233.camel@stadio>

MVC Framework for Pygtk2 version 0.9.0 has been released. 

MVC is a fully Python-based implementation of the Model-View-Controller
and Observer patterns for the Pygtk2 toolkit. 
MVC is a pattern that can be successfully used to design and develop
well structured GUI applications. 

The MVC pattern basically helps in separating sematics and data of the
application, from their representation. The Observer pattern is also
embedded here. This pattern allows making separated parts independent,
but still connected each other. 

About this implementation:
- easy to understand and to use
- makes code extremely easy to write and read
- fully documented
- straightly runs under many platforms (unixes, windows, solaris,
  etc.)
- essential, it does only what it was designed for
- can be ported to other graphic toolkits, since the view component 
  depends on pygtk2

Latest version and information can be found at this URL:
       

gtkmvc 0.9.0 - Python-based Model-View-Controller framework for the Pygtk2 toolkit. (15-01-04) License is LGPL. -- _/_/_/ _/_/_/ Roberto Cavada _/ _/ _/ ITC-irst http://www.irst.itc.it _/ _/ _/ Automated Reasoning Systems - Formal Methods Group /_/_/ _/ Via Sommarive, 18 - 38050 Povo (TN) - Italy _/ _/ Tel: +39 0461 314 328 Fax: +39 0461 302 040 _/ _/_/ cavada at irst.itc.it http://sra.itc.it/people/cavada From Vincent.Raaijmakers at ge.com Tue Jan 27 08:42:41 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Tue, 27 Jan 2004 07:42:41 -0600 Subject: JPG - PNG conversion problem Message-ID: <971323274247EB44B9A01D0A3B424C8505907BF8@FTWMLVEM02.e2k.ad.ge.com> I agree with all te comments that I got regarding the expected growth of my file size in PNG. However, when I use Gimp in Linux, the PNG conversion (using default settings) on the same picture, the file size grows form 14k (JPG) to 18k (PNG). Using PythonMagick it grows to 64k!! So, why is Gimp more efficient in the conversion? I must be doing something different. Today I will try to use some Java imaging libraries to see how efficient they are. A growth from 14k to 64k is unacceptable. We are talking about a picture with a size of 160x120. For now, what tips and tricks are available to reduce my output file size using Magick? Tried to work with filtering and quality settings, no huge results so far. 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 Jason Harper Sent: Monday, January 26, 2004 10:00 PM To: python-list at python.org Subject: Re: JPG - PNG conversion problem "Raaijmakers, Vincent (GE Infrastructure)" wrote: > Who can explain the huge increase in size when I convert a JPG into a PNG format using PythonMagick: > I read the JPG from a video server and has a resolution of 352x240, size is about 15k > After my PNG conversion and resizing the resolution to 160*120, the size is 64k!! JPEG is a lossy compression format (well, normally - there are some obscure exceptions to this). It throws away subtle details (details that the human eye is relatively insensitive to) in order to achieve its high compression ratios. PNG uses only lossless compression. You are guaranteed that the image you get out will be pixel-for-pixel identical to the image you put in. Unfortunately, this greatly limits the possibilities for compression - in fact, no lossless compressor can guarantee ANY reduction in file size over all possible inputs. Basically, converting a lossy to a lossless format gives you worst of both worlds - the loss of detail of one, and the large file size of the other. Jason Harper -- http://mail.python.org/mailman/listinfo/python-list From try_vanevery_at_mycompanyname at yahoo.com Tue Jan 13 06:30:41 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 03:30:41 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Brandon J. Van Every" wrote in message news:bsd101$c1oj1$1 at ID-207230.news.uni-berlin.de... > I am > > - *TENTATIVELY* - > > (operative word) undertaking the project of porting the GPL open source game > "Freeciv" to Python. Freeciv is, in essence, an almost straight clone of > Sid Meier's Civilization II, albeit with better cross-platform and > multiplayer support. www.freeciv.org Here's a postmortem. Short version: I've canned the project. Many of you will say "I told you so," but at least I almost have a VS .NET 2003 build to show for it. First I decided to tackle the subgoal of freeing Freeciv from the UNIX Cygwin / MinGW crud. As I write this, I have it compiling and running on VS .NET 2003, and that isn't a small accomplishment. But, the game hangs shortly after the server starts. I'm probably within spitting distance of completing this subgoal, but it has taken too long and has been really really boring. If there isn't some major lurking horror I'll get it working eventually, but I've put it on the backburner. Personal projects have to be personally rewarding, and this isn't it. Looking at the Freeciv C code in more detail, I've realized that there's way too much code to consider "generally" rewriting stuff in Python. Rather, I'd have to embed Python and add / rework game functionality piecemeal. This is a lot of work, there's a whole lot of boring "wrapper code" to cough up. Between performing this kind of labor on a GPL project, and performing it for Ocean Mars, I've decided that the former is not rational. And more importantly, it doesn't make me happy. I've also become extremely disillusioned with Open Source developers. Basically, for a commercially minded developer such as myself, I don't think they're any value add at all. Ergo, all public projects I might conceive of are fundamentally DOA. For 6 months I've experimented with how Open Source development might fit my commercial goals. What I've found is that I can't rely on people, only their coding artifacts. Every Open Source game developer I've met in the past 6 months has been, at a basic level, a hobbyist. Hobbyists simply don't manage projects according to the demands of commercial development. This implies that if I'm in charge, they won't like my style; and when they're in charge, it drives me fucking nuts. I've now accepted that the Open Source talent pool is what it is. It is capable of being fun for programmer geeks. But with few exceptions, such as perhaps http://nebula.sourceforge.net, it cannot achieve the kinds of projects I have in mind. I'm also starting to downright despise Linuxers. If I see another project that's "cross-platform, so long as your platform is Linux," I'm going to cut someone's head off. Linuxers have this completely broken piece of shit build management mentality about them. They think that because on *their* OS all these libraries are preinstalled, and everyone's compiling things all the time, that they don't have to do anything to maintain consistent builds on other platforms. Rather, it's always the induhvidual's responsibility to download and install all the needed component libraries. Of course these are usually UNIX-centric libraries, often not readily compiled on Windows. Or requiring Cygwin or MinGW, which real Windows developers don't want to use. Versioning becomes a nightmare, is it the Cygwin or MinGW version? It's just not the way mainstream Windows developers do things. Whether my Freeciv VS .NET 2003 build makes it into the official Freeciv source pool remains to be seen. The Freeciv people are, after all, a bunch of Linuxers. They don't have a single .NET developer among them, and I'm not about to become their .NET buildmaster. When I say things like "Windows people want to link libpng and zlib against MSVCRT71.dll," they say, "we don't want to bloat our source tree with needed libraries." Maybe in time I will get them to accept a separate package of underlying libraries for Windows folk. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Desperation is the motherfucker of Invention." - Robert Prestridge From http Thu Jan 22 00:16:52 2004 From: http (Paul Rubin) Date: 21 Jan 2004 21:16:52 -0800 Subject: Secure Voting software References: <87zncgy544.fsf@strauser.com> <20040122000103.21852.00000518@mb-m06.aol.com> Message-ID: <7xu12oftq3.fsf@ruckus.brouhaha.com> piedmontbiz at aol.com (PiedmontBiz) writes: > I checked out the site: http://gnosis.python-hosting.com/voting-project/ > > This is a huge and important project. I suppose the programming > language is really not that important. The issue is trustworthy > system development (applications, operating systems, drivers, > libraries, hardware, etc.), and developing ways to validate > software. There's bigger problems than any software can solve. See http://www.blackboxvoting.com a view of some of them. From rick_muller at yahoo.com Wed Jan 21 11:22:57 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 21 Jan 2004 08:22:57 -0800 Subject: distutils uninstall Message-ID: <5eb8fb88.0401210822.55b60ef7@posting.google.com> I've been trying to figure out whether there are any plans to add an "uninstall" feature to the Python distutils. Googling has found several people posting the same question, but, to the best of my knowledge, no answers. Can anyone tell me whether this has been proposed before? Thanks in advance. From claird at lairds.com Mon Jan 12 16:42:07 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 12 Jan 2004 21:42:07 -0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <100655fo84c2211@corp.supernews.com> In article , Derek wrote: . . . >I would not dismiss C++ (or even vanilla C) outright. I strongly >suggest starting in Python and looking to C and C++ when you have good >reason -- that is, when those languages will let you do something that >Python is less than than stellar at: large applications, system >software, performance-critical applications, embedded programming, >etc. . . . I contest the proposition that "Python is less than stellar at large applications ...", and, in particular, that C++ is super- ior there. I recognize you're not alone in that; for me, though, large-scale programming is one of Python's *strengths*. I don't have a good decision mechanism to propose. Trial by ordeal (and most large-team projects fit in that category) seems as apt as any. -- Cameron Laird Business: http://www.Phaseit.net From me at privacy.net Wed Jan 28 07:36:59 2004 From: me at privacy.net (Duncan Booth) Date: 28 Jan 2004 12:36:59 GMT Subject: Python Importing and modifying print References: <9742a725.0401280426.329d2178@posting.google.com> Message-ID: kenney at netacc.net (J. Kenney) wrote in news:9742a725.0401280426.329d2178 at posting.google.com: > Good Morning, > > Is there a way for a function called within an _imported_ > library to call back to _calling_ python program to run a > function? (Shown below) Yes, you *could* do that, see the code below: the script is loaded into a module called __main__ so all you have to do is import __main__ and you can access the scripts variables. > #newlib.py import __main__ def go(): __main__.main() __main__.main() go() This still won't have quite the results you want, as the function main doesn't exist at the point when you import the other module. You need to define it before the import (remember, the code in a module is executed the first time the module is imported): #first_file.py #!/usr/local/bin/python def main(): print 'hi' import newlib However, you probably don't want to do that. A much better solution is either to put your 'main' function into another module, or to pass the callback function around as a parameter: #first_file.py import newlib def main(): print 'gi' newlib.go(main) #newlib.py def go(where): where() where() > > Also can you overload the print function to have it do > redirect output to an array for a bit, and then switch > it back. (for example: right before importing make print > append each line to an array vice printing it, then going > back to normal after the import is complete.) > Yes, the easiest way would be to reassign sys.stdout to put output into your array using cStringIO and then restore sys.stdout after you have finished. Again though, it isn't a good idea to do real work on an import; much better to do the work in a function and have no real code in the imported module. From sandskyfly at hotmail.com Wed Jan 21 05:36:22 2004 From: sandskyfly at hotmail.com (Sandy Norton) Date: 21 Jan 2004 02:36:22 -0800 Subject: personal document mgmt system idea References: Message-ID: Stephan Diehl wrote: [...] > Just dump your files somewhere in the filesystem and keep a record of it in > your database. I think I will go with this approach. (see other posting for details) > In addition, a real (text) search engine might be of help. I'm using swish-e > (www.swish-e.org) and are very pleased with it. Just downloaded it... looks good. Now if it also had a python api (-; > Maybe, before you invest to much time into such a project, you should check > out the following: > > Chandler (http://www.osafoundation.org) > if it's finished, it will do excactly what you are aiming for (and > it's written in Python) Still early stages... I see they dropped the ZODB. > ReiseFS (see www.namesys.com -> Future Vision) > Gnome Storage (http://www.gnome.org/~seth/storage) > WinFS > (http://msdn.microsoft.com/Longhorn/understanding/pillars/WinFS/default.aspx) Wow! Very exciting stuff... I guess we'll just have to wait and see what develops. > Hope that helps Yes. Very informative. Cheers for the help. > Stephan Sandy From amuys at shortech.com.au Sun Jan 18 21:08:29 2004 From: amuys at shortech.com.au (Andrae Muys) Date: 18 Jan 2004 18:08:29 -0800 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> Message-ID: <7934d084.0401181808.6e698042@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <7934d084.0401152058.164a240c at posting.google.com>, > Andrae Muys wrote: > > > >Found myself needing serialised access to a shared generator from > >multiple threads. Came up with the following > > > >def serialise(gen): > > lock = threading.Lock() > > while 1: > > lock.acquire() > > try: > > next = gen.next() > > finally: > > lock.release() > > yield next > > I'm not sure this is generic enough to go in the standard library. > Usually, I'd recommend that someone wanting this functionality consider > other options in addition to this (such as using Queue.Queue()). I'm curious to know how a Queue.Queue() provides the same functionality? I have always considered a Queue.Queue() to be an inter-thread communcation primitive. serialise() (at least the corrected version discussed later in this thread) is strictly a synchronisation primitive. Andrae From jepler at unpythonic.net Mon Jan 5 20:37:08 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Jan 2004 19:37:08 -0600 Subject: Repost: Can't sys.exit() from SIGTERM handler? In-Reply-To: References: Message-ID: <20040106013708.GD5514@unpythonic.net> If I had to guess, I'd bet you had a blanket exception handler somewhere. sys.exit merely raises SystemExit, and if this exception propogates all the way back up, Python treats it specially by exiting instead of printing the exception's traceback. :r term.py import os, signal, time, sys, traceback def sigterm(a, b): print "sigterm" sys.exit() signal.signal(signal.SIGTERM, sigterm) os.system("(sleep 1; kill %s) &" % os.getpid()) print "Sleeping (should be killed)" try: time.sleep(2) except SystemExit: traceback.print_exc() raise print "sleep finished (!?)" :r!python -u term.py Sleeping (should be killed) sigterm Traceback (most recent call last): File "term.py", line 14, in ? time.sleep(2) File "term.py", line 5, in sigterm sys.exit() SystemExit From tepihlaj at NOpaju.SPAMoulu.fi Mon Jan 5 20:58:02 2004 From: tepihlaj at NOpaju.SPAMoulu.fi (Tero Pihlajakoski) Date: 6 Jan 2004 01:58:02 GMT Subject: Grab input&output of program on Windows References: Message-ID: Patrick L. Nolan wrote: > I'm going nuts trying to port an application from Linux > to Windows. We have a python/Tkinter script which runs > a C++ application. It starts it with popen4 and > communicates through the two pipes. It reads text output > from stdout until a prompt appears, then sends commands > through stdin. Sorry, if this is basic, but: Did you flush() after write()? Try using popen2() (there was something about popen4() on win32...), if possible (import popen2, etc.)? > On Windows it seems to get all tangled up in the buffering > of the two streams. When the script just reads stdout, it > seems to be OK. As soon as the first command is sent to > stdin, stdout blocks forever. > I tried borrowing an idea from the Python Cookbok, recipe > 9.6. I made the streams nonblocking and put a call to > select in a loop. The results were promising on Linux, > but there was a mysterious error message on Windows. > I think select works only for sockets, not pipes. > This seems like the sort of thing that might be solved by > expect. Will that work? Is there some other way? -- From seanl at chaosring.org Sat Jan 3 22:06:31 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 19:06:31 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: Serge Orlov wrote: > You're right, the wording is not quite correct. My point was that it should > take effort to make attributes _public_, for example, going to another > source line and typing attribute name or doing whatever "declaration" means. > This way adding new attribute or leaking "unsecured" object will > raise an exception when untrusted code will try to access it. Otherwise > one day something similar to rexec failure will happen: somebody > added __class__ and __subclasses__ attributes and rexec blindly > allowed to access them. The leading underscore doesn't matter, it > could be name like encode/decode that is troublesome. > > By the way, my code above is buggy, it's a good idea that you're > not going to use it :) Let me try it the second time in English words: > If the attribute 'attr' is declared public give it. If the function with > UUID has access to attribute 'attr' on object 'obj' give it. Otherwise fail. Ok, I think you've pretty much convinced me here. My choices for protected attributes were to either name them specially and only allow those attribute accesses on the name "self" (which I treat specially), or to make everything protected by default, pass all attribute access through a checker function (which I was hoping to avoid), and check for a special attribute to define which attributes are supposed to be public. Do you think it's good enough to make all attributes protected as opposed to private by default? > Nevermind, it's just a scary word :) It can concern you if you worry > about information leaking from one security domain to another. Like > prisoners knocking the wall to pass information between them. In > computers it may look like two plugins, one is processing credit > cards and the other one has capability to make network connections. > If they are written by one evil programmer the first one can "knock > the wall" to pass the information to the second. "knocking the wall" > can be encoded like quick memory allocation up to failure = 1, no > quick memory allocation = 0. Add error correction and check summing > and you've got a reliable leak channel. Hmmm, I think this would be even more difficult to protect from than doing resource checks. Fortunately, I'm not planning on processing any credit cards with this code. The primary purpose is so that multiple programmers (possibly thousands) can work in the same memory space without stepping on one another. > I'm not sure how to deal with str.encode too. You don't know what > kind of codecs are registered for that method for sure, one day there > could be registered an unknown codec that does something unknown. > Shouldn't you have two (or several) codecs.py modules(instances?) > for trusted and untrusted code? And str.encode should be transparently > redirected to the proper one? I guess I'll just make attributes protected by default, and force the programmer to go out of their way to make things public. Then I can use the Zope/RestrictedPython technique of assuming everything is insecure until proven otherwise, and only expose parts of the interface on built-in types that have been audited. Thank you very much for your extremely informative responses! From RAV at ns.artphila.com Wed Jan 28 03:30:57 2004 From: RAV at ns.artphila.com (RAV at ns.artphila.com) Date: Wed, 28 Jan 2004 10:30:57 +0200 Subject: RAV AntiVirus scan results Message-ID: <200401280830.i0S8UvLr005550@ns.artphila.com> RAV AntiVirus for Linux i686 version: 8.3.2 (snapshot-20020108) Copyright (c) 1996-2001 GeCAD The Software Company. All rights reserved. Registered version for 2 domain(s). Running on host: ns.artphila.com ----------------------- RAV Antivirus results ----------------------- The infected file was saved to quarantine with name: 1075278657-RAVi0S8UrLr005535. The file (part0002:file.zip)->file.pif attached to mail (with subject:MAIL DELIVERY SYSTEM) sent by python-list at python.org to phila at artphila.com, is infected with virus: Win32/Mydoom.A at mm. Cannot clean this file. Cannot delete this file (most probably it's in an archive). The mail was not delivered because it contained dangerous code. ------------------------ this is a copy of the e-mail header: Scan engine 8.11 () for i386. Last update: Tue Jan 27 05:03:51 2004 Scanning for 89279 malwares (viruses, trojans and worms). To get a free 60-days evaluation version of RAV AntiVirus v8 (yet fully functional) please visit: http://www.ravantivirus.com From sross at connectmail.carleton.ca Sun Jan 25 11:19:00 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 25 Jan 2004 11:19:00 -0500 Subject: xrange not hashable - why not? References: Message-ID: "Sean Ross" wrote in message news:FSRQb.95$qU3.31981 at news20.bellglobal.com... > There's a bit of an efficiency issue with using 'n in k' for something like > xrange(100, sys.maxint), > since you have to walk through the items in that range to see if n is in > there, and that's a large range. Hmm, I don't think what I said there is correct, please disregard. Sorry for any confusion, Sean From michele.simionato at poste.it Tue Jan 13 04:30:30 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 Jan 2004 01:30:30 -0800 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <95aa1afa.0401130130.3b0cd694@posting.google.com> Samuel Walters wrote in message news:... > Lisp/Scheme: > Lisp and Scheme are two languages that people claim will give you > Jedi-like powers as a programmer. I'm learning them right now, so I can't > give you advice on why one would learn them. I can think of two situations: 1. You want to learn more about programming. 2: You want to implement your own programming language. About 1: Lisp/Scheme are traditionally at the frontier of the research in programming languages, so they have everything (Common Lisp) or you can easily implement everything (Scheme). So, when you have learned Lisp/Scheme, you have learned nearly every concepts in programming. This is the reason why (IMHO opinion) you should not try to learn them as first languages, especially Common Lisp. It is too difficult. Learn Python first! About 2: if you want to implement a programming language, it is much easier to write it on top of Lisp/Scheme (thanks to the macro facility) than to write it from scratch. Of, course, if you want performance, you would implement it in C, but still Lisp/Scheme can be useful to prototype it. Apart for these two situations, I would stay with Python. Just my 2 eurocents, Michele From max at alcyone.com Wed Jan 14 18:31:08 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 14 Jan 2004 15:31:08 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <4005D13C.65347E30@alcyone.com> Brandon Van Every wrote: > Referring to Bent's astute post, it's more like criticizing an OSS > restaurant that says it serves a lot of things, but in fact doesn't. > "Cross-platform, so long as your platform is Linux." Unix, not Linux. You may not care about the non-Linux Unix, but the developers do. You characterizing it as Linux only is just ignorance. There are different levels of portability; the fact that Windows portability may not be high on some peoples' priorities doesn't mean that their code still can't be widely portable. But, of course, even that assertion is wrong to begin with. Freeciv.org indicates that there are both Cygwin and win32 native ports. You're just complaining that there isn't a .NET port, something which the developers never promised (and probably rightly don't care about at this point). As usual, you are all bluster and no content. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Patiently, I'm still / Holding out until -- Sandra St. Victor From iny+news at iki.fi Wed Jan 14 14:11:46 2004 From: iny+news at iki.fi (=?iso-8859-1?q?Ilpo_Nyyss=F6nen?=) Date: Wed, 14 Jan 2004 21:11:46 +0200 Subject: Does anyone else not find the fun in programming...? References: Message-ID: chris.lyon at spritenote.co.uk (Chris Lyon) writes: > This is work dammit, At work you do what you are told to do. As a hobby you can do what you want to do. Both can be fun. Just compare programming to filling a crossword puzzle or writing a poem. Programming gives something to think about. And then finding a solution for a problem or getting the program released or getting good feedback... the feelings can be awesome. And then, look at the code, it can be ugly or beautiful. Python luckily makes you to write better looking code. :) -- Ilpo Nyyss?nen # biny # /* :-) */ From rshaw2 at midsouth.rr.com Tue Jan 27 18:15:42 2004 From: rshaw2 at midsouth.rr.com (Richard) Date: 27 Jan 2004 15:15:42 -0800 Subject: [ANN] ip2cc-0.3: now it works with Python 2.3 References: Message-ID: <84e0f331.0401271515.2ed5c4f0@posting.google.com> I get an error when trying to use it... here's the problem below: C:\Tools>ip2cc.py www.google.com Traceback (most recent call last): File "C:\Tools\ip2cc.py", line 338, in ? db = CountryByIP(db_file) File "C:\Tools\ip2cc.py", line 14, in __init__ self.fp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: 'C:\\Tools\\ip2cc.db' Looks like the database file is not included with the download. Richard From skip at pobox.com Wed Jan 21 11:34:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 10:34:07 -0600 Subject: distutils uninstall In-Reply-To: <5eb8fb88.0401210822.55b60ef7@posting.google.com> References: <5eb8fb88.0401210822.55b60ef7@posting.google.com> Message-ID: <16398.43519.420033.297431@montanaro.dyndns.org> Rick> I've been trying to figure out whether there are any plans to add Rick> an "uninstall" feature to the Python distutils. Googling has found Rick> several people posting the same question, but, to the best of my Rick> knowledge, no answers. This has been proposed before. It's not a trivial problem though. Distutils would need to record all the files and directories it creates during installation and carefully remove stuff during the uninstall process (do things "backwards", not remove directories which still contain files, etc). That wouldn't be foolproof though, because unlike packaging systems such as Red Hat's RPM, you don't have a full system picture. What if your distutils-installed package provides a new version of /etc/magic? If you uninstall it, /etc/magic would be deleted, since distutils couldn't tell that /etc/magic was actually used by many other parts of the system. Skip From todcsmith at yahoo.com Mon Jan 19 11:21:33 2004 From: todcsmith at yahoo.com (todd smith) Date: 19 Jan 2004 08:21:33 -0800 Subject: problems with os.path.isdir on windows shares (i've read the FAQ) References: <4489035c.0401161545.75b63ce@posting.google.com> Message-ID: <4489035c.0401190821.bf3ff14@posting.google.com> "Michel Claveau/Hamster" wrote in message news:... > Hi ! > > \\\\ren\\backup is perhaps no a directory, but the name of a shared > ressource. > > > > @-salutations i'm a bit confused as to what you mean by a shared resource. but \\ren\backup is definately a shared directory, i mkdir'd it myself :) From tleese22 at yahoo.com Sun Jan 18 22:05:14 2004 From: tleese22 at yahoo.com (Taylor Leese) Date: Sun, 18 Jan 2004 19:05:14 -0800 (PST) Subject: Python 2.3.3 on FreeBSD 4.8 Message-ID: <20040119030514.48456.qmail@web60501.mail.yahoo.com> I am trying to compile Python 2.3.3 on FreeBSD 4.8 and I am getting this compiling error. Anybody have any ideas? case $MAKEFLAGS in *-s*) CC='gcc' LDSHARED='cc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; *) CC='gcc' LDSHARED='cc -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; esac Traceback (most recent call last): File "./setup.py", line 1148, in ? main() File "./setup.py", line 1143, in main scripts = ['Tools/scripts/pydoc', 'Tools/scripts/idle'] File "/home/cleverli/public_html/Python-2.3.3/Lib/distutils/core.py", line 123, in setup dist.parse_config_files() File "/home/cleverli/public_html/Python-2.3.3/Lib/distutils/dist.py", line 330, in parse_config_files filenames = self.find_config_files() File "/home/cleverli/public_html/Python-2.3.3/Lib/distutils/dist.py", line 293, in find_config_files check_environ() File "/home/cleverli/public_html/Python-2.3.3/Lib/distutils/util.py", line 155, in check_environ import pwd ImportError: No module named pwd *** Error code 1 __________________________________ Do you Yahoo!? Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes http://hotjobs.sweepstakes.yahoo.com/signingbonus From nav+posts at bandersnatch.org Thu Jan 15 15:38:49 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 15 Jan 2004 15:38:49 -0500 Subject: New candidate for Python mascot References: Message-ID: Tim Churches writes: > See http://news.independent.co.uk/world/asia/story.jsp?story=476931 For those who like to have a visual of the proposed mascot: http://story.news.yahoo.com/news?tmpl=story&u=/040107/1911/bthde3bgn1 Unfortunately, it fails both the cute-and-cuddly and the can-I-take-it-home tests. 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 shevitz at lanl.gov Fri Jan 23 17:54:02 2004 From: shevitz at lanl.gov (Danny Shevitz) Date: Fri, 23 Jan 2004 15:54:02 -0700 Subject: help with unittest Message-ID: <4011a610$1_2@news3.es.net> Why doesn't the following code snippet work? The error is ImportError: No module named myTestCase2 TIA, Danny %<-------------------------------------------------------------------- # import the unittest module import unittest # create the first testcase class myTestCase(unittest.TestCase): def testTrue(self): self.assertEqual(1,1) # create the first testcase class myTestCase2(unittest.TestCase): def testTrue(self): self.assertEqual(1,1) if __name__ == '__main__': #unittest.main() suite = unittest.defaultTestLoader.loadTestsFromNames(['myTestCase2.testTrue']) unittest.TextTestRunner().run(suite) From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 21 23:36:55 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 15:26:55 +1050 Subject: Secure Voting software References: <20040121174434.28446.00000428@mb-m15.aol.com> <7xvfn4lq9m.fsf@ruckus.brouhaha.com> <87zncgy544.fsf@strauser.com> Message-ID: On Thu, 22 Jan 2004 04:35:07 GMT, Kirk Strauser wrote: > At 2004-01-22T01:35:01Z, Paul Rubin writes: >> The book "Security Engineering" by Ross Anderson is a good place to start >> reading if you're interested in the subject. > > I just finished "Practical Cryptography" by Niels Ferguson and Bruce > Schneier. It was almost enough to make me not want to bother trying. > :-/ Security is much more than just cryptography. Program reliability, protection from bad input, protection from other misbehaving programs; mitigation of *any* kind of risk or threat is the realm of security. -- \ "Last year I went fishing with Salvador Dali. He was using a | `\ dotted line. He caught every other fish." -- Steven Wright | _o__) | Ben Finney From james at logicalprogression.net Wed Jan 21 16:24:48 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 21:24:48 +0000 Subject: Need help with Python class idioms In-Reply-To: <20040121210142.GA27469@mail.theserver.ath.cx> References: <200401212101.33605.james@logicalprogression.net> <20040121210142.GA27469@mail.theserver.ath.cx> Message-ID: <200401212124.48006.james@logicalprogression.net> On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote: > # P.S. Since you're asking about idiom, it would be more Pythonic to write: > # > # if self.mandatoryVar1 is None: > # > # using the identity test "is" rather than equality test "==", since there > is # only one None. > > I'd write > > if not self.mandatoryVar1: > > but the first method works, too. Are you sure an empty sequence or zero aren't valid values? J. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From cygnus at cprogrammer.org Sat Jan 24 11:01:53 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sat, 24 Jan 2004 11:01:53 -0500 Subject: progress bar In-Reply-To: <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> References: <59e5b87.0401231329.6e084d6f@posting.google.com> <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> Message-ID: <20040124160153.GA14409@mail.theserver.ath.cx> # > Try Venster: # > http://venster.sourceforge.net # > # > IIRC the test_coolbar.py script includes a progress bar. # # I wonder what possessed someone to start another GUI framework. Aren't # there more than enough existing ones? The reasoning for it wasn't # immediately apparent on the web page. Aside from any pure utility, because it's fun. :) -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From klappnase at web.de Wed Jan 21 22:20:10 2004 From: klappnase at web.de (klappnase) Date: 21 Jan 2004 19:20:10 -0800 Subject: Tkinter bitmap bug ? References: Message-ID: Eric Brunel wrote in message news:... > As you saw, this won't work: the only way I found to set an iconbitmap on a > window is using the '@/path/to/file' syntax. Why not keep the data for your > image in the code and generate a temporary file from this data? Then you can use > the '@...' stuff without having to carry an external file everywhere. Just don't > forget to delete the file when your application exits. We do that all the time > and it works quite fine. > > HTH Thanks, I have tried this already, too and it works fine, I just thought there might be a more "elegant" solution; however I still wonder why the Bitmap in my test2() function does not appear. I looked at many suggestions that have been made how to create bitmaps out of strings with the BitmapImage class and nothing seems to work. It still looks to me like a bug. Thanks and best regards Michael From Mike at DeleteThis.Geary.com Wed Jan 21 01:16:52 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 20 Jan 2004 22:16:52 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <20040120181009.060C.JCARLSON@uci.edu> <20040120182610.060F.JCARLSON@uci.edu> <100rutd6kge1g9f@corp.supernews.com> <20040120203101.3E3B.JCARLSON@uci.edu> Message-ID: <100s6aoc067q2c4@corp.supernews.com> > > > Technically os.system("c:\\path\\help.chm") and > > > os.system("start c:\\path\\help.chm") also work, > > > though are less intuitive. > > No, os.system is the wrong way to do it. That function > > launches a new command shell, which in turn runs > > the program you want. Because of that, if you're not > > already running in a console window, it will open a > > new console window. > > > > You had it right with os.startfile. That calls the > > ShellExecute function in Windows, which is the way > > you would do it in a native Windows application > > written in C. > When the command completes, the window dissappears. > This is the case when running from a script within > pythonw or even inside of a py2exe frozen module. While > it may not be the 100% correct way of doing things (and > you have to properly escape spaces in the file name, which > then results in having to give a window title, etc.), it does > result in a final outcome that is the same - the help file is > open, your program continues execution. > > Certainly he will be using os.startfile(), but knowing that > you can use windows shell commands with os.system > can be useful. Hi Josiah, Yes, it is definitely useful to know that you can use os.system to run Windows shell commands. That's what os.system is meant for. But you really wouldn't want to use it to run a GUI app such as the HTML Help viewer. If your application's Help menu opens a spurious console window along with the help viewer, your users will wonder what the heck is going on. :-) It also takes more memory and other resources, but that's less significant than the user experience. So do it the right way, with os.startfile. Or if you want more control over the exact parameters to the underlying ShellExecute function, you can use win32api.ShellExecute (if you know that the win32api module will be available on the target systems). -Mike From martin at v.loewis.de Sun Jan 4 06:48:09 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 04 Jan 2004 12:48:09 +0100 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: References: Message-ID: <3FF7FD79.5000209@v.loewis.de> Peter Astrand wrote: > The popen* stuff for Windows (and OS2 etc) in posixmodule.c is complicated > because: > > 1) It's written in low-level C > > 2) It contains lots of old DOS stuff Such code could be eliminated now; DOS is not supported anymore. Would you like to contribute a patch in that direction? Regards, Martin From no at spam.edu Fri Jan 30 18:46:52 2004 From: no at spam.edu (Doug Holton) Date: Fri, 30 Jan 2004 17:46:52 -0600 Subject: mod_speling for python In-Reply-To: References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Message-ID: >> I didn't interpret the OP's question as wanting to automatically map >> Foo to >> foO, but to give the user a more helpful error message, suggesting other >> candidate names which he might have mistyped. This can be helpful for beginners especially, to catch not only capitalization and minor misspellings, but perhaps other minor errors too such as being one space off when indenting, or forgetting a colon. The python compiler module can check syntax, it just isn't all documented. See this example code: http://mail.python.org/pipermail/python-dev/2000-September/009501.html See also the tokenize module: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 Or you might go so extreme as metaprogramming and language parsing. See PLY: http://systems.cs.uchicago.edu/ply/ and http://gnosis.cx/TPiP/ From naren at trillium.com Thu Jan 8 21:38:25 2004 From: naren at trillium.com (Narendra C. Tulpule) Date: 8 Jan 2004 18:38:25 -0800 Subject: Python equivalent of settimeofday()? Message-ID: <781faf41.0401081838.10de95c9@posting.google.com> Hi, do you know how (or if) I can set time on a system using Python? i.e. is there an equivalent of the shell's 'date -s' or the system call settimeofday()? Thanks - -- Naren. From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 10 10:54:07 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 10 Jan 2004 16:54:07 +0100 Subject: Databases: Which one's right for me? References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: Marc: >Basically I need a db that will travel with my executable script and >faithfully store and edit the data needed in that script. Have a look at ZODB. Introduction: http://www.python.org/workshops/2000-01/proceedings/papers/fulton/zodb3.html Programming guide (PDF): http://cvs.zope.org/ZODB3/Doc/zodb.pdf?rev=1.3 -- Ren? Pijlman From swalters_usenet at yahoo.com Mon Jan 5 13:31:50 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 18:31:50 GMT Subject: Scripting C++ Game AI object using Python Generators References: Message-ID: |Thus Spake The_Incubator On the now historical date of Sun, 04 Jan 2004 03:32:11 -0800| > Where I would like to go from there is to be able to associate a Python > script with a C++ object, so that on every frame update I could run the > Python script (which would have functionality implemented as a generator) > until it yields, then move on to updating the next object, and on the next > frame, have the generator continue from where it left off. I have not dabbled with boost, but I like pyrex, and it allows you to write c++ classes that can run python code. http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ You should at least dig in and skim over the c/python api. You'll learn a lot about what pyrex does. I suggest "The Python Bible" http://www.amazon.com/exec/obidos/tg/detail/-/0764548077/104-2573336-8032758?v=glance Of all the documents I've scanned so far, it was the one that I understood best. YMMV. It has a kind of cookbook method: "Here's how you do this, Here's how you deal with that kind of data, etc" Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From rpm1deleteme at direcway.com Tue Jan 6 21:28:05 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Tue, 6 Jan 2004 21:28:05 -0500 Subject: YAPLP - Yet Another Python Links Page References: <8089854e.0401060424.12465fcb@posting.google.com> Message-ID: "Fuzzyman" wrote in message news:8089854e.0401060424.12465fcb at posting.google.com... > As part of a python project I've been working on ( atlantibots - > www.atlantibots.org.uk )I've collected Python and programming > links.... for what it's worth I thought I'd make them publicly > available.... > > http://www.voidspace.org.uk/coollinks/python_links.shtml > > Fuzzyman Cool site! Thanks! Patrick From francisgavila at yahoo.com Sun Jan 18 21:11:27 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 18 Jan 2004 21:11:27 -0500 Subject: Python Text Adventure Authoring System References: Message-ID: <100mf8ial58jf57@corp.supernews.com> Zachary wrote in message ... >I have already seen another text adventure development system written in >Python, called Paws. I thought this would be a sort of first project. I don't want to stop you, but I warn you that developing a system like this is far more complex than you think. Take a look at PAWS, and after that some of the mechanisms in the language Inform. Studying another language specifically designed for text-adventure authoring will give you an idea of the mechanisms involved, particularly in grammar and parsing, where a lot of things are needed that you might not otherwise think of. -- Francis Avila From fowlertrainer at anonym.hu Mon Jan 5 11:03:45 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 5 Jan 2004 17:03:45 +0100 Subject: Sorry, again: Module Loading Problem In-Reply-To: <16129653189.20040105164050@anonym.hu> References: <16129653189.20040105164050@anonym.hu> Message-ID: <4731027244.20040105170345@anonym.hu> Hello ! I have used mod_python. But it is don't reload my modules when I editing them. I try with this: -------------------- # Module importer import os import traceback import kinterbasdb import sys import time import threading import imp import stat ImpLock=threading.Lock() IModuleDir="C:/bhaweb/modules" IModules={} def LoadModule(ModName): fp, pathname, description = imp.find_module(ModName) try: mod=imp.load_module(ModName, fp, pathname, description) print mod sys.modules[ModName]=mod finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close() def ImportModules(Modules): ImpLock.acquire() try: if not (IModuleDir in sys.path): sys.path.append(IModuleDir) # Do imports, if needed print Modules for m in Modules: sf=IModuleDir+"/"+m+".py" if sys.modules.has_key(m): sd=os.stat(sf) lm=sd[stat.ST_MTIME] if IModules.has_key(m): dd=IModules[m] if (dd<>lm): print "ReLoad" reload(sys.modules[m]) IModules[m]=lm else: print "Load" LoadModule(m) sd=os.stat(sf) lm=sd[stat.ST_MTIME] IModules[m]=lm ''' import s sf=IModuleDir+"/"+s ''' print IModules finally: ImpLock.release() #for k in sys.modules.keys(): print k,sys.modules[k] ''' f=file(IModuleDir+"/test.py","w") f.write("print 1") f.close() ''' #print os.stat(IModuleDir+"/test.py")[stat.ST_MTIME] #sys.exit() ''' ImportModules(["test"]) f=file(IModuleDir+"/test.py","w") f.write("print 2") f.close() time.sleep(2) ImportModules(["test"]) ''' ImportModules(["test"]) test.test() -------------------- test.py is this: def test(): print 1 -------------------- But python is say: > Executing: C:\Program Files\ConTEXT\ConExec.exe > "C:\Python\python.exe" "C:\bhaweb\modules\ModImport.py" ['test'] Load {'test': 1073316581} Traceback (most recent call last): File "C:\bhaweb\modules\ModImport.py", line 75, in ? test.test() NameError: name 'test' is not defined > Execution finished. I run this in native mode, but do this in under mod_apache also. Why ? What I do wrong ? Plase send the email in private also, because I'm in digest mode. Thanx: KK -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From python at hitmedia.com Fri Jan 23 13:31:27 2004 From: python at hitmedia.com (Python Baby) Date: Fri, 23 Jan 2004 10:31:27 -0800 Subject: [OPINION] - does language really matter if they all do the same thing? Message-ID: <20040123183127.GA35281@mail.hitmedia.com> Are programming languages like spoken languages, in the sense that they all say the same things, just using different words? Like many PHP people, I was never a "real" programmer, but just picked up PHP as my HTML websites started to mature. Now that even my PHP sites have grown, (50,000 lines of PHP!), I got interested in object-oriented approach. Since my old website needed an overhaul anyway, I thought it'd be a good time to learn. I start learning Ruby. Then Python. Wondering if, since I'm about to re-write my entire website anyway, if I should use Ruby or Python instead of PHP. As I've fretted over this for way too many hours, I started wondering: Can Ruby do something (important) that Python can't? Can Python do something (important) that PHP can't? Can PHP do something (important) that Ruby or Python can't? Are they all just the same, and it's just a matter of taste? Should I stick with PHP for the same reason that pop singers worldwide sing in English for maximum compatibility with the medium? Though PHP wasn't design for OOP should I use it that way anyway? Any opinions on the subject, from people that know and use many languages, would be appreciated. From jsbenson at bensonsystems.com Wed Jan 28 21:53:37 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 28 Jan 2004 18:53:37 -0800 Subject: Oracle db connection problem solved Message-ID: <031f01c3e613$17f364e0$6309500a@jsbwxp3> Thanks much for help with the Oracle db connection problem. That, plus some local assistance getting the sqlnet.ora default domain right, got everything fixed. Now I'm connected, and have been able to retrieve information from Oracle into my PC Python session. I seem to see a lot of advice asking people to google before submitting a problem to the list. This was nicely illustrated by the suggestion to google on the verbatim Oracle database error code. I was amazed to see all the stuff it brought up, and I'll certainly add googling for even proprietary error codes to my bag of tricks. Thanks again. From hans at zephyrfalcon.org Sun Jan 25 19:28:16 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun, 25 Jan 2004 19:28:16 -0500 Subject: xrange not hashable - why not? In-Reply-To: <20040126001145.GB2593@unpythonic.net> References: <20040125144724.GA13741@nl.linux.org> <40145A07.2070906@zephyrfalcon.org> <20040126001145.GB2593@unpythonic.net> Message-ID: <40145F20.7070402@zephyrfalcon.org> Jeff Epler wrote: > On Sun, Jan 25, 2004 at 07:06:31PM -0500, Hans Nowak wrote: > >>So far, everybody who replied seems to agree or assumes that xrange indeed >>isn't hashable. However: > > [...] > > It wasn't in older versions: > $ 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. > >>>>hash(xrange(0)) > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unhashable type Huh. This is really weird: (C:\) $ python22 Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> hash(xrange) 503376880 (C:\) $ \Python21\python.exe Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> hash(xrange) 504420928 (C:\) $ \python152\python.exe Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> hash(xrange) 504409536 ...?! Maybe it's platform-specific? Confused-ly y'rs, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From CousinStanley at hotmail.com Thu Jan 15 15:33:11 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Thu, 15 Jan 2004 13:33:11 -0700 Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> Message-ID: > Why is it the best minicomputer ever made? > I really want to know! | Since nobody ever produced any other. | Only IBM produced machines that can be called "midrange" | (something between microcomputer and "real computer", | the famous S/390 mainframe). They still use this terminology. Jarek .... Honeywell also produced a line of mid-range machines called the Level 6 minicomputers .... These machines ran an operating system which had an internal architecture and command line interface different from, but vaguely similar, to Multics, a Honeywell mainframe OS .... Multics was a major predecessor of Unix, a euphemism for Multics Without Balls deemed so by the original developers themselves .... Without Multics there might not be any such thing as Unix or Linux .... You can find the history of Multics at .... http://www.multicians.org -- Cousin Stanley Human Being Phoenix, Arizona From danb_83 at yahoo.com Sun Jan 4 19:59:35 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Jan 2004 16:59:35 -0800 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: mersmann at szut.uni-bremen.de (Frank) wrote in message news:<3987e01c.0401030832.114c6f2a at posting.google.com>... > Hi, > > can anybody help with the following problem? ... > i = 5 / 10 gives me 0 as expected, but > i = -5 / 10 gives -1 as result. The problem is that you aren't using "from __future__ import division" ;-) (This causes the results to be 0.5 and -0.5, and will be the default division semantics in Python 3.0. If you want integer division, use the // operator.) > Is this a feature or a bug? It's a feature. The advantage of defining x // y as floor(x / y) is that x % y is always nonnegative. As as example of why this is useful, consider the datetime.date.weekday method. This could be implemented as def weekday(self): return (self.fromordinal() - 1) % 7 If the datetime module was changed to allow BC(E) dates (which have nonpositive Rata Die numbers), the weekday method would still work. In C++, you'd have to treat such dates as a special case. From hans at zephyrfalcon.org Fri Jan 23 14:20:22 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 23 Jan 2004 14:20:22 -0500 Subject: debugging In-Reply-To: <88bc63c6.0401230416.7acf904c@posting.google.com> References: <88bc63c6.0401230416.7acf904c@posting.google.com> Message-ID: <401173F6.8080705@zephyrfalcon.org> Doug Farrell wrote: > Hi all, > > Can someone help me out a little with Python? What do people use to > debug Python code? I don't understand how to use the built in debugger > and I haven't had any luck getting ddd to debug my Python programs. I > end up falling back on inserting print statements in my code to figure > out what's going on. This works but isn't always the fastest route to > a solution. So, I'm just wondering what other people do. "The most effective debugging tool is still careful thought, coupled with judiciously placed print statements." -- Brian Kernighan (1978) The 'print statements' method still works, anno 2004. Aside from that, I use unit tests. I never use a debugger; I find stepping through code, or breaking execution off halfway, rather clumsy. Just my $0.02, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From rkern at ucsd.edu Mon Jan 19 17:10:24 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 19 Jan 2004 22:10:24 GMT Subject: Fw: PDF library for reading PDF files In-Reply-To: <100nlf2b1qjdae2@corp.supernews.com> References: <100luvhbh3vr75d@corp.supernews.com> <100nlf2b1qjdae2@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Robert Kern wrote: > >>Cameron Laird wrote: >> >>>In article , >>>Harald Massa wrote: >>> >>> >>>>>I am looking for a library in Python that would read PDF files and I >>>>>could extract information from the PDF with it. I have searched with >>>>>google, but only found libraries that can be used to write PDF files. >>>> >>>>reportlab has a lib called pagecatcher; it is fully supported with python, >>>>it is not free. >>>> >>>>Harald >>> >>> >>>ReportLab's libraries are great things--but they do not "extract >>>information from the PDF" in the sense I believe the original >>>questioner intended. >> >>No, but ReportLab (the company) has a product separate from reportlab >>(the package) called PageCatcher that does exactly what the OP asked >>for. It is not open source, however, and costs a chunk of change. > > > Let's take this one step farther. Two posts now have > quite clearly recommended ReportLab's PageCatcher http://reportlab.com/docs/pagecatcher-ds.pdf >. I > completely understand and agree that ReportLab supports > a mix of open-source, no-fee, and for-fee products, and > that PageCatcher carries a significant license fee. I > entirely agree that PageCatcher "read[s] PDF files ... > and ... extract[s] information from the PDF with it." > > HOWEVER, I suspect that what the original questioner > meant by his words was some sort of PDF-to-text "extrac- > tion" (true?) and, unless PageCatcher has changed a lot > since I got my last copy, PDF-to-text is NOT one of its > functions. Rereading http://www.reportlab.com/PageCatchIntro.html , you're right. My apologies. I thought you were talking about the open source reportlab package and not PageCatcher specifically. From stadt at borbala.com Sat Jan 24 11:23:37 2004 From: stadt at borbala.com (Richard van de Stadt) Date: Sat, 24 Jan 2004 17:23:37 +0100 Subject: Sending e-mail with python 1.5.2 References: Message-ID: <40129C09.F153F3D2@borbala.com> Andrew McLean wrote: > > I am writing a CGI script on an account that only has Python 1.5.2. It's > principal purpose is to take some user input from a form, do some > manipulation and return some information to the user. However, I would > also like it to send some information to an e-mail account (behind the > scenes). > > The e-mail could be quite simple, but I wouldn't rule out wanting to > send a pickled object or two. > > Now if I was using a recent Python I would just use the email package, > but I don't think it's compatible with v1.5.2. I know I have access to > the sendmail binary, so something should be possible. Any pointers > gratefully received. > > -- > Andrew McLean This should help to get you going: message = """\ Message-ID: <%(messageID)s> Subject: %(subject)s Date: %(date)s From: %(fromstring)s <%(fromaddr)s> Reply-To: %(fromaddr)s X-Mailer: Python smtplib %(to_cc_list)s %(body)s """ try: mail = smtplib.SMTP(LocalMailServer) #mail.set_debuglevel(1) mail.sendmail(fromaddr, email_recipients_tuple, message % locals()) mail.quit() except: print 'Could not send email!' --- Richard. From swalters_usenet at yahoo.com Sun Jan 18 06:31:53 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 11:31:53 GMT Subject: Forums for Teachers Using Python - Where are they? Message-ID: I'm currently considering a position teaching math and possibly programming at a small local magnet school. If I was also teaching programming, I would, of course, be using Python. So, I went out and googled around for resources. I found lots of articles about using Python to teach programming, but I have yet to turn up one forum where teachers using Python talk amongst themselves. Can anyone point me to such a resource, or, at least any "Must Read" articles that I might have missed? Also, does anyone have any experience using "Thinking Like A Computer Scientist" as a textbook? Does it fit well within a single semester? If not, how far were you able to make it into the book? Thanks for any advice. Sam Walters. P.S. An thought provoking general interest paper about computers in education is here: http://www.cs.berkeley.edu/~bh/stop.html It was written 21 years ago and still raises a relevant question. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From amy-g-art at cox.net Fri Jan 23 15:41:39 2004 From: amy-g-art at cox.net (Amy G) Date: Fri, 23 Jan 2004 12:41:39 -0800 Subject: Various strings to dates. Message-ID: <4GfQb.16187$AA6.14368@fed1read03> I have seen something about this beofore on this forum, but my google search didn't come up with the answer I am looking for. I have a list of tuples. Each tuple is in the following format: ("data", "moredata", "evenmoredata", "date string") The date string is my concern. This is the date stamp from an email. The problem is that I have a whole bunch of variations when it comes to the format that the date string is in. For example I could have the following two tuples: ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 03:15:06") I know there is some way to use the date string from each of these to get a date usable by python, but I cannot figure it out. I was trying to use time.strptime but have been unsuccesful thus far. Any help is appreciated. From buzzard at urubu.freeserve.co.uk Sat Jan 31 10:49:47 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 31 Jan 2004 15:49:47 -0000 Subject: timeit References: Message-ID: "Robert Brewer" wrote in message news:mailman.1071.1075531877.12720.python-list at python.org... Duncan Smith wrote: > >>> import SDC_table > >>> import subtract > >>> import timeit > >>> t = SDC_table.RandomTable(1, 12, (2,3,4)) > >>> s = """\ > p = subtract.p_risk(t.values, 10) > """ > >>> tim = timeit.Timer(stmt=s) > >>> tim.timeit(10) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > tim.timeit(10) > File "C:\Python23\lib\timeit.py", line 158, in timeit > return self.inner(it, self.timer) > File "", line 6, in inner > NameError: global name 'subtract' is not defined > > # yet > >>> exec(s) > >>> p > 0.242621453769059 I believe you need to put *any* initialization code (like "import subtract") into the "setup" parameter to Timer(). So try something like: > >>> import timeit > >>> s = """p = subtract.p_risk(t.values, 10)""" > >>> tim = timeit.Timer(stmt=s, setup="import SDC_table, subtract; t = SDC_table.RandomTable(1, 12, (2,3,4))") > >>> tim.timeit(10) That does the job. Cheers. Duncan From tchur at optushome.com.au Thu Jan 8 17:03:03 2004 From: tchur at optushome.com.au (Tim Churches) Date: 09 Jan 2004 09:03:03 +1100 Subject: [OT] Database reporting software In-Reply-To: References: Message-ID: <1073599383.1866.59.camel@emilio> On Fri, 2004-01-09 at 08:32, Steve Horsley wrote: > I have an existing system working on MS Access, and software that > regularly logs events into it (and deletes old events after a year). > > Now need to move to real servers, probably Solaris though possibly > Linux. Modifying the software to update the database (maybe mySQL or > Oracle) contents is easy enough, but how do I produce reports > (statistics and summaries) on the database contents? > > I could contemplate web based or application based report generation, > but are there easy to use draggy-droppy report designing applications > around? Just the names would enable me to look them up. Have a look at the GPLed version(s) of Rekall, which is a cross-platform semi-clone of MS Access. Still somewhat buggy, I have found, but definitely usable. And Rekall is programmed in Python, not Visual Basic. Bliss! > I am struggling with OpenOffice.org at the moment, trying to see if it > can do what I'm looking for, but it doesn't seem to be able to do GROUP > BY and SUM() - simple aggregation stuff. Yup, you probably need to do those in your database back-end first. But as a line-listing or report formatter (if the data manipulation and aggregation is done beforehand), OpenOffice has quite a lot to recommend it,particularly if integration with text commentary is required. And it too is drivable with Python (albeit somewhat painfully and slowly via PyUNo - but it does work). Suggest you look at Rekall, though. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From james at logicalprogression.net Fri Jan 16 11:13:06 2004 From: james at logicalprogression.net (James Henderson) Date: Fri, 16 Jan 2004 16:13:06 +0000 Subject: Bug or feature? In-Reply-To: References: Message-ID: <200401161613.06481.james@logicalprogression.net> On Friday 16 January 2004 2:44 pm, Alexey Nezhdanov wrote: > I know the case where such python behaivoir causes hard-to-catch problems. > I do not know any case (anybody knows? please give example) where such > "feature" may be useful. > > So I proposing to make a change into python and reverse the order of > calculations. > Just for sure: > === Order used now === > ## a+=a.Sub(b) > 1. evaluate value of 'a' > 2. evaluate value of 'a.Sub(b)' > 3. evaluate the sum > 4. store the result into 'a' > === Proposed order === > ## a+=a.Sub(b) > 1. evaluate value of 'a.Sub(b)' > 2. evaluate value of 'a' > 3. evaluate the sum > 4. store the result into 'a' -1 In any language that uses such an operator I would expect: a += b to be synonymous with: a = a + b You are suggesting that it should mean: a = b + a It is not like Python to attach its own idiosyncratic semantics to operators already well known from other languages. I think this would catch a lot of people out. Of course, it's probably best to avoid writing code where the order makes a difference. :) James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ From gerrit at nl.linux.org Sun Jan 4 14:46:37 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 20:46:37 +0100 Subject: Proposal: new peps always in clpa In-Reply-To: References: Message-ID: <20040104194637.GA16882@nl.linux.org> Aahz wrote: > In article , > Gerrit Holl wrote: > >would it be a good idea to automatically sumbit all new peps to > >comp.lang.python.announce? After all, each PEP is an announcement and > >may be important to the entire Python community. Another possibility > >would be to python-dev, but since c.l.py.announce has a broader public, > >I'd prefer the first one. What do you think? > > That's a good idea, but c.l.py.announce needs to have its Followup-To: > set to c.l.py. I think I asked for that once before, but didn't get a > response. I think Followup-To: should be set to c.l.py for _any_ posting in c.l.py.announce, not only for peps, but that is another issue altogether. Gerrit. -- 256. If his community will not pay for him, then he shall be placed in that field with the cattle (at work). -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From ralsina at my-deja.com Wed Jan 14 22:24:08 2004 From: ralsina at my-deja.com (Roberto Alsina) Date: 14 Jan 2004 19:24:08 -0800 Subject: PyQT: qt.qApp References: Message-ID: "Axel Mittendorf" wrote in message news:... > Hello, > in my application I want to subclass qt.QApplication and > use this subclass instead of QApplication for my gui. Some > of my modules are automatically generated by pyuic and > I am not allowed to change their source code. The problem > is these modules do "from qt import *" and use an object > called 'qApp' which seems to be an instance of qt.QApplication > and I want them to use my subclass (exactly its instance) > instead of 'qApp'. How can I solve this? > > Can someone tell me what qt.qApp is and what it is used for? > (I'm using PyQT 3.6.) Well, there are some times when you need to call a method of QApplication. For example, if you want to put a hourglass cursor for the whole app, you call qApp.setOverrideCursor Anyway, you shouldn?t worry about this. Whatever object you create that inherits QApplication will be qApp. Since there can only be one of those, there is no way it?s gonna get confused ;-) -- Roberto Alsina From faizan at jaredweb.com Thu Jan 8 10:03:33 2004 From: faizan at jaredweb.com (Fazer) Date: 8 Jan 2004 07:03:33 -0800 Subject: Time-controlled execution? References: <7b454334.0401071421.53a8cebb@posting.google.com> <7xsmirtn2i.fsf@ruckus.brouhaha.com> Message-ID: <7b454334.0401080703.690259a5@posting.google.com> Paul Rubin wrote in message news:<7xsmirtn2i.fsf at ruckus.brouhaha.com>... > faizan at jaredweb.com (Fazer) writes: > > Lets say that I need to open a large file in Python. However, I only > > want this operation to take no more than four seconds. If it takes > > longer than four seconds to open this file, abort the process. How > > can I do this? > > http://python.org/doc/current/lib/node304.html Perfect! Thanks a lot! From crap at crud.com Thu Jan 15 22:52:40 2004 From: crap at crud.com (Moosebumps) Date: Fri, 16 Jan 2004 03:52:40 GMT Subject: working on multiple files in IDLE Message-ID: So say I am working on two separate .py files in IDLE that are part of the same program. Does anyone have problems where when you modify one file, and then run the other, the changes you made in the first aren't updated? I usually just close all the files, and restart IDLE, but this is a pain. Maybe because I always use right click -> edit with IDLE (on Windows). That starts up a separate Python Shell too, which I always close. MB From sombDELETE at pobox.ru Sun Jan 4 17:19:29 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 5 Jan 2004 01:19:29 +0300 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Sean R. Lynch" wrote in message news:srudnTjvU9BOH2qiRVn-uA at speakeasy.net... > Ok, I think you've pretty much convinced me here. My choices for > protected attributes were to either name them specially and only allow > those attribute accesses on the name "self" (which I treat specially), > or to make everything protected by default, pass all attribute access > through a checker function (which I was hoping to avoid), and check for > a special attribute to define which attributes are supposed to be > public. Do you think it's good enough to make all attributes protected > as opposed to private by default? Are you talking about C++ like protected fields and methods? What if untrusted code subclasses your proxy object? > > I'm not sure how to deal with str.encode too. You don't know what > > kind of codecs are registered for that method for sure, one day there > > could be registered an unknown codec that does something unknown. > > Shouldn't you have two (or several) codecs.py modules(instances?) > > for trusted and untrusted code? And str.encode should be transparently > > redirected to the proper one? > > I guess I'll just make attributes protected by default, and force the > programmer to go out of their way to make things public. Then I can use > the Zope/RestrictedPython technique of assuming everything is insecure > until proven otherwise, and only expose parts of the interface on > built-in types that have been audited. Thinking about str.encode I conviced myself that global state shouldn't be shared by different security domains so that means codecs.py and __builtins__ must be imported into each security domain separately. It's pretty easy to do with codecs.py since it's python code. But importing __builtins__ more than once is pretty hard since it wasn't designed for that. -- Serge. From FBatista at uniFON.com.ar Mon Jan 5 12:23:43 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 5 Jan 2004 14:23:43 -0300 Subject: Get UID of username Message-ID: Florian Lindner wrote: #- Hello, #- how can I find out the UID of a username on a linux system? Use the password database module: http://www.python.org/doc/current/lib/module-pwd.html . 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 p at trick.lu Fri Jan 23 14:31:46 2004 From: p at trick.lu (Patrick Useldinger) Date: Fri, 23 Jan 2004 20:31:46 +0100 Subject: C compilers References: Message-ID: On Fri, 23 Jan 2004 13:13:27 GMT, "Lucas Raab" wrote: >I realize that this is a Python newsgroup, but do any of you know any good >C/C++ compilers?? I'm interested in imbedding C with Python. > >Thanks > Borland C++ 5 - and it's free. -- http://www.homepages.lu/pu/ From candiazoo at comcast.net Tue Jan 6 02:13:40 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Tue, 06 Jan 2004 07:13:40 GMT Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> <38ec68a6.0312181529.729b654@posting.google.com> <1071900300.434091@yasure> <38ec68a6.0401052235.2c223dca@posting.google.com> Message-ID: Ouch! That sounds painful! ;) > Re: Beginner question - How to effectively pass a large list From gagenellina at softlab.com.ar Fri Jan 2 20:25:55 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 02 Jan 2004 22:25:55 -0300 Subject: Multiple exception syntax In-Reply-To: Message-ID: <5.2.1.1.0.20040102222218.02429a90@192.168.0.115> At 2/1/2004 09:58, you wrote: >Normally in Python there is no need to write parenthesis for a tuple : >a,b,c=(1,2,3) >(a,b,c)=1,2,3 > >are the same, and so are : > >for (x,y) in enumerate(aList) >for x,y in enumerate(aList) > >But with "except" the behaviour is very different with or without >parenthesis : >- "except x,y" means : if exception x is raised, then y is the instance of >the x class holding information about the exception >- "except (x,y)" means : if one of the exceptions x or y is raised (or both) > >So it took me some time to figure out why this code was wrong : I've been hit by the same error a couple of times. >I find this confusing. It would be clearer for me to have : > >"except Error1 or Error2 or Error3" I agree. Gabriel Genellina Softlab SRL From mir4uu at yahoo.com Sat Jan 17 12:03:56 2004 From: mir4uu at yahoo.com (mir nazim) Date: 17 Jan 2004 09:03:56 -0800 Subject: needed PyXPCOM tutorial. References: <425cc8d1.0401150908.287de0d8@posting.google.com> Message-ID: <425cc8d1.0401170903.3c331ab9@posting.google.com> Christoph Becker-Freyseng wrote in message news:... > mir nazim wrote: > > >hi > >i m in need of a PyXPCOM tutorial. it should explain using python > >(instead of JavaScript) for creating apps. if any body can point me to > >some web resources or a printed book . > >thankz > > > > > Maybe those will help (check 3! They've some more links) > > http://lxr.mozilla.org/seamonkey/source/extensions/python/xpcom/ > http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/ > http://pygecko.sourceforge.net/ > http://xul.sourceforge.net/ > http://luxor-xul.sourceforge.net/ > http://www.thomas-schilz.de/MozPython/ (the downloads-dirctory > contains installers for upgrading Mozilla to Python-Interpretability) > > > > Christoph Becker-Freyseng yeah i know about them all but what i acutally need is an indepth tutorial/guide/refrence. From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 16 06:23:22 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 16 Jan 2004 12:23:22 +0100 Subject: python mode vi References: Message-ID: <5dif00pi2rs0cp3qh3o40r7gvfe1ep11d8@4ax.com> km: > how to invoke python mode in vi editor ? http://www.python.org/editors/config.html -- Ren? Pijlman From necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com Thu Jan 22 23:13:56 2004 From: necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com (necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com) Date: Thu, 22 Jan 2004 23:13:56 -0500 Subject: get "yesterday's" date in iso format Message-ID: Hi, I am trying to find a simple way to get "yesterday's" date. I know I can build various check to seee if we are in leap year, if we are the 1st then yesterday is the 31(or 30 depending of the month) etc. but there is got to be a simpler way than that. I was thinking of using the gmtime (field 7 as you can see int the code)then substract one, then use strptime to rebuild the time but it doesn't work(probably because I misunderstood strptime): improt time gmt = time.gmtime() yesterdaytime = str(int(gmt[7]) - 1) print gmt[7] print yesterdaytime newtime = time.strptime(yesterdaytime,'%j') print newtime (1900, 1, 22, 0, 0, 0, 0, 22, -1) can someone enlighten me please? Thanks David From sombDELETE at pobox.ru Sun Jan 25 03:54:17 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 25 Jan 2004 11:54:17 +0300 Subject: trouble w/ unicode file References: Message-ID: "Guilherme Salgado" wrote in message news:mailman.752.1074995324.12720.python-list at python.org... > Hi there, > > I have a python source file encoded in unicode(utf-8) with some > iso8859-1 strings. I've encoded this file as utf-8 in the hope that > python will understand these strings as unicode () > strings whithout the need to use unicode() or u"" on these strings. But > this didn't happen. You hoped, but you forgot to pray Why do you think Python should behave this way? There is (an experimental?) option -U that forces all string literals to be unicode. Obviously if you use this option your sources won't be easily distributable to other people C:\Python23>python -U 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. >>> type('a') > Am I expecting something that really shoudn't happen or we have a bug? We have a bug here as well. But in your code. The coding must be the same as the coding of your source file. bar.py must be: #-*- coding: latin-1 -*- x = '????????????' print x, type(x) -- Serge. From paul at boddie.net Thu Jan 29 05:35:21 2004 From: paul at boddie.net (Paul Boddie) Date: 29 Jan 2004 02:35:21 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: <23891c90.0401290235.2b73e314@posting.google.com> Chuck Spears wrote in message news:... [Quoting someone else...] > >The conclusion may seem obvious to _you_ but this is no guarantee that > >everyone else also possesses this knowledge. OSS is being hailed as > >the second coming, ...by generally clueless analysts and journalists whose day job seems to focus exclusively on speculation and rumour forwarding, switching over to hyping Microsoft and other vendors "du jour" when they feel the need to encourage a "debate". > If you can get by his trolling and unbearable arrogance, there are > some kernels of truth in there. I come from a commercial background > as well but instead of trying to exploit the OSS community, ive been > lurking around looking for a project I feel I could contribute to. Yes, this is the key to the issue. If you regard open source software as a huge pile of "free stuff" to plunder, then whilst you may get some productivity benefits in the short term, the longer term will most likely bring maintenance issues as the community continues on its own course and you continue on yours. (If you actually have a course of developing the code, that is, as opposed to just dropping the plundered code into some directory and virtually forgetting that you have it.) > Most geeks by their nature, are very independent and abhor order. I'm not sure that I equate "open source developer" with "geek" in the same way that this generalisation demands, but if you mean that most open source developers who are working on projects in their own time or under their own motivation won't take orders from newcomers, I think it's quite obvious why that is. > You have to have order to get anything done. True, but numerous open source projects have "order" without conventional forms of management. On the other hand, if you're saying that a bunch of "elite" 13 year olds on IRC can't scale their project beyond a slightly larger group of well-trained primates, then you're making an obvious point. > Thats why most > successful projects have one or at most a few people pulling the > strings because if you don't, the project will flounder. I've > personally based a few of my projects on some OSS projects and they > failed miserably. Because of the bugs and the Authors unwilligness to > address them or even accept them as bugs. You can say "well why didnt > you just fix it yourslef" but I just didnt have the time. There are lots of reasons why developers can't or won't fix the bugs. It's quite a common phenomenon in the commercial software world, too, but the reasons are more likely to be political there. Meanwhile, you don't need to be a conspiracy theorist to understand developer motivations around such issues in open source projects; quite often, developers don't have access to the same environment and can't reproduce or diagnose the bugs that you're experiencing, for example. > On the other side of the coin, i've used OSS projects like PHP and > Postgres with great results. > > The other problem with hobbyist geek programmers is they are just in > it for the fun of it. How many people with a hobby do it because they don't enjoy it? > They get bored when the last 10% of the project > which is mostly bug fixing and rengineering code coes about and > generally abandon it. Perhaps many projects need assistance from real-world users in order to get that last 10% done. Consider cases like The Gimp where the original developers basically dropped the code before the 1.0 release, but where interested parties picked it up and finished the job. If every project suffered from the same symptoms that you describe, there wouldn't be such a thing as GNOME, Sun's Java Desktop System and so on. Perhaps JDS would be based on KDE instead, however. ;-) > I've poked into literally over one hundred > sourceforge projects that started out as good ideas and had lots of > activity. i'd come back in 6 months and There would be almost no > activity. With a developer with a commericial background, he might be > more willing to see the project through. Yes, perhaps because he'd be paid to see it through. > I too get annoyed when an OSS author pulls a massive library into his > project just to get a few functions out of it he could have written > himself. It's really problematic as Brandon has said when you are > using CygWin or Ming because a lot of these libraries dont work on it. Just because one is developing with open source software doesn't mean that one is suddenly exempt from normal software engineering principles. Perhaps that was what the quoted contributor meant by those "second coming" claims, but most people understand that the universe doesn't change its rules on the basis of rumours derived from misinterpretations of claims by Eric S. Raymond. Paul From jcarlson at uci.edu Tue Jan 20 23:45:21 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 20:45:21 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <20040120181009.060C.JCARLSON@uci.edu> <20040120182610.060F.JCARLSON@uci.edu> <100rutd6kge1g9f@corp.supernews.com> Message-ID: <20040120203101.3E3B.JCARLSON@uci.edu> > > Technically os.system("c:\\path\\help.chm") and > > os.system("start c:\\path\\help.chm") also work, though > > are less intuitive. > > No, os.system is the wrong way to do it. That function launches a new > command shell, which in turn runs the program you want. Because of that, if > you're not already running in a console window, it will open a new console > window. > > You had it right with os.startfile. That calls the ShellExecute function in > Windows, which is the way you would do it in a native Windows application > written in C. Mike, When the command completes, the window dissappears. This is the case when running from a script within pythonw or even inside of a py2exe frozen module. While it may not be the 100% correct way of doing things (and you have to properly escape spaces in the file name, which then results in having to give a window title, etc.), it does result in a final outcome that is the same - the help file is open, your program continues execution. Certainly he will be using os.startfile(), but knowing that you can use windows shell commands with os.system can be useful. - Josiah From tdelaney at avaya.com Mon Jan 26 18:26:37 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 27 Jan 2004 10:26:37 +1100 Subject: Guardian: open source is a throwback says Jack Schofield Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE011DAACD@au3010avexu1.global.avaya.com> > From: Skip Montanaro > > Hmmm... If we're electing the "leader of the free world", > maybe the entire > free world ought to be able to vote. Imagine the primary > season running up > to that election! Don't need to - if we got to vote in that, we'd insist that a more rational voting system be used ;) Tim Delaney From bobmoore at pobox.com Sat Jan 31 14:23:42 2004 From: bobmoore at pobox.com (Bob=Moore) Date: 31 Jan 2004 11:23:42 -0800 Subject: Running External Programs from Within Python Message-ID: <5a40bf6a.0401311123.4b7f783f@posting.google.com> I'm considering making the transfer from Rexx to Python as a scripting language, but there's one thing I can do in Rexx that I can't seem to do in Python: run an external program. Suppose I have a Tkinter GUI and I want to just push a button and run the Windows utility notepad.exe. Or push another button and run one of my old Rexx programs. Basically I want to send a command line to Python and have it run that command line as if I'm sending it to the Windows command-prompt, an MS-DOS window, or clicking on an appropriate program icon. Can I run (call? exec? eval?) an external program from inside a Python program? I have checked the FAQ and documentation. Thanx, Bob=Moore From dpryde+usenet at cis.strath.ac.uk Wed Jan 7 11:03:42 2004 From: dpryde+usenet at cis.strath.ac.uk (Daniel Pryde) Date: Wed, 07 Jan 2004 16:03:42 +0000 Subject: Regions of similarity in a matrix Message-ID: <3ffc2dd9$1@nntphost.cis.strath.ac.uk> Hi again everyone. I was wondering if anyone knew of any python modules that are able to detect and extract regions of similarity from a matrix. My problem is that I have a self organizing map that has been trained, but now need to detect and extract the areas that contain similar values. In my case, each matrix point contains 9 pixels. I have calculated the euclidean values for each 9 pixel tuple in order to search for edges, so I'm guessing that an edge would just be a radical change between neighbouring values. I'm pretty sure that I'll be able to code it up myself, but was just asking in the hope that a module may already exist to help me along the way. :) Any help would be greatly appreciated. Daniel From claird at lairds.com Wed Jan 28 16:29:42 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Jan 2004 21:29:42 -0000 Subject: executing an external app References: Message-ID: <101gae65oh6ig72@corp.supernews.com> In article , Joe Francia wrote: >Joseph Krauze wrote: >> Hi all, >> >> I have a simple question which I cannot solve (relatively new to Python). >> I want to write a script that executes an application on the go. I looked >> into the exec*e() calls but the problem there is that they do not return. >> I also looked into execfile() but here the PATH is not taken into account >> and I couldn't figure out to pass the file that's executed arguments. >> >> So, is there a simple way to execute an external app? >> i.e. execvpe('cat', 'myFile') - this will not return >> >> Thanks, >> Joseph > >Look at os.spawn* or os.popen* . . . And os.system(). And commands.getoutput(). -- Cameron Laird Business: http://www.Phaseit.net From paulo.pinto at cern.ch Fri Jan 30 08:12:13 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Fri, 30 Jan 2004 14:12:13 +0100 Subject: package similar to XML::Simple In-Reply-To: <4017C630.5A6DD35@engcorp.com> References: <4017C630.5A6DD35@engcorp.com> Message-ID: I mean multiple nested dictionaries with lists. But handyxml seems to solve my problem. Thanks, guys Peter Hansen wrote: > Paulo Pinto wrote: > >>does anyone know of a Python package that >>is able to load XML like the XML::Simple >>Perl package does? >> >>For those that don't know it, this package >>maps the XML file to a dictionary. > > > A simple dictionary is insufficient to represent XML in general, > so perhaps you're talking about a subset of XML, maybe with no > attributes, and where the order of the child elements doesn't > matter? Or something else? > > Or do you really mean something like a multiply-nested > dictionary, perhaps with lists as well? > > >>Of course I can build such a package myself >>but it would be better if it already exists :) > > > We were able to build something similar by stripping down > Fredrik Lundh's elementtree until we had little more than the > calls to the expat parser (i.e. we used his source as a tutorial > on using expat :-), so if this is something like the XML-subset > I mention above, you could do it in an hour or so from scratch > if you knew Python well. > > -Peter From peter at engcorp.com Wed Jan 14 09:42:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Jan 2004 09:42:40 -0500 Subject: I come not to bury C++, but to praise it... References: Message-ID: <40055560.7A0DCD0D@engcorp.com> John Benson wrote: > [snip] > I think that the already-posted comments seeking to appreciate the > historical origin and motivations of C++ are essential to understanding it's > applicability in the present. > > C++ started as a quintessentially Unix-like exercise in software > engineering: add functionality by leveraging existing software components to > the max. Another level of preprocessor (Cfront) was added to the compiler > tool chain and Bingo! you had a new language. [snip] > > I think that C++ was a great exercise, but software engineering has > advanced. John, thanks for the reminder about the origins of C++. (I suspect the majority of readers in this group were not even programming during the CFront era (roughly 1983-85?), and a history lesson is always good from time to time.) I remember C++ as a welcome enhancement which allowed me to extend the scope of several large C projects without significantly affecting their complexity. Over the years I gradually found C++, especially as a result of its ongoing evolution, to be negatively affecting my development instead, however, and I was happy to finally move on to the more modern languages which software engineering has produced in the over 20 years since C++ came out. -Peter P.S.: Found http://merd.net/pixel/language-study/diagram.html while researching the timing on C++' conception... interesting, and might be nice wallpaper for some. From francisgavila at yahoo.com Thu Jan 8 11:48:41 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 8 Jan 2004 11:48:41 -0500 Subject: Descriptor puzzlement References: Message-ID: Mirko Zeibig wrote in message ... >John Roth said the following on 01/08/2004 01:34 PM: >Hm, I don't know __set__ and __get__, there are __getattr__ (or >__getattribute__) and __setattr__ for dynamically assigning attributes. >Or take a look at properties >(http://www.python.org/2.2/descrintro.html#property) Properties are just a wrapper/interface/application of/to descriptors (whose protocol involves __set__ and __get__). http://users.rcn.com/python/download/Descriptor.htm for details. -- Francis Avila From webmaster at beyond-thoughts.com Wed Jan 7 18:11:05 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Thu, 08 Jan 2004 00:11:05 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: <3FFA7E82.4020609@beyond-thoughts.com> Message-ID: <3FFC9209.7060703@beyond-thoughts.com> Gerrit Holl wrote: > Christoph Becker-Freyseng wrote: > >>[1] I think Path being a subclass of str is odd. There are a lot of >>string-operations that don't fit to path (some of them should be >>implemented in a different way e.g. __mul__ if at all). >>However the point with the old os function etc. is very sound. So it >>might be a good idea to have Path being a subclass of str *for >>transition*. But finally all those functions should call str(argument) >>instead of of demanding a str-object as argument (if they don't already >>today). > > > Another possibility, which I have put in the Pre-PEP, is; > > We can add a method .openwith(), which takes a callable as it's first > argument: p.openwith(f, *args) would result in f(str(p), *args). This > would make p.open(*args) a shorthand for p.openwith(file, args). > > What do you think? > openwith would be a nice add-on. I see two problems with it: 1.) it's long. I mean f(str(path), *args) is shorter than path.openwith(f, *args) I got an idea of shortening this and making it look a bit like shell (I'm not convinced of it very much, but I didn't want to keep it secret --- maybe others like it ...) path > (f, arg1, arg2, ...) (this works by overwriting path.__gt__) 2.) the position of the argument for the path can only be the first one. (maybe one could misuse even more operators e.g. the __r...__ ones; But I think this will result in obscure code) path.open shouldn't always call the ordinary file-constructor. I mean it should be changed for special path-classes like FTPPath ... (Of course for ordinary file-paths the ordinary file-class is the right one.) > >>This takes me to my last point: >>What about invalid paths? >>Should Path-Class take care of always being a valid path (this doesn't >>necessarily mean a path of an existing file/directory) > > > It may be a good idea to do so. At first, I didn't understand what it > meant, an 'invalid path', but let's define it as anything that triggers > a TypeError when passed to open or listdir. On POSIX, I know only one > case: \0 in path. It may be a lot more difficult on Windows or the Mac. > I'm not sure about this idea yet. But it could avoid a lot of trouble when accessing the path. Maybe I've a better idea (see below) > > >>Especially if someone uses string-methods on a Path-object there could >>arise invalid paths, even if finaly the path is valid again. > > > Yes. But I can't really think of a use case for doing operations on a > path which make it invalid. Does it occur in practice? It easily happens on old FAT-FS. Think of a function that wants to expand paths e.g.: (this is kind of "string-based") def myfiles(path): if path.endswith('*'): return [ path[:-2] + 'file1.txt', path[:-2] + 'game.exe', ] else: return path But probably sometimes stuff like this is useful. Additionaly path-validity is filesystem-dependend. And worse on system like Linux there can be more than one file system within the same root / and they all could have different restrictions! (if I were a viscious guy I could even umount and mount a different fs making a valid path possibly invalid) So I think the better solution would be to define a path.isValid() method. It would just evaluate on call (which makes it unlikely that things change during call and usage of the result -- without locking a file/dir more isn't possible) We also need a path.exists() method. I'm not sure how both should interact ?? Another Point: Should Path be immutable like string? Christoph Becker-Freyseng From jjl at pobox.com Sat Jan 10 12:44:16 2004 From: jjl at pobox.com (John J. Lee) Date: 10 Jan 2004 17:44:16 +0000 Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> <871xq8ri6h.fsf@pobox.com> Message-ID: <87eku7y9zj.fsf@pobox.com> Samuel Walters writes: > |Thus Spake John J. Lee On the now historical date of Fri, 09 Jan 2004 > 20:16:54 +0000| > > > or again, you can set .addheaders on OpenerDirector (which will cause > > those headers to be added to all requests). (just to clarify, I meant an OpenerDirector instance, not the class itself) > This, however, does not stop the original User-agent header to be sent, > and google still filters out the request. Instead, it just causes a > second user-agent to be sent. No, it does stop them being sent. Perhaps you mutated the base class .addheaders by mistake (using .append(("User-agent", "blah")), for example)? Don't do that! Mutating class attributes is a bad idea. > Here is the very bad code I used to solve this problem. There are better > ways, I assure you, but it should point you in the right direction. You [...] No need to assure me of *that* . You can call a base class constructor directly, you know. And clobbering the base class' constructor is another very bad idea. John From __peter__ at web.de Sun Jan 11 12:36:22 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Jan 2004 18:36:22 +0100 Subject: [Newb] Still not able to solve class attribution References: Message-ID: Knoppix User wrote: > class GIP(wx.Frame): > def __init__(self, parent, ID, title): > wx.Frame.__init__(self, parent, ID, title, size = (600, 460)) > > .... > Just an idea: how about moving the following statement up immediately after the wx.Frame.__init__(...). The DisplayImg() method *could* be called in the code you abbreviate with the above four dots. > self.Image = wx.StaticBitmap(self, -1, > wx.EmptyBitmap(*self.thumbSize), > pos = (160,10)) <<<<<<<<<<<<<<<<<<< Message-ID: On Wed, 28 Jan 2004 15:22:05 GMT, wes weston wrote: > Switch from windoze to linux and provide screen dumps. I don't understand part of your comment. Windows can provide screen dumps also. That's not a reason to switch. :-) --dang From gerrit at nl.linux.org Tue Jan 27 08:16:51 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 27 Jan 2004 14:16:51 +0100 Subject: How does compare work? In-Reply-To: <20040126235704.GD13453@siliconimage.com> References: <40158680$0$7044$ba620e4c@news.skynet.be> <20040126235704.GD13453@siliconimage.com> Message-ID: <20040127131651.GA3495@nl.linux.org> Inyeol Lee wrote: > (This unusual definition of comparison was used to simplify the > definition of operations like sorting and the in and not in operators. > In the future, the comparison rules for objects of > different types are likely to change.) > """ When comparing mixed types becomes illegal, does that mean sorting a sequence of mixed types becomes illegal as well? Or will sort be a special case? yours, Gerrit. -- 136. If any one leave his house, run away, and then his wife go to another house, if then he return, and wishes to take his wife back: because he fled from his home and ran away, the wife of this runaway shall not return to her husband. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From harry.g.george at boeing.com Fri Jan 9 05:57:00 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 9 Jan 2004 10:57:00 GMT Subject: Database interfacing References: Message-ID: "Michael T. Babcock" writes: > I'm working with databases (MySQL primarily) more and more with > Python, and having used PERL in the past for similar work, I'm > wondering if there are good tools for doing 'intelligent' > selects/inserts to/from dictionaries, etc. For example: > > data = {'FirstName': 'Michael', 'LastName': 'Babcock', 'Age': 99} > lastid = db.insert('Users', data) > > ... which would execute "INSERT INTO Users (FirstName, LastName, Age) > VALUES ('Michael', 'Babcock', 99)" > > And also helpful would be: > > data = db.query("dbname", "SELECT * FROM Users WHERE Age >= 99)") > > ... which would return me an array of dictionary items like: > > [ {'ID': 143, 'FirstName': 'Michael' ... }, {'ID': 242, ... }, ... ] > > Just curious, thanks (I've written a piece of code to generate the > array of dictionary results myself actually, but I'm sure someone > else's is better). > > -- > Michael T. Babcock > C.T.O., FibreSpeed Ltd. > http://www.fibrespeed.net/~mbabcock > > > You can write tools like this yourself or use existing tools. For starters take a look at: http://skunkweb.sourceforge.net/PyDO/ If you roll your own, here are some considerations: You need to synchronize the table definitions in the DBMS with the class definitions in python. Some approaches start with the DBMS and extract the table definitions (attributes, keys, etc) for use in generating the needed python code. Some start with python and define a list of attributes and their meta data as a class-level var for a class. (I've tried both ways.) Python-first opens the door to aspectual programming. But you may need both approaches when you need to work with existing code or databases. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From python-url at phaseit.net Mon Jan 5 20:43:49 2004 From: python-url at phaseit.net (Emile van Sebille) Date: Tue, 06 Jan 2004 01:43:49 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 5) Message-ID: QOTW: "Name me any product (except maybe TeX) that was mature at version 1.0. I remember using Visual Basic at v1.0 and it definitely wasn't mature..." -- Alan Gauld on the maturity of IDLE "Most Python users don't know C, and will never see the C implementation." -- Tim Peters Rob Hughes wishes all a Happy New Year in a multilingual piece of code. http://groups.google.com/groups?threadm=809f2610.0401011312.190dfb44 at posting.google.com Art Haas announces the eleventh development release of PythonCAD, a fully scriptable drafting program written in python. http://groups.google.com/groups?selm=mailman.1072891982.24293.clpa-moderators at python.org Daniel Pryde gets some ideas on optimizing a best match searching algorithm. http://groups.google.com/groups?threadm=a0YHb.5354%24DC4.2417%40fe2.texas.rr.com Barry A. Warsaw releases Mailman 2.1.4, a bug fix release that also contains support for four new languages: Catalan, Croatian, Romanian, and Slovenian. http://groups.google.com/groups?selm=mailman.1072897503.19303.clpa-moderators at python.org Oh Kyu Yoon asks how to implement plots from scipy, chaco, etc into wxPython widget. http://groups.google.com/groups?threadm=bt04a4$2e3$1 at news.Stanford.EDU Bjorn Stabell announces the creation of Python and Zope/Plone Chinese Forums. http://groups.google.com/groups?selm=mailman.1073049482.17069.clpa-moderators at python.org hokieghal99 asks Is Python Mac Centric? http://groups.google.com/groups?threadm=bss8qn$mb7$1 at solaris.cc.vt.edu Greg Lindstrom gets help monitoring an MS Exchange mailbox. http://groups.google.com/groups?threadm=mailman.20.1072730275.8134.python-list%40python.org Tim Churches and Adam Twardoch point out articles that may require a revision in the Guinness Book of World Records. -- http://news.independent.co.uk/world/asia/story.jsp?story=476931 -- http://www.wftv.com/news/2732086/detail.html Peter Astrand solicits comments on PEP 324, a proposal to introduce a new POSIX process module popen5. http://groups.google.com/groups?threadm=mailman.47.1073137666.12720.python-list at python.org http://groups.google.com/groups?threadm=mailman.60.1073175311.12720.python-list%40python.org Mike gets help with a problem building on BeOS. http://groups.google.com/groups?threadm=NLhJb.31440$I07.78784 at attbi_s53 Black asks about implementing undo and redo using tkinter. http://groups.google.com/groups?threadm=mailman.20.1073011134.12720.python-list%40python.org Roger Jack is looking for the best tool for templating source code files and then generating python code. http://groups.google.com/groups?threadm=CMudnfQnOeIn1GqiRVn-uQ at comcast.com Randall Smith needs a way to convert a datetime string of unknown format to a python datetime object. http://groups.google.com/groups?threadm=MnIJb.33778$xU1.16252 at fe1.texas.rr.com Robert Brewer updates his recur.py, then later provides an example of using recur.interval with threading.Timer. http://groups.google.com/groups?threadm=mailman.58.1073173611.12720.python-list at python.org Hye-Shik Chang announces Anonfunc 1.0, a C extension module that creates anonymous functions based on operator overloading. http://groups.google.com/groups?selm=mailman.1073232664.14285.clpa-moderators at python.org Francois releases Allout-Vim 040103, a tool that eases the handling of Allout files from within a Python-enabled Vim. http://groups.google.com/groups?selm=mailman.1073155262.15776.clpa-moderators at python.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 newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of 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 has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ 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 exarkun at intarweb.us Sat Jan 31 09:18:31 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 31 Jan 2004 09:18:31 -0500 Subject: problem with weakref.proxy In-Reply-To: References: Message-ID: <20040131141831.GA1064@intarweb.us> On Sat, Jan 31, 2004 at 02:52:45PM +0100, Walter Haslbeck wrote: > Hello, > > I'm a completly Python newbie. As a first learning project I want to port > an game-engine I have writte some time ago in pure C to Python using OO > methods. > > So I created a base-class 'GOb' (GameObject). This class should have > a sorted list of all instances stored as as class-attribte __olist[]. > > When I add a reference of the new created object in the constructor > (with GOb.__olist.append(self)) I have 2 references to each created > instance and if I 'del' the instance the destructor is not called, > because __olist[] holds another reference to that object. > > Now I got to tip to use the weakref module. Well I thought this should > be exactly what I need and changed the program to add not a reference > to the instances but a weakref.proxy. > > So now my instances are deleted really deleted when I use 'del', but: > How do get corresponding weakref.proxy object out of __olist[]? > > I tried to use the callback parameter from weakref.proxy, but at the > time when the callback takes place, the proxy object is allready 'dead', > I get an Exception when I try to remove the proxy-instance from __olist[]: A WeakKeyDictionary or WeakValueDictionary might be a better fit for your problem. There is no need for you to remove the object from these manually. When the object is no longer referenced anywhere else, it also no longer belongs to the dictionary. >>> class foo: pass ... >>> import weakref >>> d = weakref.WeakValueDictionary() >>> x = foo() >>> d['key'] = x >>> print d.items() [('key', <__main__.foo instance at 0x401eeb2c>)] >>> del x >>> print d.items() [] >>> Jp From FBatista at uniFON.com.ar Tue Jan 6 11:45:02 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 6 Jan 2004 13:45:02 -0300 Subject: prePEP "Decimal data type" v0.2 Message-ID: aahz at pythoncraft.com wrote: #- Overall, looks good. I think the biggest point of #- disagreement still is #- the behavior of Decimal interacting with floats. I hope more people #- will comment once you get a PEP number. Yes, I know. I don't like one more than other, I just hope to get community consensus... I'll wait until tomorrow to get some responses, justo to send to pep at ... a more polished version (or with less semantic errors, :p). #- One major correction: "Rationale" means "reason"; "rational" #- refers to #- fractions. Several times you use "rationale" when you mean #- "rational". Paul Moore pointed that too, sorry for my english, :( . Facundo From mfranklin1 at gatwick.westerngeco.slb.com Thu Jan 22 06:15:41 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 22 Jan 2004 11:15:41 +0000 Subject: Jython and SciTE In-Reply-To: References: Message-ID: <1074770140.1056.3.camel@m-franklin> On Wed, 2004-01-21 at 02:28, rt lange wrote: > I'm trying to get my jython scripts running and compiling on SciTE. > This is what I have in my python.properties file: > > command.name.1.*.py=Go Jython > command.1.*.py=jython $(FileNameExt) Just in case try inserting the full path name of the jython script here perhaps when SciTE calls out it creates a sub shell (and in that the PATH is NOT set...) command.1.*.py=/usr/jython2.1/jython $(FileNameExt) HTH Martin From webmaster at beyond-thoughts.com Thu Jan 8 15:55:27 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Thu, 08 Jan 2004 21:55:27 +0100 Subject: PRE-PEP: new Path class; open, openwith, __call__ In-Reply-To: References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <3FFDC3BF.7070404@beyond-thoughts.com> Gerrit Holl wrote: > Christoph Becker-Freyseng wrote: > >>openwith would be a nice add-on. I see two problems with it: >>1.) it's long. I mean >> f(str(path), *args) >> is shorter than >> path.openwith(f, *args) > > > This is indead a disadvantage. On the other hand, although p.openwith is > longer, I do think it is more readable. It occurs often that shorter is > not more readable: just think of all those 'obfuscated-oneliners' > contests in C and Perl. Sure. However this case seems to be quite obvious both ways. > > >>path > (f, arg1, arg2, ...) >> >>(this works by overwriting path.__gt__) > > > I think this is not a good idea. In my opinion, any __gt__ method should > always compare, no more, no less. Further, it's very unusal to call > something like this. Additionaly getting the right documentation for these "operator-tricks" is harder. > > Another possibility is defining __call__: > > path(f, *args) == f(str(path), *args) > > which may be unconvinient as well, however. Is it intuitive to let > calling mean opening? I like this one. What else could calling a path mean? > > >>2.) the position of the argument for the path can only be the first one. >>(maybe one could misuse even more operators e.g. the __r...__ ones; But >>I think this will result in obscure code) > > > Hm, I think almost all file constructors have the path as the first > argument. Are there counter-examples? The whole openwith (other then path.open) is IMO mainly for "backward-compatibility" if the function doesn't know the path-class. I think openwith or better __call__ could be used for other things, too --- not only for opening a file. E.g. there could be some "FileWatcher-Modules" that might only accept strings and have a call like: watchFile(onChangeFunc, path_string) For different postition of the path_string we could make a special case if the path-object is given as an argument of the call. path(f, arg1, arg2, path, arg3, arg4, ...) results in: f(arg1, arg2, str(path), arg3, arg4, ...) Changing old code to use the new Path-class could be done with a minimal amount of work then. OLD: result= f(arg1, arg2, path, arg3, arg4, ...) # path is/was a string here .... result= f,arg1, arg2, path, arg3, arg4, ...) .... result= (f, arg1, arg2, path, arg3, arg4, ...) NEW: result= path(f, arg1, arg2, path, arg3, arg4, ...) > > >>path.open shouldn't always call the ordinary file-constructor. I mean it >>should be changed for special path-classes like FTPPath ... >>(Of course for ordinary file-paths the ordinary file-class is the right >>one.) > > > Yes... I was planning to define it in a class which is able to 'touch' > the filesystem, so an FTPPath could subclass basepath without the need > to overload open, or subclass ReadablePath with this need. Fine :-) Christoph Becker-Freyseng P.S.: ((I'll post the other things in different Re:'s)) From skip at pobox.com Wed Jan 14 07:16:11 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 06:16:11 -0600 Subject: Safe prime numbers in Python In-Reply-To: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> Message-ID: <16389.13067.921116.858507@montanaro.dyndns.org> Tim> Does any know of or have Python code (or C or Fortran code wrapped Tim> as a Python module) for efficiently finding safe prime numbers - Tim> that is a number p such that p and (p-1)/2 are both prime? Here's what I came up with using gmpy: import gmpy def safe_primes(last=1): while True: next = gmpy.next_prime(last) if gmpy.is_prime((next-1)/2): yield next last = next Seems to work fairly well. Skip From amk at amk.ca Wed Jan 21 08:53:02 2004 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 21 Jan 2004 07:53:02 -0600 Subject: Pyrex without Python (was Re: calling Pyrex results from C) References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> Message-ID: <6_CdnXaaT8ejGZPdRVn-hQ@speakeasy.net> On Wed, 21 Jan 2004 12:58:26 +0000, Richie Hindle wrote: > How does it know the types? Pyrex adds additional syntax to do this, but > if you're using the plain vanilla compiler package then presumably you're > doing something else? Types are predeclared using a different mechanism; the compiler goes in with a list of all the inputs and outputs and a list of internal variables. --amk From usenet at -OBFUSCATION-joefrancia.com Wed Jan 14 13:22:03 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Wed, 14 Jan 2004 18:22:03 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: <4004AC8E.46A3104F@alcyone.com> References: <40047290$1@news.012.net.il> <4004AC8E.46A3104F@alcyone.com> Message-ID: Erik Max Francis wrote: > You're trying to put this weird spin on your public displays of > embarassment is not really working. Trying and failing is a part of > life. Trying and failing, over and over again, consistently, despite > insisting quite urgently on how important you are to a community, is > starting to get suspicious. > > >>Those who never taste failure are haughty. > > > And those who never taste success should probably come to the > realization, eventually, that they are doing something wrong. This reminds me of the old expression: "A winner never quits. A quitter never wins. But if you never win and never quit, you're a fucking idiot." From samirw at connection.com Tue Jan 6 23:18:12 2004 From: samirw at connection.com (Sambo) Date: Tue, 06 Jan 2004 20:18:12 -0800 Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> <7xd69wy5zq.fsf@ruckus.brouhaha.com> Message-ID: <3FFB8884.9080907@connection.com> Paul Rubin wrote: > Ville Vainio writes: > > >>Paul Rubin writes: >> >> >>>>The above code works, but I don't like making two read() calls. Any >>>>way to avoid it, or a more elegant syntax? Thanks. >>>> >>>You can make it even uglier: >>> >>> f = file(filename, 'rb') >>> while 1: >>> data = f.read(1024) >>> if len(data) <= 0: >>> break >>> someobj.update(data) >>> f.close() >>> >>>There's been proposals around to add an assignment-expression operator >>>like in C, so you could say something like >>> >>> f = file(filename, 'rb') >>> while len(data := f.read(1024)) > 0: >>> someobj.update(data) >>> f.close() >>> >>It's funny, but I find the first version much more readable than the >>second one. Especially if I consciously forget the "do lots of stuff >>in condition part of while" indoctrination from C. If there is lots of >>stuff in while you have to stare at it a bit more, and it becomes >>"idiomatic", something you learn, perhaps even cookbook stuff, instead >>of obvious-as-such. >> > > Idioms exist because they're useful, and there's already plenty of > them in Python, like ''.join(stringlist) or "for i in xrange(n)" etc. > > Maybe the condition in the while statement makes that statement twice > as hard to read. However, the example as a whole can still be easier, > simply because it's shorter. > > Version 1: > > Statement Reading difficulty > ========= ================== > > f = file(filename, 'rb') 1 > while 1: 1 > data = f.read(1024) 1 > if len(data) <= 0: 1 > break 1 > someobj.update(data) 1 > f.close() 1 > > Total reading difficulty: 7 > > Now the second version: > > Statement Reading difficulty > ========= ================== > > f = file(filename, 'rb') 1 > while len(data := f.read(1024)) > 0: 2 > someobj.update(data) 1 > f.close() 1 > > > Total reading difficulty: 5 > > I got through college on a version of this reasoning. I was a math > major. I had friends studying history and literature who said "that's > a hard subject", but I thought they were crazy. But in a normal math > class, there's one textbook that you use for the whole semester, and > you cover maybe half the chapters in it. I was able to keep up. But > in a literature course, you usually have to read a different entire > book from cover to cover EVERY WEEK. I took a couple classes like > that and barely survived. Yes, it takes a lot more effort to read a > page of a math book than a page of a novel. When you compare the > total reading load though, math was a much easier major than > literature or history. > > It's the same with programs. I'd rather read 5 lines of tight code > that each actually does something, than 3 pages of loose code (the > kind that's usually written in Java) that spastically meanders trying > to do the same thing, even if the individual loose lines are easier to > read than the tight lines. > I would say, that depends on the persons competency in a given language. Naturally once you are writing long/large programs it is better to have tight code, but for a newby it is too much to translate at once. While I consider myself expert in "C" , I am still learning "C++". That does not mean a language has to lack the capability. Then again how large a program can you or would you want to write with python? Cheers, Sam. From phleum_nospam at chello.se Fri Jan 9 16:05:35 2004 From: phleum_nospam at chello.se (Carl) Date: Fri, 09 Jan 2004 22:05:35 +0100 Subject: Python is far from a top performer according to benchmark test... Message-ID: "Nine Language Performance Round-up: Benchmarking Math & File I/O" http://www.osnews.com/story.php?news_id=5602 I think this is an unfair comparison! I wouldn't dream of developing a numerical application in Python without using prebuilt numerical libraries and data objects such as dictionaries and lists. I have been experimenting with numerical algorithms in Python with a heavy use of the Numeric module. My experience is that Python is quite fast in comparison with (and sometimes as fast as) traditional languages such as C or C++. The greatest advantage of Python is the great increase in productivity and the generation of a much smaller number of bugs due to the very clean and compact structure Python invites you to produce. Sometimes it amazes me how fast I can produce a working algorithm in Python. The step from an algorithmic outline on a paper to a working code is very short. The interactive nature of the Python console invites numerical experimentation and data exploration. This wasn't mentioned in the article, what a pity! Carl From michael at foord.net Wed Jan 28 04:18:21 2004 From: michael at foord.net (Fuzzyman) Date: 28 Jan 2004 01:18:21 -0800 Subject: Cross Platform Browser Launcher Message-ID: <8089854e.0401280118.2f07fb65@posting.google.com> I've written a simple application in python with an HTML help file. I'm looking for a cross platform way of launching the help file. On windows I'd use : os.system('start help.html') Which automatically opens the file with the users browser. Is there a cross-platform way of doing the same thing ? I can do a platform test and use different techniques for different systems - but I don't know how to achieve the same effect on a Linux (Unix ? Mac ?) machine..... Any help appreciated. Fuzzy -- 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.voidspace.org.uk/atlantibots/pythonutils.html Python functions - home of dateutils, ConfigObj, StandOut, CGI-News and more.... -- 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 davecook at nowhere.net Sat Jan 10 23:13:48 2004 From: davecook at nowhere.net (David M. Cook) Date: Sun, 11 Jan 2004 04:13:48 GMT Subject: Emacs python mode question References: Message-ID: In article , jblazi wrote: > If I should like to go to line 345: how can I do that? Typing M-x > goto-line and then 345 is a bit cumbersome. > I defines the key Alt-g to be goto-line, but it does not work. In XEmacs, you can just highlight the error line and middle-click. I don't know whether this feature is missing in Gnu Emacs or just turned off. Dave Cook From nomail at nospam.net Tue Jan 13 04:56:40 2004 From: nomail at nospam.net (Olaf Meyer) Date: Tue, 13 Jan 2004 09:56:40 GMT Subject: problems with dict() in python 2.2 Message-ID: I'm trying to build a dictionary using python's dict type, but somehow it does not work the way I expect it to. Here's the code: Python 2.2.1 (#7, Jan 9 2004, 16:59:31) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> data=dict(red=1) Traceback (most recent call last): File "", line 1, in ? TypeError: 'red' is an invalid keyword argument for this function What am I doing wrong? Thanks, Olaf From jjl at pobox.com Sun Jan 18 07:11:08 2004 From: jjl at pobox.com (John J. Lee) Date: 18 Jan 2004 12:11:08 +0000 Subject: Webbrowser and Mozilla control on linux References: <1d17eeb7.0401171633.170e313a@posting.google.com> Message-ID: <87ad4lqwwz.fsf@pobox.com> Joe Francia writes: > Jay Davis wrote: > > I can launch a browser on linux with the webbrowser module > > and the .open() method. However, I want to be able also to > > control the browser, specifically, I'd like to be able to go to a > > URL and invoke the automatic form filler and post > > the form, all from within a python script. [...] > If all you're trying to do is automatically fill out web forms, you'll > probably be better off using ClientForm (and possibly ClientCookie) > from this page: > http://wwwsearch.sourceforge.net/ ...or if not, it's PyXPCOM that you want. There are a couple of links on the "General FAQ" page at the site above. Unfortunately, PyXPCOM doesn't have a maintainer with enough time to do it justice ATM, so you might have trouble building it. See this bug (which contains a patch that should let you build it): http://bugzilla.mozilla.org/show_bug.cgi?id=129216 John From nospam-deets at web.de Tue Jan 27 09:29:00 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Tue, 27 Jan 2004 15:29:00 +0100 Subject: threads References: Message-ID: Hi, > If the above is not suitable for threading, please give me a short > example of something that is. Its not suitable for threading. The reason is that threading itself doesn't give you magically more computational power. Threading simply allows for severeal threads of execution - hence the name - to be performed (quasi-)parallel. Its similar to multi-processing: you can start several processes (programs, so to speak), and they appear to work simultanously. This is achieved by interrupting each process after a certain amount of time, put it to sleep and continue to execute another process. This is done at so short time-slices that it appears to the human user that everything works in parallel. Threads and processes differ in what scope they run in. In a modern OS like *NIXes and e.g XP/NT, all processes run in separate portions of memory, and can't access other processes memory. This can only achieved explicitely by inter process communication, which is a wide topic and I won't dive into it right here. OTH Threads are parallel threads of execution "inside" one process. They all share the same memory and thus variables and data-structures. The responsibilities are now reverse: You can access everything, so to prevent thread A from altering a datum thread B is currently working on, you have to somehow serialize/synchronize access to that datum. This is done using semaphores, mutexes or locks - things you can read about in the api docs. Now when do you _need_ threads then? This easier asked than answered, and sometimes a question of choice or taste. But I think these are some indicators: - you want several parts of your program to be responsive to user input while they perform some actual work. I bet you have expirienced locked GUIs in programs that were doing some stuff, like decompression an archive or the like - this could be avoided by a special gui-thread that allows you to tinker with menus/buttons while the work is done in the background. - if you actually have a mulitprocessor-machine, the quasi from quasi-parallel vanishes. Then one processor can execute one thread, and another one the other. Of course this scales only up to the number of processsors you have. - in languages that don't features like coroutines/generators, sometimes applicatioin logic is much more natural when expressed in different threads, where each thread has his own call-stack, state and so on. This is e.g. the case in JAVA. However, there _is_ a cost for that, as the so called context-switch between threads isnt't for free, and synchronizing can eat up precious time. - some people use threads to handle blocking io. This is similar to the point above - if you have a net-based protocol, its much more natural to implemnt when you don't have to care if and when its waiting for input and then would pass back execution to a point where your program waits for all your sockets to return with data. Then you'd have to dispatch to the appropriate part of the protocol-implementation. A thread just would sit on the socket and wait until it returns. Then the logic goes on uninterrupted. Hope that shed some light on it for you, Diez From Stephane.Ninin at fr.invalid Sat Jan 24 15:27:49 2004 From: Stephane.Ninin at fr.invalid (Stephane Ninin) Date: Sat, 24 Jan 2004 21:27:49 +0100 Subject: nested class problem Message-ID: <4012d34f$0$17124$626a54ce@news.free.fr> Hello all, I am trying to play with nested class in a script I am making, and I am not sure I really understand how they work. Here is some code: __all__ = ["ITest"] from exceptions import Exception class ITest(object): def __init__(self): if (self.__class__ == ITest): raise Exception("ITest cannot be instanciated") def read(self,filename): self.__filename = filename def _getFilename(self): return self.__filename def make_reader(): return _PTest() make_reader = staticmethod(make_reader) class _PTest(ITest): class _PHandler(object): def __init__(self): super(_PHandler,self).__init__() #self.__map={} def test(self): pass def __init__(self): super(_PTest,self).__init__() def read(self,filename): super(_PTest,self).read(filename) print "HERE" print dir() print dir(self) print self.__class__ print dir(self.__class__) dh = self._PHandler() #dh.test() if __name__=='__main__': a=ITest.make_reader() print dir(a) b=a.read("") print b I want to put class _PHandler in _Ptest, and use _PHandler in _Ptest methods, but anything I try doesnot work... On this configuration, I have: Traceback (most recent call last): File "./test.py", line 58, in ? b=a.read("") File "./test.py", line 51, in read dh = self._PHandler() File "./test.py", line 34, in __init__ super(_PHandler,self).__init__() NameError: global name '_PHandler' is not defined and I have similar problems if I try to access _PHandler in different ways... Is this possible somehow ? Or what is the problem with my approach ? I know I could just dont use nested classes.., but I'd like to try. Thanks in advance. Regards, -- Stephane Ninin From cygnus at cprogrammer.org Thu Jan 29 22:31:27 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Thu, 29 Jan 2004 22:31:27 -0500 Subject: Python vs. Io In-Reply-To: <711c7390.0401291301.3f95794@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <20040130033127.GA30452@mail.theserver.ath.cx> As other posts have indicated, this is not the io-user-list. While you probably have good, purely academic intentions with your post, this is not the correct forum. Create an io-vs-python list somewhere and I'm sure you'll get a few subscribers. :) -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From mark at mceahern.com Thu Jan 15 14:29:02 2004 From: mark at mceahern.com (Mark McEahern) Date: Thu, 15 Jan 2004 13:29:02 -0600 Subject: TUPLE & LIST In-Reply-To: <%7xNb.55$Uw3.50@newsr2.u-net.net> References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <4006E9FE.50104@mceahern.com> Yomanium Yoth Taripo?t II wrote: >3) im looking the fucking manual, and cant add value in my tuple, when it already created :/ > > there's a manual for fucking that talks about tuples? sounds fun. do share. cheers, // m From jzgoda at gazeta.usun.pl Tue Jan 27 11:19:44 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 27 Jan 2004 16:19:44 +0000 (UTC) Subject: python As400 References: Message-ID: Enrique pisze: > 2.- files in as400 are in ebcdic. But i need to work in ascii to sort de > data later. Can i work in as400 with ascii files? Sure. You can use codecs.open() to open such files, this will provide you with transparent decoding to unicode objects during reading. To write ascii, use encode() function of unicode object to get string in desired encoding. I found working with unicode objects more convenient, although re.UNICODE is broken. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From xah at xahlee.org Sun Jan 25 04:36:04 2004 From: xah at xahlee.org (xah lee) Date: Sun, 25 Jan 2004 01:36:04 -0800 Subject: perl bug File::Basename and Perl's nature In-Reply-To: <20040125091051.GA14795@nl.linux.org> References: <7fe97cc4.0401242131.22acf485@posting.google.com> <20040125091051.GA14795@nl.linux.org> Message-ID: think not what other messages are doing, think of what your message is doing. i am a known positive troll. It is people like you, who piggy back on me, supports my constructive undoing. Thanks. PS if perl is demising, then it will benefit Python (because they are competitors), and as well all other non-irresponsible programers and languages, and consequently the programing industry, and society, and software might stop to crash, and people might start to like computers. Please read the following article: --------------------------- Responsible Licenses Xah Lee, 2003 July http://xahlee.org/UnixResource_dir/writ/responsible_license.html Software is a interesting invention. Software has this interesting property, that it can be duplicated without cost, as if like copying money. Never in history are goods duplicable without cost. But with the invention of computer, the ephemeral non-physical programs breaks that precept. In digital form, program and music and books all become goods in essentially infinite quantity. All is good except, bads in digital form can also multiply equally, just as goods. Wellknown examples are computer viruses and email spams. Unknown to the throng of unix morons is software bads. In a unix moron's mind, the predominant quip among hackers is "where is your code?", singnifying the mentality that a hacker's prestige is judged on how much code he has contributed to the community. Therefore, every fucking studs and happy-go-lucky morons put their homework on the net, with a big stamp of FREE, and quite proud of their "contributions" to the world. These digital bads, including irresponsible programs, protocols, and languages, spread like viruses until they obtained the touting right of being the STARDARD or MOST POPULAR in industry, as if indicating superior quality. Examplary are C, Perl, RFC, X-Windows, Apache, MySQL, Pretty Home Page (and almost anything out of unix). The harm of a virus is direct. The harm of irresponsible software (esp with unscrupulous promotion) is the creation of a entire generation of bad thinking and monkey coders. The scales can be compared as to putting a bullet in a person brain, versus creating a creed with the Holocaust aftermath. Distribution of software is easily like pollution. I thought of a law that would ban the distribution of software bads, or like charging for garbage collection in modern societies. The problem is the difficulty of deciding what is good and what is bad. Like in so many things, i think the ultimate help is for people to be aware; so-called education; I believe, if people are made aware of the situation i spoke of, then irresponsible software will decrease, regardless any individual's opinion. -- The most important measure to counter the tremendous harm that irresponsible software has done to the industry is to begin with responsible license, such that the producer of a software will be liable for damage incurred thru their software. As we know, today's software licenses comes with a disclaimer that essentially says the software is sold as is and the producer is not responsible for any damage, nor guaranteeing the functionality of the software. It is this, that allows all sorts of sloppitudes and fucking fads and myths to rampage and survive in the software industry. Once when software producers are liable for their products, just as bridge or airplane or transportation or house builders are responsible for the things they build, then injurious fads and creeds the likes of (Perl, Programing Patterns, eXtreme Programing, "Universal" Modeling Language...) will automatically disappear by dint of market force without anyone's stipulation. In our already established infrastructure of software and industry practices that is so already fucked up by existing shams, we can not immediately expect a about-face in software licenses from 0 liability to 100% liability. We should gradually make them responsible. And this, comes not from artificial force, but gradual establishment of awareness among software professionals and their consumers. (Producers includes single individual to software houses, and consumers includes not just mom & pop but from IT corps to military.) ------------ Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html On Jan 25, 2004, at 1:10 AM, Gerrit Holl wrote: > Just bumped into another irresponsibility in perl. What's this doing in the Python newsgroup? Gerrit. From pinard at iro.umontreal.ca Thu Jan 22 11:59:27 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 22 Jan 2004 11:59:27 -0500 Subject: Program Python in VIM In-Reply-To: <871xpsc5zf.fsf@tulip.whu.ca> References: <871xpsc5zf.fsf@tulip.whu.ca> Message-ID: <20040122165927.GA19145@alcyon.progiciels-bpi.ca> [Peter Wu] > I'm giving vim a try to program Python. The following are the steps I > follow to code/test a python program. > vi test.py > [key in some python code] > :wq > :!python test.py > Is there any other way? I don't want to type 'python test.py' every time > I've made any modifications. In Emacs, I can simply fire C-c C-c to fire > the python interpreter. Thanks! I do not know if there is a better way, but what I do for one is to create a small Makefile like: try: python test.py (there is really a TAB above), and then, from `vim', do `:make'. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From __peter__ at web.de Tue Jan 20 18:46:02 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Jan 2004 00:46:02 +0100 Subject: always the same object References: Message-ID: Uwe Mayer wrote: > Hi, > > I am using struct.unpack() quite often. unpack() returns a tuple, however > a tuple with always the same id(), which is AFAIK the memory location of > the structure. > > I found myself working with above tuple, initialising other data > structures, etc... and when I tried to change one list element, suddenly > all list elements change => so they all contain the identical object > > Now what are the rules when Python re-uses an old object (as with > struct.unpack() ) and when does it create new objects? > And what ist the proposed solution for dealing with this situation, i.e. > how to I create a true copy of what struct.unpack() returns me? Most likely your problems have nothing to do with struct.unpack(), as it returns a tuple containing - as far as I know - only immutable objects. I suppose you are using the same list multiple times later in your script, and making a shallow copy otherList = list(someList) should suffice to remedy the observed "change once, see anywhere" experience. However, this is hard to tell without any sourcecode. So in the future, please take the time to compose a minimal script reproducing the observed behaviour along with a short description of what the script is supposed to do. Peter From timr at probo.com Mon Jan 5 20:39:30 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 05 Jan 2004 17:39:30 -0800 Subject: using cgi form via http and extracting results References: <3ff84844.0@news1.mweb.co.za> Message-ID: bmgx wrote: >I would like to use an already existing online service (currency >converter) basically consisting of a html form with a few options that >is submitted and returns the results. I really don't know where to start >but I have assumed the following steps need to be taken: > >1) Make an http connection to the remote script (http://server/script.cgi) > >2) Fill out the html form (1x TEXT and 2x SELECT input fields) > >3) Submit the form > >4) extract the actual returned result. (using regex or something..) You don't actually need steps 1 and 2 at all. HTTP transactions are all completely separate. The results of a form submission are just a URL. If the form has fields "FromCurrency", "ToCurrency", and "Amount", all you have to do is this: http://www.currencyservice.com?FromCurrency=dollars&ToCurrency=pounds&Amount=15 You don't have to HAVE the form source in order to submit a request. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Sat Jan 31 12:33:24 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 31 Jan 2004 18:33:24 +0100 Subject: problem with weakref.proxy References: Message-ID: Walter Haslbeck wrote: > Hello, > > I'm a completly Python newbie. As a first learning project I want to port > an game-engine I have writte some time ago in pure C to Python using OO > methods. > > So I created a base-class 'GOb' (GameObject). This class should have > a sorted list of all instances stored as as class-attribte __olist[]. > > When I add a reference of the new created object in the constructor > (with GOb.__olist.append(self)) I have 2 references to each created > instance and if I 'del' the instance the destructor is not called, > because __olist[] holds another reference to that object. > > Now I got to tip to use the weakref module. Well I thought this should > be exactly what I need and changed the program to add not a reference > to the instances but a weakref.proxy. > > So now my instances are deleted really deleted when I use 'del', but: > How do get corresponding weakref.proxy object out of __olist[]? > > I tried to use the callback parameter from weakref.proxy, but at the > time when the callback takes place, the proxy object is allready 'dead', > I get an Exception when I try to remove the proxy-instance from __olist[]: > > Exception exceptions.ReferenceError: 'weakly-referenced object no > longer exists' in ignored > > And if I iterate throu all objects in __olist[] I get an > 'ReferenceError: weakly-referenced object no longer exists' > > > please look at the following source: [...] I'd recommend being lazy and using a WeakValueDictionary instead of building the machinery on your own. Your code would then look similar to the following: import weakref class GOb: all = weakref.WeakValueDictionary() def c_show_all(): print "all GObs, sorted by priority:" values = GOb.all.values() values.sort() for i in values: print i c_show_all = staticmethod(c_show_all) def __init__(self, name="GOB", priority=0): self.priority = priority self.name = name GOb.all[id(self)] = self def __del__(self): print "Destruktor called for GOB " + self.name def __str__(self): return self.name + " " + str(self.priority) def __cmp__(self, other): return cmp(self.priority, other.priority) if __name__ == '__main__': a=GOb("T1", 0) b=GOb("T2", 2) c=GOb("T3", 1) GOb.c_show_all() print "delete T1:" del a GOb.c_show_all() Peter From sombDELETE at pobox.ru Sun Jan 18 12:28:31 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 18 Jan 2004 20:28:31 +0300 Subject: newbie question about compression and ascii References: Message-ID: "Haim Ashkenazi" wrote in message news:mailman.470.1074442222.12720.python-list at python.org... > Hi > > I'm a real newbie, so sorry if this is a trivial question. > > I'm writing a script that collect a list of files and creates a zipfile from > these files. when running it on linux everything works fine, but when I'm > running it on windows I get this error when running the command: > > myZip.write(file) > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa8 in position 10: > ordinal not in range(128) > > the file variable contains: u'C:\\Document and Settings\\haim\etc...'. A unicode file name... Zip format doesn't support unicode file names. > > is there a way to solve this? Only work around. Encode the unicode string using an encoding of your choice. For windows it's probably "mbcs": if isinstance(file_name, unicode): myZip.write(file_name.encode('mbcs')) -- Serge. From jjl at pobox.com Fri Jan 9 09:09:49 2004 From: jjl at pobox.com (John J Lee) Date: Fri, 9 Jan 2004 14:09:49 +0000 (GMT) Subject: win32: internet explorer automation problem Message-ID: [sorry to send this separately from my direct email reply, but the headers implied that Micha's reply wasn't sent to the newsgroup] On Fri, 9 Jan 2004, [iso-8859-2] Micha? ?yli?ski wrote: [...] > I don't think this could work - my piece of code is assumed to be completely > separated from the HTML itself. I don't know what you mean by that. > It just 'watches' the MSIE behaviour and > simulates the user work. And...? > AFAIK opening popup creates another MSIE instance, > so I simply loose the context. That should just be an implementation detail, shouldn't it? > It'd be perfect if external window will be > treated using IHTMLDocument object model, It is. Or at least, I'd be amazed if it weren't. How else would people use popups from JavaScript via the usual window interface? > but window object works according > to this excerpt from MSDN like this: > > 'Typically, the browser creates one window object when it opens an HTML > document. However, if a document defines one or more frames (that is, > contains one or more frame or iframe tags), the browser creates one window > object for the original document and one additional window object for each > frame' And...? There is presumably some way of doing this from JavaScript (right?): so do the same using the interfaces exposed via COM. > So there is no easy way of doing it like > Document.NewWindow.documentelement.outerHTML. There is some ppDisp parameter What's NewWindow, here? John From peter at engcorp.com Mon Jan 19 09:34:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 09:34:57 -0500 Subject: Where to post an article? References: <4f0a9fdb.0401181356.79a1ec87@posting.google.com> Message-ID: <400BEB11.E5572142@engcorp.com> Miki Tebeka wrote: > > I have a little article I'd like to publish. > It's about how to use Python to repidly develop an assembler (2.5 days in my case). > > Can you recommend a site/paper to publish it? Is the focus on Python, or on the "rapid" part? If any agile processes were used, maybe test-driven development, you would of course be best off posting on the extremeprogramming Yahoo mailing list. Else here, as Michael has suggested. -Peter From spam_no_thx_ei0stjo at chl.chalmers.se Sun Jan 4 21:02:29 2004 From: spam_no_thx_ei0stjo at chl.chalmers.se (Jonas) Date: Mon, 05 Jan 2004 03:02:29 +0100 Subject: problem with async chat client in windows Message-ID: Hi, I'm writing a small chat client to learn some python and networking. No problem with the network stuff tho, the problem is when the user should be able to interact and type messages to send. Since I work with windows I can't use the select function (http://www.python.org/doc/current/lib/module-select.html). Maybe it could work if I use two threads? One thread reading keyboard and the other handling network stuff, but I would prefer to leave threads out from this. Any suggestions? thx for your time From jjl at pobox.com Sat Jan 17 15:54:34 2004 From: jjl at pobox.com (John J. Lee) Date: 17 Jan 2004 20:54:34 +0000 Subject: How robust is embedding?? References: Message-ID: <874quuthx1.fsf@pobox.com> "Roberto" writes: > I know that surely depend on how robust is my script just wondering if > anyone is using this in production. Yes, people do. Eg., see recent thread on commercial games that embed Python. Generally, people tent to prefer to extend Python rather than embed it, though. John From crap at crud.com Wed Jan 7 03:19:12 2004 From: crap at crud.com (Moosebumps) Date: Wed, 07 Jan 2004 08:19:12 GMT Subject: Syntax highlighting in .NET IDE Message-ID: <4iPKb.764$K_3.702@newssvr29.news.prodigy.com> Is there a way to have the .NET IDE do syntax highlighting for python? I haven't looked into it that much, but perhaps there is some config file one can download. Don't ask why, I know there are better editors, but I have special circumstances. : ) MB From amy-g-art at cox.net Mon Jan 19 17:12:23 2004 From: amy-g-art at cox.net (Amy G) Date: Mon, 19 Jan 2004 14:12:23 -0800 Subject: Simple question from Python newb... What am I doing wrong? For x, y, z in aTuple: References: Message-ID: <5DYOb.10922$AA6.7084@fed1read03> Thanks for the help. Got it working like a dream now. "Dave Kuhlman" wrote in message news:buhi49$i49rc$1 at ID-139865.news.uni-berlin.de... > Amy G wrote: > > > I have a whole bunch of tuples that look something like this, > > > > aTuple = ('1074545869.6580.msg', 't_bryan_pw at gmcc.ab.ca', 'Your > > one stop prescriptions') > > > > now that I have this I try > > > > for x, y, z in aTuple: > > do something with x > > do something with y > > do something with z > > > > But I am getting the error that there are too many values to > > unpack. If I do... > > The "for" statement processes each item in a sequence object. The > first object in your sequence object (aTuple) is a string. The > string has more that three characters. So, that string cannot be > unpacked into your three variables x, y, and z. > > In contrast, consider the following: > > >>> value = (('aa', 'bb', 'cc'), ('dd', 'ee', 'ff')) > >>> for x, y, z in value: > print 'x:', x > print 'y:', y > print 'z:', z > > x: aa > y: bb > z: cc > x: dd > y: ee > z: ff > >>> > > In this example, the first item in the tuple is itself a tuple > with three items. Therefore, it can be unpacked into the > variables x, y, and z. > > Dave > > -- > http://www.rexx.com/~dkuhlman > dkuhlman at rexx.com From bart_nessux at hotmail.com Sat Jan 24 13:01:40 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Sat, 24 Jan 2004 13:01:40 -0500 Subject: time.time() Message-ID: am I doing this wrong: print (time.time() / 60) / 60 #time.time has been running for many hours if time.time() was (21600/60) then that would equal 360/60 which would be 6, but I'm not getting 6 so I'm not doing the division right, any tips? From astrand at lysator.liu.se Tue Jan 6 11:47:42 2004 From: astrand at lysator.liu.se (Peter Astrand) Date: Tue, 6 Jan 2004 17:47:42 +0100 (CET) Subject: PEP 324: popen5 - New POSIX process module In-Reply-To: <1xqedn2c.fsf@yahoo.co.uk> Message-ID: > I've read the PEP, and I'd like to help with an implementation for > Windows, if no-one else is doing it. Help is always appreciated. I haven't got very far yet. It might be useful to look at http://starship.python.net/~tmick/#process as well (but we should really try to get a smaller code base than this). >Initially, I'll probably use > win32all (or maybe ctypes) but the intention is that longer term the > necessary functions be migrated into a supporting C extension. I like this approach. Ideally, popen5 should work on any Python 2.3+ system with win32all, or using the build-in support, when we have added that. So, when we are writing supporting C code, we should probably keep the interface from win32all. > 1. The preexec_* arguments have no meaning on Windows, where the > low-level functionality is CreateProcess (spawn) rather than > fork/exec. This isn't too crucial, as use of the argument can > either be ignored, or probably better, treated as an error on > Windows. Yes, I've thought of this. I also think that these arguments (preexec_fn and preexec_arg) should be treated as errors. > 2. The method name poll() doesn't seem appropriate in a Windows > context (I don't know how it fits with Unix). Better might be > is_complete() returning True/False, and use returncode to get the > status separately. Yes, perhaps. This needs some thought. > 3. The whole thing about the return code encoding both the exit status > and the signal number is very Unix-specific. Why not split them - > status and signal attributes, and maybe have is_complete() return 3 > possible values - +1 = completed OK, 0 = still running, -1 = died > due to a signal. Perhaps. poll() and wait() is mainly a heritage from popen2. I have no objections to change this, if we can come up with a good and clean solution. Your idea looks interesting, although I've not convinced on the name "is_complete()". Currently, popen5 provides both the unaltered "exit status" (via poll/wait) and the "returncode" (via the .returncode attribute). This is good, because it's makes it easy to migrate from the earlier API. > 5. I don't like the names fromchild, tochild, and childerr. What's > wrong with stdin, stdout, and stderr? OK, stdin is open for write, > and the other two for read, but that's fairly obvious as soon as > you think about it a bit. Here's how I see it: (fromchild, tochild, childerr): + Same as with popen2. Easy to migrate etc. + No risk for confusion when connecting the parents stdout to the childs stdin, for example. (stdin, stdout, stderr): + Nice symmetri with the arguments to the Popen class. + Not as ugly as (fromchild, tochild, childerr) I need input on this one. I'll change this to whatever people likes best. > The biggest issue, though, is that args as a sequence of program > arguments is very Unix-specific. This is a big incompatibility between > Unix and Windows - in Windows, the low-level operation (CreateProcess) > takes a *command line* which is passed unchanged to the child process. > The child then parses that command line for itself (often, but not > always, in the C runtime). In Unix, exec() takes an *argument list*. > If you have a command line, you have to split it yourself, a task > which is usually delegated to /bin/sh in the absence of anything else. > This is hard to handle portably. Oh, I've never thought of this. > I'd suggest that the Windows implementation allow two possibilities > for the "args" argument. If args is a string, it is passed intact to > CreateProcess. That is the recommended, and safe, approach. The shell > is still not invoked, so there's no security issue. If a (non-string) > sequence is passed, the Windows implementation should (for Unix > compatibility) build a command line, using its best attempt to quote > things appropriately (this can never be safe, as different programs > can implement different command line parsing). This is not safe (wrong > answers are the main problem, not security holes), but will improve > portability. I've found some documentation on this. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/progs_12.asp is interesting. It describes how the MS C runtime translates the commandline to an argv array. Let's call this "Algorithm A". When passed a sequence, popen5 should translate this sequence into a string by using algorithm A backwards. This should definitely be implemented in popen5. There are two more cases: 1) Should popen5 support a string argument on Windows? and 2) Should popen5 support a string argument on UNIX? You seems to have made up your mind about case 1, and even thinks that this should be "recommended". I'm not that sure. What about case 2 ? This could be supported by converting the string to an sequence using Algorithm A. One large problem though is that Algorithm A is *not* the same as a typical shell uses. For example, an OS X user might want to do: Popen("ls '/Applications/Internet Explorer'") This won't work if we use Algorithm A. If we extend Algorithm A to support single quotes as well, this will not work as expected on Windows: Popen("echo 'hello'") Sigh. > I agree with Guido's comments on python-dev - this module (popen5 is a > *horrible* name - I'd prefer "process", but am happy if someone comes > up with a better suggestion) should aim to be the clear "best of > breed" process control module for all platforms. The only drawback with "process" is that it is already in use by http://starship.python.net/~tmick/#process. > I hope this is of some use, Indeed. -- /Peter ?strand From rroberts at adobe.com Tue Jan 13 12:07:45 2004 From: rroberts at adobe.com (Read Roberts) Date: Tue, 13 Jan 2004 09:07:45 -0800 Subject: Help in unwrapping a PyObject* returned by an embedded Python function In-Reply-To: References: Message-ID: You have resolved my confusion. The key that I was missing is that " (item)" does not evaluate as a tuple containing "item", that I have to add a comma to force the value to be a tuple with a single element. Somehow I have managed to not notice this, despite some years of Python work. Thank you very much! - Read Roberts >Hello, > >> Thank you taking the time to read and reply. >> >> In fact, I did try all combinations of >> >> in the Python call-back function : >> return myString >> return (myString) > >These 2 are the same, a tuple with length one has a comma in it, like > > myString, > >or (I prefer having brackets around it) > > (myString,) > >The key to making a tuple is the ',' though and not the '(' and ')'. > >> and, in the C calling function, >> >> PyArg_ParseTuple(pyStringResult, "s", myString) >> PyArg_ParseTuple(pyStringResult, "(s)", myString) >> >> Also, the Python documentation (and other working code examples I >> have) indicate that 'PyArg_ParseTuple', unlike BuildValues, always >> assumes the arguments are supplied in a argument tuple, even if there >> is only one argumen. > >PyArg_ParseTuple is intended to unravel arguments given to a function. >These arguments are always stored in a tuple (or in Pythoneese, a >sequence). > >> I speculate that an argument list object, as required by >> PyArg_ParseTuple, is not in fact a simple tuple., and that >> PyArg_ParseTuple cannot be used to parse a regular tuple. Any idea if >> this is correct? > >I would be highly surprised if this was the case. In my experience, >Python is very orthogonal and robust. I expect these things to work. >(I wrote a generator for interfacing Python from C++, and people using >that generator do much more tricky things than what you try to do). > >I did an experiment, and it seems to be working here. > >Things to note: >- PyArg_ParseTuple always needs a tuple as first argument (as you > already stated). >- The return value from Python is passed 'as is', thus 'return "bla"' > gives a string PyObject, 'return ("bla",)' gives a tuple object with 1 > string value, and 'return (("bla",),)' gives a tuple object with 1 > tuple object containing 1 string object. > >Python 'return "bla"' will thus never be parsed by PyArg_ParseTuple, >because it is not a tuple object. > >PyArg_ParseTuple(pyStringResult, "s", myString) >will match 'return ("bla",)' and > >PyArg_ParseTuple(pyStringResult, "(s)", myString) >will match 'return (("bla",),)' > >if myString is of type 'char **' . > >See also the attached example code. >(x.c is a generated (c++) file, manually edited afterwards for the >experiment. I left the generated code (which uses low level API calls) >in, may be it is useful to you if you decide to do things yourself >(and get rid of the tuple requirement from PyArg_ParseTuple in the >process). > > >If you want to parse 'return "bla"' with PyArg_ParseTuple, you will have >to first construct a tuple with 1 element around the return value in C >before handing it over to PyArg_ParseTuple. >(ie something like > tuple==PyTuple_New(1); > PyTuple_SET_ITEM(tuple,0,pyStringResult); > PyArg_ParseTuple(tuple, "s", myString); > > (followed by the usual DECREF, etc). >) > > >Hope this helps. > > >Albert >-- >Unlike popular belief, the .doc format is not an open publically >available format. > >Content-Type: TEXT/PLAIN; charset=US-ASCII; name="x.c" >Content-ID: >Content-Description: >Content-Disposition: attachment; filename="x.c" > >Attachment converted: \:x.c (TEXT/ttxt) (0023E0B6) >Content-Type: TEXT/PLAIN; charset=US-ASCII; name="bla.py" >Content-ID: >Content-Description: >Content-Disposition: attachment; filename="bla.py" > >Attachment converted: \:bla.py (TEXT/ttxt) (0023E0B7) >Content-Type: TEXT/PLAIN; charset=US-ASCII; name="mk" >Content-ID: >Content-Description: >Content-Disposition: attachment; filename="mk" > >Attachment converted: \:mk (TEXT/ttxt) (0023E0B8) -- ----------------------------------------------------------------------------------------- Read K. Roberts rroberts at adobe.com Adobe Systems San Jose TW12 (408)-536-4402 on Weds San Francisco (415) 642-5642 Mon, Tues, Thurs, Fri From graham__fawcett at hotmail.com Fri Jan 30 09:13:43 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 30 Jan 2004 06:13:43 -0800 Subject: RESTful Python References: Message-ID: "SimonW" wrote in message news:... > Can anyone point me to some REST style implementations in Python? Dave Kuhlman has written on RESTful programming with the Quixote Web framework: http://www.rexx.com/~dkuhlman/quixote_index.html -- G From philh at invalid.email.address Fri Jan 23 09:11:53 2004 From: philh at invalid.email.address (phil hunt) Date: Fri, 23 Jan 2004 14:11:53 +0000 Subject: Easibox 0.4.2 released - an archiving program Message-ID: I've just released version 0.4.2 of my Easibox program, which is used to automate the creation of archive files (tar, tar.gz, tgz, tar.bz2 and zip formats), typically for open source projects. New features in Easibox 0.4.2 ============================= Version 0.4.2 adds new features to Easibox: * the "easiunbox" program unpacks archive files. * the main easibox executable now deals better with subdirectories and hidden files. * the --info option has also been enhanced. The "easiunbox" program does the opposite of the "easibox" program: it takes one archive file, and unpacks it to produce its individual component files. You use easiunbox from the command line like this: $ easiunbox somearchive.tar.gz Easiunbox uses the extension (in this case .tar.gz) to work out what sort of archive file it is; then it unpacks it. Easiunbox doesn't do anything you couldn't do from the command line with unzip, tar, gunzip, or bunzip2, but it easier just to remember one command than all of those with all their options. Further information =================== Easibox is written in Python and licensed under the GNU General Public License; see file COPYING (which comes with the distribution) for details. Release notes for the latest version of Easibox: The Easibox home page: Easibox page on Freshmeat: -- "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 mwilson at the-wire.com Tue Jan 27 14:45:13 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 27 Jan 2004 14:45:13 -0500 Subject: Best way to do this? References: <100jg9er3qak890@corp.supernews.com> <40106D38.3010302@void.com> Message-ID: In article <40106D38.3010302 at void.com>, sambo wrote: > >>The "obscure" for/else can help: >> >> >>def get_password (prompt): >> for i in (1, 2, 3): >> password = raw_input (prompt) >> if password == 'mypass': >> return True >> else: >> print "Try Again" >> else: >> print "Too Bad" >> return False >> >Obscure? at least it does something. Well, yeah, but I did put it in quotes. It was some time before I realized that else could go with for. And a bit longer before I got my head around what it did. In retrospect, I would say that for/else would have looked its best in a code snippet, as presented by the original poster. "Cleaning up" the code into a function meant that I could have ditched the "else" and just made the next two statements the last in the function. So: for i in (1, 2, 3): password = raw_input (prompt) if password == 'mypass': good_password = True break else: print "Try Again" else: print "Too Bad" good_password = False ... if good_password: ... >What is the advantage of the following assignment ( a few messages up) > >attempts, password = 3, 'mypass' > >Reading difficulty - at least 3 (no relation, hehe) No particular advantage I can imagine. When two variables are fated to be together throughout the algorithm, then you can help express this with tuple unpacking. The serious reason for tuple unpacking is to make sure that all the value calculations are done before you try the assignments: a, b = b, a or try: v1, v2, v3 = f1(), f2(), f3() except some_exception: ... which makes the assignments to the v's an all-or-nothing operation. Regards. Mel. From mcshane7 at blueyonder.co.uk Wed Jan 7 11:42:30 2004 From: mcshane7 at blueyonder.co.uk (Paul Mcshane) Date: Wed, 7 Jan 2004 16:42:30 -0000 Subject: Newbie question Message-ID: I havn't got a clue what I'm doing so don't treat me like I'm stupid even though I am compared to all of you. What is the basics to programming, you write the code and compile it? I know a few useless web languages so they should come in handy on my way. So you need a compiler to compile your code unless you can do it yourself? Once the program is compiled you can run it as a normal executable? Any answers are appreciated, I just wanna get to know what I'm doing before I start to learn anything. Thanks again, Paul Mc. From JTesser at nbbc.edu Tue Jan 13 08:31:33 2004 From: JTesser at nbbc.edu (Jason Tesser) Date: Tue, 13 Jan 2004 07:31:33 -0600 Subject: wxwindows question Message-ID: <04875CB4331F0240A0AD66F970978651160A77@paul> I am looking into using wxwindows for a gui to develop applications. The Apps need to be cross-platform Mac, Windows, Linux. I work For a bible college and will be developing applications ranging from online Registration to business office software. My question is what is your guys Experiences with wxwindows/python? What is the best tool that is stable I can use? I am looking into using wxDesigner with maybe Wing or Komodo. What do you guys think? From cygnus at cprogrammer.org Thu Jan 29 23:44:47 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Thu, 29 Jan 2004 23:44:47 -0500 Subject: wxPython: images from URLs In-Reply-To: References: <84fc4588.0401280613.771ac07@posting.google.com> Message-ID: <20040130044446.GA30604@mail.theserver.ath.cx> # Why wouldn't you use wxBitmapFromImage? The api docs suggest that using the wxBitmap(image) constructor is better. Besides: this is beside the point -- this code fails: stream = cStringIO.StringIO(imgdata) imgobj = wx.wxImage(stream) The second line raises a TypeError: "String or Unicode type required." -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From ptmcg at users.sourceforge.net Thu Jan 22 16:19:07 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Thu, 22 Jan 2004 21:19:07 GMT Subject: Ordered dictionary? References: Message-ID: "Leif K-Brooks" wrote in message news:leWPb.231$af7.162835 at newshog.newsread.com... > I need to associate a string (key) with an integer (value). A dictionary > would do the job, except for the fact that it must be ordered. I also > need to look up the value for a specific key easily, so a list of tuples > wouldn't work. > If you really need to access the dictionary in sorted key order, is this so difficult? dKeys = d.keys() dKeys.sort() for k in dKeys: # do stuff with k and d[k], such as: print k, "=", d[k] Or if you are worried about updates to d between the time of key retrieval and time of traversal (for instance, if a separate thread were to delete one of the keyed entries), take a snapshot as a list: dItems = d.items() # from here on, you are insulated from changes to dictionary 'd' dItems.sort() # implicitly sorts by key dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer for k,v in dItems: # do stuff with k and v, such as: print k, "=", v # <-- added benefit here of not re-accessing the list by key -- Paul From mwh at python.net Tue Jan 13 05:58:11 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 10:58:11 GMT Subject: Python is far from a top performer according to benchmarktest... References: Message-ID: Robin Becker writes: > this was also my understanding, the difficulty is that humans can't do > the correct analysis in their heads for all, but the most simple > programs. I seem to remember that almost all the compilers I used had > mechanisms for turning off the most aggressive optimisations so if the > card deck suddenly started working with them off then you could try and > figure out what was wrong. Another nastiness was that by putting prints > in you often disrupted the optimisations and the values you got printed > seemed to indicate everything was fine. This last point is true in C, too, particularly with floating point code on x86: turn optimization off or put in debugging prints and then the floats get rounded to C doubles (64 bytes) frequently; don't, and they stay as 80 bit values in the FPU for longer. This can lead to differing behaviour (and thus programmer insanity). Cheers, mwh -- 41. Some programming languages manage to absorb change, but withstand progress. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From martin at v.loewis.de Mon Jan 26 01:11:58 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 26 Jan 2004 07:11:58 +0100 Subject: xrange not hashable - why not? In-Reply-To: References: <20040125144724.GA13741@nl.linux.org> <40145A07.2070906@zephyrfalcon.org> <20040126001145.GB2593@unpythonic.net> Message-ID: Hans Nowak wrote: > (C:\) $ python22 > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> hash(xrange) > 503376880 You shouldn't hash the xrange function, but instance of the xrange type. Regards, Martin From michael at foord.net Mon Jan 26 06:21:15 2004 From: michael at foord.net (Fuzzyman) Date: 26 Jan 2004 03:21:15 -0800 Subject: Dateutils, ConfigObj, StandOut, CGI-News.......... Message-ID: <8089854e.0401260321.3580d924@posting.google.com> A few functions I'm 'making available' (FWIW) and also a new project I'm starting.... http://www.voidspace.org.uk/atlantibots/pythonutils.html Slight updates to ConfigObj and StandOut (simple config parser and flexible output object) - bugfixes and addition of a coupel of features to ConfigObj. Dateutils - These are various functions for dealing with dates (including leap years and so on). Useful especially for situations where you have to arrange appointments. (e.g. second Tuesday of the month etc...) CGI-News - start of a project to give me NNTP access via HTTP (CGI)... I've done proof of concept and got it online - see the subject lines of the last ten posts to comp.lang.python :-) Feedback welcome... 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.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. Building with Python - programming language that rules the world. --- 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 tottinge at indy.rr.com Thu Jan 29 00:04:22 2004 From: tottinge at indy.rr.com (Tim Ottinger) Date: Thu, 29 Jan 2004 05:04:22 GMT Subject: "static" checking References: <160Sb.19106$fo1.10783@newssvr25.news.prodigy.com> Message-ID: On Thu, 29 Jan 2004 04:37:17 +0000, Moosebumps wrote: > I'm wondering what kind of checking I can do on a python program before > running it (besides reading over every line). Check in IDLE isn't bad. I'm not sure what it's running. I know that it runs tabnanny and probably runs pychecker also. Pychecker is quite handy. Tim Ottinger From max at alcyone.com Fri Jan 16 23:27:58 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 16 Jan 2004 20:27:58 -0800 Subject: YA string interpolation and printing idea References: <7x3caf5mga.fsf_-_@ruckus.brouhaha.com> Message-ID: <4008B9CE.CC140EF@alcyone.com> Paul Rubin wrote: > How about adding a string interpolation method ... You already have one with the % operator: "hello %(name)s" % locals() > ... and a some print > methods to strings. Why in the world would you want that? Printing methods go on the things that do work of printing, which are file-like objects, not strings. And, on file-like objects, that method is called `write'. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ It comes from inside, and that's what I consider to be soul music. -- Sade Adu From claird at lairds.com Wed Jan 14 16:00:04 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 14 Jan 2004 21:00:04 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <87brp7agl7.fsf@pobox.com> <7xvfnfmzy8.fsf@ruckus.brouhaha.com> <878yka2sze.fsf@pobox.com> Message-ID: <100bbekd61fbl53@corp.supernews.com> In article <878yka2sze.fsf at pobox.com>, John J. Lee wrote: . . . >Not sure what the goals were, but I'm not sure they were to compete >with Netscape and IE. CNRI funding -- "R" for research -- seems to . . . Certainly not the *original* goal, because Grail antedated those latecomers. -- Cameron Laird Business: http://www.Phaseit.net From llothar at web.de Thu Jan 1 17:33:31 2004 From: llothar at web.de (Lothar Scholz) Date: 1 Jan 2004 14:33:31 -0800 Subject: Rekall Binary References: <8a27e309.0312310529.3c1f43a8@posting.google.com> <8a27e309.0401010633.20271486@posting.google.com> Message-ID: <6ee58e07.0401011433.5ce91221@posting.google.com> > > How strong a buisness model is GPL software is a relative issue. If > you mean making the kind of money that software developer houses used > to make in the BOS (Before Open Source) days then it isn't. But you > just may be able to support your family on it and pay the rent (and > maybe even buy a modest house if you are really successful). I see > nothing wrong with that. This are hard times you know. "The Kompany" wasn't able to pay the developer for month with non GPL software, why do you think they can do it with GPL now (if you say yourself that it will be less then in the BOS days) ? In fact i believe that a main stream desktop tool like "Rekall" has no future when it must live on support contracts only. If you need support then the product has an error, but i don't want to use errounous software. This is the reason why GPL does not work for a lot of software products. From jcarlson at nospam.uci.edu Fri Jan 30 15:30:22 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 12:30:22 -0800 Subject: PEP 327: Decimal Data Type In-Reply-To: References: Message-ID: > (In my dreams) I want to "float" to be decimal. Always. No more binary. > Maybe in ten years the machines will be as fast as is needed to make this > posible. Or it'll be implemented in hardware. > > Anyway, until then I'm happy having decimal floating point as a module. In my dreams, data is optimally represented in base e, and every number is represented with a roughly equivalent amount of fudge-factor (except for linear combinations of the powers of e). Heh, thankfully my dreams haven't come to fuition. While decimal storage is useful for people and money, it is arbitrarily limiting. Perhaps a generalized BaseN module is called for. People could then generate floating point numbers in any base (up to perhaps base 36, [1-9a-z]). At that point, having a Money version is just a specific subclass of BaseN floating point. Of course then you have the same problem with doing math on two different bases as with doing math on rational numbers. Personally, I would more favor a generalized BaseN class than just a single Base10 class. - Josiah From max at alcyone.com Thu Jan 22 22:15:33 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Jan 2004 19:15:33 -0800 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: <401091D5.EFA41F7@alcyone.com> "David M. Cooke" wrote: > Or, expressing the idea that they're the ends of a number line: > > PosInf, NegInf > PosInfinity, NegInfinity > PositiveInfinity, NegativeInfinity > > If IEEE floating point was done correctly everywhere, I'd say make > them the corresponding floating-point constants (Inf+ and Inf-). The "if" conditional here is bad. Naming something "infinity" if it weren't the IEEE floating point constants as well would be seriously misleading. After all, this _isn't_ a number line since we're talking about comparing arbitrary objects. > Or, > FreakingHuge, FreakingHugeTheOtherWay Don't be silly; that latter one should be FreakingUnhuge :-). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Things are as they are because they were as they were. -- Thomas Gold From BrenBarn at aol.com Wed Jan 28 13:25:58 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 28 Jan 2004 18:25:58 GMT Subject: Curious string behavior References: Message-ID: mark wrote: > address2 = ' ' > line = 'function, dealer, type, firstname, lastname, vin, blank' > print 'Address2 Type (first check): ', type(address2) > function, dealer, type, firstname, lastname, vin, blank = > # ^ LINE ABOVE CONTAINS ERROR > string.split(line, ',') > print 'Address2 type (second check): ', type(address2) > Address2 Type (first check): > Address2 type (second check): > Traceback (most recent call last): > File > "C:\PROGRA~1\Python\lib\site-packages\Pythonwin\pywin\framework\scri > ptut ils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Program Files\Python\test1.py", line 7, in ? > print 'Address2 type (second check): ', type(address2) > TypeError: 'str' object is not callable In the marked line, you assign a string to a variable called "type". This means that you overwrote your reference to the type function that you are trying to use in type(address2). When you "call" type(address2) you are now trying to call the string which you have assigned to the name "type". Use a different name for your variable (a name that the library doesn't use) and you will be fine. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From nuffsaid at phreaker.net Sat Jan 31 17:21:38 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 31 Jan 2004 23:21:38 +0100 Subject: wxPython documentation References: <401c25a3$0$11357$636a55ce@news.free.fr> Message-ID: On Sat, 31 Jan 2004 23:01:07 +0100, Olivier wrote: > Where could I find a good documentation about wxPython (a documentation > which is not for C++ !!!) You will find a lot of stuff (including a tutorial) on the wxPython wiki: http://wiki.wxpython.org/ Moreover, the source code of the demos coming with wxPython is very helpful for many people. But don't give up on the C++ documentation; you will need it when you want to do more advanced stuff with wxPython (and it isn't really hard to translate from C++ to Python in that case). HTH / Nuff From elainejackson7355 at home.com Sat Jan 31 00:23:24 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 31 Jan 2004 05:23:24 GMT Subject: newbie py2exe difficulty References: Message-ID: Thanks for your help. Everything's cool now. "Mike C. Fletcher" wrote in message news:mailman.1028.1075452591.12720.python-list at python.org... | Open a command-prompt window. (You'll find the command-prompt's icon in | Start|Programs or Start|Programs|Accessories, it may be called "MSDOS | Prompt".) | | Switch to the directory where your setup.py file is (use the shell's cd | command to move between directories, you can use the "dir" command to | see what files are in the current directory to confirm that the setup.py | file is present), | | P:\>cd OpenGLContext | | P:\OpenGLContext>dir setup.py | Volume in drive P is DATASTORE | Volume Serial Number is 74A4-1C80 | | Directory of P:\OpenGLContext | | 27/01/2004 06:01p 3,853 setup.py | 1 File(s) 3,853 bytes | 0 Dir(s) 11,575,771,136 bytes free | | *then* run: | | python setup.py py2exe --help | | from that command prompt. You may need to specify the full path to | python if you haven't added your python installation directory to the | path, something like: | | P:\OpenGLContext>c:\bin\lang\py23\python.exe setup.py build | running build | running build_py | running build_ext | | depending on where you installed python. | | HTH, and good luck, | Mike | | | Elaine Jackson wrote: | | >Hi. I'm trying to use py2exe (http://starship.python.net/crew/theller/py2exe/) | >in Windows 98. I copied the necessary files into my Python23 directory (where I | > | > | ... | | >My problem is that, when I attempt to follow the first instruction (details | >follow), it opens a DOS window that may indeed display all available | >command-line flags to the py2exe command, but isn't very helpful because it | >immediately disappears. (In fact I'm really not sure what a command-line flag | >is, or what I'm supposed to do with it.) I've also tried simply running | >setup.py: the DOS window disappeared immediately and there was no 'dist' | >directory in evidence. | > | > | ... | | _______________________________________ | Mike C. Fletcher | Designer, VR Plumber, Coder | http://members.rogers.com/mcfletch/ | | | From peter at engcorp.com Wed Jan 21 09:20:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Jan 2004 09:20:32 -0500 Subject: Reading BLOB References: <400e3510.18785312@news.eunet.be> Message-ID: <400E8AB0.9D4DEB79@engcorp.com> Johan Vervoort wrote: > > How can I read a binary value from a blob via ODBC (Microsoft VFP > driver-win32all)? The value seems to be truncated at the first '\0' Maybe posting a very small snippet of code which reproduces the problem would help get you responses. I can't help, as I don't know what VFP driver-win32all is, but if there was example code I might be able to see the problem anyway, and others more expert in this area would likely see the problem right away. -Peter From skip at pobox.com Fri Jan 9 11:12:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 9 Jan 2004 10:12:06 -0600 Subject: Database interfacing In-Reply-To: <3FFECC82.20305@fibrespeed.net> References: <3FFECC82.20305@fibrespeed.net> Message-ID: <16382.53974.902208.708653@montanaro.dyndns.org> Michael> I'm working with databases (MySQL primarily) more and more with Michael> Python, and having used PERL in the past for similar work, I'm Michael> wondering if there are good tools for doing 'intelligent' Michael> selects/inserts to/from dictionaries, etc. Perhaps you'd be interested in object-relational mappers. Search for "relation" on PyPi's database topics page: http://www.python.org/pypi?:action=browse&asdf=256 Slo[ From chouyiyu at hotmail.com Tue Jan 13 16:10:06 2004 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Tue, 13 Jan 2004 21:10:06 +0000 Subject: Build vtk classes - HELP !!! Message-ID: Hi all python users, I am trying t build my own vtk classes and use them in python but I encounter some problems. I tried to change the example a little bit in VTK/Example/Build/vtkMy/Common/ // vtkBar.h #ifndef __vtkBar_h #define __vtkBar_h #include "vtkObject.h" #include "vtkmyCommonWin32Header.h" class VTK_MY_COMMON_EXPORT vtkBar : public vtkObject { public: static vtkBar *New(); vtkTypeRevisionMacro(vtkBar,vtkObject); int inData; int outData; protected: vtkBar() ; ~vtkBar() ; private: vtkBar(const vtkBar&); // Not implemented. void operator=(const vtkBar&); // Not implemented. }; #endif // vtkBar.cxx #include "vtkBar.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkBar, "$Revision: 1.3 $"); vtkStandardNewMacro(vtkBar); vtkBar::vtkBar() { this->inData = 0; this->outData = 0; } vtkBar::~vtkBar() { } ............................................................................................................................... Under /VTK/Example/Build/vtkMy I ran : ccmake . Press "c" twice, then press "g" Enter : make Go to /vtkMy/bin Ran : python >>> from vtk import * >>> from libvtkmyCommonPython import * >>> A = vtkBar() >>> A.inData Then I got the following error message : AttributeError: inData What's wrong with my procedure.....?????? Please help me !!! Thanks a lot !! Best, YY _________________________________________________________________ ????????MSN ?????? Match.com ???????????????? ? http://match.msn.com.tw From newz at rekon.org.NOSPAM Sat Jan 17 20:40:19 2004 From: newz at rekon.org.NOSPAM (Wil Schultz) Date: Sat, 17 Jan 2004 17:40:19 -0800 Subject: Best way to do this? In-Reply-To: References: <100jg9er3qak890@corp.supernews.com> Message-ID: <100jopnkursdf5f@corp.supernews.com> Well, not quite that far yet but apparently there are a few different way's. Mine of course being the most primitive! ;) Thank you both! Wil my 2? "When everything seems to be going well, you have obviously overlooked something." Jeff Epler wrote: > def getpass(password, count=3): > for i in range(count): > p = raw_input("Password: ") > if p == password: return 1 > return 0 > > No need to initialize count to 0 and use a while loop, use a "for" loop > instead. No need to initialize password above the loop (and if you had > to, use None instead of "null"), and no need to set count to 3 when the > correct password is entered---just use return or break. > > Jeff > From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 21 21:59:47 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 13:49:47 +1050 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: <400F3D90.2176087B@alcyone.com> Message-ID: On Wed, 21 Jan 2004 19:03:44 -0800, Erik Max Francis wrote: > You are iterating over a mutable sequence while you are mutating it. > That is a big no-no. Got a pointer to somewhere that says so? Or at least describes the expected behaviour for iteration over mutable types? -- \ "Love is the triumph of imagination over intelligence." -- | `\ Henry L. Mencken | _o__) | Ben Finney From none at none.com Tue Jan 6 15:25:11 2004 From: none at none.com (Derek) Date: Tue, 6 Jan 2004 15:25:11 -0500 Subject: Iterating over a binary file Message-ID: Pardon the newbie question, but how can I iterate over blocks of data from a binary file (i.e., I can't just iterate over lines, because there may be no end-of-line delimiters at all). Essentially I want to to this: f = file(filename, 'rb') data = f.read(1024) while len(data) > 0: someobj.update(data) data = f.read(1024) f.close() The above code works, but I don't like making two read() calls. Any way to avoid it, or a more elegant syntax? Thanks. From premshree_python at yahoo.co.in Fri Jan 9 11:22:06 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Fri, 9 Jan 2004 16:22:06 +0000 (GMT) Subject: Py Website Message-ID: <20040109162206.71702.qmail@web8307.mail.in.yahoo.com> Thought I'd let you'll know about the Python section that I maintain at my website: http://premshree.resource-locator.com/python.htm -Premshree ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From swalters_usenet at yahoo.com Wed Jan 14 04:27:41 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Wed, 14 Jan 2004 09:27:41 GMT Subject: Inserting while itterating References: Message-ID: | Thomas Guettler said | > Hi, > > Simple excerise: > > You have a sorted list of integers: > l=[1, 2, 4, 7, 8, 12] > > and you should fill all gaps: > > result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > How would you code this? > > Constrain: The original list should be changed, don't create a copy. > > thomas The word "exercise" raises my suspicions that this is a homework problem. You know you only cheat yourself when you ask others to do your homework. #simple, but only works for ints l = [1, 2, 4, 7, 8, 12] l = range(l[0],l[-1]+1) print l #naive, but broader #only use when sorting is cheap. l = [1, 2, 4, 7, 8, 12] #iterate through each possible item. for x in range(l[0],l[-1]+1): if x not in l: l.append(x) l.sort() print l #missing-merge: more general pattern #useful for strange, hard to sort data: #where sorting is expensive, #but comparison is cheap. l = [1, 2, 4, 7, 8, 12] missing = [] #iterate through each possible item for x in range(l[0], l[-1]+1): #build a list of each missing item. if x not in l: missing.append(x) #merge the two lists for x in range(0, len(l) + len(missing) - 1): if l[x] > missing[0]: l = l[:x] + missing[0:1] + l[x:] missing.pop(0) print l Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From tommie at iae.nl Mon Jan 26 20:38:04 2004 From: tommie at iae.nl (tommie at iae.nl) Date: Tue, 27 Jan 2004 02:38:04 +0100 (CET) Subject: ***SPAM?*** vvpezyy In-Reply-To: <20040127013755.5612C2F19F@relay3.vianetworks.nl> References: <20040127013755.5612C2F19F@relay3.vianetworks.nl> Message-ID: <20040127013804.91EB92AA62@mailhub4.vianetworks.nl> This account will cease to exist on: Dit account wordt opgeheven op: 1 sep 2003 Thomas. From vjovanovic at houston.rr.com Sat Jan 3 00:25:11 2004 From: vjovanovic at houston.rr.com (Vojin Jovanovic) Date: Sat, 03 Jan 2004 05:25:11 GMT Subject: problem using pickle / cPickle References: <3FF5CB56.4000309@caltech.edu> Message-ID: Try it in Python 2.2. "Jesse Bloom" wrote in message news:3FF5CB56.4000309 at caltech.edu... > I keep running into a problem when I use pickle or cPickle to unpickle a > python object I have serialized from the database. I read the string > for the serialized object. Apparently I am missing an argument? Here's > what happens: > > cPickle.loads(s) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: __new__() takes exactly 2 arguments (1 given) > > Same thing happens when I use pickle: > > >>> pickle.loads(s) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.3/pickle.py", line 1394, in loads > return Unpickler(file).load() > File "/usr/local/lib/python2.3/pickle.py", line 872, in load > dispatch[key](self) > File "/usr/local/lib/python2.3/pickle.py", line 1097, in load_newobj > obj = cls.__new__(cls, *args) > TypeError: __new__() takes exactly 2 arguments (1 given) > From michi.goettsche at gmx.de Thu Jan 1 09:56:09 2004 From: michi.goettsche at gmx.de (Michael_Goettsche) Date: Thu, 1 Jan 2004 15:56:09 +0100 Subject: Uploading a file with ftplib In-Reply-To: References: Message-ID: <200401011556.09842.michi.goettsche@gmx.de> On Thursday 01 January 2004 15:14, Rene Pijlman wrote: > Michael_Goettsche: > >can anybody please tell me how to upload it properly? > > This is a snippet from one of my scripts, that works fine: > > ftp = ftplib.FTP(Hostname,Username,Password) > ftp.cwd(WorkingDirectory) > ftp.storbinary("STOR " + RemoteZipFile, file(LocalZipFile, "rb")) > ftp.quit() > > -- > Ren? Pijlman thank you, works perfect. regards, Michael. From jjl at pobox.com Fri Jan 23 11:37:08 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 16:37:08 +0000 Subject: Web board with mailing-list mirror? [was: Re: "Lecture Preparation"...] References: <1010a26.0401212246.3cac7d06@posting.google.com> Message-ID: <87r7xqbozv.fsf_-_@pobox.com> aahz at pythoncraft.com (Aahz) writes: [...] > While I'm generally interested in such discussions, I won't be > participating because I hate web boards. Me too. > I vastly prefer netnews, with > grudging use of e-mail lists. [...] Surely somebody has written a web board that'll let you subscribe to a mailing list? (or even read a public IMAP mailbox -- not very popular, though) Anybody know of one? John From NAIGIMSESRIMAIL at gims.com Fri Jan 30 10:37:59 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 30 Jan 2004 17:37:59 +0200 Subject: ALERT - GroupShield ticket number OB71_1075477076_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: latex-bugs at latex-project.org Sent: 154799872,29615943 Subject: Re: hello 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: 1797 bytes Desc: not available URL: From marco at bubke.de Tue Jan 20 07:48:42 2004 From: marco at bubke.de (Marco Bubke) Date: Tue, 20 Jan 2004 13:48:42 +0100 Subject: Pyrex and numarray References: Message-ID: thx but I need to extract the array to a float*. I do NA_OFFSETDATA(NA_InputArray(odata, tFloat64, C_ARRAY)) but this isn't working because Pyrex says he can't storage it. There is a unknown size. I only need the pointer tp a C array of floats. Thats all. ragards Marco From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jan 15 08:07:20 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 15 Jan 2004 14:07:20 +0100 Subject: Newbie: how to write modules without C In-Reply-To: References: Message-ID: <40069088$0$327$e4fe514c@news.xs4all.nl> Maarten van Reeuwijk wrote: > 1) Is it necessary to resort to C when writing modules or can you use normal > Python? Absolutely not! I'm wondering what you've read that made you think this. That text should be rewritten to be more clear: you write *extension modules* in C (or C++). 'normal' modules are just Python files. For example: Python's standard library is hundreds of modules written in pure Python... (and also a bunch of extension modules written in C, for various reasons). > 2) How do you load a Python script into a python session? Not sure what you mean here? What's wrong with: >>> import MaartensNiceModule ? > 3) Can various python scripts be combined into a module? Perhaps you're confusing the concepts of 'script', 'module' and 'package'. A python 'module' is just a script actually. A 'package' is a special directory that can contain lots of modules and sub packages. A Python module can contain lots of classes, function definitions, and other code. It is not constrained to a single class implementation like for instance Java has. It's closer to the way C/C++ work with their source files. And Python packages are related to C++ namespaces, but more powerful. I strongly recommend you read chapter 6, Modules, of the tutorial: http://www.python.org/doc/current/tut/node8.html Good luck! --Irmen de Jong. From theller at python.net Tue Jan 27 04:57:44 2004 From: theller at python.net (Thomas Heller) Date: Tue, 27 Jan 2004 10:57:44 +0100 Subject: Py2exe and WMI module References: Message-ID: Tim Golden writes: > While I'm on the subject, is there anything I can offer to do within > the wmi module itself which will make it easier to py2exe it? It > doesn't look like it, but I thought I'd make the offer. > In wmi.py probably. If it turns out that py2exe'ing the wmi module is difficult, you could create a page somewhere in the py2exe wiki: http://starship.python.net/crew/theller/moin.cgi/Py2Exe Thomas From ketulp_baroda at yahoo.com Thu Jan 15 00:51:39 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 14 Jan 2004 21:51:39 -0800 Subject: what is best for web development?? References: <87oet9grqy.fsf@blakie.riol> <6ee58e07.0401140638.672d50a7@posting.google.com> <100b4qoeeeq7d57@corp.supernews.com> Message-ID: We're not considering a self-contained Web application, including the Web server itself. The Web server could be any Apache , IIS or the python ones. It depends on the customer. claird at lairds.com (Cameron Laird) wrote in message news:<100b4qoeeeq7d57 at corp.supernews.com>... > In article <6ee58e07.0401140638.672d50a7 at posting.google.com>, > Lothar Scholz wrote: > >graham__fawcett at hotmail.com (Graham Fawcett) wrote in message > >news:... > >> Wilk wrote in message news:<87oet9grqy.fsf at blakie. > > >> If it has to be a one-shot install, I would suggest a Web server > >> written in Python -- Medusa or Twisted, probably -- that you could > >> bundle with your Python app. Find a Web app framework that (a) works > >> on Medusa or Twisted and (b) has the templating features you > >> require/desire. > > > >I would not recommend this. A distribution with an own apache server > >seems to be the best. It is easy to hide the setup and the customers > >know that there is a good working technologie behind the scenes. And > >it can be managed by every normal administrator. This is a very > >important point for larger customers. > > > >I would recommend webware+Fun Form Kit+cheeta together with apache. > > I'm unsure what you're recommending. We're considering a self-contained > Web application, including the Web server itself. Are you proposing: > 1. An installer which does a conventional Apache > installation, except with enough stuff confi- > gured so it comes up in a safe state, PLUS > a separate installation segment just for the > Python-based part; or > 2. A custom installer which knows internal details > of both Apache and the Python-based application? > > What advantage do you see for either of these over the pure-Python ap- > proach suggested above? Is your point that customers feel more > comfortable with "Apache inside"? From jcarlson at uci.edu Tue Jan 20 21:27:55 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 18:27:55 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <20040120181009.060C.JCARLSON@uci.edu> Message-ID: <20040120182610.060F.JCARLSON@uci.edu> > Personally, I would suggest: > os.startfile("c:\\path\\help.chm") > > It is documented to do exactly what you want it to do, open up the help > file with the microsoft help file viewer. That is, if .chm files are associated with the microsoft help file viewer. Technically os.system("c:\\path\\help.chm") and os.system("start c:\\path\\help.chm") also work, though are less intuitive. - Josiah From francisgavila at yahoo.com Mon Jan 12 14:47:07 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 12 Jan 2004 14:47:07 -0500 Subject: Using switches with exec? References: Message-ID: <1005ufs36m9n5fd@corp.supernews.com> Premshree Pillai wrote in message ... > --- "Diez B. Roggisch" wrote: > >> I need to run a Python program dynamically within >> > another program. I am using exec for the purpose. >> Is >> > there a way to pass parameter switches to exec? >> >> You can pass a globals-dictionary to exec, which can >> hold the switches >> values. >> >> Diez >> -- >> http://mail.python.org/mailman/listinfo/python-list > >Could you please elucidate with a sample script. >Suppose I need to pass the switch "-w" to the >dynamically loaded code (using eval()/exec()). >Any help is appreciated. > >-Premshree > What do you mean by a parameter switch? You mean a command-line switch? If this is what you mean, it seems you're mixing concepts. If you run the Python program as an external program, just do so using os.system or os.popen or such--the fact that it's written in Python makes no difference, and exec/execfile is not involved. os.system('python mypythonprg -w'), for example. If you want to have Python code from one program exposed to another, the best approach is to write a module which can be used either as a library or a stand-alone program. The idiom is to put something like this: if __name__ == '__main__': main() at the bottom of your code. When you run this file alone, main() will be executed; if you import the file, it won't be. If you really need to execute external Python code internally (and it's very rare and special circumstances where you'd want to), use execfile(). Now, if you're using execfile, it is unlikely that the code you're running would use command line switches--this implies that it's a stand-alone program, in which case you should either be running it externally (as in first solution above) or importing it, and providing a mechanism to use it programmatically. This is why I say you seem to be mixing concepts. That said, command line arguments are available via sys.argv, and this is most likely how the external program accesses them. You can modify sys.argv before execfile(). This, however, is a mess, because you clobber the global sys.argv of the original program. You need to somehow redirect any access to sys.argv by the script. You can do so like this: >>> sys.argv [''] >>> class ShadowObject(object): ... def __init__(self, shadowed, **override): ... """Shadow attr access to shadowed with override.""" ... self.__dict__.update(override) ... self.shadowed = shadowed ... def __getattr__(self, attr): ... """Called only if attr was not in override.""" ... return getattr(self.shadowed, attr) ... >>> exec '''print sys.argv #We get the right one? ... print sys.getdefaultencoding() #Make sure we're shadowing. ... sys.argv = sys.argv[-1:] #Test reassignments. ... print sys.argv ... ''' in globals(), {'sys':ShadowObject(sys, argv=['progname','-w'])} ['progname', '-w'] latin-1 ['-w'] >>> sys.argv # the real sys.argv is unchanged [''] Don't do this. It's almost certainly not the best way to do what you want. Why don't you tell us your broader task, and maybe we can suggest something more Pythonic? -- Francis Avila From andymac at bullseye.apana.org.au Sun Jan 25 19:50:59 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 26 Jan 2004 11:50:59 +1100 (EST) Subject: xrange not hashable - why not? In-Reply-To: <20040126105606.F83014@bullseye.apana.org.au> References: <20040125144724.GA13741@nl.linux.org> <20040126105606.F83014@bullseye.apana.org.au> Message-ID: <20040126114346.B83462@bullseye.apana.org.au> On Mon, 26 Jan 2004, Andrew MacIntyre wrote: > On Sun, 25 Jan 2004, Gerrit Holl wrote: > > > why is an xrange object not hashable? > > xrange() returns an iterator. iterators seem universally unhashable, > probably because they can't be deemed "concrete", though I can't find > anything in the 2.3.3 docs about this - perhaps the relevant PEPs might. Hmmm... part fact, part BS on my part. Prior to 2.3, xrange() returned an object that implemented lazy item access, which didn't have explicit hash support. With 2.3, xrange() began returning an iterator, which is hashable (as others have pointed out). -- 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 theller at python.net Fri Jan 16 11:35:30 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 17:35:30 +0100 Subject: Very strange unicode behaviour References: Message-ID: Syver Enstad writes: > Here's the interactive session > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> ord('\xe5') > 229 >>>> '\xe5'.find(u'') > -1 >>>> 'p\xe5'.find(u'') > UnicodeError: ASCII decoding error: ordinal not in range(128) >>>> 'p\xe4'.find(u'') > -1 >>>> 'p\xe5'.find(u'') > UnicodeError: ASCII decoding error: ordinal not in range(128) >>>> print '\xe5' > ? >>>> print 'p\xe5' > p? >>>> 'p\xe5' > 'p\xe5' >>>> def func(): > ... try: > ... '\xe5'.find(u'') > ... except UnicodeError: > ... pass > ... >>>> func() >>>> for each in range(1): > ... func() > ... > UnicodeError: ASCII decoding error: ordinal not in range(128) >>>> > > It's weird that \xe5 throws and not \xe4 but even weirder that the > exception is not cleared so that the loop reports it. > > Is this behaviour the same on Python 2.3? No, it behaves correctly as it seems: 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. >>> ord('\xe5') 229 >>> '\xe5'.find(u'') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) >>> '\xe4'.find(u'') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) >>> Thomas From peter at engcorp.com Thu Jan 15 14:59:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Jan 2004 14:59:56 -0500 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> Message-ID: <4006F13C.7D432B98@engcorp.com> Laurent Therond wrote: > > Consider: > --- > from cStringIO import StringIO > > def bencode_rec(x, b): > t = type(x) > if t is str: > b.write('%d:%s' % (len(x), x)) > else: > assert 0 The above is confusing. Why not just do def bencode_rec(x, b): assert type(x) is str b.write(.....) Why the if/else etc? > def bencode(x): > b = StringIO() > bencode_rec(x, b) > return b.getvalue() > > --- > Now, if I write bencode('failure reason') into a socket, what will I get > on the other side of the connection? This is Python. Why not try it and see? I wrote a quick test at the interactive prompt and concluded that StringIO converts to strings, so if your input is Unicode it has to be encodeable or you'll get the usual exception. > a) A sequence of bytes where each byte represents an ASCII character Yes, provided your input is exclusively ASCII (7-bit) data. > b) A sequence of bytes where each byte represents the UTF-8 encoding of a > Unicode character Yes, if UTF-8 is your default encoding and you're using Unicode input. > c) It depends on the system locale/it depends on what the site module > specifies using setdefaultencoding(name) Yes, as it always does if you are using Unicode but converting to byte strings as it appears StringIO does. -Peter From ebolonev at punkass.com Mon Jan 5 20:04:13 2004 From: ebolonev at punkass.com (Egor Bolonev) Date: Tue, 6 Jan 2004 11:04:13 +1000 Subject: python and LAN References: Message-ID: Hello, Thomas! You wrote on Mon, 05 Jan 2004 16:09:42 +0100: TG> What operating system do you use? winXP, LAN consists of ~300 pc's, 5 segment, Iam not admin TG> Some systems answer ping to the TG> broadcast address, but not all Is there any modules for LAN in python? How to get list of pc's now working? ... >>> f=open('\\\\DELTA\\upload\\sobaka.swf','rb') >>> s=f.read() >>> print s CWS?? >>> import glob >>> glob.glob('\\\\delta\\upload\\*') ['\\\\delta\\upload\\RAdmin', '\\\\delta\\upload\\Norton AntiVirus 2002', '\\\\delta\\upload\\htm', '\\\\delta\\upload\\K&M', '\\\\delta\\upload\\AVP', '\\\\delta\\upload\\From DemoN', '\\\\delta\\upload\\From Merkava_Mk4 \xec\xf3\xeb\xfc\xf2\xfb', '\\\\delta\\upload\\Max Payne 2 Bonus', '\\\\delta\\upload\\Demoscene', '\\\\delta\\upload\\3DAnalyze', ... With best regards, Egor Bolonev. E-mail: ebolonev at rin.ru From mnations at airmail.net Mon Jan 26 20:09:49 2004 From: mnations at airmail.net (Marc) Date: 26 Jan 2004 17:09:49 -0800 Subject: Confusing problem between Tkinter.Intvar() and self declared variable class Message-ID: <4378fa6f.0401261709.664ca799@posting.google.com> Hi all, I was using Tkinter.IntVar() to store values from a large list of parts that I pulled from a list. This is the code to initialize the instances: def initVariables(self): self.e = IntVar() for part, list in info.masterList.items(): obj = setattr( self.e, part, IntVar() ) That allowed me to save bundles of info without having to create another large dictionary or list. I was using the variable in entry boxes to store the amount of parts ordered: Entry( cscGroup.interior(), width=3, textvariable = getattr(self.e, part), text=e.get()).grid(row=x, column=2, padx=4 ) However, I ran into problems when I tried to pickle the instances in order to recall them later. To fix that problem I created my own simple data class that allowed me to save the data the same way while also having the ability to pickle it: class DataVar: def __init__(self): self.data = 0 self.partName = "" def set(self, value): self.data = value def get(self): return self.data But I just discovered another problem. It doesn't appear to hold data the same way. The information appeared global when it was IntVar(). Now when I go outside the class that set up the entry boxes, the information does not appear to be in DataVar. I print out the info the following way: def printValues(self): for part, list in info.masterList.items(): e = getattr(self.e, part) print str(part) + " --->" + str( e.get() ) This function is in the same class that initialized the DataVar variables and also that called the class that setup the window to enter the amount of parts. When I call that class I pass in the variable in the following way: spares = Spares(self.master, self.e) So obviously there's something about Tkinter that causes the info to be global. But even though the DataVar class is an independent class, for some reason the information is not being maintained. Does anyone have any idea why this is happening and how to fix it? Thanks ahead of time, Marc From RAV at ns.artphila.com Wed Jan 28 03:31:07 2004 From: RAV at ns.artphila.com (RAV at ns.artphila.com) Date: Wed, 28 Jan 2004 10:31:07 +0200 Subject: RAV AntiVirus scan results Message-ID: <200401280831.i0S8V7Lr005568@ns.artphila.com> RAV AntiVirus for Linux i686 version: 8.3.2 (snapshot-20020108) Copyright (c) 1996-2001 GeCAD The Software Company. All rights reserved. Registered version for 2 domain(s). Running on host: ns.artphila.com ----------------------- RAV Antivirus results ----------------------- The infected file was saved to quarantine with name: 1075278667-RAVi0S8V0Lr005555. The file (part0002:file.zip)->file.pif attached to mail (with subject:MAIL DELIVERY SYSTEM) sent by python-list at python.org to phila at artphila.com, is infected with virus: Win32/Mydoom.A at mm. Cannot clean this file. Cannot delete this file (most probably it's in an archive). The mail was not delivered because it contained dangerous code. ------------------------ this is a copy of the e-mail header: Scan engine 8.11 () for i386. Last update: Tue Jan 27 05:03:51 2004 Scanning for 89279 malwares (viruses, trojans and worms). To get a free 60-days evaluation version of RAV AntiVirus v8 (yet fully functional) please visit: http://www.ravantivirus.com From richard.philips at ua.ac.be Wed Jan 28 11:21:54 2004 From: richard.philips at ua.ac.be (Richard Philips) Date: Wed, 28 Jan 2004 17:21:54 +0100 Subject: Deprecated modules Message-ID: <4017E1A2.9090103@ua.ac.be> Hi, How can I look for deprecated standard library modules in my scripts WITHOUT executing these scripts? Regards, Richard -- ================================================================ Dr. Richard PHILIPS University of Antwerp Systemmanager Anet Phone: +32 3 820.21.53 Fax: +32 3 820.21.59 GSM: 0478/36.76.28 Email: Richard.Philips at ua.ac.be ================================================================ From bucodi_no_spam at ahoo.fr Mon Jan 12 12:17:30 2004 From: bucodi_no_spam at ahoo.fr (Rony) Date: Mon, 12 Jan 2004 18:17:30 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Group : comp.lang.python > I have now free time and money to do what I want :-) > ..... If I would have enough money and free time to do what I want, I would *stop* programming.... But if you insist on wanting to write software, Python is a **very** good choice. -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi_no_spam at yahoo.fr (delete _no_spam) / | www.bucodi.com - My work \ www.ifrance/karamusic -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From claird at lairds.com Fri Jan 23 12:36:50 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 23 Jan 2004 17:36:50 -0000 Subject: Tkinter color names/codes References: Message-ID: <1012mti57i1nsa5@corp.supernews.com> In article , Jeff Seale wrote: >Nuff Said wrote in . . . >> http://wiki.tcl.tk/8606 >> - list with all named colors in Tcl/Tk >> >> http://wiki.tcl.tk/colors >> - W3C names, hex codes and Tcl/Tk names for the >> 16 HTML 3.2 colors (i.e. the basic VGA set) >> >> HTH / Nuff >> > >Is it possible to translate all those colors into their #hex combinations? >The ones I know about already are Red #FF0000, Yellow #FFFF00, Green # >00FF00, Cyan #00FFFF, Blue #0000FF, Magenta #FF00FF, White #FFFFFF and >Black #000000. I'm not sure what you're asking. The references do just that, in several variations, although they're coded in Tcl/Tk, rather than Tkinter. Do you realize you can type $ python Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> l = Tkinter.Label() >>> l.winfo_rgb("red") (65535, 0, 0) >>> yourself? -- Cameron Laird Business: http://www.Phaseit.net From nospam-deets at web.de Thu Jan 29 11:18:36 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Thu, 29 Jan 2004 17:18:36 +0100 Subject: Get number of iteration References: Message-ID: > If I iterate through a list, is there a way I can get the number of the > iteration: first, second, third, ... > > l = ["three", "four", "five", "six"] > for x in l > print x > print x.iteration() # <- That's what I'm looking for! > print "next" No, this won't work - x is the value of the list element, not an c++-like iterator-object (that has to be dereferenced before accessing the actual value). So usually x won't have an iteration-method. But of course you can alwas do this: for i in xrange(len(l)): x = l[i] print x print i print "next" Or - if len() can't be applied to your sequence for whatever reason, as it is e.g. a iterable object, you can of course keep track with your own counter: i = 0 for x in some_iterable_thingy: print x print i i += 1 print "next" Regards, Diez From jjl at pobox.com Tue Jan 20 13:01:01 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jan 2004 18:01:01 +0000 Subject: calling Pyrex results from C References: Message-ID: <87smiawlcy.fsf@pobox.com> Kyler Laird writes: [...] > This means that I can't, for example, make a function that takes a > filename (string), uses PIL to do a bunch of operations, and > returns a string. I don't see why you shouldn't be able to write a module in Pyrex, then use standard embedding techniques to embed Python and then call your module with a few C API calls. Or do the same, but also write a Pyrex cdef function to wrap it all up, so you can just call that as a "plain old" C function instead of those final few C API calls (you'll still need other embedding calls, of course, to initialise Python, etc.). Try the pyrex mailing list if you're stuck. I'd very definitely check to make sure you aren't going to get marked down for being a smartass, though (even if you're generating C that doesn't depend on Python at all, it might still be unreadable). > Any suggestions (besides "suck it up and do it all in C")? I think I'd do it in C, regardless of whether or not it's allowable to use Pyrex. John From wfolta at netmail.to Tue Jan 13 23:29:52 2004 From: wfolta at netmail.to (Wayne Folta) Date: Tue, 13 Jan 2004 23:29:52 -0500 Subject: Python used in Freedom Force Message-ID: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> I don't know if it's been discussed since the game came out a while ago, but I was looking through some temp files that were installed with the game Freedom Force (a very fun game) and the scenarios are programmed in Python! (This is on the Mac, but I assume it also used Python on the PC.) An example of the code is: def OnPowerup(object, hero): if (object == 'powerup5'): speakNoCB('minute_man', 'MISSPCH_1_MM_12') elif (object == 'powerup1') or (object == 'powerup6'): speakNoCB('minute_man', 'MISSPCH_1_MM_11') Object_SetAttr(object, 'used', 1) UpdateTrainArrow(object) def OnInterrogation(char, hero): print 'OnInterrogation' Object_SetAttr(char, 'used', 1) UpdateTrainArrow(char) # kill(char) : : # chase def startChase(event): startPatrol('runfciv', 3, run = 1, priority = ai.goal.PRI_HI) addMoveGoal('thugb16', Get_ObjectPos('runfciv'), fn = 'continueChase') def continueChase(event): addMoveGoal('thugb16', Get_ObjectPos('runfciv'), fn = 'continueChase') def endChase(event): clearGoals('runfciv') speakNoCB('runfciv', 'MISSPCH_1_F1_02') From mhammond at skippinet.com.au Thu Jan 15 21:11:14 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 16 Jan 2004 13:11:14 +1100 Subject: Py2Exe and Outlook (array bounds change!?) In-Reply-To: References: <982e9537.0401130858.4d37dae5@posting.google.com> Message-ID: Thomas Heller wrote: > hlubocky at uiuc.edu (Brian Hlubocky) writes: > > >>This one is really puzzling me. I am not that familiar with COM or >>py2exe, but I have tested this a fair amount and am pretty sure of >>what I am about to explain. The MSDN website says that the item list >>in Outlook has array bounds from 1 to length. Using this information, >>I wrote a program that adds contacts to outlook using an external >>database. When I went to try this out with py2exe however, I got an >>exception. >> >>What I found out is that when using py2exe, the bounds on the items >>list changes from 1 to len, to 0 to len-1. Does anyone have any idea >>why this might be? It seems goofy that this would happen. Testing is >>on the developer machine, so I don't think different dlls could be the >>problem. Thanks! > > > Just a wild idea: can it be that you're using makepy generated modules > in the script, and late bould com in the py2exe'd file? That will almost certainly be the issue. The (next/latest/??) version of py2exe has full support for including typelib info in your script. Mark. From exarkun at intarweb.us Sun Jan 18 21:12:29 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 18 Jan 2004 21:12:29 -0500 Subject: Python Text Adventure Authoring System In-Reply-To: References: Message-ID: <20040119021229.GA1104@intarweb.us> On Sun, Jan 18, 2004 at 05:44:00PM -0800, Zachary wrote: > Hello, > I've recently thought of how ideal Python is for the development of what > used to be called text adventures. In case any of you don't know, these > were basically sort of a computer game in which the player guided the > story by typing in natural language commands, e.g. get ball. > > Some popular games of the 1980's include Zork, A Mind Forever Voyaging, > among others. > > I was just wondering if anyone has any module that might help in the > implementation of a text parser, something to read player commands. My > idea is to have each room, item, creature, etc. Be represented as a > Python instance. > > For example, the following code might setup a room class: > > class room: > def __init__(self, rdesc, exit): > self.desc = rdesc > #Add Other code here > > If anyone has any idea how this might be done, I would love to hear from > you. > > P.S: > > I have already seen another text adventure development system written in > Python, called Paws. I thought this would be a sort of first project. > There are a few modules in Twisted's CVS repository that are handy in this area (as a few people are aware, Twisted is actually a support framework for multiplayer interactive fiction or text adventure games). Documentation is sparse, but much of the code is pretty simple (a *few* parts are mind bendingly complex, but none of those are related to text parsing ;) cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co Reality cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co NewReality cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co Imagination There was also a presentation about Reality at last year's PyCon. The paper is available in Twisted CVS (history docs directory), or with viewcvs at: http://cvs.twistedmatrix.com/cvs/doc/historic/2003/pycon/twisted-reality/ Imagination represents the most current thinking on the topic, but Reality and NewReality have more infrastructure for actually dealing with user input (Imagination is like a hyper distillate of our ideas currently, and so can't be bothered to cover such things as handling user input ;). And of course, many of the developers frequent #twisted on irc.freenode.net and just *love* it when someone wants to talk about Reality instead of boring things like HTTP and IMAP4 ;) Hope this helps, Jp From wfolta at netmail.to Fri Jan 30 02:12:03 2004 From: wfolta at netmail.to (Wayne Folta) Date: Fri, 30 Jan 2004 02:12:03 -0500 Subject: Sort by key, then by content Message-ID: <9A8139BC-52F3-11D8-9115-000A959CB2EC@netmail.to> As an experiment, I've written a Python script which reads my mailboxes and prints a report on how many messages I've gotten from from each unique sender. I use a dictionary with a key of the email address and each entry is a list with the 0th element being the user's name (if known) and the 1st being the count. At the end, I print the report, sorted by email address. But then I want to print it sorted by frequency of message. What would be the most efficient, idiomatic, iterative, functional way to do that. After some head-twisting (it's way past my bedtime), I finally figured that heapq's would help me, but it seems there should be a cool way to turn the dict into a list (map) and also turn it inside out at the same time... keys = addr_dict.keys () keys.sort () heap = [] for k in keys: print "%s (%s)\t%d" % (k, addr_dict[k][0], addr_dict[k][1]) heapq.heappush (heap, (addr_dict[k][1], k, addr_dict[k][0])) print '*' * 80 while (heap): print "%d\t%s (%s)" % heapq.heappop (heap) Any suggestions? From spamfilter at macspeno.com Thu Jan 8 09:50:38 2004 From: spamfilter at macspeno.com (John P. Speno) Date: Thu, 8 Jan 2004 14:50:38 +0000 (UTC) Subject: NNTP Server for this group References: Message-ID: In jonas at jonasgalvez.com (Jonas Galvez) writes: >Can anyone recommend a good NNTP server for accessing this group? gmane.comp.python.general on http://www.gmane.org/? comp.lang.python is also available as a mailing list: http://mail.python.org/mailman/listinfo/python-list Take care. From elainejackson7355 at home.com Sun Jan 4 01:50:21 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 04 Jan 2004 06:50:21 GMT Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: Sorry, I should have said "C rounds toward zero". In other words, the result of casting x to integer type is sgn(x)*floor(abs(x)). "Elaine Jackson" wrote in message news:uEOJb.933787$pl3.753391 at pd7tw3no... | C rounds toward the nearest integer and Python rounds down. The behavior is | consistent in each case. | | "Frank" wrote in message | news:3987e01c.0401030832.114c6f2a at posting.google.com... | | Hi, | | | | can anybody help with the following problem? | | | | In C++ | | | | i = 5 / 10 and | | i = -5 / 10 both have the same result 0. | | | | In python | | | | i = 5 / 10 gives me 0 as expected, but | | i = -5 / 10 gives -1 as result. | | | | Is this a feature or a bug? I remember Delphi gave me the same result as | | C++. | | | | TIA, | | Frank | | From bmgx_no_sp at mgleesonprop.co.za Sun Jan 4 12:21:03 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Sun, 04 Jan 2004 19:21:03 +0200 Subject: using cgi form via http and extracting results In-Reply-To: <3ff84844.0@news1.mweb.co.za> References: <3ff84844.0@news1.mweb.co.za> Message-ID: <3ff84b7c.0@news1.mweb.co.za> I found a possible solution: http://wwwsearch.sourceforge.net/ClientForm bmgx wrote: > I would like to use an already existing online service (currency > converter) basically consisting of a html form with a few options that > is submitted and returns the results. I really don't know where to start > but I have assumed the following steps need to be taken: > > 1) Make an http connection to the remote script (http://server/script.cgi) > > 2) Fill out the html form (1x TEXT and 2x SELECT input fields) > > 3) Submit the form > > 4) extract the actual returned result. (using regex or something..) > > Any help on which modules to use would be much appreciated! > From rodrigob at elo.utfsm.cl Tue Jan 27 07:30:06 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Tue, 27 Jan 2004 09:30:06 -0300 Subject: Pickling Tkinter widgets - Where does Python stand now? References: <4378fa6f.0401262135.3e05d217@posting.google.com> Message-ID: <401655f4$1_2@nova.entelchile.net> are not there Pickle versions that allow you to pickle python code, or simply pickle classes ? That could be use to pickle the code that create the widget. Thus the pickling would pickle the creation code and the unpickling would reobtain it and instanciate the code class. That is a strategy but I'm not sure if it is what you need... rodrigob. "Marc" escribi? en el mensaje news:4378fa6f.0401262135.3e05d217 at posting.google.com... > Hi all, > > After some research I've decided that my previous question (Confusing > problem between Tkinter.Intvar...) was headed in the wrong direction. > Partly because I think I have a greater understanding of what was > happening, and partly because pickling Tkinter widgets is an issue > that seems to have been touched on over the years but never really > acted on. > > Postings back to '96 have talked about the need to pickle Tk widgets. > People have asked about it at various points, and no one has ever > really even come up with a workaround (that I could find). > > So I am wondering a couple of things: Are there any plans in the > future to alter Tkinter so that it will be Pickle compliant in the > main release? Has anyone ever found a workaround (whether through > altering the main Tkinter.py file or other) that will allow pickling > of Tk widgets. > > Thanks, > Marc From samirw at connection.com Tue Jan 6 22:43:45 2004 From: samirw at connection.com (Sambo) Date: Tue, 06 Jan 2004 19:43:45 -0800 Subject: Finaly found a simple enough task for python, took the plunge, but..... References: <3FFB5312.1030803@connection.com> Message-ID: <3FFB8071.9070107@connection.com> It did get rid of the blank window but it also does not appear on the task bar( or get focus), but I can ALT+TAB to it. maybe it is my Vind-Blows 95. Thanks , Sam. vincent wehren wrote: > "Sam" schrieb im Newsbeitrag > news:3FFB5312.1030803 at connection.com... > | Only 2 weeks messing around with it ( thanks to programs like SYNCHRONEX > and > | BITORRENT ), and already trying to create windows ( the paths are just too > long > | for me to want to type them ). > | After much trial and error I finaly got the following code to open the > 'get dir' > | dialog , but I am getting another blank window titled 'tk' and "NOT > RESPONDING" > | When I kill it (end task), I get reiniit/restart (CTRL+F6) in my shell > window > | What am I doing wrong? Do I need to do anythink to clean up after using > the > | dialogs? > > Take a look at the tkFileDialog module. Or better, use it for convenience. > It already provides some "standard" dialogs. You code would then look > similar to: > #----------------------- > import Tkinter > import tkFileDialog > > def me(): > root = Tkinter.Tk() > root.withdraw() # do this to remove the "blank screen" you mention > dirname = tkFileDialog.askdirectory() > return dirname > > print me() > #------------------------ > > HTH > > Vincent Wehren > > > From gerrit at nl.linux.org Wed Jan 28 08:28:51 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 28 Jan 2004 14:28:51 +0100 Subject: newsgroup lib In-Reply-To: <6b17fa95.0401280501.4be454cb@posting.google.com> References: <6b17fa95.0401280501.4be454cb@posting.google.com> Message-ID: <20040128132851.GA4338@nl.linux.org> Jesper Olsen wrote: > Is there a python module for accessing newsgroup articles? You're looking for nntplib http://www.python.org/dev/doc/devel/lib/module-nntplib.html For example, >>> s = NNTP('news.cwi.nl') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', >>> last Group comp.lang.python has 59 articles, range 3742 to 3803 >>> resp, subs = s.xhdr('subject', first + '-' + last) >>> for id, sub in subs[-10:]: print id, sub ... 3792 Re: Removing elements from a list while iterating... 3793 Re: Who likes Info files? 3794 Emacs and doc strings 3795 a few questions about the Mac implementation 3796 Re: executable python scripts 3797 Re: executable python scripts 3798 Re: a few questions about the Mac implementation 3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules 3802 Re: executable python scripts 3803 Re: \POSIX{} wait and SIGCHLD >>> s.quit() '205 news.cwi.nl closing connection. Goodbye.' Gerrit. -- 5. If a judge try a case, reach a decision, and present his judgment in writing; if later error shall appear in his decision, and it be through his own fault, then he shall pay twelve times the fine set by him in the case, and he shall be publicly removed from the judge's bench, and never again shall he sit there to render judgement. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jjl at pobox.com Fri Jan 9 09:12:56 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jan 2004 14:12:56 +0000 Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> Message-ID: <871xq9ky6v.fsf@pobox.com> michael at foord.net (Fuzzyman) writes: [...] > I'm using urllib (for the first time)..... and google don't seem very > keen to let me search the group from within a program - the returned > pages all tell me 'you're not allowed to do that' :-) Don't do it, then. Use the google API (mind you, not certain that google groups is part of that). [...] > Could anyone tell me how to subclass this correctly with the version > attribute set and what text string I should use to mimic Internet > explorer and/or mozilla ? IIRC, opener.addheaders = [("User-agent", "whatever")] Use a program like ethereal to find what your browser sends for "whatever". John From francisgavila at yahoo.com Mon Jan 12 15:09:10 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 12 Jan 2004 15:09:10 -0500 Subject: Using switches with exec? References: Message-ID: <1005vp68v80mm44@corp.supernews.com> Premshree Pillai wrote in message ... >Hmm...maybe I should have been clearer. >What I need to do is run an external Python code from >within another program, and while doing so I need to >pas a switch (yes, like a command-line switch) to this >code; i.e., I need to open an external Py program from >within another Py program... Use os.system or os.popen, not exec. It doesn't matter at all that the program you're executing happens to be a Python program. But if it's already written, and you can modify it, you might as well package it up nicely to use as a module. Then you won't be bothering with switches at all, and you won't have to rely on os services. -- Francis Avila From g.winter at dl.ac.uk Wed Jan 7 05:38:41 2004 From: g.winter at dl.ac.uk (Graeme) Date: Wed, 07 Jan 2004 10:38:41 +0000 Subject: C++ extension Message-ID: Hi All, I guess that this will be a point which has come up in the past, but I can't find any references to it anywhere. I am writing a Python extension in C++, and as a part of the extension class I have an STL list of things i.e class WhatNot { public: PyObject_HEAD; . . private: list foo; }; However, I have found that this works fine when I use the class from C++ code, but doesn't work with PyObject_New (the list is not properly initialised and I get a segmentation fault.) Is there an easy way around this problem? Cheers, Graeme From beliavsky at aol.com Thu Jan 15 14:25:30 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 15 Jan 2004 11:25:30 -0800 Subject: keeping Python code properly indented Message-ID: <3064b51d.0401151125.711ade4c@posting.google.com> How do you keep Python code properly indented as you modify it? I use an Emacs-type editor that has a Python mode, so the initial indenting is easy. If I later want to put a 'for' loop (or an 'if' statement) around a bunch of code, I find myself going through the body of the loop, manually re-indenting to keep the nested loops correct. There should be a better way. I think that having a 'for' loop end with a matching 'next' statement, as done in (for example) Basic, is a safer and clearer way of writing loops, although some Python programmers consider this a 'feature' rather than a 'bug'. From sombDELETE at pobox.ru Tue Jan 27 19:02:44 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Wed, 28 Jan 2004 03:02:44 +0300 Subject: [ANN] ip2cc-0.3: now it works with Python 2.3 References: <84e0f331.0401271515.2ed5c4f0@posting.google.com> Message-ID: "Richard" wrote in message news:84e0f331.0401271515.2ed5c4f0 at posting.google.com... > I get an error when trying to use it... here's the problem below: > > C:\Tools>ip2cc.py www.google.com > Traceback (most recent call last): > File "C:\Tools\ip2cc.py", line 338, in ? > db = CountryByIP(db_file) > File "C:\Tools\ip2cc.py", line 14, in __init__ > self.fp = open(filename, 'rb') > IOError: [Errno 2] No such file or directory: 'C:\\Tools\\ip2cc.db' > > Looks like the database file is not included with the download. Try running update.py first to retrieve the database from internet. The exception should of course be caught by ip2cc script and a clear explanation should be printed. -- Serge. From whitekid at netian.com Fri Jan 16 04:28:34 2004 From: whitekid at netian.com (whitekid) Date: Fri, 16 Jan 2004 18:28:34 +0900 Subject: SimpleXMLRPCServer In-Reply-To: Message-ID: <200401160931.i0G9ViHZ071726@neurogenex.com> SimpleXMLRPCServer.py is Just Simple! A few days age. I considered XMLRPC framework for our service. But finally I choose WebWare. Read paper below: http://webware.sourceforge.net/Papers/IntroToWebware.html > -----Original Message----- > From: python-list-bounces+whitekid=netian.com at python.org > [mailto:python-list-bounces+whitekid=netian.com at python.org] > On Behalf Of Maxim Khesin > Sent: Friday, January 16, 2004 6:01 PM > To: python-list at python.org > Subject: SimpleXMLRPCServer > > Hi, > the typical usage of SimpleXMLRPCServer registers some > class with the server instance and then jumps into a > serve-forever loop, e.g. > > server = SimpleXMLRPCServer(('', 8000)) > server.register_instance(MyClass()) > server.serve_forever() > > is there a way to process actions other than XML-RPC > requests using SimpleXMLRPCServer? Is is possible to do > something like > > server = SimpleXMLRPCServer(('', 8000)) > server.register_instance(MyClass()) > while(1) > if(checkSomeCondidion()): > server.serve_once() > else: server.stop() > > thanks, > max > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From brandon6684 at yahoo.com Fri Jan 2 22:20:50 2004 From: brandon6684 at yahoo.com (Brandon) Date: 2 Jan 2004 19:20:50 -0800 Subject: Python for Embedded Devices? Message-ID: Java seems to have taken off as the platform and language of choice for many embedded devices. Would it be feasible for Python(perhaps running on an embedded version of Linux) to act in such a capacity. Most of my experience with Python has been with Unix-type scripting tasks and using it when it is an applications built in scripting, but I know some people try to use to build larger complex applications. Is the Python interpreter portable and good enough to be used in resource constrained devices like cell phones? From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jan 11 14:31:19 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 11 Jan 2004 20:31:19 +0100 Subject: python-dev Summary for 2003-12-01 through 2003-12-31 In-Reply-To: References: Message-ID: <4001a488$0$317$e4fe514c@news.xs4all.nl> First: thanks Brett, for the summary. And get well soon from your pneumonia. Brett wrote: > ------------------------ > Compiling 2.4 under .NET > ------------------------ > Martin v. L?wis has started sandbox work on an MSI installer and moving > Python 2.4 over to VC 7. MSI? Why, what is wrong with the old installer? I'm not too fond of MSI installers, I find them slow and large. Especially when using lots of files. That may be a problem in the installer script, but almost all MSI installers I encountered were extremely slow when installing and deinstalling a program that consists of a lot of files (and Python does). (I must note that this is much less so with recent versions than before, because the help files are no longer in seperate html files but in a single chm file). --Irmen From python at quixs.com Sun Jan 18 10:13:41 2004 From: python at quixs.com (Lars Heuer) Date: Sun, 18 Jan 2004 16:13:41 +0100 Subject: wxwindows question In-Reply-To: References: <1h6pd1-788.ln1@wintermute.g2ctech> Message-ID: <229419755.20040118161341@quixs.com> Hi Nuff, I missed the begin of the thread, so I answer you. :) >> It would be very good if wxPython was more python centric instead of [...] > I agree. Having wrappers for existing libraries and software is > an important thing and having *prototyping* in mind, one should > not try to make such wrappers as pythonic as possible. (Moreover, > this would make the maintenance of the wrappers more complicated.) Maybe WAX is an interesting project. It tries to build a wrapper ahead of wxPython to serve a more python-ic way to code python programs: See: http://wiki.wxpython.org/index.cgi/Wax http://zephyrfalcon.org/labs/dope_on_wax.html Best regards, Lars From maoy at cis.upenn.edu Sun Jan 25 18:13:08 2004 From: maoy at cis.upenn.edu (Yun Mao) Date: Sun, 25 Jan 2004 18:13:08 -0500 Subject: python distribution question Message-ID: Hi, I wrote a simple python module and try to distribute it by using distutil. The setup.py looks straightforward to me, but I'm confused a little in distributing the "additional files". It looks like the user can change the install dir and prefix by suplying some --install-data argument, or --prefix, whatever. My question is that how can my python module be aware of where the data are finally installed to? Thanks. -- Y From bhan at andrew.cmu.edu Sat Jan 24 14:58:58 2004 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Sat, 24 Jan 2004 14:58:58 -0500 (EST) Subject: Psyco on PowerPC? In-Reply-To: <26b7aa41.0401232250.3e6588a8@posting.google.com> References: <30E0BEC9-4DE7-11D8-B663-000393DB5438@andrew.cmu.edu> <26b7aa41.0401232250.3e6588a8@posting.google.com> Message-ID: Ok here is what I did 1. pulled the latest CVS 2. did a "python setup.py install" 3. ran this testing program: -- CUT -- #!/usr/bin/env python import time import psyco def f (x): p1=p2=ret=0 for i in xrange(0,x+1): if i==1: p1=ret=1 else: ret=p2+p1 p2=p1 p1=ret return ret startTime=time.time() print f(100000) endTime=time.time() print '* Elapsed time =',endTime-startTime fastF=psyco.proxy(f) startTime=time.time() print fastF(99) endTime=time.time() print '* Elapsed time =',endTime-startTime -- CUT -- The result (on my PowerBook G4): 2597406.... (big number) * Elapsed time = 2.41602706909 Fatal Python error: psyco: out of memory Abort trap I have 1 GB memory. Maybe it's still in the early development stage? Thanks, Ben On Sat, 23 Jan 2004, Roberto Lopez-Gulliver wrote: > Hi Ben, > > Directly from Armin > > http://codespeak.net/pipermail/pypy-dev/2003q3/002219.html > > Haven't try it myself though. > > Please post here any success/failure you may experience in Mac OSX. > > Hope this helps. > > --roberto > > Han Benjamin wrote in message news:<30E0BEC9-4DE7-11D8-B663-000393DB5438 at andrew.cmu.edu>... > > Is anyone aware of any effort in bringing Psyco onto other platforms, > > esp. PowerPC (Mac OS X)? I checked the website but it's still stated as > > X86 only. > > > > Thanks, > > > > Ben > --- Benjamin Han (http://www.cs.cmu.edu/~benhdj) Language Technologies Institute, School of Computer Science Carnegie Mellon University From cartermark46 at ukmail.com Tue Jan 20 09:33:09 2004 From: cartermark46 at ukmail.com (Mark Carter) Date: 20 Jan 2004 06:33:09 -0800 Subject: best book: aint no such thing, and encouragement for old coots References: <95aa1afa.0401192355.77568ed4@posting.google.com> Message-ID: > > I suppose that Schemers and Lispers take the attitude that a lack of > > syntax is an advantage, because you can ultimately program in any > > paradigm you wish. It's "just" a case of writing code that implements > > the paradigm. > > Uh? The lack of syntax has nothing to do with the lack of paradigm, > I miss you point, sorry. What I meant was: programs written in s-exprs makes it possible to accomodate new paradigms because, ultimately, everything is a list, which you can parse to accomodate your new paradigm. Programs not written in s-exprs require extra syntax to be bolted onto the language. But I suppose, if you want, to argue that all Turing Complete languages are equivalent, so they support all the paradigms that the others support. From rganesan at myrealbox.com Sat Jan 24 05:11:33 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Sat, 24 Jan 2004 15:41:33 +0530 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: > Is that all that people mean, though, when they talk about Perl's > superiority for text mangling? Is there more to it? -- It's probably not just regular expressions. In my case, Python's IO performance is simply not upto the mark. Even Python 2.3 is atleast twice slower than perl for text manipulation simply because of this IO overhead. As mentioned in an earlier post, I had to fix a program that searched for patterns in a gzipped word list to launch zgrep in a pipe and post process it in python to get acceptable performance. The perl "built-in" idioms for text processing is not only a syntactic convenience, there are real performance advantages. For example a simple perl loop like while (<>) { } is nearly 6 times slower in python (8 time slower with Python 2.2) using fileinput. Every appears to know that fileinput is slower and avoid it when performance is a concern; but even manually doing the equivalent is slower in python. I've simply switched back to using perl for my text processing needs - especially one off or short scripts where I don't care so much about maintainability as about finishing the job faster. Ganesan -- Ganesan R From NOusenetSPAM at gdargaud.net Wed Jan 21 04:28:20 2004 From: NOusenetSPAM at gdargaud.net (Guillaume Dargaud) Date: Wed, 21 Jan 2004 10:28:20 +0100 Subject: Checking for duplicate instances of a script... Message-ID: <400e4638$0$19274$626a54ce@news.free.fr> Hello, python beginner here, How can I make sure that a given script is never run more than once at the same time in a system ? Besides checking 'ps' for its own name. Most modern langages have a direct way to do that. Thanks -- Guillaume Dargaud http://www.gdargaud.net/ "Here is your parachute and here is the manual. Welcome to Linux." From grahamd at dscpl.com.au Thu Jan 15 05:19:50 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 15 Jan 2004 02:19:50 -0800 Subject: I come not to bury C++, but to praise it... References: <40055560.7A0DCD0D@engcorp.com> <100aoq8efq3nt1e@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) wrote in message news:<100aoq8efq3nt1e at corp.supernews.com>... > In article <40055560.7A0DCD0D at engcorp.com>, > Peter Hansen wrote: > . > . > . > >John, thanks for the reminder about the origins of C++. (I suspect the majority > >of readers in this group were not even programming during the CFront era > >(roughly 1983-85?), and a history lesson is always good from time to time.) > . > . > . > I was still fussing with cfront in the early '90s. > Its era *had* passed by then, though. Ahh yes, the good old days. Well maybe not. I once played with version E of cfront once. Ie., before even version 1.0, the E being for experimental. At least that is from memory what is was called. That was back in 1984 and even at that time version 1.2 of cfront was already out I think. At the end of that year I got a student vacation job at the first company in Australia to be using C++. We had access to beta versions of the compiler from AT&T/USL and I think during that time a beta version of 2.0 turned up. Not sure how long after that it actually got released properly. It was after that that Sun and Centerline brought out compilers based on cfront. Note that these compilers still didn't implement templates, they only turned up some number of years later in version 3.0 in the early 90's some time. In the interim we were using a hacked up cpp which could understand enough of the C++ template syntax to allow us to make decent use of them. From memory, the first C++ compiler to actually come out with support for templates wasn't even the AT&T/USL version 3.0 of cfront, instead it was a hacked up version of cfront 2.1 made to support templates and was released by ObjectStore, the OODBMS developer. Don't think it supported template functions though, only template classes. Anyway later cfront 3.0 became more available. Actually, it was version 3.0.1. Version 3.0 mustn't have lived very long because we never actually got to see it. There was a subsequent cfront 3.0.2 and I think that was the last of them from USL. Sun and Centreline also came out with versions based on cfront 3.0.1 before Centerline dissappeared altogether and Sun changed to the cafe based compiler which they developed. There was GNU C++ as well, but it was quite late to the game in providing a version with templates which actually worked. Lucid C++ was an interesting compiler but it also died. At that time the best compilers were probably those based on the EDG engine. Oh must not forget the SGI and HP versions of cfront 3.0.1. Ah, but then maybe we should forget the HP version. Anyway, there were a number of other C++ compiler vendors as well, especially in the cross development arena, but enough already. From martin at v.loewis.de Wed Jan 28 01:09:19 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 28 Jan 2004 07:09:19 +0100 Subject: Tcl style traces In-Reply-To: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain wrote: > Does Python have something similar to Tcl style tracing? That is, the > ability to call a subroutine when a variable is written to or read from? No. However, sys.settrace might come close. Regards, Martin From aahz at pythoncraft.com Tue Jan 20 17:22:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 20 Jan 2004 17:22:02 -0500 Subject: keynote speaker, PyCon Reminder: Early bird reg deadline 2/1 References: Message-ID: In article , John Benson wrote: > >Isn't Kapor the Lotus guy that tried to quash Borlands Quattro Pro because >it offered an alternative Lotus-user-friendly menuing structure? (see >http://lpf.ai.mit.edu/Copyright/copyright.html) According to http://www.kapor.com/homepages/mkapor/bio0701.htm : He founded Lotus Development Corp. in 1982 and with Jonathan Sachs, who was responsible for technical architecture and implementation, created Lotus 1-2-3. He served as the President (later Chairman) and Chief Executive Officer of Lotus from 1982 to 1986 and as a Director until 1987. According to http://www.lgu.com/publications/softcopy/20.shtml Lotus began in early 1987 by filing suit in federal court in Massachusetts against Paperback Software and Mosaic Software, two so-called Lotus "clone" developers. These companies had published programs which copied the Lotus 1-2-3 command sequence virtually word for word. The cases were assigned to Judge Robert Keeton. So it's not clear to what extent, if any, Kapor was responsible for these legal shenanigans. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From ramen at lackingtalent.com Sat Jan 17 16:09:19 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 17 Jan 2004 21:09:19 -0000 Subject: building strings with variable input References: Message-ID: In article , Olaf Meyer wrote: > Sometimes if find it clumsy unsing the following approach building strings: > > cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime, > directory) > > Especially if you have a lot of variable input it makes it hard to match > the variables to the proper fields. From other scripting languanges I'm > used to something like: > > $cmd = "$executable -start $startTime -end $endTime -dir $directory" > > This makes it very easy to see how the string is actually built. You > dont't have to worry where which variables go. > > Is there a similar way to do this in python? Go here: http://lfw.org/python/ Look under "string interpolation for Python". Examples supported: "Here is a $string." "Here is a $module.member." "Here is an $object.member." "Here is a $functioncall(with, arguments)." "Here is an ${arbitrary + expression}." "Here is an $array[3] member." "Here is a $dictionary['member']." Thanks to Ka-Ping Yee! I've succesfully used this to build a homebrew templating language. It's nice and lightweight. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From jjl at pobox.com Tue Jan 20 07:30:12 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jan 2004 12:30:12 +0000 Subject: Pythonwin working on linux Message-ID: <871xpuyf8r.fsf@pobox.com> Well, seems there's a new Python IDE on linux: http://wwwsearch.sf.net/bits/pythonwin.png It's running on Debian woody GNU/Linux under KDE 3.2 with Crossover office (commercial distribution of wine - http://www.winehq.com/), Python 2.3, win32all 157. Seems to work fine! Even some parts of win32com work. It managed to create a GUID and ran gen_py on the Word type library, and the MSOffice test launched Word, but crashed on setting the Visible property. It feels like cheating, somehow: john[1]$ cxoffice/bin/wine .cxoffice/dotwine/fake_windows/Python23/python.exe Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> You can even type control-D to exit. I remember somebody here reporting that making Windows installers works using McMillan installer, too, and I read somewhere that it's even possible to install MSVC 6! John From nuffsaid at phreaker.net Tue Jan 13 18:55:15 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Wed, 14 Jan 2004 00:55:15 +0100 Subject: wxwindows question References: Message-ID: On Tue, 13 Jan 2004 07:31:33 -0600, Jason Tesser wrote: > I am looking into using wxwindows for a gui to develop applications. > The > Apps need to be cross-platform Mac, Windows, Linux. I work > For a bible college and will be developing applications ranging from > online > Registration to business office software. My question is what is your > guys > Experiences with wxwindows/python? wxpython is fine (actually: *very fine* :-) for Windows applications, but I would not use it for cross-platform development, because it is not stable enough on Linux. (Even some of the widgets in the wxpython demo crash on Linux; and if you use wxpython with Unicode support, the situation gets even worse. This might change in the near future, but right now, wxpython is not stable enough on Linux IMHO.) For things like 'online registrations' etc., I would write a web based application (using one of the many web application frameworks which are available for Python or maybe just good old CGIs written in Python). Don't really know what you mean by 'business office software', but it sounds like you need a powerful text widget and maybe a good canvas widget. Check out Tkinter (Python bindings for Tcl/Tk) for that. (Though Tkinter does not provide widgets like a notebook, print preview resp. a printing system etc. as wxpython does.) GTK (i.e. PyGTK for Python) might be worth a look if you plan to use other programming languages apart from Python, too. HTH / Nuff From jjl at pobox.com Thu Jan 1 13:59:03 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Jan 2004 18:59:03 +0000 Subject: canonical file access pattern? References: <874qvhkpm2.fsf@pobox.com> Message-ID: <8765fvpkaw.fsf@pobox.com> Hans-Joachim Widmaier writes: > Am Wed, 31 Dec 2003 14:51:01 +0000 schrieb John J. Lee: [...] > > If that were true, why did exceptions get invented? If you don't need > > to do something different in all those except: clauses, then don't put > > them in. > > One thing I need is to create an informative and useful error message .strerror? [...] > Hmm. The farther away from the actual point of error you catch it, the > harder it is to tell exactly what happened and to redo/work around it. [...] So in some cases, you have fewer except statments, in others, more. There's really no "canonical pattern" to it. John From jdhunter at ace.bsd.uchicago.edu Tue Jan 27 22:58:33 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 27 Jan 2004 21:58:33 -0600 Subject: Best way to compare a list? In-Reply-To: <7b454334.0401271739.59267018@posting.google.com> (faizan@jaredweb.com's message of "27 Jan 2004 17:39:42 -0800") References: <7b454334.0401271739.59267018@posting.google.com> Message-ID: >>>>> "Fazer" == Fazer writes: Fazer> Hello, I was wondering which would be the best way to Fazer> compare a list? Fazer> I was thinking of just using a for loop and testing the Fazer> condition. Fazer> What do you guys think? The best/fastest way of comparing Fazer> lists. What do you want to compare for, equality of all elements? Give a little more info about what you need to do. JDH From amonroejj at yahoo.com Wed Jan 14 20:15:08 2004 From: amonroejj at yahoo.com (R. Alan Monroe) Date: Thu, 15 Jan 2004 01:15:08 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <40051cb3$1@news.012.net.il> Message-ID: In article , "Brandon J. Van Every" wrote: >> >> It >> >> was an unbelievable waste of time, since you've managed to convice >> >> (maybe still wrongfully) all the people that you are completely >> >> clueless. >> > >> > Why, because I turned around a project in 3 weeks while having the >> > flu half the time? >> >> No, because you dumped the project because it was boring. > >You're a fool then. What's your school of advice, keep working on things no >matter how much of a boring waste of time they become? "Being able to finish something is a form of expertise." --Brandon Van Every http://groups.google. com/groups?q=finish+project+%22brandon+van+every%22+group:comp.games. development. *&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3f6ab8de%40shknews01&rnum=9 Alan From ralobao at click21.com.br Thu Jan 8 22:11:41 2004 From: ralobao at click21.com.br (Ruivaldo Neto) Date: Fri, 9 Jan 2004 01:11:41 -0200 Subject: books In-Reply-To: <5r5svvccvt4lqjnlaurftejbgluu1fepoc@4ax.com> References: <3FFDC029.AB0A4097@unet.univie.ac.at> <5r5svvccvt4lqjnlaurftejbgluu1fepoc@4ax.com> Message-ID: <200401090111.41400.ralobao@click21.com.br> You can learn very well it from the web .. its my opinion, but people say that Learning python is the best.. and there is too the python bible Em Sex 09 Jan 2004 00:55, Terry Carroll escreveu: > On Thu, 08 Jan 2004 20:40:08 GMT, Thomas Mang > > wrote: > >I have programmed mostly in C++ lately, and I want to start learning > >Python now. > > > >Which books would you recommend to buy? > > > >I am both looking for an introduction into the language, as well as > >complete guides. > > As an intro, I really liked O'Reilley's "Learning Python." As a > reference, I *really* like their "Python In A Nutshell." > > I didn't care much at all for their "Programming Python," but lots of > people swear by it, so your milage may vary. -- RS: Ruivaldo Neto From swalters_usenet at yahoo.com Sun Jan 11 05:40:06 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 11 Jan 2004 10:40:06 GMT Subject: OT: Of C, Fortran and pointer aliasing Was: Python if far from a top performer... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: |Thus Spake Rainer Deyke On the now historical date of Sun, 11 Jan 2004 06:46:50 +0000| > Samuel Walters wrote: >> So, I guess that my point is that C might not be the right language for >> doing numerical processing, but it seems the right language for >> implementing the primitives of numerical processing. > > The issue with C is that it is too slow for implementing those > primitives (in part due to pointer aliasing issues). Fortran is > considerably faster. I stand corrected. Please help me to understand the situation better. I went digging for technical documents, but thus far haven't found many useful ones. It seems everyone but me already understands pointer aliasing models, so they might discuss them, but they don't explain them. I am limited in part by my understanding of compilers and also by my understanding of Fortran. Here is what I have gathered so far: Fortran lacks a stack for function calls. This promotes speed, but prevents recursive functions. (Most recursive functions can efficiently be written as loops, though, so this shouldn't be considered a hindrance.) Fortran passes all arguments by reference. (This is the peppiest way to do it, especially with static allocation) Fortran 77 lacks explicit pointers and favors static allocation. This allows for the compiler to apply powerful automatic optimization. Fortran 90 added explicit pointers, but required them to only be pointed at specific kinds of objects, and only when those particular objects are declared as targets for pointers. This allows the compiler to still apply powerful automatic optimizations to code. I'm a bit hazy as to whether Fortran 90 uses static or dynamic allocation, or a combination of both, and whether it permits recursion. These pointers not only reference location, but also dimension and stride. Stride is implicit in C pointer declarations (by virtue of compile-time knowledge of the data type pointed to) but dimension is not. Fortran's extensions for parallel programming have been standardized, and the language itself makes it easy to decide how to parallelize procedures at compile time. Thus, it is especially favored for numeric computation on big iron with lots of parallelism. Now, for C: Because of dynamic allocation on the stack and the heap, there is no compile-time knowledge of where a variable will live, which adds an extra layer of reference for even static variables. This also invalidates many of optimizations used by Fortran compilers. C lacks many of the fundamental array handling semantics and primitives that Fortran programs rely on. Implementing them in C is a real PITA. C memory allocation is just plain goofy in comparison to Fortran. To sum up: Fortran sacrifices generality and dynamism for compile-time knowledge about data, and deeply optimizes based on that knowledge. C sacrifices speed for the sake of generality and dynamism. Please correct me or help me flesh out my ideas. Please don't skimp on the low-level details, I've done my fair share of assembly programming, so what I don't understand, I'll probably be able to find out by googling a bit. Some other interesting things I found out: There are two projects that allow interfacing between Python and Fortran: F2Py http://cens.ioc.ee/projects/f2py2e/ PyFortran http://sourceforge.net/projects/pyfortran Fortran amply supports interfaces to C and C++ Fortran is compiled. (Doh! and I thought it was interpreted.) There are lots of debates on whether C++ will ever be as fast as Fortran. The consensus seems to be "Only if you use the right compiler with the right switches and are insanely careful about how you program. IOW Don't bother, just use Fortran if you want to do numeric processing. Well, there's another language to add to my list of languages to learn. It seems to be "The Right Tool" for a great many applications, it interfaces well with other languages, and it's extremely portable. Chances are, I'll end up using it somewhere somehow someday. Now. To find some Fortran tutorials. Thanks in advance for any of your knowledge and wisdom you are willing to confer upon me. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From galfip at freestart.hu Mon Jan 26 05:58:12 2004 From: galfip at freestart.hu (Peter Galfi) Date: Mon, 26 Jan 2004 11:58:12 +0100 Subject: Overriding compare in SequenceMatcher Message-ID: <001a01c3e3fb$4d409380$7800a8c0@mailer> I am trying to make a compare between two lists of numbers using the SequenceMatcher, however I would need somehow to override the method which is used by SequenceMatcher to determine if two elements of the list are equal or not. In my specific case a number of the list might be equivalent with another number of the list yet their values would be different. Any idea as to how what and how I can override or any workaround for this problem? Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Jan 18 10:20:38 2004 From: aahz at pythoncraft.com (Aahz) Date: 18 Jan 2004 10:20:38 -0500 Subject: Forums for Teachers Using Python - Where are they? References: Message-ID: In article , Samuel Walters wrote: > >I'm currently considering a position teaching math and possibly >programming at a small local magnet school. If I was also teaching >programming, I would, of course, be using Python. > >So, I went out and googled around for resources. I found lots of articles >about using Python to teach programming, but I have yet to turn up one >forum where teachers using Python talk amongst themselves. edu-sig -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From skip at pobox.com Sat Jan 10 13:39:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 12:39:06 -0600 Subject: what is best for web development?? In-Reply-To: References: Message-ID: <16384.18122.805770.494951@montanaro.dyndns.org> ketulp> i am developing a web application and i am really confused on ketulp> what should i use. should i use just python and use the cgi ketulp> module availabe. Or should i use application like WebWare.Also ketulp> there is PSP available. I am really confused and need help As Wilk indicated, there are lots of options and you didn't say much/anything about your environment or requirements for your web app. If all your developers are mostly Python programmers, I think you might like Quixote. If you have a diverse group of people with different skills (programmers, web designers, marketing types), you might find Zope more to your liking. There are tons of other options as well. It all depends... Skip From merkosh at hadiko.de Mon Jan 19 06:22:36 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Mon, 19 Jan 2004 12:22:36 +0100 Subject: adding elements to python tuples Message-ID: Hi, is it possible to append new elements to a tuple? I know tuples are immutable and that this would mean to create a new tuple with one more element, but how do you do it? i.e. i have (1,2,3) and want to append 4: (1,2,3,4) instead of ((1,2,3),4) I wanted to use it as a return value of a function and an assignment, but: (a,b,c),d = myfunc() doesn't look nice to me. I intended to have a,b,c,d = myfunc() Thanks for any suggestions. Ciao Uwe -- From tchur at optushome.com.au Fri Jan 9 16:52:25 2004 From: tchur at optushome.com.au (Tim Churches) Date: 10 Jan 2004 08:52:25 +1100 Subject: Python is far from a top performer according to benchmark test... In-Reply-To: References: Message-ID: <1073685145.1186.20.camel@emilio> On Sat, 2004-01-10 at 08:13, Krzysztof Stachlewski wrote: > "Carl" wrote in message > news:ryELb.238$tK2.228 at amstwist00... > > > I have been experimenting with numerical algorithms in Python with a heavy > > use of the Numeric module. My experience is that Python is quite fast in > > comparison with (and sometimes as fast as) traditional languages such as C > > or C++. > > With "heavy use of Numeric module" you were calling functions > written in C. So how can you say that Python is fast, > when C code is doing all the work. Well, yes, but the Python VM is also written in C, and every time you make a call to a dictionary, or list etc, it is C code which is doing all the work. If you like, you could say that Python is a set of extremely clever wrappers around a bunch of optimised C code - but that rather diminishes the achievement of Python. I dare say that the Microsoft .NET and Visual Basic VMs are also written in C/C++, so you could say the same things about them - but I don't think that is a useful perspective. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bh at intevation.de Tue Jan 6 15:29:32 2004 From: bh at intevation.de (Bernhard Herzog) Date: Tue, 06 Jan 2004 21:29:32 +0100 Subject: PRE-PEP: new Path class References: Message-ID: <6qy8skkehf.fsf@salmakis.intevation.de> "John Roth" writes: > 5) Should == operator be the same as os.path.samefile()? > > Why not... ISTM, that it would essentially make path objects non-hashable. posixpath.samefile compares the os.stat values for both filenames. These values can change over time vor various reasons so object equality changes too. That it changes is desired, obviously, but what do you use as hash value? p1 == p2 has to imply that hash(p1) == hash(p2) but the only way to achieve that is to give all path objects the same hash value. That would make dicts with path objects as keys very inefficient, though. As for the path objects in general: Cute idea, but IMO strings for filenames work fine and there's nothing unpythonic about it. The virtual filesytem bit seems like a good reason not to introduce the path type just yet: > 2) virtual file system extensibility. > > No opinion at this time. I'd like to see a couple > of attempts at an implementation first before > settling on a single design. At this point it doesn't seem clear what virtual filesystems would mean for Python, so it's unclear, too, what it would mean for a Path class. Introduce a Path class once there is a need for having several distinct classes, not earlier. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From kevin at sb.org Wed Jan 28 14:44:51 2004 From: kevin at sb.org (Kevin Ballard) Date: Wed, 28 Jan 2004 14:44:51 -0500 Subject: getting files over ftp References: <560d84ab.0401281049.18d377f3@posting.google.com> Message-ID: On 2004-01-28 13:49:15 -0500, heavens7s at hotmail.com (Joe) said: > How can you grab files over an ftp connection using ftplib? I can > make the connection, browse to the directory, view directory, but > can't copy over the files. > > Thanks > How about the retrbinary() function? From CousinStanley at hotmail.com Fri Jan 9 19:54:31 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 9 Jan 2004 17:54:31 -0700 Subject: Problem with OpenGL.GLUT References: <7447dd2a.0401071402.2c0737e6@posting.google.com> <3FFF0B8B.4050208@rogers.com> Message-ID: | PyOpenGL doesn't include the actual GLUT library, | just a wrapper around it | .... | You can find a link for GLUT for win32 here: | | http://pyopengl.sourceforge.net/documentation/installation.html Mike .... Thanks for the info .... Sticking a copy of glut32.dll from the link you provided above in /site-packages/OpenGL fixed the import problem and the PyOpenGL demos now seem to fly as expected, with a few exceptions that have some errors that are of a different nature .... I also have a working version of PyOpenGL under Python 2.2 that has the glut32.dll in /site-packages/OpenGL and assumed that the installer that I used many months ago had stuck it there since I couldn't find any other GLUT related files in my archived downloads .... However, I probably somehow deleted it post-install .... -- Cousin Stanley Human Being Phoenix, Arizona From paul at prescod.net Thu Jan 22 12:40:37 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 22 Jan 2004 09:40:37 -0800 Subject: I support PEP 326 In-Reply-To: References: Message-ID: <40100B15.7060308@prescod.net> As a matter of style wouldn't it be nice to refer to PEPs both by number and by name? It is just a minor oversight but there is a tendency of communities to migrate to refering to things just by numbers in a way that excludes newcomers or hobbiests. NOT directed at you in particular Gary! Paul Prescod From shalabh at cafepy.com Thu Jan 15 01:31:09 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 14 Jan 2004 22:31:09 -0800 Subject: Deleting objects In-Reply-To: References: Message-ID: user at domain.invalid wrote: > Say I have an object (foo), that contains an > array (bar) of references to other objects. > > Now I want to puff some of the objects from the > array so that I remove the array element, and > destroy the oject. You don't need to jump through hoops for this. All you need to do is: del foo If there are no other references to the object that was called foo above, then (and only then) it will be destroyed. Python keeps a reference count for each object. When the count hits 0 (no references pointing to object) it is destroyed. Because of this, attributes of foo (eg foo.bar) will automatically be destroyed when foo is destroyed (assuming they don't have references from elsewhere). > > but when I do: > > del foo.bar[0] > > Python says: > object doesn't support item deletion > > So do I need to define __del__? And what would I > put there? What is the type of foo.bar? > > What if I wanted to remove the array element > but still have the object exist? del foo.bar This will remove the reference foo.bar. > What happens if I succeed in destroying an object > that other objects still think they are referencing? Try as you might, shooting yourself in the foot is pretty hard in Python (see above :) -- Shalabh From max at alcyone.com Tue Jan 6 18:23:07 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 Jan 2004 15:23:07 -0800 Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> <3FF9F0D0.3AA099CD@alcyone.com> <3FFAB034.E8513A36@engcorp.com> Message-ID: <3FFB435B.C34747DF@alcyone.com> Peter Hansen wrote: > I have or once had an absolutely excellent book on serial > communications > programming in C (probably called that, too) which made an excellent > case > for replacing all the myriad ways in which we represent end-of-line > with > a simple \v, since it is used effectively for no other purpose at this > point. I wish I had a copy of the ASCII Standard; it's possible that the Standard itself has some constraints on the usage of VT that would disallow this (I don't know for sure, though). The ISO-8859-1 control characters (not used in ISO/IEC 8859-1 -- gets confusing, doesn't it?) reserves another 32 codes for control characters from 0x80 to 0x9f (inclusive); included is NEL Next Line (0x85), which presumably was intended as a character to resolve the issue once and for all but which of course never caught on. The Unicode Standard does talk about NEL as an acceptable end-of-line indicator in exchange, though. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I dream things that never were and say, "Why not?" -- Robert F. Kennedy (after George Bernard Shaw) From paul at prescod.net Tue Jan 20 20:29:02 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 20 Jan 2004 17:29:02 -0800 Subject: Pyrex without Python (was Re: calling Pyrex results from C) In-Reply-To: <20040121005749.GA27424@unpythonic.net> References: <20040121005749.GA27424@unpythonic.net> Message-ID: <400DD5DE.90405@prescod.net> Jeff Epler wrote: > As I mentioned in another thread a few weeks ago, a current hobby is > writing code for small embedded processors, where "small" means 1k-4k > instructions and 128-1k bytes data. C is a fine language for this as long > as you don't use FP arithmetic or much of the standard library. You're definiately pushing the edge. Your domain name is appropriate. ;) > I wish I could write my code in Pyrex, of course keeping to 'int8_t' > and 'int16_t' as only basic data types, but it inevitably makes Python > API calls. > > How close to impossible would it be to make Pyrex emit Python-free code > if there are only 'cdefs'? It will generate a bunch of Python module crap. You could extract the pure-C code from the middle of it. The C code generated by the cdefs is pretty pure. static int __pyx_f_11pyrexmodule_fast_fib(int __pyx_v_n,int __pyx_v_a,int __pyx_ v_b) { int __pyx_r; int __pyx_1; /* "/Users/pprescod/code/fib/pyrexmodule.pyx":5 */ __pyx_1 = (__pyx_v_n == 0); if (__pyx_1) { /* "/Users/pprescod/code/fib/pyrexmodule.pyx":6 */ __pyx_r = __pyx_v_b; goto __pyx_L0; goto __pyx_L2; } /*else*/ { /* "/Users/pprescod/code/fib/pyrexmodule.pyx":8 */ __pyx_r = __pyx_f_11pyrexmodule_fast_fib((__pyx_v_n - 1),__pyx_v_b,(__pyx_v_ a + __pyx_v_b)); goto __pyx_L0; } __pyx_L2:; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; __Pyx_WriteUnraisable("pyrexmodule.fast_fib"); __pyx_L0:; return __pyx_r; } > ... Are there any obvious gotchas in > Pyrex-generated code if 'int' is a 16-bit datatype? Is there some > reason that large stack frames and/or calls to malloc() would be > unavoidable in Pyrex? Well...I think it is great to use Pyrex to avoid C (even ignoring Python extending). But onje of the main benefits of Pyrex is memory management (refcount + GC just like Python). I really don't see much benefit to using Pyrex if even _C_'s standard memory management is too extravagent for your needs. What exactly would Pyrex buy you if you can't afford to use its high-level features like memory management, constructors and OO? Paul Prescod From mhammond at skippinet.com.au Fri Jan 23 20:37:46 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 24 Jan 2004 12:37:46 +1100 Subject: weird COM hazard In-Reply-To: References: Message-ID: mic wrote: > and after a short debugging it looks like at some moment I loose the > reference to the ConnectionStatus class, though obviously I make no such > operation at all. As it happens 50% of times I run the same script and seems > to stop not only at the same event, I'm starting to believe that this is > kind of a bug in win32com. Does anybody experienced anything like that? What environment is this being run in? The only way I could see this being set to None externally is if Python itself is in the process of shutting down. There is nothing in win32com that will prevent Python terminating while COM objects are alive, so there is the potential that an external program tries to call back into Python during shutdown. I can't see how this could happen using Python.exe though. It is certainly nothing that has been reported before. Mark. From leo at lspace.org Mon Jan 19 13:10:41 2004 From: leo at lspace.org (Leo Breebaart) Date: Mon, 19 Jan 2004 18:10:41 +0000 (UTC) Subject: Delayed evaluation and setdefault() Message-ID: Hi all, I have a question about Python and delayed evaluation. Short-circuiting of Boolean expressions implies that in: >>> if a() and b(): any possible side-effects the call to b() might have will not happen of a() returns true, because then b() will never be executed. However, if I go looking for dictionary keys like this: >>> d = {} >>> d.setdefault('foo', b()) then b() *does* get executed regardless of whether or not the value it returns is actually used ('foo' was not found) or not ('foo' was found). If b() has side-effects, this may not be what you want at all. It would seem to me not too exotic to expect Python to have some sort of construct or syntax for dealing with this, just as it supports Boolean short-circuiting. So I guess my question is twofold: one, do people think differently, and if so why?; and two: is there any elegant (or other) way in which I can achieve the delayed evaluation I desire for setdefault, given a side-effect-having b()? -- Leo Breebaart From fumanchu at amor.org Fri Jan 2 12:38:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 2 Jan 2004 09:38:09 -0800 Subject: Conditional except: blocks Message-ID: I don't have a quesiton or problem, I just figured some of you would enjoy the somewhat bizarre logic of the snippet I just wrote for a CGI request dispatcher: try: return nextHandler(args) except (None, Exception)[self.trapErrors], exc: if page == u'-Error': raise exc else: return self.handle_error(exc, scriptWithPath) If self.trapErrors is True, all exceptions (which subclass Exception) get trapped, otherwise, no exceptions are trapped. Spiffy. :) FuManChu From mwh at python.net Tue Jan 13 05:52:31 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 10:52:31 GMT Subject: Python 2.3.3 compilation problems an HP-UX References: Message-ID: Olaf Meyer writes: > Aahz wrote: > > > In article , > > Olaf Meyer wrote: > > > >>I'm having some problems compiling Python 2.3.3 on HP-UX (B.11.00). > >> I've tried sevral different options for the configure script > >> (e.g. enabling/disabling gcc, aCC) but I always get the same > >> problem during the final linking stage. Several PyThread_* symbols > >> are undefined (for details see the output below). > > I'd suggest that you look at the recent threads about compiling for > > HP-UX on python-dev. It's starting to look like a SIG might be a good > > way to go. > > Thanks for pointing me there. It seems that there's some clean-up > needed for HP-UX. Luckily compiling 2.2.1 works fine for me, so I > think I'll stick with it until the 2.3 versions compile with HP-UX > 'out-of-the-box' ;-) Hmm. The 2.3 versions compile out of the box on *some* versions of HP-UX, because Anthony and I did it, on the Compaq testdrive machines. But I think they're 11.20 or so. Bah. Cheers, mwh -- If trees could scream, would we be so cavalier about cutting them down? We might, if they screamed all the time, for no good reason. -- Jack Handey From antonmuhin at rambler.ru Thu Jan 8 10:50:35 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Thu, 08 Jan 2004 18:50:35 +0300 Subject: Name of the function In-Reply-To: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> References: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> Message-ID: Olaf Meding wrote: > I am looking for a way to get at the name of the function (while > executing code inside the function) without (!) knowing the name of > the function. > > The code below works, but requires the name of the function. I am > looking for a way to do the same w/o specifying the name of the > function. > > def olaf(): > # requires name of the function > print olaf.__name__ > > # this does not work > print self.__name__ This seems to work: def foo(): print inspect.currentframe().f_code.co_name regards, anton. From usenet at mail-2-me.com Fri Jan 30 07:47:51 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: 30 Jan 2004 04:47:51 -0800 Subject: How to start a DTS Package on MS-SQL-Server? Message-ID: Hi! Does anybody know how to start a DTS-Package on a MS-SQL-Server out of a Python-Script? Thanks for your help! Dirk From shalabh at gameboard.org Sat Jan 10 22:05:17 2004 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: Sun, 11 Jan 2004 03:05:17 GMT Subject: Variable Scope 2 -- Thanks for 1. References: <3fff16b6$0$315$e4fe514c@news.xs4all.nl> Message-ID: Duncan Booth wrote: > Be careful. The integer object is actually altered, at least in so far as > its reference count (which is part of the object) is changed: > >>>> import sys >>>> sys.getrefcount(29) > 11 >>>> age = 29 >>>> sys.getrefcount(29) > 12 >>>> > Off the orig topic, but I think this only happens for small numbers (optimization - only one object exists for small numbers in Python). >>> a = 101 >>> sys.getrefcount(101) 2 >>> b = 101 >>> sys.getrefcount(101) 2 >>> In other words: >>> a = 29 >>> b = 29 >>> a is b True >>> a = 101 >>> b = 101 >>> a is b False Of course, 'is' isn't useful when comparing int objects. For other operations, the semantics are not affected anyway as int objects are immutable. -- Shalabh From carroll at tjc.com Fri Jan 9 14:44:21 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri, 09 Jan 2004 19:44:21 GMT Subject: Unicode and exception strings References: Message-ID: On 09 Jan 2004 13:18:39 +0100, Rune Froysa wrote: >Assuming an exception like: > > x = ValueError(u'\xf8') > >AFAIK the common way to get a string representation of the exception >as a message is to simply cast it to a string: str(x). This will >result in an "UnicodeError: ASCII encoding error: ordinal not in >range(128)". > >The common way to fix this is with something like >u'\xf8'.encode("ascii", 'replace'). However I can't find any way to >tell ValueErrors __str__ method which encoding to use. Rune, I'm not understanding what your problem is. Is there any reason you're not using, for example, just repr(u'\xf8')? In one program I have that occasionally runs into a line that includes some (UTF-8) Unicode-encoded Chinese characters , I have something like this: try: _display_text = _display_text + "%s\n" % line except UnicodeDecodeError: try: # decode those UTF8 nasties _display_text = _display_text + "%s\n" % line.decode('utf-8')) except UnicodeDecodeError: # if that still doesn't work, punt # (I don't think we'll ever reach this, but just in case) _display_text = _display_text + "%s\n" % repr(line) I don't know if this will help you or not. From fumanchu at amor.org Sat Jan 24 16:58:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 24 Jan 2004 13:58:48 -0800 Subject: xray module Message-ID: I finally cleaned up the code I've been using for a while now to grab objects out of modules via dotted-package names (all this work to avoid using exec! Sheesh!). Feel free to use it, abuse it, or comment on it. I realize many of you already do this on your own--this is just sugar for the newbies. I'm releasing/announcing it for three reasons: 1. The ego rush of authorship, :D 2. I continually hear people asking for similar (if not exact) functionality, especially those coming from a Java/Tomcat background, and 3. The name is cool. I spent a lot of time on it. Here 'tis: # xray.py """Load modules, classes, functions, and attributes by dotted package names. Usage: desiredClass = xray.classes("myapp.strtools.alwayslowercase", str) newInstance = desiredClass() or for f in startup_function_names: func_object = xray.functions(f) func_object() Rationale: I try to create systems that are configurable by deployers; mostly becase I hate it when an application forces me to use the database, filesystem, communication protocol, algorithm, or operating system du jour. Abstracting these basic components of an application is its own study (look up the Gang of Four "Strategy" pattern for a start); this is often accomplished with classes which share signatures, often via subclassing. However, the deployer then needs to specify the class they wish to use. This module gives them the ability to specify that with a single string (for example, in a text configuration file). """ import sys def modules(modulePath): """Load a module and retrieve a reference to that module.""" try: aMod = sys.modules[modulePath] if aMod is None: raise KeyError except KeyError: # The last [''] is important. aMod = __import__(modulePath, globals(), locals(), ['']) sys.modules[modulePath] = aMod return aMod def attributes(fullAttributeName): """Load a module and retrieve an attribute of that module.""" # Parse out the path, module, and attribute lastDot = fullAttributeName.rfind(u".") attrName = fullAttributeName[lastDot + 1:] modPath = fullAttributeName[:lastDot] aMod = modules(modPath) # Let an AttributeError propagate outward. anAttr = getattr(aMod, attrName) # Return a reference to the attribute. return anAttr def functions(fullFuncName): """Load a module and retrieve a function object.""" aFunc = attributes(fullFuncName) # Assert that the function is a *callable* attribute. if not callable(aFunc): raise TypeError(u"'%s' is not callable." % fullFuncName) # Return a reference to the function itself, # not the results of the function. return aFunc def classes(fullClassName, parentClass=None): """Load a module and retrieve a class (NOT an instance). If the parentClass is supplied, className must be of parentClass or a subclass of parentClass (or None is returned). """ aClass = functions(fullClassName) # Assert that the class is a subclass of parentClass. if parentClass is not None: if not issubclass(aClass, parentClass): raise TypeError(u"'%s' is not a subclass of %s" % (fullClassName, parentClass.__name__)) # Return a reference to the class itself, not an instantiated object. return aClass # end xray.py Robert Brewer MIS Amor Ministries fumanchu at amor.org From sidharthk at hotmail.com Mon Jan 26 05:44:36 2004 From: sidharthk at hotmail.com (Sidharthk) Date: 26 Jan 2004 02:44:36 -0800 Subject: efficient updating of nested dictionaries References: Message-ID: <8d02ff63.0401260244.f0732e6@posting.google.com> This is untested code but i think it should work.(fingers crossed) Btw i doubt this will be fast though. def rec_update(mydict, newdict): presentKeysPairs = [(key,value) for (key, value) in newdict.items() if mydict.has_key(key)] newKeysPairs = [(key,value) for (key, value) in newdict,items() if not mydict.has_key(key)] for key, newValue in presentKeysPairs: currentValue = mydict[key] if isisntance(newValue, dict): mydict[key] = rec_update(newValue) else: mydict[key] = newValue mydict.update(dict(newKeysPairs)) return mydict regards ps. why can't you simply use tuples to represent the different dimensions, even if the number of dimensions vary. is there any particular reason why you are using these nested dictionaries? From newsgroups at jhrothjr.com Sat Jan 31 14:37:37 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 31 Jan 2004 14:37:37 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: <101o11rl6d4q6fb@news.supernews.com> "Paul Prescod" wrote in message news:mailman.1078.1075571238.12720.python-list at python.org... > Daniel Ehrenberg wrote: > > "Sean Ross" wrote > > > \> > > I'm not sure how to tell you this so I'll just give a heavily > > commented example (comments in Io are with #, //, or /* */) > > > > parentProto := Object clone //makes parentProto a new object > > //:= is used for creating new variables > > parentProto shared := 5 //parentProto's new slot shared holds 5 > > Do you know why the creator of IO decided not to use the now-ubiquitous > "." operator? I don't know whether I can define a "." operator that has > the appropriate behaviour but that wouldn't help anyhow. As far as I know, since everything is a "message send", the dot is unnecessary. Every operation is either object.paremeter(s), or syntactic sugar that gets transformed into that format. John Roth > > Paul Prescod > > From nav+posts at bandersnatch.org Sat Jan 17 21:38:43 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 17 Jan 2004 21:38:43 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <1074370049.790131@radsrv1.tranzpeer.net> Message-ID: Corey Murtagh writes: > Actually I kind of agree here. I've had plenty of problems with > Cygwin - although less with MinGW. It's always performed flawlessly for me. Have you reported the problems to the Cygwin folks, or tried to fix the issues yourself? > An OSS project that requires a Linux emulation shim to run on any > other platform is not, IMHO, cross-platform at all. Linux != Gnu, though to some that might seem like splitting hairs. What other free development environments are there for Win32 that offers power and flexibility comparable to the Cygwin tools? Visual Studio is not free (quite the opposite!), and for many OSS developers, that makes it impractical. Sorry, I realize this is getting pretty off topic, especially for the Python group, which is where I'm reading it. 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 fuf at mageo.cz Wed Jan 28 09:13:08 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 15:13:08 +0100 Subject: fast deep-copying of instances Message-ID: <20040128141308.GA11278@foof.i3.cz> hello, i have a data cache which sits between a slow database and my server and it's used to cache data retrieved from the database. in order for it to work correctly (race-conditions) i need a fast deep-copying of instances (the cache is used heavily). i tried to use copy module but it's *very* slow, then i tried cPickle to pickle and depickle instances which was faster, but still slow. then i've come across cCopy which is 8x faster than copy, but unfortunately it doesn't work with new style classes because type()'s return is crappy for them. so the question is: does there exist a fast copy module which works with new style classes? thank you, -- fuf (fuf at mageo.cz) From cookedm+news at physics.mcmaster.ca Thu Jan 29 17:25:54 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 29 Jan 2004 17:25:54 -0500 Subject: Color count in PIL References: <2ec1bc1c.0401271443.15f56742@posting.google.com> <2ec1bc1c.0401291326.5602aee2@posting.google.com> Message-ID: At some point, wrbt at email.com (Larry) wrote: > wrbt at email.com (Larry) wrote in message news:<2ec1bc1c.0401271443.15f56742 at posting.google.com>... >> I've been walking up, down, and around instances in the object model >> of PIL trying to figure out how to easily calculate how many unique >> colors are used in an image, specifically a bitmap (mode "P"). Am I >> missing something? >> >> Thanks python friends! > > So far I have: colors=len(sets.Set(list(im.getdata()))) > > That makes me want to throw up. Probably very inefficient. Have a look at im.histogram(). Something like: colours = sum( [ 1 for h in im.histogram() if h != 0 ] ) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From dave at pythonapocrypha.com Fri Jan 23 12:21:56 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 23 Jan 2004 10:21:56 -0700 Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <025101c3e1d5$670a7c90$6401fea9@YODA> Harry wrote: > "Dave Brueck" writes: > > > Moosebumps wrote: > > > So, after reading some messages about os.system, and looking at the popen > > > stuff and trying it a bit, I still have not found a way to keep a command > > > window open for several commands (on Windows 2000/XP), while seeing the > > > normal output in a command window. All I want to do is do what a batch file > > > does, but I want to actually have functions and associative arrays and all > > > the other niceties of python. > > > > Can you give an example of what you mean, in Perl as well as what you hoped > > would work in Python? I couldn't quite understand what it is that you're trying > > to do. > > > > > What's the deal with that? I thought Python started out as a scripting > > > language. And that seems like the most basic thing that a scripting > > > language should do. > > > > Dunno, although MS-DOS shell scripting is certainly a small subset of scripting > > in general. Maybe with a concrete example somebody will be able to give you a > > hand. > > > > -Dave > > > > > > I wonder if this is miscommunication over "script" vs "shell window". > This confused me when trying python scripts in MS Windows after using > then in *NIX. Yeah, I wondered that too, although I thought the OP said this problem didn't occur with Perl. Maybe I misunderstood the message though. -Dave From wmich50 at theramp.net Fri Jan 9 11:44:03 2004 From: wmich50 at theramp.net (Walt) Date: Fri, 09 Jan 2004 07:44:03 -0900 Subject: xml-rpc Message-ID: Newbie using xmlrpclib Curious about why the same very simple xml-rpc demo code should execute quickly under python2.1 but very slowly under python2.3 python2.1 ~4 seconds python2.3 ~24 seconds on the same machine Is there a well known reason for the difference? Here's the code: ----------------------------------------------------------------------------- from xmlrpclib import * import sys server = Server("http://wmich.freeshell.org/betty.php") try: print "Got '" + server.examples.getStateName(32) + "'" print "----------------------------------------------------" r = server.examples.echo('Three "blind" mice - ' + "See 'how' they run") print r print "--------------------------------------------" # name/age example. this exercises structs and arrays a = [ {'name': 'Dave', 'age': 35}, {'name': 'Edd', 'age': 45 }, {'name': 'Fred', 'age': 23}, {'name': 'Barney', 'age': 36 }] r = server.examples.sortByAge(a) print r print "---------------------------------------------" except Error, v: print "XML-RPC Error:",v ------------------------------------------------------------------------------ Thanks, Walt From http Mon Jan 12 16:46:38 2004 From: http (Paul Rubin) Date: 12 Jan 2004 13:46:38 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> Message-ID: <7xeku496wx.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > >I'd say don't bother with C++ unless you're working on a big > >multi-person project. Its design will make no sense to you unless > >you've faced the problems that come up in those projects. Otherwise > >it's a big mess. > > And if you *are* working on a big multi-person project, and you > choose C++, you're likely to end up with ... a big mess. C++ was motivated by the problems faced by big projects written in C. I'm talking about stuff like telephone switches with hundreds of programmers and millions of lines of code. Even with very competent designers and managers, those projects usually ran amuck. C++ gives some real help in keeping projects like that functioning, if the programmers and managers know what they're doing. If they don't know what they're doing (as is the case in most projects), C++ isn't that likely to help and may make the problems worse. But if you've lived through the multitudinous nightmares of projects like that, and you then read Stroustrup's book about C++, on just about every page you'll see some feature described and you'll recognize the specific nightmare that inspired it. If you haven't experienced those nightmares yourself, I can't be sure but I think the feature descriptions will just seem like feature descriptions and you won't understand the real reasons why they're there. I think the OP's list should also have included Java, which is sort of a modernized, "discount" version of C++. From me at privacy.net Tue Jan 27 19:33:00 2004 From: me at privacy.net (Heather Coppersmith) Date: 27 Jan 2004 19:33:00 -0500 Subject: I support PEP 326 References: <698f09f8.0401271318.21c9ca72@posting.google.com> Message-ID: On 27 Jan 2004 13:18:43 -0800, tweedgeezer at hotmail.com (Jeremy Fincher) wrote: > ... If I have my Min/Max objects and you have your Min/Max > objects, someone's objects simply aren't going to work as > expected. Sure they will: Mine is mymodule.Min; yours is yourmodule.Min. Use "from import" at your own risk and peril. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From fisher at energy.uch.net Mon Jan 26 05:36:48 2004 From: fisher at energy.uch.net (Serge A. Ribalchenko) Date: Mon, 26 Jan 2004 12:36:48 +0200 Subject: need something like threads, or just multiple simulateous exec's Message-ID: Hi all, I'm new in python coding... Can someone point me how can I do such a usual thing? I need to ping some hosts, and harvest results in one list. Just cause there is about 120 hosts in the LAN, and approx. 10% is down at working hours, pinging each host at a time from cycle is VERY slow solution. I did: retv = os.popen('ping -c 1 ' + ip + ' |grep \"1 packet\" |awk \'{print $4}\'') res = retv.read() In cycle. BUT. I need something FASTER. And I feel fear to scary word 'thread'. May someone give me some examle using threads for this purpose? Thanks. Best wishes, ~ Serge. From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Sat Jan 24 04:41:46 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 24 Jan 2004 11:41:46 +0200 Subject: Perl vs. Python for text manipulation (was: [OPINION] - does language really matter if they all do the samething?) References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: >>>>> "Cameron" == Cameron Laird writes: Cameron> conclusively demonstrates, at least for me; but I don't Cameron> even see Perl as distinctly superior to Python in text Cameron> mangling. I recognize that Python REs can feel a bit Me neither. People seem to think that if a language is specialized to some task, it must be superior to a language that isn't specialized to the task for performing that very task. I don't see any truth in that logic. Cameron> cumbersome, in comparison to Perl, because they essenti- Cameron> ally demand the extra step of explicit compilation. Is And even that isn't needed: re.search("hello.*ld","hello world"). Cameron> that all that people mean, though, when they talk about Cameron> Perl's superiority for text mangling? Is there more to Cameron> it? -- I think there is the argument of perl being faster in some such tasks. That shouldn't really matter for most text processing tasks that are batch runs anyway. Someone should just write a "dirtypython"-module, and importing * from the module would get all the shortcuts that make Python seem more verbose than perl: rs = re.search s = re.sub And perhaps add a lot of magic to the functions that cripple the general purpose usability, but make "common tasks" more concise. Voila', Perl. -- Ville Vainio http://tinyurl.com/2prnb From peter at engcorp.com Thu Jan 8 10:23:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Jan 2004 10:23:39 -0500 Subject: Naming convention for non-inplace methods (was Re: PRE-PEP: new Path class) References: <1073567709.3ffd57dda8cb0@mcherm.com> <3FFD72BD.780554D8@engcorp.com> Message-ID: <3FFD75FB.4F61FDF1@engcorp.com> Syver Enstad wrote: > > Peter Hansen writes: > > > I haven't been following (either discussion) closely, but this > > sounds similar to some posts I read about a discussing involved a > > .reverse() method, and the apparent conclusion that .reversed() > > [note the 'd'] was more appropriate as it didn't imply that the > > object was being modified in-place, but that it was returning a > > reversed version of itself. Same thing could apply here... > > Good point, but what about asNormalized() or asReversed()? Or > as_reversed() or as_normalized() if that is the coding > convention. Doesn't that communicate the intent even better? I wouldn't object strenuously to any one of the three approaches, although the simple .normalized() and .reversed() version feels slightly more Pythonic to me, merely because the other two don't seem to be existing conventions in, say, the standard libraries. I'd go with whatever precedent has already been set, if one has been set, and otherwise open a new discussion as the topic has a lot of merit... -Peter From jjl at pobox.com Fri Jan 23 07:45:50 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 12:45:50 +0000 Subject: Urllib2 upgrade is breaking urlopen() References: <1d17eeb7.0401221818.7d98672@posting.google.com> Message-ID: <87znce4yv5.fsf@pobox.com> dj00302003 at yahoo.com (Jay Davis) writes: > We have a lot of simple code using 'urllib', that basically > just goes out and opens and read()'s some http url. Very basic, > ten line scripts, and they work fine with urllib. > > We want to use urllib2 for everything, though, but when we > do we get: [...] > urllib2.HTTPError: HTTP Error 302: The HTTP server returned a redirect > error that would lead to an infinite loop. > The last 30x error message was: > Found Which version of Python are you using? It might also help if you can give a publicly-accessible URL that triggers the problem (mail it to me privately if you prefer). John From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Wed Jan 21 02:38:35 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 21 Jan 2004 09:38:35 +0200 Subject: an example of a singleton design pattern in python? References: <400DAF6F.6EF66415@engcorp.com> Message-ID: >> This trivial snippet might be enough for your needs: >> >> class Foo(): pass >> >> _inst = None >> >> def fooinstance(): if not _inst: _inst = Foo() return _inst peter> Looks like at least two errors, one being the parentheses peter> on the class name, and the other being a failure to flag peter> _inst as being global... True. I guess the idea got through anyway. It was late :-P. -- Ville Vainio http://tinyurl.com/2prnb From stephendotboulet at motorola_._com Mon Jan 26 15:49:25 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Mon, 26 Jan 2004 14:49:25 -0600 Subject: Zope In-Reply-To: References: Message-ID: lenk wrote: > Stephen Boulet wrote: > > > Just wondering, it's not in /etc/init.d/zope* ? > > > > there is no zope path in etc/init.d/.. > only /opt/zope/........... Does "rpm -ql zope | grep bin" return anything useful? (Hoping I'm remembering my rpm arguments ...) Stephen From max at alcyone.com Mon Jan 19 14:55:00 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 19 Jan 2004 11:55:00 -0800 Subject: HowTo distinguish between File and Directory References: Message-ID: <400C3614.2DAA2197@alcyone.com> Scott F wrote: > On Win32, is there a function in the standard modules that can take a > pathname and return whether it refers to a File or a Directory? There's certainly one in the os module: os.path.isdir and os.path.isfile. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The critical period in matrimony is breakfast-time. -- A.P. Herbert From newsgroups at jhrothjr.com Sat Jan 3 07:46:21 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 07:46:21 -0500 Subject: finding file size References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: "Martin v. Loewis" wrote in message news:bt3l9i$pog$07$3 at news.t-online.com... > Sean Ross wrote: > > > My question is this: Is there a reason why file objects could not have a > > size method or property? > > Yes. In Python, file objects belong to the larger category of "file-like > objects", and not all file-like objects have the inherent notion of a > size. E.g. what would you think sys.stdin.size should return (which > actually is a proper file object - not just file-like)? > > Other examples include the things returned from os.popen or socket.socket. I think the issue here is that the abstract concept behind a "file-like object" is that of something external that can be opened, read, written to and closed. As you say, this does not include the notion of basic implementation: a file on a file system is a different animal than a network socket, which is different from a pipe, etc. I think we need an object that encapsulates the notion of a file (or directory) as a file system object. That object shouldn't support "file-like" activities: it should have a method that returns a standard file object to do that. I like Geritt Holl's filename suggestion as well, but it's not the same as this suggestion. John Roth > > Regards, > Martin > From mcfletch at rogers.com Wed Jan 21 16:21:32 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 21 Jan 2004 16:21:32 -0500 Subject: Need help with Python class idioms In-Reply-To: References: Message-ID: <400EED5C.6040609@rogers.com> Tad Marko wrote: >Howdy! > >I'm trying to get my head around Python and I've come to realize that >there are a lot of idioms in Python that are a bit different than in >other languages. I have a class similar to what I've included below. >The only difference is that in the real class, I have even more >mandatory attributes. Too many to specify at once on a constructor and >they don't always exist at construction time anyway, so the accessor >idiom must remain. > >Can anyone suggest a more Pythony way to do the following? > > Note: shameless plug follows... With basicproperty, it would look something like this: class A( propertied.Propertied ): mandatoryVar1 = common.IntegerProperty( "mandatoryVar1", """Property that's mandatory 'cause we're cool""", ) defaultVar1 = common.IntegerProperty( "defaultVar1", """Property that's got a default value""", defaultValue = 32, ) defaultVar2 = common.StringProperty( "defaultVar2", """Property that's got a default function instead""", defaultFunction = lambda prop, client: client.__class__.__name__, ) a = A( mandatoryVar1 = 3 ) a.defaultVar2 a.defaultVar1 however, you continue on to show you're using a database, so you'd probably prefer something like pytable (which is built on top of basicproperty, but uses database schemas to control the creation and operation of the properties): from pytable.schemabuilder import * schema = table( "my_table", comment = """Table for storing whatevers""", fields = ( field( 'mandatoryVar1', 'integer',0, # name, sql data-type, size constraints = ( notNull(), ), ), field( 'defaultVal1', 'integer',0, # name, sql data-type, size defaultValue = 32, # sql default value constraints = ( notNull(), ), ), field( 'Var2', 'timestamptz',0, # name, sql data-type, size defaultValue = '"timestamp"(\'now\'::text)', # sql default value constraints = ( notNull(), ), ), ), indices = ( index( primary=1, fields=('mandatoryVar1', 'defaultVal1')), ), ) print schema.itemClass help( schema.itemClass ) row = schema.itemClass( mandatoryVar1 = 33 ) row.insertQuery( my_db_connection ) # get one from pytable row.mandatoryVar1 = 34 row.updateQuery( my_db_connection ) row.deleteQuery( my_db_connection ) BasicProperty: http://basicproperty.sourceforge.net/ PyTable RDBMS Wrapper: http://pytable.sourceforge.net/ In a more general sense, for DB operations, use a database wrapper module, there's lots of them around. And even more generally, properties are *very* good at describing (common) property-based systems of objects such as you're apparently working with. Properties are new with Python 2.2, so underused sometimes, but they are very good at certain types of domain modelling. Enjoy yourself, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From alessandro at sephiroth.it Sat Jan 10 09:25:44 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Sat, 10 Jan 2004 14:25:44 GMT Subject: readling newlines Message-ID: Hi, I'm trying to detect the newlines method of a file opened. I'm using the 'U' mode as parameter when opening a file, but for every file opened the result is always "\r\n", even if the file has been saved with the "\n" newline method. Is there i'm missing? I'm on Windows with python 2.3.3 From wichert at wiggy.net Thu Jan 22 05:35:49 2004 From: wichert at wiggy.net (Wichert Akkerman) Date: Thu, 22 Jan 2004 11:35:49 +0100 Subject: utf8 encoding problem Message-ID: <20040122103549.GA5620@wiggy.net> I'm struggling with what should be a trivial problem but I can't seem to come up with a proper solution: I am working on a CGI that takes utf-8 input from a browser. The input is nicely encoded so you get something like this: firstname=t%C3%A9s where %C3CA9 is a single character in utf-8 encoding. Passing this through urllib.unquote does not help: >>> urllib.unquote(u't%C3%A9st') u't%C3%A9st' The problem turned out to be that urllib.unquote() process processes its input character by character which breaks when it tries to call chr() for a character: it gets a character which is not valid ascii (outside the legal range) or valid unicode (it's only half a utf-8 character) and as a result it fails: >>> chr(195) + u"" Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) I can't seem to find a working method to do this conversion correctly. Can someone point me in the right direction? (and please cc me on replies since I'm not currently subscribed to this list/newsgroup). Wichert. -- Wichert Akkerman It is simple to make things. http://www.wiggy.net/ It is hard to make things simple. From mjackson at alumni.caltech.edu Wed Jan 21 22:35:45 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 22 Jan 2004 03:35:45 GMT Subject: Secure Voting software References: <20040121174434.28446.00000428@mb-m15.aol.com> <7xvfn4lq9m.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > piedmontbiz at aol.com (PiedmontBiz) writes: > > What things must I keep in mind when I design a python application to be > > secure? > > > > Since python is developed using C, can python be free from the > > buffer overrun problems which plague other C programs? > > Buffer overruns are just one narrow type of security failure. > Security is really a hard subject and even systems built by experts > often have security holes. There are various books written on how to > write secure software, and also some HOWTO's. For systems like voting > machines, there are a lot of non-software issues you have to deal with too. > > The book "Security Engineering" by Ross Anderson is a good place to start > reading if you're interested in the subject. Many of the issues have been discussed on comp.risks over the years, and the archives of same contain some useful pointers to in-depth analyses. A searchable archive is found at http://www.risks.org. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson No *good* model ever accounted for *all* the facts, since some data was bound to be misleading if not plain wrong. - James D. Watson From exarkun at intarweb.us Mon Jan 5 08:13:46 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 5 Jan 2004 08:13:46 -0500 Subject: Why exception is not newstyle class? In-Reply-To: <2f9c31f.0401042349.3eea0e9b@posting.google.com> References: <2f9c31f.0401042349.3eea0e9b@posting.google.com> Message-ID: <20040105131346.GB4988@intarweb.us> On Sun, Jan 04, 2004 at 11:49:35PM -0800, kyo wrote: > > I want to use new style class, how to do that? > If I can't, Why? Because Exceptions existed before new-style classes did, and the mechanism has not yet caught up. Jp From ajw140NO at SPAM.york.ac.uk Sat Jan 17 11:30:38 2004 From: ajw140NO at SPAM.york.ac.uk (Andrew Wilkinson) Date: Sat, 17 Jan 2004 16:30:38 +0000 Subject: Overriding operator delete in a Python extension Message-ID: Hi, This is probably more of a gcc question than a python one, but hopefully someone out their will know that answer. I've written a C++ Python extension, and as part of it I override the operator new and operator delete functions to provide memory leak tracking from within the extension. When I use the code as part of a complete C++ program everything works perfectly, however when I compile it with my Python interface code the operator delete function is not called - the operator new function is called as normal however. I assume this is because the function is not linked correctly, but I'm at a loss for how to make the linker resolve the references in the .so file. Does anyone know a possible solution to my problem? Regards, Andrew Wilkinson -- University is a fountain of knowledge, and students go there to drink. From dialtone#NOSPAM#.despammed at aruba.it Fri Jan 16 18:47:45 2004 From: dialtone#NOSPAM#.despammed at aruba.it (Valentino Volonghi aka Dialtone) Date: Sat, 17 Jan 2004 00:47:45 +0100 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> <100b266i0r70g86@corp.supernews.com> Message-ID: <87ektzv4ke.fsf@vercingetorix.caesar.org> Donn Cave writes: > Python may have stricter dynamic typing than C++ has > static typing, but that's hard to quantify. On the > other hand, Python has no static typing at all. There > is no way to tell it ``this function must be applied > to a string and must return an int.'' If applied to > a list instead, there's a non-trivial chance it will > manage to do something absurd with it. If it returns > None under certain circumstances, there's a non-trivial > chance that value will be stashed away somewhere and > you'll later wonder where the heck that None came from. You clearly don't know enough of python to talk like this about the language features... You need static typing (why then... I cannot see any good reason, anyway...)? Well then, use pyrex. You'll find yourself writing code like this: cdef int a, b def sum(int a, int b): return a+b Then using pyrex parser you would build a python extension module which you will compile it. If you do errors using types it will catch it. Anyway there's no need to use this stuff... absolutely no reasonable need. Except if you need a lot of speed and you need to implement an algorithm directly in C using native C types and not python objects. -- Valentino Volonghi, Regia SpA, Milan Linux User #310274, Gentoo Proud User From seanl at chaosring.org Sun Jan 4 17:39:21 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sun, 04 Jan 2004 14:39:21 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: Serge Orlov wrote: > "John Roth" wrote in message news:vvg0h93ue63c0b at news.supernews.com... > >>Much of this thread has focused on "capabilities" and the use of >>proxies to implement capabilities. AFIAC, that's not only putting >>attention on mechanism before policy, but it's putting attention on >>mechanism in the wrong place. > > > I'm not sure why it should be discussed here since Sean refered > to E in the first post (http://www.erights.org/), so I think he's > comfortable with the policy defined by E? I think he has > missed the part that implementation should help as much as > it can prevent leaking capabilities from one security domain to > another. I pointed to that already. I am comfortable (so far) with the policy defined by E. However, I've been learning more about that policy as I go, including the necessity of helping the programmer prevent leaks, which I've started to implement by making objects completely opaque by default and requiring that classes list attributes that they want to make public. I have kept my name-mangling scheme for private attributes. I'm working on making classes opaque while still allowing code to call methods defined on superclasses but only on self, not on other objects that happen to inherit from the same superclass. >>What I *haven't* seen in this thread is very much consideration of >>what people want from a security implementation. > > > I think Sean is talking about his own implementation. I didn't > see anywhere he said he's going to write general implementation > for other people. He said what he wants from his implementation. I would like my implementation to be as general as possible, but I'm writing it for my own projects. All this talk of "breaking existing code" and the like is not particularly relevant to me because, while I'd like code to look as much like regular Python as possible, it's simply not possible not to break existing code while helping the programmer prevent leaks. Making objects opaque by default is going to break a hell of a lot more code than not having a type() builtin, so I think people can see why I'm not too concerned about leaving various builtins out. >>One problem I've been playing around with is: how would you >>implement something functionally equivalent to the Unix/Linux >>chroot() facility? The boundaries are that it should not require >>coding changes to the application that is being restricted, and it >>should allow any and all Python extension (not C language >>extension) to operate as coded (at least as long as they don't >>try to escape the jail!) Oh, yes. It has to work on Windows, >>so it's not a legitimate response to say: "use chroot()." This is an interesting problem, but not one I'm trying to solve here. I'm modifying RestrictedPython to make it possible to use a pure capabilities-based security model in an application server. The application server must scale to tens of thousands of security domains, and I see no reason why the security model can't or shouldn't be language-based instead of OS-based. There's E for Java, why can't we make something similar for Python? There is nothing particularly special about Java that makes it more suitable for E than Python is. Both have unforgeable references. I've already added object encapsulation. I'm working on eliminating any static mutable state. Ultimately, I'd like to have user-level threads, too. I'm considering either using Stackless for this or doing some mangling of ASTs to make it easier to use generators as coroutines. Unfortunately, I can't think of a way for the compiler to tell that you're calling a coroutine from within a coroutine and therefore needs to output "yield (locals, resultvarname, func, args, kwargs)" instead of a regular function call without using some special syntax. Actually, I don't even know if it's possible to modify the locals dict of a running generator without causing trouble. From jcarlson at nospam.uci.edu Wed Jan 28 16:51:05 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 28 Jan 2004 13:51:05 -0800 Subject: Best way to compare a list? In-Reply-To: <7b454334.0401281242.3bd604e6@posting.google.com> References: <7b454334.0401271739.59267018@posting.google.com> <7b454334.0401281242.3bd604e6@posting.google.com> Message-ID: Fazer wrote: > John Hunter wrote in message news:... > >>>>>>>"Fazer" == Fazer writes: >> >> Fazer> Hello, I was wondering which would be the best way to >> Fazer> compare a list? >> >> Fazer> I was thinking of just using a for loop and testing the >> Fazer> condition. >> >> Fazer> What do you guys think? The best/fastest way of comparing >> Fazer> lists. >> >>What do you want to compare for, equality of all elements? Give a >>little more info about what you need to do. >> >>JDH > > > Sorry about that. > > Basically, I have to lists. I have to compare them and pick out the difference(s). > > Maybe the simple/fast approach would be to use a for loop? > > Thanks, If position information matters to you, I would imagine your initial code is something like this... import itertools def list_differences(a, b): l = [(x,y) for x,y in itertools.izip(a,b) if x != y] if len(a) != len(b): d = abs(len(a)-len(b)) if len(a) < len(b): l.extend(zip(d*[None], b[len(a):])) else: l.extend(zip(a[len(b):], d*[None])) return l If position information matters, the above is pretty much optimal. There doesn't seem to be a method in Python that would further speed up iterating through two lists. If positional information doesn't matter, and you just care about whether or not objects exist in one, the other, or both lists, then I believe this is easily done with Sets in Python 2.3. I don't know for sure, I haven't used them yet. - Josiah From trendmicro at wuest.de Wed Jan 28 13:58:22 2004 From: trendmicro at wuest.de (trendmicro at wuest.de) Date: Wed, 28 Jan 2004 19:58:22 +0100 Subject: Virus Alert Message-ID: <20040128185822.6D53135F60@obelix.wuest.de> The mail message (file: message.zip) you sent to leo at wuest.de contains a virus. (on obelix) From LittleDanEhren at yahoo.com Sat Jan 31 15:20:52 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 31 Jan 2004 12:20:52 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> Message-ID: <711c7390.0401311220.763be80a@posting.google.com> > Perhaps it isn't more flexible. On the other hand, it does allow anyone > to read your code and know that there isn't any magical syntax that is > usable on one Python x.y installation, that isn't on another. > > - Josiah What are you talking about? There's tons of new "magical syntax" in Python. Examples for "magical syntax" features that don't work on 1.5.2 include: *List comprehensions *String methods *Generators *Emulating numeric types *Nested scopes * * and ** in function declarations *for line in this_file *Subclassing types There's tons of stuff still being added to Python. Daniel Ehreberg From jim-usenet at jimdabell.com Wed Jan 14 17:23:57 2004 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Wed, 14 Jan 2004 22:23:57 +0000 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: Brandon J. Van Every wrote: [snip] > OSS people are doing "their thing," and it is not my thing. [snip] So don't try working with OSS. Open-source developers typically work under different constraints to proprietary developers, and you will almost certainly be unsuccessful if you attempt to impose a different set of constraints upon them or assume they have the same priorities as proprietary developers. If you need people to work for you, hire them. [Removing comp.lang.python from followups; this isn't anything to do with Python.] -- Jim Dabell From mickel at csc.fi Mon Jan 19 09:35:55 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Mon, 19 Jan 2004 16:35:55 +0200 (EET) Subject: Memory and speed with lots of objects on Tkinter.Canvases Message-ID: Hi everybody, This is a question about Tkinter.Canvases and performance: I am writing a Tkinter application that among other things contains a number of Tkinter.Canvases that in turn hold rectangle and text objects that can be moved along with clicking and dragging the mouse. Everything works fine and well when I have just a few of these objects on the canvases, but when the number of objects on the canvases grow over a thousand, the application gets really sluggish. (I am running Python 2.3.2 on Redhat Linux 9 on a 866 MHz Pentium III with 256 MB of RAM (and approx. 0.5 GB of swap space, if that matters ...).) Does anybody else have experience with having thousands of objects on Tkinter.Canvases and how this impacts on the speed of the application? Are there any nice tricks for tuning up performace when having lots of objects on Tkinter.Canvases? Help! :) /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 Florian.Lindner at xgm.de Thu Jan 22 07:34:56 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Thu, 22 Jan 2004 13:34:56 +0100 Subject: prog/lib to draw graphs Message-ID: Hello, I'm looking for a program or python library to draw graphs. They should look like the that: /--------\ /--------\ | Node A | ------ belongs to ----> | Node B | \--------/ \--------/ Which is a result of the function call like that: connectNodes(firstNode, secondNode, description, lineStyle) connectNodes("Node A", "Node B", "belongs to", dashed) It should have a open scalable vector format as output (DVI, SVG, PDF, ...) and should be able to make automatic optimal placement of the items. Do you know something like that? Thx, Florian From brian at sweetapp.com Fri Jan 23 20:35:46 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 23 Jan 2004 17:35:46 -0800 Subject: [OPINION] - does language really matter if they all do thesamething? In-Reply-To: <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> Message-ID: <046b01c3e21a$641bdac0$0000fea9@dell8200> Dietrich wrote: > Python seems to take the middle ground. It's build from a procedural > standpoint, in an environment where most things are objects and some > are functions. I'd be interested to know why you don't think that functions are objects. I would argue that they are because they have attributes, methods, and are bound to variables the same way as other Python objects. > It's not what I'd choose as an example of an object > oriented language. There are no messages, only function calls, so you > can't capture them. You certainly can capture them. Could you demonstrate the Objective-C or Smalltalk syntax for doing so? Maybe it is a lot easier in those languages. Cheers, Brian From alan.gauld at btinternet.com Thu Jan 22 16:24:50 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2004 21:24:50 GMT Subject: Program Python in VIM References: <871xpsc5zf.fsf@tulip.whu.ca> Message-ID: <40103ee7.108130723@news.blueyonder.co.uk> On Thu, 22 Jan 2004 19:08:33 +0000, Paul Moore wrote: > Peter Wu writes: > > vi test.py > > [key in some python code] > > :wq You should only need :w here. The q will close the window which presumably you don't want? > > :!python test.py > > > > > > Is there any other way? I don't want to type 'python test.py' every time :!! repeats the last command. However if you are using vim in a *nix terminal rather than the GUI version you could use CTRL-Z to suspend vim then run python foo.py from the shell prompt. Resume python, edit and CTRL Z again. !! at the prompt will repeat the last run command. > > ...In Emacs, I can simply fire C-c C-c to fire :!! is probably the nearest direct equivalent. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From deadlink27 at web.de Fri Jan 30 09:56:30 2004 From: deadlink27 at web.de (Sebastian Stelzer) Date: Fri, 30 Jan 2004 15:56:30 +0100 Subject: Get error "ImportError: No module named _tkinter" References: Message-ID: Aahz wrote: > In article , > Sebastian Stelzer wrote: >> >> import _tkinter # If this fails your Python may not be configured for >> Tk >>ImportError: No module named _tkinter >> >>I'am using Suse Linux 9.0 with Python 2.3.3. > > You need to install Tck/Tk devel package, then rebuild Python. I did it and I' got the same error. Can you tell it more exactly please? From __peter__ at web.de Thu Jan 15 19:22:14 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Jan 2004 01:22:14 +0100 Subject: Inserting while itterating References: <1074140382.26201.26.camel@dev.internal> Message-ID: Skip Montanaro wrote: >>>>>> "Mark" == Mark McEahern writes: > > Mark> On Wed, 2004-01-14 at 02:43, Thomas Guettler wrote: > >> Hi, > >> > >> Simple excerise: > >> > >> You have a sorted list of integers: > ... > >> and you should fill all gaps: > ... > >> How would you code this? > >> > >> Constrain: The original list should be changed, don't create a > >> copy. > > Mark> In the spirt of unit testing... > > Mark> #!/usr/bin/env python > ... > > Here's a version which is much faster if you have large gaps and appears > to be only marginally slower if you have small gaps. > > Skip > > #!/usr/bin/env python > > #!/usr/bin/env python > > def fillGaps1(seq): if len(seq) == seq[-1]: raise Exception("nothing to do") > expectedLength = seq[-1] - seq[0] + 1 > i = 1 > while i < expectedLength: > if seq[i] - seq[i-1] > 1: > seq.insert(i, seq[i-1] + 1) > i += 1 > > def fillGaps(seq): > expectedLength = seq[-1] - seq[0] + 1 > i = 1 > while i < expectedLength: > if seq[i] - seq[i-1] > 1: > gap = seq[i-1] - seq[i] > fill = range(seq[i-1]+1, seq[i]) > seq[i:i] = fill > i += len(fill) > i += 1 > > if __name__ == "__main__": > import timeit > > print "timing with one large gap:" > t = timeit.Timer(setup='from fillgaps import fillGaps1 as fillGaps', > stmt='fillGaps([1, 5000])') > print "old fillgaps:", t.timeit(number=100) > t = timeit.Timer(setup='from fillgaps import fillGaps', > stmt='fillGaps([1, 5000])') > print "new fillgaps:", t.timeit(number=100) > > print "timing with many small gaps:" > t = timeit.Timer(setup='from fillgaps import fillGaps1 as > fillGaps;l=range(1,5001,2)', > stmt='fillGaps(l)') I think the list should be initialized in the statement instead of the setup. Otherwise subsequent passes will measure for range(1, 5000). > print "old fillgaps:", t.timeit(number=100) > t = timeit.Timer(setup='from fillgaps import > fillGaps;l=range(1,5001,2)', > stmt='fillGaps(l)') > print "new fillgaps:", t.timeit(number=100) > > import unittest > class test(unittest.TestCase): > def test(self): > for fg in (fillGaps1, fillGaps): > l = [1, 2, 4, 7, 8, 12] > fg(l) > self.assertEquals(l, range(1, 13)) > > l = [1, 5000] > fg(l) > self.assertEquals(l, range(1, 5001)) > > unittest.main() Here's another fillgap version: def fillGapsPeter(seq): # inspired by anton muhin lo = seq[0] hi = seq[-1] seq[1:1] = range(lo+1, hi+1) while len(seq) > hi: i = seq.pop() seq[i-lo] = i def fillGapsMark(seq): expectedLength = seq[-1] - seq[0] + 1 i = 1 while i < expectedLength: if seq[i] - seq[i-1] > 1: seq.insert(i, seq[i-1] + 1) i += 1 def fillGapsSkip(seq): expectedLength = seq[-1] - seq[0] + 1 i = 1 while i < expectedLength: if seq[i] - seq[i-1] > 1: gap = seq[i-1] - seq[i] fill = range(seq[i-1]+1, seq[i]) seq[i:i] = fill i += len(fill) i += 1 if __name__ == "__main__": import timeit, fillgaps, sys fnames = [fname for fname in dir(fillgaps) if callable(getattr(fillgaps, fname))] fnames.sort() for header, lst in [ ("original test case", [1, 2, 4, 7, 8, 12]), ("timing with one large gap:", [1, 5000]), ("timing with many small gaps:", range(1, 5001, 2))]: print header for fn in fnames: t = timeit.Timer(setup='from fillgaps import %s as fillGaps' % fn, stmt='fillGaps(%s)' % (lst,)) print "\t%s:" % fn, t.timeit(number=100) print import unittest class test(unittest.TestCase): def test_all(self): for fg in [getattr(fillgaps, fn) for fn in fnames]: l = [1, 2, 4, 7, 8, 12] fg(l) self.assertEquals(l, range(1, 13)) l = [1, 5000] fg(l) self.assertEquals(l, range(1, 5001)) def test_mine(self): """ Hard to prove I'm not cheating, hope I got it right... """ class myint(int): def __repr__(self): return "my" + int.__repr__(self) original = map(myint, [1, 2, 4, 7, 8, 12]) l = list(original) fillGapsPeter(l) self.assertEquals(l, range(1, 13)) for i in original: self.assert_(i is l[i-1]) self.assert_(repr(i).startswith("my")) unittest.main() My findings: original test case fillGapsMark: 0.00151419639587 fillGapsPeter: 0.00127387046814 fillGapsSkip: 0.00162696838379 timing with one large gap: fillGapsMark: 0.872708797455 fillGapsPeter: 0.0312719345093 fillGapsSkip: 0.0336079597473 timing with many small gaps: fillGapsMark: 0.973310947418 fillGapsPeter: 0.412738800049 fillGapsSkip: 1.47315406799 Peter From antonmuhin at rambler.ru Fri Jan 9 14:30:10 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 09 Jan 2004 22:30:10 +0300 Subject: Variable Scope In-Reply-To: References: Message-ID: Jens Thiede wrote: > In the following terminal; could someone inform me as to why it is > posible to print a global variable without having to declare it using > global. This has affected some source of mine, and allows you to > modify a global in a local scope *without* the global keyword, for > instance, you can append to a global list, but *not* assign it a new > value, for then, you create a new local variable. -- Why. > > Python 2.3.2 (#1, Jan 3 2004, 23:02:08) > [GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r3, propolice)] on linux2 > > IDLE 1.0 > >>>>x = 10; >>>>def test(): > > x += 1; > > > >>>>test(); > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > test(); > File "", line 2, in test > x += 1; > UnboundLocalError: local variable 'x' referenced before assignment > >>>>def test2(): > > print x; > > > >>>>test2(); > > 10 > > Any help would be appreciated, > > Jens Thiede. I suppose because Python prohibits rebinding of global variables, not modifications. You actually cannot change an integera (as an immutable type) with rebinding a varibale. Lists (as mutable types) allows modifications without rebinding. E.g. l = [] def f1(): l.append(0) def f2(): l = l + [0] f1() print l f2() print l Python says: [0] Traceback (most recent call last): File "1.py", line 12, in ? f2() File "1.py", line 7, in f2 l = l + [0] UnboundLocalError: local variable 'l' referenced before assignment regards, anton. From reidyre at yahoo.com Wed Jan 21 18:12:59 2004 From: reidyre at yahoo.com (Ron Reidy) Date: 21 Jan 2004 15:12:59 -0800 Subject: Compiling DCOracle2 on RH Linux 8.0 Message-ID: All, I am trying to compile DCOracle2 on RedHat 8.0 and make is giving me the following error: gcc -pthread -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include/python2.3 -I/usr/local/include/python2.3 @DEFS@ -I/oracle/app/oracle/9i/rdbms/demo -I/oracle/app/oracle/9i/network/public -I/oracle/app/oracle/9i/plsql/public -I/oracle/app/oracle/9i/rdbms/public -DORACLE9i -c ././dco2.c -o ./dco2.o gcc: cannot specify -o with -c or -S and multiple compilations Did I do something wrong? Thanks for your help. From engsolnom at ipns.com Sat Jan 10 14:40:23 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Sat, 10 Jan 2004 11:40:23 -0800 Subject: Simple Python Speed Benchmark Message-ID: Knowing absolutely zero about benchmarks, I was interested in the posting referencing the paper by Dr. Cowell-Shah. I was curious how long Python takes just to read and display time.clock(), soI made the simple test below. I was amazed at the difference in speed depending on when/how the clock times were converted to milliseconds....almost 4 to 1...as indicated in the RESULTS below. I understand the variation in the times is probably due to other running processes. Any explanation? The machine used is: P3, 1gHz, 256 meg of ram, Windows 2000, Python 2.3 Also, I did duplicate the intArithmetic (intMaz), using 1,000,000,000, as per the paper, and it *did* take a long time. I tried a variety of ways to implement the process (while, range, xrange, etc), and made some improvement, but not much. And of course I did see the "out of memory" message. Norm # THE CODE import time module_time_start = time.clock() start_time_1 = time.clock() stop_time_1 = time.clock() print 'Test 1: ', (stop_time_1 - start_time_1) * 1000 start_time_2 = time.clock() * 1000 stop_time_2 = time.clock() * 1000 print 'Test 2: ', stop_time_2 - start_time_2 def get_time_1(): start_time_3 = time.clock() stop_time_3 = time.clock() duration = (stop_time_3 - start_time_3) * 1000 print 'Test 3: ', duration def get_time_2(): start_time_4 = time.clock() * 1000 stop_time_4 = time.clock() * 1000 print 'Test 4: ', stop_time_4 - start_time_4 print '\nOK, now loop the methods...\n' for ix in range(10): print get_time_1() get_time_2() module_time_stop = time.clock() print '\nTotal module time: \n', (module_time_stop - module_time_start) * 1000 # THE RESULTS: Test 1: 0.00363174649292 Test 2: 0.0167619068904 OK, now loop the methods... Test 3: 0.00810158833036 Test 4: 0.0145269859717 Test 3: 0.006984127871 Test 4: 0.0145269859717 Test 3: 0.00586666741164 Test 4: 0.0145269859717 Test 3: 0.00614603252648 Test 4: 0.0145269859717 Test 3: 0.00614603252648 Test 4: 0.013968255742 Test 3: 0.00586666741164 Test 4: 0.0128507952826 Test 3: 0.00586666741164 Test 4: 0.0136888906272 Test 3: 0.0055873022968 Test 4: 0.0136888906272 Test 3: 0.00642539764132 Test 4: 0.0145269859717 Test 3: 0.0108952394788 Test 4: 0.0145269859717 Total module time: 2.89142893859 From tjreedy at udel.edu Wed Jan 28 15:03:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Jan 2004 15:03:05 -0500 Subject: r prefix bug ... or my lack of understanding? References: Message-ID: "Bill Sneddon" wrote in message news:bv8gtj$5ob$1 at ngspool-d02.news.aol.com... > Below is from python 2.3.3 on windows. > I have tryed on Pythonwin and Idle and on > a Solaris unix build 2.2.2. > > I know there are work arounds but the behavior > seems a bit strange to me. > > >>> path = r'c:\data' #this is fine > >>> print path > c:\data > > >>> path = r'c:\data\' > Traceback ( File "", line 1 > path = r'c:\data\' > ^ > SyntaxError: EOL while scanning single-quoted string > > >>> path = r'c:\data\\' > >>> print path > c:\data\\ Behaves as per manual. Note: for almost all usages, even on windows, normal Unix-style forward slashes works as directory terminators and avoids backslash problems entirely. path = 'C:/data/' Terry J. Reedy From martin at v.loewis.de Sun Jan 4 10:19:48 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 04 Jan 2004 16:19:48 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <20040103165041.GA31412@nl.linux.org> <3FF740ED.9020909@rogers.com> Message-ID: Gerrit Holl wrote: >>Are unicode filenames something we should care about? > > > That's a difficult issue. I don't know how to solve that. It depends on the platform. There are: 1. platforms on which Unicode is the natural string type for file names, with byte strings obtained by conversion only. On these platforms, all filenames can be represented by a Unicode string, but some file names cannot be represented by a byte string. Windows NT+ is the class of such systems. 2. platforms on which Unicode and byte string filenames work equally well; they can be converted forth and back without any loss of accuracy or expressiveness. OS X is one such example; probably Plan 9 as well. 3. platforms on which byte strings are the natural string type for filenames. They often have only a weak notion of file name encoding, causing a) not all Unicode strings being available as filenames b) not all byte string filenames being convertible to Unicode c) the conversion may depend on user settings, so for the same file, Unicode conversion may give different results for different users. POSIX systems fall in this category. So if filenames where a datatype, I think they should be able to use both Unicode strings and byte strings as their own internal representation, and declare one of the two as "accurate". Conversion of filenames to both Unicode strings and byte strings should be supported, but may fail at runtime (unless conversion into the "accurate" type is attempted). Regards, Martin From premshree_python at yahoo.co.in Tue Jan 13 15:00:29 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 13 Jan 2004 20:00:29 +0000 (GMT) Subject: Python In-Reply-To: Message-ID: <20040113200029.89255.qmail@web8304.mail.in.yahoo.com> Is that possible?? Maybe you could use C++ within Py, eh? -Premshree [http://www.qiksearch.com/] --- sandhya wrote: > How to generate a .pyd file from a c++ file?? > > plz do respond > > thanks > regards > Sandhya > > -- > http://mail.python.org/mailman/listinfo/python-list ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From jcarlson at nospam.uci.edu Mon Jan 26 19:26:49 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 16:26:49 -0800 Subject: compress string of data In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Josiah Carlson" wrote in message > news:bv3bdd$a0j$3 at news.service.uci.edu... > >>Piet van Oostrum wrote: >> >> >>>>>>>>Gerrit Holl (GH) wrote: >>> >>> >>>>>How i could compress string of data?. >>>>> >>>>> >>>>>>>import zlib >>>>>>>zlib.compress("Hello, world") >>> >>>GH> 'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' >>> >>>GH> http://www.python.org/doc/current/lib/module-zlib.html >>> >>>Waw, that compresses it from 12 bytes to 20 bytes :=) >> >> >>There is no such thing as universal compression > > > Only if you specify invertibility (losslessness). > > f(s) == '' compressess everything except '' itself ;-) > > and that len(f(s)) < len(s) for some s and not just <= for all s (which > allows identity 'compression' f(s) == s). > > >>- some compressions result in expansion. > > > Which is to say that if a 1-1 function maps some strings to smaller > strings, it must correspondingly map others to larger strings. An > interesting CS tidbit that people keep discovering by stumbling over. > > Lossless universal expansion is possible: f(s) == ' '+s. But it is into > rather than onto, so only strings starting with ' ' can be inversely > mapped. Exactly (I was too short on time to say the equivalent this morning, and even if I had said the equivalent, it likely would not have been as clear). - Josiah From bichoverde at sapo.pt Mon Jan 12 08:05:19 2004 From: bichoverde at sapo.pt (Bicho Verde) Date: Mon, 12 Jan 2004 13:05:19 -0000 Subject: Why learn Python ?? Message-ID: <40029dad$0$28706$a729d347@news.telepac.pt> I have now free time and money to do what I want :-) I have some basic skills in programming (C, Pascal, Macromedia Actionscript) but don't know exactly what to do in the world of programming. And also I don't know exactly why would I learn Python rather than C#, C++ or Perl. Basicaly I don't know where to start, if there is much to do or if it is has it seems and there is software to everything nowadays and so doesn't make sense to spend time in learning a programming language. I just have this idea that I would like to contribute to the curve of accelarated exponential progress (technological singularity), artificial intelligence and so on. From that point of view there is much to do... But can I stand for it and where to start? Anyone would help me and give me some hints? -BichoVerde From cookedm+news at physics.mcmaster.ca Mon Jan 12 10:58:31 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 12 Jan 2004 10:58:31 -0500 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <6ee58e07.0401120542.5d79090d@posting.google.com> Message-ID: At some point, llothar at web.de (Lothar Scholz) wrote: > Samuel Walters wrote in message news:... > >> I know very little about numeric processing, and even less about Fortran. >> It's true that my background is in mathematics, but in *pure* mathematics >> where pointer-based languages tend to be helpful, not hurtful. > > Okay seems that you don't know a lot about compiler writing. > > A C compiler only knows a little bit about the context so it must > always assume that a data inside a member can be referenced from > another place via an alias pointer. > > Fortran does not have this problem so a lot of optimizations can be > done and values can be hold in registers for a much longer time, > resulting in much greater speed. > > Remember that on supercomputers a 25% spped enhancement (which a good > fortran compiler is faster then C) can mean a few million dollars of > saved hardware costs. The coding time is not importing compared to the > running time. So real hard numerics are always done in Fortran. > > GNU Fortran is a stupid project because it translates the Fortran code > to C. Err, no. You're thinking of f2c. GNU Fortran uses the same backend as the GNU C compiler, in that it translates to the same intermediate language (sort of assembly language) on which optimizations are done. But the C front end and the Fortran front end are separate. The advantage of GNU Fortran is it's *portable*. It runs on everything that GCC works on -- which is a lot. This makes a difference when you're developing (like on my Apple iBook running Linux). And it looks like the G95 project is humming along nicely. > Python for hardcore numerics, even with PyNumerics, is simply a very > bad solution. You're not limited to pure Python. No one's saying you must use only C, or only Fortran, or only Python. Use the best tool for the job. Python just has the advantage that mixing C and Fortran into it is easy. Write your big, number-crunching code as a Fortran routine, wrap it with f2py, then add a Python script around it to run it. Presto, no fiddling with Fortran for reading in input files, or output files (depending on your routine). You can even write a GUI in Python if you wish. Or add a webserver. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From andreas.lobinger at netsurf.de Tue Jan 20 04:20:35 2004 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Tue, 20 Jan 2004 10:20:35 +0100 Subject: Fw: PDF library for reading PDF files References: <400BFF7B.95F21050@netsurf.de> Message-ID: <400CF2E3.29506EAE@netsurf.de> Aloha, Peter Galfi schrieb: > Thanks. I am studying the PDF spec, it just does not seem to be that easy > having to implement all the decompressions, etc. The "information" I am > trying to extract from the PDF file is the text, specifically in a way to > keep the original paragraphs of the text. I have seen so far one shareware > standalone tool that extracts the text (and a lot of other formatting > garbage) into an RTF document keeping the paragraphs as well. I would need > only the text. As others wrote here, the simplest solution is to use a external pdf-2-text programm and postprocess the data. Read comp.text.pdf There is no simple and consistent way to extract text from a .pdf because there are many ways to set text. The optical impression of a paragraph may not be represented by a similar command structure in the .pdf. Adobe recognized the difficulties for document reuse and introduced tagged .pdf in 1.4. With tagged-pdf it is possible to insert structural information in the .pdf. If you are interested in using this, contact me. Wishing a happy day LOBI From eric-amick at comcast.net Mon Jan 26 20:15:22 2004 From: eric-amick at comcast.net (Eric Amick) Date: Mon, 26 Jan 2004 20:15:22 -0500 Subject: Single and double asterisks preceding variables in function arguments References: Message-ID: On Mon, 26 Jan 2004 09:51:02 -0600, Stephen Boulet wrote: >I've run across code like "myfunction(x, *someargs, **someotherargs)", >but haven't seen documentation for this. > >Can someone fill me in on what the leading * and ** do? Thanks. Try section 4.7.2 of the tutorial. -- Eric Amick Columbia, MD From jjl at pobox.com Sun Jan 11 09:14:55 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jan 2004 14:14:55 +0000 Subject: help with Python Environment For Blind User References: Message-ID: <87hdz2lggw.fsf@pobox.com> "Zachary" writes: > I'm a blind non-programmer trying to learn Python. > I've got python 2.3 for windows, but the problem is that Idle doesn't seem > to work two well with my screen reading program. > Is notepad, then, my only other real choice? Pythonwin worked similarly > badly. > The problem is my programs inability to track the cursor. It doesn't tell > me what line I'm on, where I am in that line, or what I just deleted. It > would do this in a normal editor. > Any help with this would be appreciated. There have been several threads on this in the past: http://www.google.com/groups?as_q=blind%20whitespace%20group%3Acomp.lang.python&safe=images&ie=ISO-8859-1&lr=&num=30&hl=en Including one from T. V. Raman, author of emacspeak, revealing that emacs / python-mode works for blind users (emacs is vi's enemy in the endless emacs-vi editor war ;-). Whichever editor you choose (toss a coin), be prepared for a struggle: editors like vi and emacs are an *entirely* different species to something like notepad. It's certainly worth it in the end. John From vitali_vg at yahoo.com Fri Jan 23 16:23:55 2004 From: vitali_vg at yahoo.com (Vitali Gvozdev) Date: 23 Jan 2004 13:23:55 -0800 Subject: How to place window on top? Message-ID: Hi, Using win32 extensions and windows scripting, I'm trying to open an application in Windows2K to send some keystrokes to it. But every time the application window is openning below other windows and key are sent to the applications, which should not be affected. WshShell = win32com.client.Dispatch('WScript.Shell') ... def Initialize(theCommand, theName): if not WshShell.AppActivate(theName): WshShell.Run(theCommand) ... Can you explain me how to put the desired window on top (switch focus)? From donn at u.washington.edu Tue Jan 13 12:48:57 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 13 Jan 2004 09:48:57 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> Message-ID: In article <40041576.D070723E at engcorp.com>, Peter Hansen wrote: > Donn Cave wrote: > > > > Python has the advantage of a clean start, but > > from a software engineering standpoint it really seems like a > > hacker language. > > Ohh.... nice controversial statement. :-) > > I would strongly disagree with the above statement for a number > of reasons, including (random thoughts): > > - packages > - interactive interpreter > - no static typing > - high productivity > - ease of testing > - flexibility > - extremely broad library support > - low learning curve > > and probably a dozen others. I think this has all been discussed before, > though, so I won't belabour the point. Basically, as a software engineer > (nominally a "Systems Design Engineer") I find Python to be hands down > *the* best language I've encountered for use in serious work. I can't > actually think of another which excels on so many fronts. But your list describes the perfect hacker language, at least on some counts. I'm nominally a Software Engineer myself, but I have no formal CS education and have never worked on a large project, so I feel right at home with the hacker culture here. But help me out here, suppose we're going to go in and develop one of those massive projects - I don't know, say the IRS needs a new computer system - what on that list would we care about? Maybe vague promises like high productivity and ease of testing would be attractive, but anyone can say that for some ideal context. Library support is probably not even on the charts. I would think a major consideration at the outset of a project like this would be whether the code that all these teams is writing will eventually come together and work like it's supposed to, and from that point of view it's tempting to look for some support for architectural consistency, like "interfaces" and that sort of thing. Donn Cave, donn at u.washington.edu From djmitchell at spamfree.optushome.com.au Thu Jan 29 19:11:06 2004 From: djmitchell at spamfree.optushome.com.au (David Mitchell) Date: Fri, 30 Jan 2004 11:11:06 +1100 Subject: TCP server as a Windows service using Python? Message-ID: Hello group, I'm trying to create a TCP server using Python, and I want it to run under Windows as a service. Now, I'm fine with building the TCP server using Python - done it lots of times, and I know there's lots of sample code out there I can grab if I ever need to. Equally, I think I've got the simpler concepts about creating Windows services using Python clear. I've got the Python Win32 book, worked through the example code in there and haven't had any real problems with it. Where I'm having trouble is with the overlapped I/O call. When I create a TCP server, I need to have it sit there waiting for a client connection. With a Windows service, it has to sit there waiting for administrative messages such as e.g. a "stop service" message. The example code in the Python Win32 book uses named pipes to do IO - I'm constrained to using TCP sockets. I can't see how to let the service accept *either* an incoming TCP client connection *or* an e.g. "stop service" message. If someone could point me to some sample code, I'd greatly appreciate it - Google hasn't been helpful. Thanks in advance Dave M. From neanthumain at yahoo.com Sat Jan 10 19:43:41 2004 From: neanthumain at yahoo.com (N?ant Humain) Date: 10 Jan 2004 16:43:41 -0800 Subject: Providing Default Value for User Input Message-ID: I have just begun learning Python so that I can write a simple script to make modification of a file used by another Python script easier. This file is basically a list of regular expressions. What I want to do is allow the user to select one of these regular expressions to modify, but I've realized I know of no way to provide a default value for user input. I could choose to show the regular expression the user has chosen and simply allow the user to retype it and modify it from there, but that is time consuming and error prone. Does Python support a way to do this? If worse comes to worst, is there a way I could write such code on my own without having to write a C-based module (I'd like to stick to Python code only since some users will be running this script on Windows without a C compiler)? From rob02omni at vodafone.it Tue Jan 13 08:47:25 2004 From: rob02omni at vodafone.it (Roberto) Date: Tue, 13 Jan 2004 14:47:25 +0100 Subject: Embedded python reference Message-ID: Hi there, I've compiled the demo example demo/embed/demo.c succesfully. Just a question : how i can reconstruct (and make my exe to point to) the directories of python ?? For exmpale if i use the zlib.pyd i want to make it avaiable in DLLs just the way it is in python path. Also i wonder about classes if i use a class.py in my embedded python c program how it works? (can "clone" all the pythons path?). Thanks, Rob -- Roberto Federici .:: SAEC - Studio Associato Enrico e Catozzo & C. .:::: Fraz. Pont Suaz, 104 Charvensod (AO) .:::::: Tel. 0165-43149 - Fax 0165-230153 .:::::::: info at saec.net www.saec.net ********************************************************************** Ai sensi della legge n. 675/1996 si informa che : Questa email (e relativi allegati) contiene informazioni riservate indirizzate ai soli destinatari. E' fatto esplicito divieto di utilizzare i contenuti per qualsiasi scopo. E' fatto altres? divieto di utilizzare gli indirizzi email per attivit? indesiderate e/o non richieste (spamming). In caso di ricevimento per errore vi preghiamo di segnalarlo a info at saec.net ********************************************************************** From jacek.generowicz at cern.ch Fri Jan 9 04:42:35 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Jan 2004 10:42:35 +0100 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> <4de76ee2.0401081318.bab6f62@posting.google.com> Message-ID: David, Thank you for your refreshingly constructive followup. davidb at mcs.st-and.ac.uk (David Boddie) writes: > Jacek Generowicz wrote in message news:... > > [...] > > revealed that the basic information about the PYTHONDOCS environment > variable can be found at the foot of the following page: > > http://www.python.org/dev/doc/devel/lib/module-pydoc.html This strikes me as not very helpful to someone looking to solve the problem of _keyword_ documentation not working. Remember, we're talking about poor lost newbies. > > If these instructions are, as it seems, absent, then I would > > appreciate advice on what I can do to make them appear in the > > appropriate place, and what the appropriate place might be. > > They could always be written up in the PythonInfo Wiki, then at > least you have a python.org URL to give your students. I hadn't thought of that opiton. Thanks. > > I recognize my impatience with poor documentation as a pathological > > flaw in my characer, which is why I am asking for help in > > finding/creating this documentation here. > > You're going to have to be quite patient, though. If the documents > you want aren't obvious then it's probably up to you to write them. :-/ That is exactly what I was implying with my use of the word "creating". > David > > P.S. You'll note that I haven't come up with my own recipe so far. > For what it's worth, a document describing how to obtain help on > keywords might start in the following way: > > Configuring Python to supply help on keywords > ============================================= > > Introduction > ------------ > Recent versions of Python include the ability to display help on > existing objects, or to search for information on installed modules, > from within the interactive environment. However, it is also possible > to use the help system to display information on the keywords used > in the language itself, such as "if" and "for. This feature appears > to be less well-known, possibly because users seek basic language > information elsewhere, but maybe also because it is not always > enabled by default. > > Requirements > ------------ > In order to seek help on keywords from within the interactive > environment, two things need to be done before Python is invoked: > > * The HTML documentation needs to be downloaded and installed in an > accessible location; this will depend on the operating system in > use. > > * The PYTHONDOCS environment variable will need to be set to the > path of the installed HTML files. > > Setting it up > ------------- > First of all, check whether the HTML documentation has already been > installed for the version of Python you are using. This could save > you the effort of downloading and installing it manually. > > If the documentation is required then go to:: > > http://www.python.org/download/ > > and find the appropriate documentation. Download it and install it > in a place where it can be read by those who will be using it. How about If the documentation is required then go to: http://www.python.org/doc//download.html and download the HTML documention and install it in a place where it can be read by those who will be using it. ? > Checking it works > ----------------- > Using the appropriate method provided by your operating system, set > the PYTHONDOCS environment variable to the directory which contains > the main index file for the documentation. > > For example, you may have installed the documentation in > /usr/share/doc/python so that the directory layout look like:: > > /usr/share/doc/python > |- Misc > |- README > \- html > |- about.html > |- acks.html > |- api/ > |- dist/ > |- doc/ > ... > > and so on. Therefore, PYTHONDOCS should be set to /usr/share/doc/python/html > since this contains the information required. On Linux systems, using the > bash shell, you might type:: > > export PYTHONDOCS=/usr/local/share/python/html python > > to start the interpreter. Within the Python environment, typing:: > > help("if") > > should now cause something like the following to be displayed:: > > 7.1 The if statement > > The if statement is used for conditional execution: > > if_stmt ::= "if" expression[1] ":" suite[2] > ( "elif" expression[3] ":" suite[4] )* > ["else" ":" suite[5]] > > Download entire grammar as text.[6] > > It selects exactly one of the suites by evaluating the expressions one > by one until one is found to be true (see section 5.10[7] for the > definition of true and false); then that suite is executed (and no other > part of the if statement is executed or evaluated). If all expressions > are false, the suite of the else clause, if present, is executed. > > Enabling this by default > ------------------------ > Any ideas? I guess this would require the HTML documentation to be bundled in with the Python distribution tarball, and I can imagine that being an unpopular suggestion. Now, currently one gets the following from Python's built-in help: >>> help('if') Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. How about augemnting this with something like: The HTML documentation files can be obtained from http://www.python.org/doc//download.html ? And then there's the wart surrounding the following: lambda, and, not, or I always get could not read docs from $PYTHONDOCS//ref/lambda.html Note, I even get 'lambda.html' in the message when asking for help on the other three. Any ideas what's going on there ? Furthermore, is there anyway of getting help of keywords via pydoc ? From zensunni at rochester.rr.com Sat Jan 24 23:24:15 2004 From: zensunni at rochester.rr.com (Brian Samek) Date: Sun, 25 Jan 2004 04:24:15 GMT Subject: Newbie Nested Function Problem References: Message-ID: Oh wow! Thanks a lot - that was exactly the issue. I changed the variable name and the program works perfectly now. I didn't realize that a variable name in a program would have that effect. Brian "Rich Krauter" wrote in message news:mailman.753.1075001453.12720.python-list at python.org... Looks like you are setting the variable 'leave' to the user input, and then you are calling the function leave(), but remember that 'leave' has been set to some string. So say you enter 'xqz', and expect it to restart the loop when you get to the leave call --- well, what you are doing is trying to call the function xqz(). Rich On Sat, 2004-01-24 at 21:45, Brian Samek wrote: -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Tue Jan 6 13:49:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 13:49:27 -0500 Subject: Speed? References: <3FFABBA8.3A24716F@engcorp.com> Message-ID: <3FFB0337.64806341@engcorp.com> Skip Montanaro wrote: > > [ on creating benchmarks ] > > Peter> And with Python, of course, it's almost trivial to do this kind > Peter> of thing, compared to some other languages. Sigh. > > Which was just another data point in your decision, right? After all, if > Python is so much easier to write your benchmarks in than some/most/all of > the alternatives, that has to factor into the choice of implementation > language. Well, I suppose it would have been a factor in the decision, if the decision had really been about which language to use. In fact in this case we had already picked Python as a key technology, but needed to see whether the performance of the hardware was adequate to support its use. Doing it with C was an alternative, but we'd already tried a prototype with C and concluded that while performance was fine, naturally, we would not complete the required feature set in our lifetimes (or at least in our funding's lifetime ;-) ). To be completely honest: we ended up picking faster hardware in the long run, but the choice was more because the trial platform was too limited in RAM and ROM memory (1MB each) and had an inadequate development platform. The final choice (as I mentioned in another thread today) uses 32MB RAM and ROM (Compact Flash actually) and happens to run at 100MHz instead of the 33MHz of the first one. Tying this in with yet another thread: we have spent next to no time optimizing, so far, because we're still adding features and making things work. I firmly believe we could have optimized the code for the original 33MHz system to a point where it would have run acceptably, and still in much less time than it would have taken to get a C version running (that was the alternative possibility). I'm just happy we were able to buy our way out of having to spend a lot of time optimizing. In summary: we picked Python for reasons relating to ease of use (development and maintenance) and flexibility, and performance was really not a significant issue. As I've said before, we've written literally hundreds of programs with it, ranging from small utilities to major products, and have only *very* rarely had to pause to consider performance and spend time optimizing anything. Python is *not* slow! -Peter From jason at tishler.net Thu Jan 29 09:56:37 2004 From: jason at tishler.net (Jason Tishler) Date: Thu, 29 Jan 2004 09:56:37 -0500 Subject: Error under Cygwin - threading module In-Reply-To: <20040128173040.37859.qmail@web21108.mail.yahoo.com> References: <20040127150408.GB1204@tishler.net> <20040128173040.37859.qmail@web21108.mail.yahoo.com> Message-ID: <20040129145637.GD920@tishler.net> AdSR, Please keep you replies on-list. On Wed, Jan 28, 2004 at 09:30:40AM -0800, Artur de Sousa Rocha wrote: > --- Jason Tishler wrote: > > I "spoke" too soon -- I was able to reproduce the problem after 160 > > iterations. Please try the latest snapshot: > > > > http://cygwin.com/snapshots/ > > > > and report back whether or not this solves your problem. > > I installed the latest snapshot of cygwin1.dll > (cygwin1-20040126.dll.bz2). The problem persists, error messages show > about as often as previously. Thanks for trying the above. Please post your problem to the Cygwin mailing list -- we will get more traction there. I will attempt to help when I see your post. Thanks, 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 mailund at birc.dk Wed Jan 14 15:21:41 2004 From: mailund at birc.dk (Thomas Mailund) Date: Wed, 14 Jan 2004 21:21:41 +0100 Subject: Cyclic garbage collection and segfaults... Message-ID: Hi group. I have a problem with some C extensions I am working with and hope that some of you can help. Basically, I am wrapping a a tree structure from C where I have python methods for extracting either the entire tree or subtrees; since I don't want the full tree to be deallocated while python has references to the subtrees, I INCREF the full tree whenever I hand out a subtree reference. I don't want any of the subtrees to be deallocated while the full tree lives, either, so I want the fulltree to have a reference to each of the subtrees. Naturally, this gives me a cyclik reference structure, and I want to be able to garbage collect it. But this is where my problems begin... For some reason, when I turn on the cyclic garbage collection for my types, a deallocation automatically gives me a segfault. That is, if my type new type contains any data whatsoever, I cannot garbage collect without dumping core. I have boiled the problem down to the code shown below. It contains no cyclic structure, it is as simple as it gets, but it still seqfaults for me. If I comment out the magic void-pointer (which isn't used for anything) I don't get the segfault. #include struct SimpleObject; static PyObject * Simple_new (PyTypeObject *type, PyObject *args, PyObject *kwds); static int Simple_init (struct SimpleObject *self, PyObject *args, PyObject *kwds); static int Simple_traverse(struct SimpleObject *self, visitproc visit, void *arg); static void Simple_dealloc (struct SimpleObject *self); typedef struct SimpleObject { /* object stuff */ PyObject_HEAD /* dark magic */ void *magic; } SimpleObject; static PyTypeObject simple_SimpleType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "simple.Simple", /*tp_name*/ sizeof(SimpleObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Simple_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "Simple objects", /*tp_doc*/ (traverseproc)Simple_traverse, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ (initproc)Simple_init, /*tp_init*/ 0, /*tp_alloc*/ Simple_new, /*tp_new*/ 0 /*...the rest...*/ }; static PyObject * Simple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { SimpleObject *self = (SimpleObject *)type->tp_alloc(type, 0); return (PyObject*)self; } static int Simple_init(SimpleObject *self, PyObject *args, PyObject *kwds) { return 0; } /* cyclic gc */ static int Simple_traverse (SimpleObject *self, visitproc visit, void *arg) { fprintf(stderr,"Simple_traverse...\n"); return 0; } static int Simple_clear(SimpleObject *self) { fprintf(stderr,"Simple_clear...\n"); return 0; } static void Simple_dealloc(SimpleObject *self) { fprintf(stderr,"Simple_dealloc %p\n", self); self->ob_type->tp_free((PyObject*)self); /* <= segfault here */ return; } static PyMethodDef simple_methods[] = { {0} /* sentinel */ }; void initsimple(void) { if (PyType_Ready(&simple_SimpleType) < 0) return; Py_INCREF(&simple_SimpleType); PyObject* m = Py_InitModule3("simple", simple_methods, "Simple module."); PyModule_AddObject(m,"Simple",(PyObject*)&simple_SimpleType); } A script sufficient to provoke the fault is this: import simple simple.Simple() Can anyone explain what I'm doing wrong? Or perhaps suggest a better solution to my "real" problem, if I'm approaching the problem completely wrong :-) Yours, /mailund From myfirstname at mylastname.com Sat Jan 3 20:19:43 2004 From: myfirstname at mylastname.com (Dan Bullok) Date: Sun, 04 Jan 2004 01:19:43 GMT Subject: Parametrized inheritance Message-ID: I have a couple of classes: ????class?Base: ????????... ????class?Sub(Base): ????????... I want to subclass Base and Sub, i.e. define classes: ????class?MyBase(Base): ????????... ????class?MySub(Sub): ????????...? The inheritance looks like this: ????Base->MyBase ????????->Sub->MySub But I'd really like it to look like this: ????Base->MyBase->Sub->MySub i.e. define Sub as "class Sub(X)", where I can change X at the time of instantiation.??Then?I?could?define?MySub?as?"class?MySub(Sub(MyBase))". (I hope that it's obvious that I'm looking for this effect, not this syntax) Of course, someone is going to ask "why?" I need to override a few members in Base.??Sub?is?mostly?fine?as-is,?so?if?I could have MySub=Sub(MyMBase), that would be fine. From amy-g-art at cox.net Fri Jan 9 19:37:24 2004 From: amy-g-art at cox.net (Amy G) Date: Fri, 9 Jan 2004 16:37:24 -0800 Subject: Using .seek(0) to read. Message-ID: <5PHLb.63142$BQ5.4900@fed1read03> "Peter Otten" <__peter__ at web.de> wrote in message news:btjbot$f56$00$1 at news.t-online.com... > You can open the file in "r+" mode and then f_vm.seek(0) before writing. > However, from the above example I can not see why you even bother to check > the old contents and don't just write the new data. > > Peter I got this respnse on a prior post. Peter was correct about not needing to compare the old contents, and I was able to easily fix my code by taking out any read. However, now I need to open the file in "r+" mode and do a .seek(0) on it. I am opening up the .procmailrc file for each user in a database that has a "save_junkmail" == 1 and inserting some lines. They need to be inserted in the correct spot and each user has a different number of lines in their .procmailrc. Everything prints out correctly. I now want to write the lines instead of printing to stdout. If I set up the open() statement to say: procmailrc_file = open("/home/%s/.procmailrc" %userid, 'r+') How do I then get the values with .seek(0)? Is it simply file_in_list = procmailrc_file.seek(0) ....? Is there a better way to do this? *********************CODE SNIPPET**************************************************** c.execute("""SELECT save_junkmail, userid from users where save_junkmail = '1'""") d = c.fetchall() if (hasElements(d) == 1): for save_junkmail, userid in d: #IS JUNKMAIL OFF - IF IT IS TURN IT ON. ELSE DO NOTHING junkmail_off = os.popen("/bin/ls /home/%s/ | grep spam$" %userid) if (junkmail_off): junk_off = stripLs(junkmail_off.readlines()) #os.system("/bin/mv /home/%s/%s /home/%s/mail" %(userid, item, userid)) procmailrc_file = open("/home/%s/.procmailrc" %userid, 'r') procmailrc = stripLs(procmailrc_file.readlines()) x = procmailrc.index("| /usr/local/bin/spamc") procmailrc.insert((x+2), ":0:\n* ^X-Spam-Status: Yes\n$HOME/probably-spam\n") procmailrc.insert((x+2), ":0:\n* ^X-Spam-Level: \*\*\*\*\*\*\*\*\*\*\*\*\*\n$HOME/almost-certainly-spam\n") for line in procmailrc: print line **************************************************************************** *********** Thanks for your help. From http Mon Jan 12 20:10:37 2004 From: http (Paul Rubin) Date: 12 Jan 2004 17:10:37 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> Message-ID: <7xhdz08xgy.fsf@ruckus.brouhaha.com> Donn Cave writes: > I don't know if we're on very solid ground from which to laugh at > C++, though. Python has the advantage of a clean start, but from a > software engineering standpoint it really seems like a hacker > language. Full of neat tricks that work like magic, but does it > really even attempt to offer anything in the area you're talking about? It makes some feeble ones but is somewhat hobbled by its origins as a scripting or "glue" language. Also, Python is really still in its infancy. Maybe after PyPy is completed, someone can try writing a serious compiler for it, and the issues brought out by writing the compiler can drive the design of a successor language, Python II or whatever. The one attempt I know of to write a substantial Python application competitive with similar applications written in C was the Grail web browser, and AFAIK that was a complete failure. However, for small to medium sized projects which don't have to run fast, Python is great. From usenet_spam at janc.invalid Wed Jan 14 20:43:39 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 15 Jan 2004 01:43:39 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Brandon J. Van Every" schreef: > I am not sure how I feel about it. I think it only bothers me when > they claim to be cross-platform in theory, and the Windows build > simply does not work in practice. A working Windows build should be > easy to obtain all the dependencies for, and it should just build. > When it doesn't do that, when you have to chase all over Hell's green > acre to find the libraries, and then the build simply coughs and gags > and dies, I'm not even slightly amused at how "cross-platform" some > Linuxer is claiming things to be. You think "cross-platform" means "it runs out-of-the-box on all possible platforms that ever existed, now exist, and will ever exist"? Please go searching and come back when you find 1 (one) program which fits that definition... :-p -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From danb_83 at yahoo.com Sun Jan 18 17:51:33 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jan 2004 14:51:33 -0800 Subject: Printing variable names References: Message-ID: Mark McEahern wrote in message news:... > Mike wrote: > > >mylist = [a, b, c] > > > >I want to print out the names of the variables in mylist (not the > >values of a, b, and c). How do I go about doing this. Thanks. > > There's no simple answer to this. Consider the fact that you can have > more than one name bound to any given mutable instance. Why did you specify "mutable"? The same applies to immutable instances. > I'm curious what problem you're trying to solve. So am I. The question shows up here all the time, but I've never seen a reason for it. From tjreedy at udel.edu Mon Jan 19 18:44:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Jan 2004 18:44:26 -0500 Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> Message-ID: <0aqdnVcPUPNM9pHdRVn-jw@comcast.com> "Wayne Folta" wrote in message news:mailman.524.1074550958.12720.python-list at python.org... > For me, it's just totally natural that I'd say, "The POP3 package is > built using the socket package and socket exceptions are not caught by > POP3." That single sentence immediately tells me everything I needed to > know. If you consider it a doc bug or deficiency, go to sourceforge, register if you have not, go to http://sourceforge.net/tracker/?group_id=5470&atid=105470 and file a doc bug. Give a specific suggestion like the above, giving the LibRef section number and paragraph and sentence number where you would put it. Also give rationale (which I snipped) explaining how as newcomer you were unnecessarily puzzled, mislead, or whatever. If one of doc maintainers agree, as they have with most of my suggestions, they will add to the LaTex master copy. (Patches to LaTex source are also accepted, for those who can make such.) This is how docs keep getting better. > No trolling intended. I never thought so. You have obviously looked pretty carefully at all three languages, given them a fair if personal evaluation -- and come to the 'right' conclusion ;-). Terry J. Reedy From theller at python.net Mon Jan 26 04:43:17 2004 From: theller at python.net (Thomas Heller) Date: Mon, 26 Jan 2004 10:43:17 +0100 Subject: -- Pythonic control of Windows GUI application: tabs and listviews References: <4b3b1124.0401251706.6cf67f27@posting.google.com> Message-ID: <1xpnrqoa.fsf@python.net> zapazap at yahoo.com (zapazap) writes: > -- Pythonic control of Windows GUI application: tabs and listviews > > Dear Snake-charming Gurus, > > I have learned to manipulate some controls ("Button", "ComboBox", etc) > through such means as: > > win32gui.SendMessage(hwnd, win32con.BM_GETCHECK, 0 ,0) > win32gui.SendMessage(hwnd, win32con.CB_GETCOUNT, 0 ,0) > > provided by Python Win32 Extensions, and understand that such > constants as: > > win32con.BM_GETCHECK > win32con.CB_GETCOUNT > > corresponding to distinct messages (documented at [1] and [2]) that > can be sent to such controls. > > For the "List-View" and "Tab" controls then, I expected to find the > constants > > win32con.LVM_GETCHECK > win32con.TCM_GETITEMCOUNT > > corresponding to the distinct messages documented at [3] and [4]. > Unfortunately the module win32com module does not have any LVM_* or > TCM_* attributes, and I have not found reference to such constants in > the Extensions documentation. These constants are defined in the 'commctrl' module: 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 commctrl >>> commctrl >>> commctrl.LVM_GETITEMCOUNT 4100 >>> commctrl.TCM_GETITEMCOUNT 4868 Thomas From dave at pythonapocrypha.com Fri Jan 9 17:40:23 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 9 Jan 2004 15:40:23 -0700 Subject: Python is far from a top performer according to benchmarktest... References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <025601c3d701$91f5a580$6401fea9@YODA> Iwan: > > The greatest advantage of Python is the great increase in productivity and > > the generation of a much smaller number of bugs due to the very clean and > > compact structure Python invites you to produce. > > So dogma dictates. And I've found it to be true on many occasions, if > not all. BUT, the famed Python Productivity Gain is very difficult to > quantify. And for me that's a BIG but. I'm trying to push Python within > my company. Nicely presented "performance benchmarks" go down well with > management, bevause those are quantities which are supposedly > understood. Understood, perhaps, but very often irrelevent. That being the case, using performance benchmarks to argue your case is a weak approach. If you're talking to management, talk to them about something they care about, like money. For most programs it's hard to translate performance improvements into money: e.g. it's hard to assert that by doubling the speed of your spell-checker implementation that sales will increase. There of course are exceptions, but even then there's no guarantee that management would still prefer performance above other factors if given a choice. It's much more powerful to speak about reduced time to market, for example. Or the ability to compete against companies with legions of programmers. Or the decreased time it takes to turn ideas into implemented features (especially when it's your competitor that came up with the idea). Or a lower cost of changing directions technologically. Etc. -Dave From me at privacy.net Sat Jan 10 07:14:35 2004 From: me at privacy.net (Duncan Booth) Date: 10 Jan 2004 12:14:35 GMT Subject: Variable Scope 2 -- Thanks for 1. References: <3fff16b6$0$315$e4fe514c@news.xs4all.nl> Message-ID: JCM wrote in news:btn6ks$ada$1 at fred.mathworks.com: > Irmen de Jong wrote: > ... >> A very important concept with Python is that you don't have variable >> assignment, but name binding. An "assignment statement" binds a name >> on an object, and the object can be of any type. A statement like >> this: > >> age = 29 > >> doesn't assign the value 29 to the variable age. Rather, it labels >> the integer object 29 with the name age. > > I think this statement is misleading--it seems to imply the integer > object is altered somehow. Personally I see no problem with saying > the value 29 is assigned to the variable age, so long as you > understand the semantics. > Be careful. The integer object is actually altered, at least in so far as its reference count (which is part of the object) is changed: >>> import sys >>> sys.getrefcount(29) 11 >>> age = 29 >>> sys.getrefcount(29) 12 >>> -- Duncan Booth duncan.booth at suttoncourtenay.org.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From llothar at web.de Sat Jan 10 00:29:56 2004 From: llothar at web.de (Lothar Scholz) Date: 9 Jan 2004 21:29:56 -0800 Subject: Python is far from a top performer according to benchmark test... References: Message-ID: <6ee58e07.0401092129.302cb9d4@posting.google.com> Samuel Walters wrote in message news:... > For numerical processing, C is the right tool, Definitely not, you don't want a pointer language when using numerical processing: use Fortran. From mark at mceahern.com Sat Jan 3 18:48:29 2004 From: mark at mceahern.com (Mark McEahern) Date: Sat, 03 Jan 2004 17:48:29 -0600 Subject: datetime string to datetime object converter In-Reply-To: References: Message-ID: <1073173709.12941.5.camel@dev.internal> On Sat, 2004-01-03 at 17:38, Randall Smith wrote: > Is there an existing module or script that can convert a datetime string > of unknown format to a python datetime object ? Search for "egenix mx.DateTime" It's amazing. // m From newsgroups at jhrothjr.com Wed Jan 28 11:10:48 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 28 Jan 2004 11:10:48 -0500 Subject: isinstance() bug References: <20040128132225.GA10842@foof.i3.cz><16407.54576.283608.505067@montanaro.dyndns.org> Message-ID: <101fnrgg9dks4dd@news.supernews.com> "Michal Vitecek" wrote in message news:mailman.925.1075304492.12720.python-list at python.org... > Skip Montanaro wrote: > >You imported the module twice (look at sys.modules) so you have two > >different A classes. I believe isinstance() uses the __class__ attribute > >and the class's __bases__ attribute to work its way up the class chain > >looking for a match. Even though they are defined identically, you have two > >different A classes. An instance of one can't also be an instance of the > >other. > > i think that if absolute path was somehow put into the classes internal > information this inconsistency would be put away. > > it's my belief that if i'm instantiating a class from the same location > no matter how i imported its definition, its instances are always of > the same class. > > and as to the sys.modules thing: this could be considered as just two > references to the same module (again its absolute path would be taken > into account), not two different modules. > > does it make sense? It depends on the operating system. I think it's quite possible to resolve the absolute path on, for example, Windows, while it's not possible in the general case on, for example, Unix. If you have two different paths hard linked to the same file, which one is the "correct" path? It gets even worse if you're accessing the file from a file server where you may not have the least idea what the aliasing policies are. The best advice I have is the same advice I give to anyone who burns themselves doing something that doesn't work quite the way they expect: don't do that. Imports need to be considered thoughtfully. John Roth > > -- > fuf (fuf at mageo.cz) > From cphsu at zen.com.tw Mon Jan 5 04:26:54 2004 From: cphsu at zen.com.tw (Kent Hsu (Hsu, Chih-Peng)) Date: Mon, 5 Jan 2004 17:26:54 +0800 Subject: codecs packages? References: Message-ID: How about to try with 'mbcs' codec? Martin v. L?wis wrote in message news:bt9t5m$q7t$07$1 at news.t-online.com... > Fortepianissimo wrote: > > I'd like to decode some email headers into unicode, including some > > Asian DBCS. I've searched several places and they pointed to the > > Python Codecs project @ SF > > (http://sourceforge.net/projects/python-codecs/), but I couldn't find > > anything there. Could someone give me a pointer to any related > > library? > > I recommend to use the cjkcodecs package, at > > http://cjkpython.i18n.org/#CJKCodecs > > (atleast, it ought to be there - cjkcodecs appears to change > its home page with each release). > > Regards, > Martin > From pgmoscatt at optushome.com.au Fri Jan 23 19:31:26 2004 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Sat, 24 Jan 2004 10:31:26 +1000 Subject: Python & Databases ? Message-ID: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> Will Python work with any of the databases like MySQL... ? Pete From fse12 at cse.usc.edu Wed Jan 21 13:21:13 2004 From: fse12 at cse.usc.edu (ACM SIGSOFT 2004 Publicity Chair) Date: 21 Jan 2004 10:21:13 -0800 Subject: CFP: ACM SIGSOFT 2004/12th Symposium on Foundations of Software Engineering Message-ID: <1b1ef86d.0401211021.42d21b27@posting.google.com> CALL FOR PAPERS AND WORKSHOPS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ACM SIGSOFT 2004 12th International Symposium on the Foundations of Software Engineering =============================================================================== October 31 - November 6, 2004 Hyatt Newporter, Newport Beach, California, USA http://www.isr.uci.edu/FSE-12 Sponsored by ACM SIGSOFT In cooperation with ACM SIGPLAN =============================================================================== Call for Papers --------------- ACM SIGSOFT 2004 brings together researchers and practitioners from academia and industry to exchange new results related to both traditional and emerging fields of software engineering. We invite submission of technical papers which report results of theoretical, empirical, and experimental work, as well as experience with technology transition. Topics of Interest We encourage submissions in any field of software engineering, including, but not limited to: * Component-Based Software Engineering * Distributed, Web-Based, and Internet-Scale Software Engineering * Empirical Studies of Software Tools and Methods * Feature Interaction and Crosscutting Concerns * Generic Programming and Software Reuse * Requirements Engineering * Software Analysis and Model Checking * Software Architectures * Software Configuration Management * Software Engineering and Security * Software Engineering Tools and Environments * Software Information Management * Software Metrics * Software Performance Engineering * Software Process and Workflow * Software Reengineering * Software Reliability Engineering * Software Safety * Software Testing * Specification and Verification * User Interfaces Submission Guidelines Paper submissions will be made electronically via the Web, at the conference web site. Both an abstract and the full paper must be submitted by their respective submission deadlines. Papers must not exceed ten (10) 8.5"x11" single spaced pages using the ACM SIG proceedings formatting instructions, which are accessible from the conference web site. Accepted papers must be accompanied by a signed ACM copyright release form. Paper submissions will be reviewed by the program committee for originality, significance, soundness, and quality of presentation. Papers must clearly present an original contribution to the state-of-the-art. Experience papers are welcome, but they must clearly present general lessons learned that would be of interest and benefit to a broad audience of both researchers and practitioners. Papers must describe work that has not been submitted to or presented at another forum. Any double submissions will be rejected without review, and the other forum will be informed of the situation. Important Dates (all in 2004) March 24 --- Abstract submission due March 29 --- Technical paper submissions due June 4 --- Author notification August 15 -- Camera ready due General Chair ------------- Richard N. Taylor, University of California, Irvine, USA; taylor at uci.edu Program Chair ------------- Matthew B. Dwyer, Kansas State University, USA; dwyer at csi.ksu.edu Program Committee ----------------- Ken Anderson, University of Colorado, Boulder, USA Annie Ant?n, North Carolina State University, USA Joanne Atlee, University of Waterloo, Canada Prem Devanbu, University of California, Davis, USA Mary Jean Harrold, Georgia Institute of Technology, USA John Hatcliff, Kansas State University, USA Jim Herbsleb, Carnegie Mellon University, USA Andr? van der Hoek, University of California, Irvine, USA Paola Inverardi, University of L'Aquila, Italy Gregor Kiczales, University of British Columbia, Canada Jeff Kramer, Imperial College London, UK Shriram Krishnamurthi, Brown University, USA Shinji Kusumoto, Osaka University, Japan Axel van Lamsweerde, Universit? Catholique de Louvain, Belgium Bashar Nuseibeh, The Open University, UK Mauro Pezz?, Universita' di Milano-Bicocca, Italy Gian Pietro Picco, Politecnico di Milano, Italy David Rosenblum, University College London, UK Gregg Rothermel, Oregon State University, USA Wilhelm Sch?fer, Universit?t Paderborn, Germany Douglas C. Schmidt, Vanderbilt University, USA Peri Tarr, IBM T.J. Watson, USA Frank Tip, IBM T.J. Watson, USA Willem C. Visser, NASA Ames Research Center, USA Call for Workshops ------------------ Workshops hosted by SIGSOFT 2004 should provide an opportunity for exchanging views, advancing ideas, and discussing preliminary results on topics related to software engineering research and applications. Workshops should not be seen as an alternative forum for presenting full research papers. Workshops hosted by SIGSOFT 2004 will last one or two days. Important Dates (all in 2004) April 15 --- Workshop proposals due Oct 31-Nov 1, 5-6 --- Workshops Workshop Chair -------------- Harald Gall, Technical University, Vienna, Austria, gall at infosys.tuwien.ac.at Publicity Chair --------------- Nikunj R. Mehta, University of Southern California, mehta at cse.usc.edu From rp at win.tue.nl Thu Jan 8 08:18:00 2004 From: rp at win.tue.nl (Reinier Post) Date: Thu, 8 Jan 2004 13:18:00 +0000 (UTC) Subject: Text-to-HTML processing program References: Message-ID: phil hunt wrote: >Does anyone know of a text-to-HTML processing program, ideally >written in Python because I'll probably be wanting to make small >modifications to it, which is simple and straightforward to use >and which uses a simple markup language (something like Wikipedia >markup would be ideal)? Last time I looked for it, I Googled for txt2html and found a program of that name based on txt2tex I haven't used them heavily. There are other "plaintext with conventions" text formats out there, but I can't find my pointers to them. -- Reinier From antonmuhin at rambler.ru Fri Jan 9 13:24:56 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 09 Jan 2004 21:24:56 +0300 Subject: Name of the function In-Reply-To: <9e5ea2c4.0401081103.6fa93bf9@posting.google.com> References: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> <9e5ea2c4.0401081103.6fa93bf9@posting.google.com> Message-ID: Olaf Meding wrote: > Is there a way to do this w/o importing another module? > > Yes this is what I was looking for except the code below requires > importing module inspect. I'm afraid that there is no way, at least none I'm aware of (except for Terry Reed suggestion, but I think it's not what you are looking for). Why you don't want to import a module? regards, anton. From brian at sweetapp.com Sat Jan 24 03:31:11 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 24 Jan 2004 00:31:11 -0800 Subject: [OPINION] - does language really matter if they all dothe samething? In-Reply-To: <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: <005e01c3e254$6c74a5a0$0000fea9@dell8200> > I agree that functions are objects in Python. However, not everything > in Python is an object. For example, names are not objects. In the > above example, "foo.bar()", neither "foo" nor "bar" are objects, but > they are references to objects. In some languages, such as C and Lisp, > references to objects can be directly manipulated (Lisp has symbols, C > has pointers). I'm having problems figuring out your follow-up. Your original point was: "It's [Python] build from a procedural standpoint, in an environment where most things are objects and some are functions." I disagreed with the contrast between functions and objects. Now you seem to be making the totally different point that names are not objects in Python. Following along: 1. I can't see how your mention of C pointers is relevant at all 2. I don't see what is so special about Lisp symbols versus Python names i.e. what functionality are you missing? [snipped] > If you think this example is contrived, maybe you haven't worked with > the paradigms used in Objective-C very much. The example above was > used dozens of times in a class that I wrote in Objective-C which draws > a grid to the screen, for example, when it asks itself or its delegate > what color the grid should be, or the maximum scale allowed. The > practice is also used heavily by Apple's Cocoa libraries, which are my > favorite UI libraries of all time to program with. The cost in writing a function to check for the availability of a method on your target object is a one-time thing (which you just did), so it doesn't seem like a big deal to me. - (void)resetToDefaultSettings { if ([delegate respondsToSelector:@selector(defaultSettingsFor:)]) [self setSettings:[delegate defaultSettingsFor:self]]; else [self setSettings:someFallbackValue]; } In Python you'd write it as: def resetToDefaultSettings(): if self.delegate().respondsToSelector_('defaultSettingsFor:'): self.setSettings(delegate().defaultSettingsFor_(self)) else: self.setSettings(someFallbackValue) I don't really like the syntax that much but I guess the guys writing the Python Objective-C bindings thought it was ok. Cheers, Brian From elainejackson7355 at home.com Thu Jan 8 19:10:01 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 09 Jan 2004 00:10:01 GMT Subject: books References: <3FFDC029.AB0A4097@unet.univie.ac.at> Message-ID: I haven't read either of these myself, but I've heard good things. The titles are "thinking in python" and "dive into python". Both are available on the net in pdf form. "Thomas Mang" wrote in message news:3FFDC029.AB0A4097 at unet.univie.ac.at... | Hello, | | I have programmed mostly in C++ lately, and I want to start learning | Python now. | | Which books would you recommend to buy? | | I am both looking for an introduction into the language, as well as | complete guides. | | | | thanks for your responses, | | Thomas | From __peter__ at web.de Sun Jan 4 15:36:55 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jan 2004 21:36:55 +0100 Subject: Launching pdb from within a script References: Message-ID: Graham Nicholls wrote: > I'm sure I was able to print the value of variables like this: > > except : > pdb.set_trace() [...] > But pdb complains that there are no such variables. It may be that I had > to add some incantation around the script startup - I just can't remember > (and its frustrating!). import pdb abc = 1 try: print "before" 1/0 except: pdb.set_trace() print "after" Now run it: before --Return-- > /(suppressed)/python2.3/pdb.py(992)set_trace()->None -> Pdb().set_trace() (Pdb) abc *** NameError: name 'abc' is not defined (Pdb) u > /(suppressed)/debugger.py(7)?() -> pdb.set_trace() (Pdb) abc 1 (Pdb) If the above sample session doesn't help, you could actually read the pdb documentation - or do something new and dangerous: search google groups for, say, Nicholls and set_trace :-) Peter From michael at telcopartners.com Tue Jan 20 13:49:35 2004 From: michael at telcopartners.com (Michael Spencer) Date: Tue, 20 Jan 2004 10:49:35 -0800 Subject: simple class question References: Message-ID: "anton muhin" wrote in message news:bujsd7$iot2m$1 at ID-217427.news.uni-berlin.de... > C GIllespie wrote: > > Dear all, > > > > I'm new to both python and OOP, so could I ask a simple question. > > > > I have class: > > > > class species: > > __init__(self,pop=0): > > self.pop=pop > > > > Now I want to do something like this: > > > > X=species(pop=10) > > Y=species(pop=X.pop) > > OK, but now I want to update X.pop and have that mirrored in Y.pop, i.e. if > > X.pop=5, Y.pop now equals 5. > > > > What is the best/nicest/simplest way of doing this? > > > > Many thanks > > > > Colin > > > > > > In some cases pop should be class attribute. > > regards, > anton. Example using class attribute: >>> class species(object): ... pop = [0] #Must be mutable object ... def __init__(self, pop = 0): ... self.pop[0] = pop ... >>> x = species(10) >>> x.pop [10] >>> y = species(5) >>> y.pop [5] >>> x.pop [5] >>> From jikosan at myrealbox.com Sun Jan 11 04:49:41 2004 From: jikosan at myrealbox.com (Jikosan) Date: Sun, 11 Jan 2004 09:49:41 GMT Subject: Help with if statement References: Message-ID: I got it working. I had originally misread the prompt. Here's the code I finally got working. It calculates PI using the Monte Carlo method. I have to graph log N vs log PI, which explains the last few lines of the program. Gene #HW1 - 1.5.2 #This code was written in the Python programming language. import random #Loads the random number generator library. import math #Loads the math library. file=open('output.txt', 'w') #Identifies output file. a, b = -1.0, 1.0 #Sets the boundary conditions for (x,y). for N in range(0, 100000, 25): #4000 trials, 1<= N <= 100000 at steps of 25. if N == 0: N = 1 onecheck = 0 for n in range(0,N): #This for loop generates (x,y) sets N times. xrand = random.random() yrand = random.random() x = a * (1.0-(xrand)) + b*(xrand) y = a * (1.0-(yrand)) + b*(yrand) c = math.sqrt(math.pow(x,2.0) + math.pow(y,2.0)) #Calculates the distance to origin. if c < 1: onecheck = onecheck+1 pi = 4.0*(onecheck*math.pow(N,-1)) #This is to calculate P(N), the ratio of points whose #distance is less than 1 to the total number of trials. if pi == 0.0: #Prevent 'log 0' calculation errors pi == 1.0 #Convert pi and N to log10 and write to a file to graph on Excel. file.write(str(math.log(N, 10))) file.write(' ') file.write(str(math.log(pi, 10))) file.write('\n') file.close() From robinfriedrich at mac.com Wed Jan 21 16:43:19 2004 From: robinfriedrich at mac.com (Robin Friedrich) Date: 21 Jan 2004 13:43:19 -0800 Subject: Build with large file support on AIX Message-ID: How does one build Python (2.2 in this case) with large file support on AIX? From not at existing.ru Fri Jan 16 08:37:41 2004 From: not at existing.ru (bva) Date: Fri, 16 Jan 2004 14:37:41 +0100 Subject: viewcvs install error on solaris Message-ID: <4007e92d$0$325$ba620e4c@news.skynet.be> Hello, While trying to install viewcvs on a solaris 5.9 machine I get the following error message: Traceback (most recent call last): File "./viewcvs-install", line 35, in ? import compat File "./lib/compat.py", line 20, in ? import urllib File "/usr/local/lib/python2.2/urllib.py", line 26, in ? import socket File "/usr/local/lib/python2.2/socket.py", line 41, in ? from _socket import * ImportError: No module named _socket Python is installed on the machine. Can anybody tell me what I'm doing wrong or what I've forgotten? TIA From danb_83 at yahoo.com Sun Jan 18 18:08:48 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jan 2004 15:08:48 -0800 Subject: re question - finiding matching () References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: Jeff Epler wrote in message news:... > Regular Expressions cannot perform the simple task of matching an > arbitrary number of parentheses. You could write an expression that > will work as long as the nesting isn't more than N levels, but the > expression quickly becomes very painful. > > Instead, you can use some method to split the string into parts: one > part for "(", one for ")" and one for any other sequence of characters: ... > Now, start scanning and counting parens, until you get back to 0 That's the way I'd recommend. However, it doesn't generalize to cases where there are multiple types of parentheses. For that situation, you can use: LEFT_PARENS = '([{' RIGHT_PARENS = ')]}' PAREN_MATCHES = dict(zip(RIGHT_PARENS, LEFT_PARENS)) def balancedParens(tokens): parenStack = [] for token in tokens: if token in LEFT_PARENS: parenStack.append(token) elif token in RIGHT_PARENS: if parenStack: correspondingLeftParen = parenStack.pop() if PAREN_MATCHES[token] != correspondingLeftParen: return False else: return False return True (There's probably a simpler way, but I can't think of one right now.) From gordonp1 at yahoo.com Wed Jan 21 22:27:48 2004 From: gordonp1 at yahoo.com (Peter Gordon) Date: 21 Jan 2004 19:27:48 -0800 Subject: How to disable dos shell window popup for os.system call Message-ID: When I try to execute another program, the dos command shell window pops up with the application. For example: os.system("notepad") brings up the notepad but I also get the command shell window. How do I prevent command shell window to open? From deets_noospaam at web.de Thu Jan 29 13:11:26 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 29 Jan 2004 19:11:26 +0100 Subject: Get number of iteration References: Message-ID: > In recent versions of Python there is an easier way: > > >>> for index, value in enumerate(["three", "four", "five", "six"]): > ... print index, value > ... > 0 three > 1 four > 2 five > 3 six Boy, one never stops learning. I'll better stop answering here and read only :) Diez From snake at penza-gsm.ru Thu Jan 15 00:40:36 2004 From: snake at penza-gsm.ru (Alexey Nezhdanov) Date: Thu, 15 Jan 2004 08:40:36 +0300 Subject: Bug or feature? Message-ID: Hello. Found a strange python behaivoir while writing some object. I've stripped out all other stuff so the problem is stright here: ================================= #!/usr/bin/python class Object: def __init__(self,val): self.val=val def Sub(self,delta): self.val-=delta return delta c=Object(1) ### case 1 ### d=c.Sub(1) c.val+=d print 'case A:',c.val ### case 2 ### c.val+=c.Sub(1) print 'case B:',c.val ================================= Case 1 and case 2 prints out different calues (1 and 2 respectively). Do not know - if this is a bug or feature of python. -- Alexey Nezhdanov From wweston at att.net Thu Jan 22 10:39:01 2004 From: wweston at att.net (wes weston) Date: Thu, 22 Jan 2004 15:39:01 GMT Subject: Importing database: newbie issue In-Reply-To: References: Message-ID: Angelo, If doing this on an ongoing basis, you might look at using shelve. from "Python Essential Reference", pg 81 import shelve object = someObject() dbase = shelve.open(filename) #open a database dbase['key'] = object #save object to db ... object = dbase['key'] #retrieve object dbase.close() Angelo Secchi wrote: > Hi, > I have a database with a fixed format structure (i.e. i know the > starting point and the length of each of the field composing the > database) and I would like to extract from it only few fields (ex the > one starting from the 32nd position with length 12...). > What is the best way to do that? > > Thanks > a > From pablofran at www.pablofrancisco.com Sat Jan 31 02:09:20 2004 From: pablofran at www.pablofrancisco.com (pablofran at www.pablofrancisco.com) Date: 31 Jan 2004 07:09:20 -0000 Subject: (no subject) In-Reply-To: <20040131070920.37338.qmail@www.1hourhosting.com> Message-ID: <20040131070920.37359.qmail@www.1hourhosting.com> Thank you for your email. I will reply to you as soon as possible. Thanks, Pablo From its1louder at yahoo.com Wed Jan 21 12:35:58 2004 From: its1louder at yahoo.com (Tom) Date: 21 Jan 2004 09:35:58 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> Message-ID: <90f2d9db.0401210935.428e0a0e@posting.google.com> Hah, thanks for the prompt help. I've been using the _programming on win32_ (Hammond) book as a reference and now I see that right under spawnve in Appendix A p. 523 (which I was using as my os module reference) is the bit about system(command). From C that should have been obvious. Trying it, os.system() didn't really work but os.startfile() works exactly as I'd like it. fixing my os.system() call is probably is easy but irrellevant. As for the other question, a portable html browser that looks & feels like the chm help browser. I realized that Boa Constructor Project has such a component, since I've used Boa help in windows and unix. I wonder if anyone has written a cross-platform CHM decoder and browser that has the help browser look & feel. I can't find one, but it seems that python would be a great language to make such a thing. Maybe I'll take a crack if it hasn't been done. I like monolithic, compressed help vs. a big directory full of html. From alexander.dejanovski at laposte.net Wed Jan 14 10:26:32 2004 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Wed, 14 Jan 2004 16:26:32 +0100 Subject: JyRetic EAI Server 1.0RC1 released Message-ID: <5.1.0.14.2.20040114162419.02a38630@127.0.0.1> Retic goes Jython now, and is thus fully compatible with the Java platform. (I won't develop no more on the former Python version of Retic. ) This gives a better connectivity, particularly through JDBC and JMS. Jython 2.1 is included in the release. Download on the sourceforge project's site => http://sourceforge.net/projects/retic Available sources are : file, FTP, HTTP, JMS, SOAP, JDBC, XMLBlaster Available pipes are : Zip, Unzip, Flat-to-XML, XML-to-Flat, XPath, XSLT, FOP (to produce PDF or PS from XSL-FO input), Excel (to produce MS Excel files from Gnumeric-XML input) Available sinks are : file, FTP, HTTP, JMS, SOAP, JDBC, XMLBlaster, Jabber (open source instant messaging), shell, SMTP, Xindice (Apache's XML database) Two new kinds of components have appeared in this release : Preprocessors and Postprocessors : executed only once respectively before and after adaptor execution. Available preprocessors : SQL, Xindice (much more to come) Available postprocessors : SQL (much more to come) The logging system is now based on log4j (I've added a Jabber appender (IMAppender), thanks to orange-soft.com). Adaptors can be launched through command-line, XMLRPC calls (retic administrator uses it) or JMS queue (the server has to be listening your queue). Retic also has now a scheduler. I know docs aren't up-to-date but I'll fix that real soon. ============================================================= WHAT IS RETIC ? Retic is an EAI Server. The aim is to permit applications to communicate, even if they don't speak the same language (which means transport protocols as well as data structures). This is done by building adaptors. An adaptor is composed of : - One source - Several pipes (process data transformations) - Several sinks (destination of data) - Several loggers (using log4j) - Preprocessors (executed only once before adaptor execution - for example => drop/create a table through a SQL query) - Postprocessors (executed only once after adaptor execution - for example => creation of an index on a table through a SQL query) It is written in Jython and works 100% fine with only Java 1.3+ installed on your system (jython 2.1 is embedded in the releases). ============================================================= I've also released a reworked version of Retic Administrator (1.0) the GUI to create adaptors, and control the server. Yet another piece of software released is reticSOAP, a small tool that parses WSDL and permits to : - test SOAP services - See the messages exchanged Both Retic Admin and Retic SOAP come as a win32 release or a wxPython 2.4 source file release (Python 2.3+ needed). Enjoy !! From jcarlson at uci.edu Thu Jan 22 12:02:17 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 09:02:17 -0800 Subject: Looking for advice: supporting multiple embedded interpreters References: Message-ID: <20040122090056.026D.JCARLSON@uci.edu> > Some background first - we have some software that embeds a Python > interpreter into a host application. Scripts are loaded dynamically and > used. But we want to support the ability to edit scripts while the app is > running. This means we have to "unload" the script and cause a reload. > Normal module reloading tricks don't work because if you try to reimport a > script that imports another script, and if the nested script is changed, it > might not be reloaded itself. Also, we have 2 parts of the software, each > using Python for its own set of scripts. We don't want scripts loaded into > each parts to "see" scripts loaded into the other part. Ideally, we would > like multiple "instances" of a Python interpreter to manage this. > > So, for Python 2.2, I came up with a system that works. When we need a new > self-contained Python interpreter, I use Py_NewInterpreter(), swap it in > using PyThreadState_Swap, load my built in modules, and swap it back out. > When I need to run some code in that interpreter, I swap it back in, load > the module I need, call methods in it, and swap it back out. When I'm done > with the interpreter, I swap it back in and call Py_EndInterpreter. > > When I want to force a reload of all the script code in a given > interpreter, I just delete the interpreter, create a new one, and load the > scripts into that one. This has worked flawlessly. And each "part" of my > application can use a different interpreter without modules and globals in > each one interfering with the other. > > Now, with Python 2.3, this code doesn't seem to work anymore. Someone told > me it is likely because of the extensive rewrite of GUSI or whatnot. It is > important to note that I'm NOT really doing any threading. I just was > self-contained interpreters for the above reasons. > > What I am wondering is if there a reliable method in 2.3 that does what I > need? > > It has recently come to my attention that Lutz Paelike is in exactly the > same situation I am in, so I don't think this is a fringe concept. My advice: use the 'reload' builtin to reload your python modules. - Josiah From newsgroups at jhrothjr.com Fri Jan 23 07:14:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 23 Jan 2004 07:14:10 -0500 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: <10124195f717m35@news.supernews.com> "David M. Cooke" wrote in message news:qnky8rzid3y.fsf at arbutus.physics.mcmaster.ca... > At some point, Erik Max Francis wrote: > > Gary Robinson wrote: > >> If there anywhere else I should be expressing my opinion on this, let > >> me > >> know. > > > > Seems quite reasonable to me. The only issue I'd take with it is the > > choice of Min and Max for the names of the singletons; they're a little > > too close to the functions min and max, which obviously they're both > > likely to be used with. I would suggest something a little more verbose > > such as Minimum and Maximum, or if you want to get silly, Infimum and > > Supremum. > > Or, expressing the idea that they're the ends of a number line: > > PosInf, NegInf > PosInfinity, NegInfinity > PositiveInfinity, NegativeInfinity > > If IEEE floating point was done correctly everywhere, I'd say make > them the corresponding floating-point constants (Inf+ and Inf-). If you do that you lose the ability to have those two constants be in a list that *also* has end delimiters. A large part of the proposal is that the end delimiters shouldn't have any other meaning: in other words, there's no rational reason to use them in any other context than ordering. (People will always come up with irrational reasons, of course.) [grin] John Roth > -- > |>|\/|< > /--------------------------------------------------------------------------\ > |David M. Cooke > |cookedm(at)physics(dot)mcmaster(dot)ca From godoy at ieee.org Sat Jan 17 21:10:09 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 18 Jan 2004 00:10:09 -0200 Subject: wxwindows question References: Message-ID: <1h6pd1-788.ln1@wintermute.g2ctech> On Saturday 17 January 2004 20:31 Nuff Said wrote in : > I use(d) wxPython 2.4.2.4 with Python 2.3.x on various Linux > systems (incl. SuSE and Fedora Core). The same here... But with Conectiva Linux. SuSE is Conectiva's partner on the United Linux Consortium. > When I compiled wxPython with Unicode support, the demo either > did not work at all resp. every second or so widget crashed. I haven't tried using Unicode. My applications still don't need it and I've seen lots of reports about it not working properly. > Without Unicode support, e.g. the StyledTextControl (Scintilla) > crashed whenever I tried to enter a 'special' character (i.e. > a character which is not a 7 bit ASCII character). The use of > other widgets resulted in seg faults, too; but I do not remember > exactly, which ones. It doesn't happen here. Since I'm Brazilian I use a lot of chars that are not 7 bit ASCII (?, ?, ?, ?, ?, etc.) in a lot of places :-) No crashes due to that, except with an old version of wxGlade on Windows, where my parter couldn't open / create a file with "special" chars on titles and notebook tabs: it crashed there. On the other hand, it worked perfectly on Linux and on the running application, so after he finished the application, he used my Linux box to add all the missing stuff (then he learnt about sed & cia. with me). > I tried to compile wxPython (resp. wxGTK) for GTK1 and GTK2; the > former seemed to be more stable (but looked awful). I agree with you on that one. I haven't insisted much on the GTK2 stuff though. > After a week or two of testing, I gave up on wxPython (for the > moment). I wrote a lot of cross platform applications in Python > (together with C and, recently, C#) using Tkinter (resp. Tcl/Tk) > and pyGTK (resp. GTK+ for other languages) and never had such > problems. But both GUI toolkits lack some important widgets and > therefore I became interested in wxPython (though I don't like the > way I have to code in wxPython; but that's my personal problem :-) Could you please say more on the way the other tools are used? I adapted better with wxPython than Tkinter here... Probably I would look after Tkinter different today and I would even try it a little more based on several comments here, but then theres wxPython and it is solving my problems very nicely. Which widgets you missed there? > Recently, I write a lot of web applications (whenever possible), > using good old CGIs, various frameworks and ASP.NET (with C#). > But my dream for Python would be a native GUI toolkit (and not > just a wrapper for something else which was not designed with > Python in mind). It would be very good if wxPython was more python centric instead of trying to be more like wxWindows. But I guess that people who prototype in wxPython and then convert some parts (or all) of their application to C++ wouldn't like such a change... There's "equilibrium" here, and messing with that would be dangerous :-) Another advantage is that wxWindows is already there and it works. It would be a shame not to benefit from that. Since you mentioned CGIs, don't you like using Python for that? Be seeing you, -- Godoy. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jan 6 20:20:29 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 07 Jan 2004 02:20:29 +0100 Subject: Getting strange characters in the command prompt In-Reply-To: <56f42e53.0401061704.523f394@posting.google.com> References: <56f42e53.0401061704.523f394@posting.google.com> Message-ID: <3ffb5edc$0$323$e4fe514c@news.xs4all.nl> sebb wrote: [...] > ... and I run it in the windows command prompt, I get strange > characters I didn't ask for. > > And when I write those non-English characters (? ? ?) directly in the > command prompt, I get the correct characters. > > Can anyone help we with that problem? Does executing chcp 1252 before running your python program help? The windows console is not set to code page 1252 by default as far as I know, but some other windows-specific encoding. --Irmen From aahz at pythoncraft.com Sat Jan 24 01:33:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 24 Jan 2004 01:33:55 -0500 Subject: [OPINION] - does language really matter if they all do the samething? References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> Message-ID: In article , Dietrich Epp wrote: > >Python, second try: > >def reset_settings(self): > method = None > try: > method = self.delegate.default_settings > except AttributeError: > pass > if method: > self.set_settings(method(self)) > else: > self.set_settings(some_fallback_value) > >If you think this example is contrived, maybe you haven't worked with >the paradigms used in Objective-C very much. The example above was >used dozens of times in a class that I wrote in Objective-C which draws >a grid to the screen, for example, when it asks itself or its delegate >what color the grid should be, or the maximum scale allowed. The >practice is also used heavily by Apple's Cocoa libraries, which are my >favorite UI libraries of all time to program with. I'm quite sure it isn't contrived. OTOH, unlike your Lisp example, this is one which I think reads more easily than the equivalent Objective-C code (or your attempt to literally translate it). I think it's possible to emulate your Lisp code in Python, but as the joke goes, every language ends up writing a Lisp emulator. On the gripping hand, Lisp does absolutely nothing to demand the clarity with which you wrote your Lisp code, and I'm not willing to pay the price of reading the occasional (or frequent! -- depending on the code writer) Perl-like monstrosity for the privilege of having that elegance readily available. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From newsgroups at jhrothjr.com Sat Jan 3 18:34:25 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 18:34:25 -0500 Subject: pickling lambdas? References: <9abf3a27.0401031446.4d73cfb2@posting.google.com> Message-ID: "gong" wrote in message news:9abf3a27.0401031446.4d73cfb2 at posting.google.com... > hi > > i would like to pickle a lambda; according to the library docs in 2.3, > i believe this shouldnt be possible, since a lambda is not a function > defined at the top level of a module (?) > > however, upon google searching for "python lambda pickle" i find 2 > posts, one including gvr, which apparently demonstrate that this was > being attempted and even suggest that it is feasible. has this become > available yet, or will it be soon? > > thanks > gong Why do you want to do this? According to the docs, all that is saved for a function or a class is the name. Code, data and so forth is not saved, so it makes no sense to try to pickle a lambda unless you've bound it to a name at the module level. See 3.14.4 (Python 2.3.3 Library Reference.) If you really want to serialize a function's code, look at the marshal module. John Roth From mcfletch at rogers.com Sun Jan 18 11:10:17 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 18 Jan 2004 11:10:17 -0500 Subject: Forums for Teachers Using Python - Where are they? In-Reply-To: References: Message-ID: <400AAFE9.1000005@rogers.com> Official forum of this type is the Education Special Interest Group (sig), or edu-sig. You can find out more, subscribe and the like here: http://mail.python.org/mailman/listinfo/edu-sig HTH, Mike Samuel Walters wrote: >I'm currently considering a position teaching math and possibly >programming at a small local magnet school. If I was also teaching >programming, I would, of course, be using Python. > >So, I went out and googled around for resources. I found lots of articles >about using Python to teach programming, but I have yet to turn up one >forum where teachers using Python talk amongst themselves. > >Can anyone point me to such a resource, or, at least any "Must Read" >articles that I might have missed? > >Also, does anyone have any experience using "Thinking Like A Computer >Scientist" as a textbook? Does it fit well within a single semester? If >not, how far were you able to make it into the book? > >Thanks for any advice. > >Sam Walters. > >P.S. An thought provoking general interest paper about computers in >education is here: >http://www.cs.berkeley.edu/~bh/stop.html > >It was written 21 years ago and still raises a relevant question. > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From sdeibel at wingide.com Thu Jan 22 09:34:56 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Thu, 22 Jan 2004 09:34:56 -0500 (EST) Subject: Nokia prefers Python In-Reply-To: Message-ID: Anyone happen to have a contact at Nokia that might be willing and able to write up a Python Success Story based on this? Or know of someone else that might? http://pythonology.org/success Thanks, - Stephan From sholden at holdenweb.com Tue Jan 13 18:39:56 2004 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 13 Jan 2004 18:39:56 -0500 Subject: PyCon opportunities Message-ID: As the final submissions deadline approaches the PSF has taken an initiative which might help you attend if finance is one of the things that's been holding you back. Three resolutions passed today are intended to encourage attendance at PyCon. I would like to publicize these opportunities as widely as possible to emphasize that they are available to any eligible applicant. 1. Students at accredited institutions can apply for a "gopher" position, which grants them free admission to the conference in exchange for administrative assistance of the conference, under the direction of the organizing committee. As conference chair I have to approve such applications. If you are a student, please get in touch if you are interested in helping in this way. Numbers are strictly limited, and paying delegates are also welcome as "gophers". This system worked well last year, and we hope to make it more useful still this time around. 2. Monies from the silver sponsorships can be allocated to help defray costs associated with sponsor-selected sprints, up to a maximum of $500. Each silver sponsor can choose which sprint to allocate the funds to. The sprint leader and the sprint chair must agree on how the monies are to be disbursed. Any reimbursement for travel or other expenses must be made based on submission of receipts. 3. Sprint leaders who organize and run sprints with at least two other full-time attendants get waived admission to the conference if they want it. Those wishing to take advantage of these latter two offers should contact the PSF directly at psf at python.org. While I'm not a PSF Board member, and therefore cannot speak for the Board, it seems to me that this is their way of trying to ensure that PyCon benefits from having more of the best Python brains present at the conference. I'd like to thank them for this support, and I hope all readers will appreciate their gesture. I hope that in future we will see the PSF promoting other development and educational activities with equal enthusiasm. See you at PyCon! regards -- Steve Holden http://www.holdenweb.com/ ReportLab Enterprise Publishing Solutions http://www.reportlab.com/ Telephone: +1-800 494 3119 Fax: +1 703 278 8289 PyCon DC 2004 George Washington University, March 24-26 From jjl at pobox.com Mon Jan 12 18:39:10 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Jan 2004 23:39:10 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> Message-ID: <87d69og2jl.fsf@pobox.com> "Derek" writes: [...] > All I know is that there are thousands of extremely large projects > written in C++, some consisting of millions of lines of code written > by hundreds of developers. C++, while far from perfect, has proven > its worth on a huge scale. Python, at the very least, has yet to do > so. See a recent thread here listing some fairly large Python projects. Of course, taking lines of code at face value is rather like talking about waiting lists instead of waiting times... John From sross at connectmail.carleton.ca Sat Jan 3 14:57:44 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 14:57:44 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> Message-ID: "Rainer Deyke" wrote in message news:kTEJb.724242$HS4.5376202 at attbi_s01... > Sean Ross wrote: > > a = bq + r and 0<=r > But 0 <= r < b is a contradiction when b < 0. > Right. But, the division algorithm states "Let a,b be integers with b>0" (which I mentioned in that post). From stach at fr.USUN.pl Fri Jan 9 16:13:58 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Fri, 9 Jan 2004 22:13:58 +0100 Subject: Python is far from a top performer according to benchmark test... References: Message-ID: "Carl" wrote in message news:ryELb.238$tK2.228 at amstwist00... > I have been experimenting with numerical algorithms in Python with a heavy > use of the Numeric module. My experience is that Python is quite fast in > comparison with (and sometimes as fast as) traditional languages such as C > or C++. With "heavy use of Numeric module" you were calling functions written in C. So how can you say that Python is fast, when C code is doing all the work. Stach From no.spam at at.all Sun Jan 25 04:09:47 2004 From: no.spam at at.all (solo) Date: Sun, 25 Jan 2004 09:09:47 +0000 (UTC) Subject: Test Message-ID: Sorry, it's a test. From herrn at gmx.net Sat Jan 24 17:27:32 2004 From: herrn at gmx.net (Marco Herrn) Date: 24 Jan 2004 22:27:32 GMT Subject: crypt, md5, sha modules Message-ID: Hi, I don't know wether this is really the best place for asking this question. If you know a better, please tell me. The problem is an understanding of the 3 modules for hash algorithms. I need a script to create hashed passwords (the user enters his password and gets back the hash for it). I need this for password verification in the mailserver exim, since it supports hashed passwords. The user then sends his password in clear (but always by using SSL), exim creates a hash and compares it to the one in a specific file (there will be the hash created by my python script). Well, it works with the crypt module. But exim also supports an md5 hashing. Now I would like to use that, since it supports much better passwords. But the md5 module works in a very different way than crypt. Does anyone know whether such hashes are compatible with exim? What makes me think about it is, that there is no salt and that the output is non-ascii unless I use hexdigest() which only returns hex numbers (when I look into my /etc/shadow each hash contains alphanumeric characters). And if possible I would also like to use sha, cause it is even a bit more safer than md5, but am not sure, whether this is supported by exim. So my main question is: can I use the md5 module for creating hashes compatible with exims md5-function? And if so, how? Thanks in advance for your help Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From premshree_python at yahoo.co.in Wed Jan 14 09:59:48 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 14 Jan 2004 14:59:48 +0000 (GMT) Subject: pulling set of unique values from a list In-Reply-To: <400551c0$1@baen1673807.greenlnk.net> Message-ID: <20040114145948.35172.qmail@web8309.mail.in.yahoo.com> http://www.premshree.resource-locator.com/python/urn.py --- Ben Davies wrote: > I need to get [1,2,3] from [1,1,1,2,2,3,3] with as > little effort possible > for my CPU (and keyboard). > I'd half expected there to be a list.values method > to do this, but there > isn't so I've have had to use a dictionary object: > > >>> l=[1,1,1,2,2,2,3,3,3] > >>> dict.fromkeys(l).keys() > [1, 2, 3] > > of course another way would be to do it 'by hand' > like this: > > >>> l=[1,1,1,2,2,2,3,3,3] > >>> values=[] > ... for v in l: > ... if not v in values: values.append(v) > >>> values > [1, 2, 3] > > personally I prefer the dictionary one-liner, but > with the second iterative > way it is probably more obvious what the code is > doing (and perhaps more > efficient?). > Is there any better way to do this that I've missed, > I was kind of surprised > not to find a values() method on the built-in list > type? > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From cpl.19.ghum at spamgourmet.com Thu Jan 29 15:33:02 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 29 Jan 2004 21:33:02 +0100 Subject: mod_speling for python References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Message-ID: > prtk3> I know there are drawbacks, disadvantages, this is "evil", > etc. prtk3> I only wanted to know what ways there are to add such > a hook if prtk3> it is possible without altering the C source for > python itself. > > Take a look at sys.excepthook. Actual implementation is left as an > exercise for the reader. And be carefull: it breaks the Zen of Python and thereby removes it's mojo. From na Mon Jan 5 12:17:06 2004 From: na (Andrew) Date: Mon, 5 Jan 2004 09:17:06 -0800 Subject: mysql python Newbie Question References: <70hkc1-r33.ln1@beastie.ix.netcom.com> Message-ID: Ok I was able to connect to my local server but how do I find the host address or port number of my remote server The host address I usually use is localhost on my remote server I searched google several times but could not find a way to look it up since my site uses php I tried phpinfo() but it did not show me anything I found the ip address of my web site through nslookup and tried to make a connection with that but to know avail How do I lookup my host ipaddress and mysql port Thanks in advance Andrew "Dennis Lee Bieber" wrote in message news:70hkc1-r33.ln1 at beastie.ix.netcom.com... > "Andrew" fed this fish to the penguins on Sunday 04 January 2004 > 17:35 pm: > > > > > how do I connect to a DB server that is not on my computer through > > python to access my records. > > > Well, in most cases, in the same way you connect to a local server... > You specify the host (or IP) address of the machine running the server > (and maybe the port number if it is not on the standard port) when > issuing the connect call. > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From Kyler at news.Lairds.org Tue Jan 20 10:22:03 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 20 Jan 2004 15:22:03 GMT Subject: calling Pyrex results from C Message-ID: I need to submit C/C++ code for a class. (It's not a programming class. The choice of language is inertial. I think that it mostly serves to distract students from the course subject.) I'm fairly fluent with C but it hurts to think about writing in C when Python is *so* much more appropriate for these operations. I'd like to keep my sanity and satisfy the course requirements by programming in Python and converting the code to C. It looks like a few people have scratched this itch already, but of the translators I found, most of them (Python2C, P2C, PyFront) seem to be dead. Pyrex, however, appears to be well-maintained and is even available as a Debian package. http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ I realize that the goal of Pyrex is to create a module that can be called from Python. For my need of calling the result from C, the other utilities are probably more appropriate but I think that Pyrex could be useful to me for less contrived situations than this so it's worthwhile to learn more about it. http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/overview.html#InterfacingWithExternal You can also use public declarations to make C functions and variables defined in a Pyrex module available to external C code. The need for this is expected to be less frequent, but you might want to do it, for example, if you are embedding Python in another application as a scripting language. Just as a Pyrex module can be used as a bridge to allow Python code to call C code, it can also be used to allow C code to call Python code. [...] You can make C variables and functions defined in a Pyrex module accessible to external C code (or another Pyrex module) using the public keyword I've discovered that as long as everything in the code is cdef-ed, I can call Pyrex code from my C code. If, however, I so much as mention anything Pythonish, it segfaults during execution. For example, this is fine. cdef public int foo(): cdef int i i = 123 return(i) And this results in a segfault. cdef public int foo(): cdef int i i = 123 j = 5 return(i) This means that I can't, for example, make a function that takes a filename (string), uses PIL to do a bunch of operations, and returns a string. Any suggestions (besides "suck it up and do it all in C")? Thank you. --kyler From rnd at onego.ru Mon Jan 5 07:19:24 2004 From: rnd at onego.ru (Roman Suzi) Date: Mon, 5 Jan 2004 15:19:24 +0300 (MSK) Subject: Is it bug or feature in sre? In-Reply-To: <16377.21361.749300.297850@montanaro.dyndns.org> References: <16377.21361.749300.297850@montanaro.dyndns.org> Message-ID: On Mon, 5 Jan 2004, Skip Montanaro wrote: > > >>> re.compile("(?P[A-Z]*)?") > Roman> Traceback (most recent call last): > ... > Roman> sre_constants.error: nothing to repeat > > Roman> I wonder why I can't do this? > > Is there some reason why > > "(?P[A-Z]*)" - I want it to be optional, so this is not what I wanted > or > > "(?P[A-Z]+)?" - this is right thing > isn't sufficient? You specified the zero-or-more repetition inside the > group. There's nothing else to have zero-or-one of. > > > Roman> I guess it's of terrible style, but is this behaviour intentional > Roman> or not? > > I suspect it's intentional, since Fredrik went to the trouble of raising an > exception with a useful error message. And I fully agree with it. > Roman> Probably it is good idea to mention this in Python update path > Roman> documents. Otherwise some old programs will mysteriously fail. > > What were you converting from, an older version of sre, pre, regex, or > (shudder) regexp? Python 1.5.2 re > Skip From michael at foord.net Fri Jan 30 04:02:57 2004 From: michael at foord.net (Fuzzyman) Date: 30 Jan 2004 01:02:57 -0800 Subject: Simple Database Package References: <8089854e.0401290034.4d57a45d@posting.google.com> <401925bb$0$575$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <8089854e.0401300102.6fb34161@posting.google.com> Brian Kelley wrote in message news:<401925bb$0$575$b45e6eb0 at senator-bedfellow.mit.edu>... > Fuzzyman wrote: > > > > Anyway - I couldn't decide between SQLobject and metakit (I'd already > > seen sqlite but wanted some advuice before I chose one to dive > > into..). > > > > Anyway - the windows download for SQLobject is zero sized - so I've > > gone for metakit and will have a play. > > To save yourself some headaches, you might want to read my annotated > metakit documentation: > > http://staffa.wi.mit.edu/people/kelley/tutorial/python.html Thanks for your help. I've had a brief look and I think it will more than do what I need and opens up some interesting possibilities. Unfortuantely due to censored internet I'm unable to follow the link you suggest - but I've emailed you to see if you can send it to me. Many Thanks Fuzzyman > > And make sure you join the metakit mailing list, we are here to help :) > > It includes some common gotchas and has example code for you to play with. > > Brian From usenet_spam at janc.invalid Fri Jan 16 00:05:19 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 16 Jan 2004 05:05:19 GMT Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <878yka2sze.fsf@pobox.com> <100bbekd61fbl53@corp.supernews.com> <100d4ljnic3l465@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) schreef: > In article , > JanC wrote: >>My copy of Netscape 0.94beta for Windows has a file date of 1994-11-22. >> >>And from the Grail docs: >>"Grail was started in August 1995 as a quick and dirty demo. It quickly >>became a serious project, as witnessed by the release of version 0.2 in >>November 1995, and again by the planned release of version 0.3 (currently >>in beta) in June 1996." > Yikes! Good research--and I'm always in favor of that. > I apologize for my error. It's certainly disquieting; > I had such a strong memory that Grail was around in > mid-'94 that I didn't verify the facts. What *was* I > thinking about? Well, I didn't know Grail was that old, so I went searching. But Netscape was largely based on Mosaic anyway; being developed by the same developers. The beta I was talking about above still has a Mosaic logo. ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 00:14:41 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 21:14:41 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "JanC" wrote in message news:Xns94711BBF5F7D6JanC at 213.119.4.35... > "Brandon J. Van Every" schreef: > > > I am not sure how I feel about it. I think it only bothers me when > > they claim to be cross-platform in theory, and the Windows build > > simply does not work in practice. A working Windows build should be > > easy to obtain all the dependencies for, and it should just build. > > When it doesn't do that, when you have to chase all over Hell's green > > acre to find the libraries, and then the build simply coughs and gags > > and dies, I'm not even slightly amused at how "cross-platform" some > > Linuxer is claiming things to be. > > You think "cross-platform" means "it runs out-of-the-box on all possible > platforms that ever existed, now exist, and will ever exist"? Please. I talked about supporting *Windows*. You know, the globally dominant OS. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From jcarlson at nospam.uci.edu Sat Jan 31 02:20:00 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 23:20:00 -0800 Subject: python in dreamweaver In-Reply-To: References: Message-ID: >>>>It would be significantly more Pythonic to have a template similar to > > the following... > > Yes, but there are the visual aspect of DM... > > > MCI So do your templates in Dreamweaver, and read them in with python during runtime. All I'm saying is that: >>> template = template.replace('REPLACE_THIS_WITH_MENU', menu) . . . >>> template = template.replace('REPLACE_THIS_WITH_CONTENT', content) is not pythonic, but using standard python string formatting options: >>> output = template%{'menu':menu, 'content':content} is not only pythonic, it is faster for large numbers of insertions, and is much easier to extend. - Josiah From raneb at slingshot.co.nz Tue Jan 27 14:54:45 2004 From: raneb at slingshot.co.nz (Rane Bowen) Date: Wed, 28 Jan 2004 08:54:45 +1300 Subject: Optional Parameters in python COM References: Message-ID: "Rane Bowen" wrote in message news:bv3pos$2no$1 at lust.ihug.co.nz... > > > "Rane Bowen" wrote in message > news:bv1rek$oof$1 at lust.ihug.co.nz... > > Hi, > > > > I am using python with a makepy generated wrapper on a COM application. > One > > of this object's methods has 3 parameters, two of which are optional. > > If I call the method with just the non-optional parameter, or all three > > parameters, it works. If I call it with the first two parameters, I get > the > > following error: > > > > (-2147352567, 'Exception occurred.', (0, 'Amphora.Session.1', 'A bad > > parameter was passed to the method', None, 0, -1610547133), None) > > > > I have tried calling the method by using the names of the optional > > parameters, and I have also tried using pythoncom.Missing and > > pythoncom.Empty for the non essential parameter. I have also edited the > > generated .py file so that it contains the following: > > > > defaultNamedOptArg=pythoncom.Empty > > defaultNamedNotOptArg=pythoncom.Empty > > defaultUnnamedArg=pythoncom.Empty > > > > But this has not made any difference! Any help would be very much > > appreciated. > > > > Cheers, > > > > Rane > > > > > > From asdf at asdf.com Fri Jan 9 04:08:09 2004 From: asdf at asdf.com (John Smith) Date: Fri, 9 Jan 2004 04:08:09 -0500 Subject: user/passwd entry Message-ID: Hello, I'm wondering how to enter the user and password for a site over http? What's the module that I should use: urllib, htmllib, HTMLParser, httplib? What are the classes I should call, etc? Thanks for any help. -k From diego.andrade at smartech.com.br Thu Jan 15 12:43:22 2004 From: diego.andrade at smartech.com.br (Diego Ribeiro de Andrade) Date: Thu, 15 Jan 2004 15:43:22 -0200 Subject: Tcl/Tk Support References: <20040109201513.GC2810@unpythonic.net> Message-ID: <002c01c3db8f$12431ba0$7900a8c0@smartech.com.br> Yeah! It Works Thanks. Everyone else told me that It was native in Python. May I did something wrong in the installation of Red Hat9? -----Mensagem Original----- De: "Jeff Epler" Para: "Diego.andrade" Cc: Enviada em: sexta-feira, 9 de janeiro de 2004 18:15 Assunto: Re: Tcl/Tk Support > try installing the RPM called > tkinter-2.2.2-26.i386.rpm > > Jeff > From sridharinfinity at yahoo.com Tue Jan 20 07:13:37 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 20 Jan 2004 04:13:37 -0800 Subject: converting base class instance to derived class instance Message-ID: <930ba99a.0401200413.5fae6fb9@posting.google.com> Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this instance! inst = some_factory() # this returns instance of Base return inst # Oops! this isn't an instance of Derived def __init__(self): # This won't be called as __new__ returns Base's instance pass The constrait is there is some factory function that creates an instance of Base class. So I _can't_ call "Base.__init__(self)" in Derived.__init__ func, as their will be _two_ instances (one created by Derived.__init__ and other created by the factory function) Simply I want to get a derived class object, but instead of allowing _automatic_ creation of Base instance, I want to use _existing_ Base's instance, then use this as a Derived's instance. Will metaclass solve this problem? From http Tue Jan 13 14:37:36 2004 From: http (Paul Rubin) Date: 13 Jan 2004 11:37:36 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> <400446D5.1265452A@engcorp.com> Message-ID: <7xoet7zlkv.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Presumably the IRS requires networking, some user interface > capabilities, probably a bunch of database interfaces, really > sophisticated testing, and these days maybe even some standardization > in the area of, say, XML or something like that. I think if there's one application that needs decimal arithmetic... From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Jan 5 04:07:58 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 5 Jan 2004 10:07:58 +0100 Subject: explicit variable declaration References: Message-ID: Hi ! "Variable" is a bad word - beurk ! - In Python there are ref-on-objects ; it's without interest with declaration (explicit). @-salutations -- Michel Claveau From mhammond at skippinet.com.au Thu Jan 15 21:09:19 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 16 Jan 2004 13:09:19 +1100 Subject: How to call a system command with flexibility on Windows In-Reply-To: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> References: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> Message-ID: Nicolas Fleury wrote: > Hi everyone, > I have a hard time trying to call a system command with the > following capability on Windows: > - Redirection of stdout and stderr. > - Have the return code. > > The documentation seems to say it's only possible on Unix, have I missed > something. Thx for your help. Some, if not all of the popen functions on Windows will return the exit code of the program when closing the last returned handle. I'm afraid I have no time to check the docs or find sample code, but it does work :) Mark. From angstrom at lionsanctuary.net Fri Jan 16 03:15:11 2004 From: angstrom at lionsanctuary.net (Owen Jacobson) Date: Fri, 16 Jan 2004 08:15:11 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: On Fri, 16 Jan 2004 07:58:39 +0000, Andrew Dalke wrote: > My favorite program for this is /bin/true. On some machines it is 0 > bytes long. It works on Unix and, with a ".bat" extension, on MS > Windows. [root at eidolon root]# uname -a Linux eidolon.lionsanctuary.net 2.4.20-24.9 #1 Mon Dec 1 11:43:36 EST 2003 i686 athlon i386 GNU/Linux [root at eidolon root]# ls -l /bin | grep true -rwxr-xr-x 1 root root 10172 Oct 29 06:44 true [root at eidolon root]# ldd /bin/true libc.so.6 => /lib/tls/libc.so.6 (0x42000000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) Not this machine, apparently. -- Some say the Wired doesn't have political borders like the real world, but there are far too many nonsense-spouting anarchists or idiots who think that pranks are a revolution. From anton at vredegoor.doge.nl Sat Jan 10 23:24:13 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 11 Jan 2004 05:24:13 +0100 Subject: help with Python Environment For Blind User References: Message-ID: <4000d088$0$7530$3a628fcd@reader2.nntp.hccnet.nl> Zachary" wrote: >I'm a blind non-programmer trying to learn Python. >I've got python 2.3 for windows, but the problem is that Idle doesn't seem >to work two well with my screen reading program. >Is notepad, then, my only other real choice? Pythonwin worked similarly >badly. >The problem is my programs inability to track the cursor. It doesn't tell >me what line I'm on, where I am in that line, or what I just deleted. It >would do this in a normal editor. >Any help with this would be appreciated. Idle provides an editor and an interactive commandline. Maybe you end up in the commandline while expecting to be in the editor? Pythonwin has a similar setup. I vaguely remember being puzzled by this too when I first met Python a long time ago. Later I had another problem in that I didn't know how to "run" a Python script. For some time I tried to use MsDos batch files to call the scripts from. In the end things settled down and I became comfortable with the tools. At the moment my setup includes a lot of tools that aren't standard, some tools were written by me, using Python! Using my eyes to read from the screen and already being a programmer when I started with Python it's a bit hard to anticipate your specific situation. Don't give up to soon. There seems to be one obvious way to do things with Python, but in my case the interpretation of what is obvious changes fairly often, for the better I hope :-) Anton From raneb at slingshot.co.nz Sun Jan 25 20:44:53 2004 From: raneb at slingshot.co.nz (Rane Bowen) Date: Mon, 26 Jan 2004 14:44:53 +1300 Subject: Optional Parameters in python COM Message-ID: Hi, I am using python with a makepy generated wrapper on a COM application. One of this object's methods has 3 parameters, two of which are optional. If I call the method with just the non-optional parameter, or all three parameters, it works. If I call it with the first two parameters, I get the following error: (-2147352567, 'Exception occurred.', (0, 'Amphora.Session.1', 'A bad parameter was passed to the method', None, 0, -1610547133), None) I have tried calling the method by using the names of the optional parameters, and I have also tried using pythoncom.Missing and pythoncom.Empty for the non essential parameter. I have also edited the generated .py file so that it contains the following: defaultNamedOptArg=pythoncom.Empty defaultNamedNotOptArg=pythoncom.Empty defaultUnnamedArg=pythoncom.Empty But this has not made any difference! Any help would be very much appreciated. Cheers, Rane From jarausch at skynet.be Mon Jan 26 16:28:31 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 26 Jan 2004 22:28:31 +0100 Subject: How does compare work? Message-ID: <40158680$0$7044$ba620e4c@news.skynet.be> Hi, what does Python do if two objects aren't comparable (to my opinion) If I've understood "Python in a Nutschell" correctly it should raise an exception but it doesn't do for me. Here are two examples if 2 > '1' : print "greater" else : print "less_or_equal" prints less_or_equal and class C: def __init__(self): pass X=C() if 2 > X : print "greater" prints greater In both cases I don't get an exception. But I'd like to since these lead to hard-to-find bugs. Thanks for shedding some light on this. P.S. This is Python 2.4 (CVS) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From michele.simionato at poste.it Tue Jan 20 02:55:11 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Jan 2004 23:55:11 -0800 Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: <95aa1afa.0401192355.77568ed4@posting.google.com> cartermark46 at ukmail.com (Mark Carter) wrote in message news:... > I suppose that Schemers and Lispers take the attitude that a lack of > syntax is an advantage, because you can ultimately program in any > paradigm you wish. It's "just" a case of writing code that implements > the paradigm. Uh? The lack of syntax has nothing to do with the lack of paradigm, I miss you point, sorry. > I have also heard claims that the existence of > parantheses in s-exprs is a red herring as far as readability is > concerned. That's true, the parentheses are a not a problem for readability, they are a problem for *writability*: in practice, they force you to use emacs or The Other Editor. Somebody can argue that this is a Good Thing, anyway ;) So, it is somewhat true that Lisp/Scheme are difficult to read, but this is due to the choice of names and to the unusual order of evaluation more than to the parentheses. Just my 2 eurocents, Michele Simionato From rays at san.rr.com Wed Jan 28 22:04:22 2004 From: rays at san.rr.com (RJ) Date: Wed, 28 Jan 2004 19:04:22 -0800 Subject: win32com - .ocx won't Dispatch... Message-ID: <5.2.1.1.2.20040128185707.05ece8d0@pop-server.san.rr.com> Hi, I've been going over the Quick Start to Client side COM and Python and many other sources, but cannot find an example that will get my com/ActiveX .ocx USB device driver imported. The Excel and Word examples run fine. win32com.client.Dispatch("Excel.Application") etc., but how does one know the (".") to type in? Excel looks only vaguely like "Excel.Application" in the com browser. Firstly, I found the ocx from the Python Object Browser. I ran makepy.py on EDREUtlX.ocx (USB device driver) which created 8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py etc. in gen_py\, but, I cannot find a syntax to get Dispatch to accept it... from win32com.client import Dispatch # failed attempts Dispatch("EDRE Utility Control") # name in browser Dispatch('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5}') Dispatch('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}') Dispatch("8AA34F82-95C9-11D3-8EB6-00C0DF2247CA") Dispatch("8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5") all return: Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) So, what is the required syntax? Thanks, Ray From jdhunter at ace.bsd.uchicago.edu Wed Jan 21 22:59:33 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 21 Jan 2004 21:59:33 -0600 Subject: python In-Reply-To: ("Jess Martin"'s message of "Thu, 22 Jan 2004 14:17:20 +1030") References: Message-ID: >>>>> "Jess" == Jess Martin writes: Jess> i need help. im just learning to program and every time i Jess> try to do a command more than a line long it wont work You probably need to terminate the partial command with a slash '\', as in >>> x = 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + \ ... 2 + 2 + 2 >>> >>> x 22 JDH From newsgroups at jhrothjr.com Sun Jan 11 16:12:20 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 11 Jan 2004 16:12:20 -0500 Subject: readling newlines References: Message-ID: <1003f4l753jqc09@news.supernews.com> "Alessandro Crugnola *sephiroth*" wrote in message news:IXTLb.87546$_P.3280883 at news4.tin.it... > Hi, I'm trying to detect the newlines method of a file opened. > I'm using the 'U' mode as parameter when opening a file, but for every file opened the result is always "\r\n", even if the file has > been saved with the "\n" newline method. > Is there i'm missing? > > I'm on Windows with python 2.3.3 Regardless of what you tell it, Python will always write a text file with the operating system's line separators. In Windows, that's \r\n. Universal newline mode only operates on input, and will translate *all* common system's line separators into /n. In other words, if you write a file in text mode using /n, and then read it back in binary mode, you'll see /r/n for the line separators. Universal newline support does not change this because it does not change what you see in binary mode. John Roth > > From vincent_delft at yahoo.com Sat Jan 10 14:36:44 2004 From: vincent_delft at yahoo.com (vincent delft) Date: 10 Jan 2004 11:36:44 -0800 Subject: what is best for web development?? References: Message-ID: <5c184570.0401101136.5585af33@posting.google.com> I've was faced to the same problem few months ago. After checked lot of different solutions, I've select Draco (draco.boskant.nl). A framework around mod_python that offers lot of flexibility and can be used for havy loaded web site. One of the nicest feature is the possibility to split code and HTML. I'm not objective, but I propose you to make your own choice amongst all the good solutions (karrigel, albatros are very good too), but have a look at draco. ketulp_baroda at yahoo.com wrote in message news:... > i am developing a web application and i am really confused on what should i use. > should i use just python and use the cgi module availabe. > Or should i use application like WebWare.Also there is PSP available. > I am really confused and need help From python at quixs.com Wed Jan 14 12:51:02 2004 From: python at quixs.com (Lars Heuer) Date: Wed, 14 Jan 2004 18:51:02 +0100 Subject: wxPython worries In-Reply-To: <375234841.20040114183449@quixs.com> References: <40055e11$0$282$4d4ebb8e@news.nl.uu.net> <375234841.20040114183449@quixs.com> Message-ID: <127075610.20040114185102@quixs.com> Hello again, Forgot to mention SPE (uses the mentioned wxGlade): http://spe.pycs.net/ Maybe this tool is more "IDE"-like. ;) Regards, Lars From thitucad6tim at jetable.org Tue Jan 27 16:31:11 2004 From: thitucad6tim at jetable.org (Nicolas Lehuen) Date: Tue, 27 Jan 2004 22:31:11 +0100 Subject: Python 2.3.3 : Win32 build vs Cygwin build performance ? References: <4016a71d$0$15004$afc38c87@news.easynet.fr> Message-ID: <4016d8a3$0$19263$626a54ce@news.free.fr> I have reproduced this on another machine. I tried playing with the optimizer options (-O, -OO) and the result is the same : on pystone, Cygwin 1.5.6-1 + Python 2.3.3-1 is nearly twice as better as the standard Python 2.3.3 distribution for Win32... I have checked that both distribution are psyco-free. Does anyone have an idea of what is going on there ? Better compilation optimisation settings ? GCC 3.3.1 producing faster code than MSVC 6 (allright, I can imagine that, but twice faster ???) ? Regards Nicolas "Nicolas Lehuen" a ?crit dans le message de news: 4016a71d$0$15004$afc38c87 at news.easynet.fr... > Hi, > > Is it me, or does anyone else get significantly better pystone results under > Cygwin versus the standard Win32 build ? > > CYGWIN 1.5.6 + python 2.3.3-1 : > $ time python /usr/lib/python2.3/hotshot/stones.py > Pystone(1.1) time for 50000 passes = 2.344 > This machine benchmarks at 21331.1 pystones/second > 850004 function calls in 4.371 CPU seconds > > Ordered by: internal time, call count > > ncalls tottime percall cumtime percall filename:lineno(function) > 50000 1.351 0.000 2.917 0.000 pystone.py:133(Proc1) > 50000 1.132 0.000 1.202 0.000 pystone.py:53(copy) > 1 0.609 0.609 4.371 4.371 pystone.py:79(Proc0) > 50000 0.239 0.000 0.239 0.000 pystone.py:208(Proc8) > 150000 0.184 0.000 0.184 0.000 pystone.py:203(Proc7) > 150000 0.157 0.000 0.157 0.000 pystone.py:221(Func1) > 50000 0.147 0.000 0.200 0.000 pystone.py:229(Func2) > 50000 0.104 0.000 0.153 0.000 pystone.py:160(Proc3) > 50000 0.098 0.000 0.153 0.000 pystone.py:184(Proc6) > 50000 0.090 0.000 0.090 0.000 pystone.py:149(Proc2) > 50002 0.070 0.000 0.070 0.000 pystone.py:45(__init__) > 50000 0.068 0.000 0.068 0.000 pystone.py:177(Proc5) > 50000 0.067 0.000 0.067 0.000 pystone.py:170(Proc4) > 50000 0.055 0.000 0.055 0.000 pystone.py:246(Func3) > 1 0.000 0.000 4.371 4.371 pystone.py:67(pystones) > 0 0.000 0.000 profile:0(profiler) > > > real 0m26.603s > user 0m25.765s > sys 0m0.280s > > Win32 : > C:\Documents and Settings\nlehuen>python c:\Python23\Lib\hotshot\stones.py > Pystone(1.1) time for 50000 passes = 4.1542 > This machine benchmarks at 12036 pystones/second > 850004 function calls in 14.917 CPU seconds > > Ordered by: internal time, call count > > ncalls tottime percall cumtime percall filename:lineno(function) > 1 3.772 3.772 14.917 14.917 pystone.py:79(Proc0) > 50000 2.226 0.000 6.314 0.000 pystone.py:133(Proc1) > 150000 1.166 0.000 1.166 0.000 pystone.py:221(Func1) > 150000 1.123 0.000 1.123 0.000 pystone.py:203(Proc7) > 50000 1.075 0.000 1.075 0.000 pystone.py:208(Proc8) > 50000 0.939 0.000 1.410 0.000 pystone.py:53(copy) > 50000 0.903 0.000 1.279 0.000 pystone.py:229(Func2) > 50000 0.795 0.000 1.157 0.000 pystone.py:160(Proc3) > 50000 0.776 0.000 1.137 0.000 pystone.py:184(Proc6) > 50000 0.500 0.000 0.500 0.000 pystone.py:149(Proc2) > 50002 0.472 0.000 0.472 0.000 pystone.py:45(__init__) > 50000 0.416 0.000 0.416 0.000 pystone.py:170(Proc4) > 50000 0.394 0.000 0.394 0.000 pystone.py:177(Proc5) > 50000 0.361 0.000 0.361 0.000 pystone.py:246(Func3) > 1 0.000 0.000 14.917 14.917 pystone.py:67(pystones) > 0 0.000 0.000 profile:0(profiler) > > (total real time elapsed > 30 seconds) > > From python-url at phaseit.net Mon Jan 26 21:58:14 2004 From: python-url at phaseit.net (John J Lee) Date: Tue, 27 Jan 2004 02:58:14 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 26) Message-ID: <101bku68i9ffe90@corp.supernews.com> QOTW: "I'd love it if we could come up with a different term for these beasts than 'new style classes'." --Barry Warsaw "Then let me suggest ectomorphic classes, as opposed to the previous endomorphic classes. Roll-your-own classes can be called mesomorphic classes. Extension classes can be called paleomorphic classes. Then there's a precise term for each kind, and bystanders are automically informed by the very terminology used that their lives are too short to worry about the distinctions being drawn ." --Tim Peters http://mail.python.org/pipermail/python-dev/2004-January/042181.html Plone wins ticket to Comdex http://osdir.com/Article199.phtml Travis Oliphant courageously asks for feedback on a controversial decision for users of large homogeneous arrays http://groups.google.com/groups?selm=mailman.517.1074548025.12720.python-list%40python.org Gandalf, Tim Peters and others discuss the risks, or otherwise, of unpickling http://groups.google.com/groups?selm=bufkot$96vl$1%40netnews.upenn.edu Peter Otten can't resist demonstrating bad Python style by emulating the lazy evaluation built into other languages http://groups.google.com/groups?selm=buhd16$1qd$01$1%40news.t-online.com What's *really* the correct way to launch a simple external Windows application? http://groups.google.com/groups?selm=100p81q3kshsuca%40corp.supernews.com Fran?ois Pinard embeds Python in Pyrex in C http://groups.google.com/groups?selm=mailman.549.1074619857.12720.python-list%40python.org Thomas Heller is persuaded to keep ctypes cross-platform http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1979390 The long-awaited Learning Python, 2nd edition is out (O'Reilly) http://books.slashdot.org/article.pl?sid=04/01/20/176200 Version 1.19 of Reportlab, the PDF generation library, is out: http://groups.google.com/groups?selm=jvHZstAn4rDAFwUV%40jessikat.fsnet.co.uk Matthias Baas releases Python Computer Graphics Kit v1.1.0 http://groups.google.com/groups?selm=mailman.1074534902.1084.clpa-moderators%40python.org Zope 2.6.4 rc1 and 2.7.0 rc1 Released (along with standalone ZODB releases) http://groups.google.com/groups?selm=mailman.1074552605.27880.clpa-moderators%40python.org http://groups.google.com/groups?selm=mailman.1074552604.27857.clpa-moderators%40python.org Marc-Andre Lemburg releases eGenix mxODBC Zope Database Adapter 1.0.8 http://groups.google.com/groups?selm=mailman.1074879183.6139.clpa-moderators%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 newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of 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 __peter__ at web.de Fri Jan 2 11:18:11 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jan 2004 17:18:11 +0100 Subject: optparse bug? References: Message-ID: Andres Corrada-Emmanuel wrote: > I'm getting a conflict between options defined between two different > scripts and I'm wondering if it is a bug or the intended effect. Neither. I'm pretty sure that you somehow managed to add all options to a single OptionParser instance. Do you know about the if __name__ == "__main__": # code to run only in standalone mode technique? For a more detailed analysis you have to provide the actual code of a minimal example. Peter From max at alcyone.com Mon Jan 5 18:18:40 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jan 2004 15:18:40 -0800 Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> Message-ID: <3FF9F0D0.3AA099CD@alcyone.com> Samuel Walters wrote: > What exactly *is* a vertical tab? I don't think I've ever seen it on > a > keyboard or used in the wild. I think I may have seen it on the > keybindings for a mainframe terminal I once used, but I didn't really > dig > too deep because, as far as operating the mainframe was concerned, I > was a > well trained monkey who could check and restart failed jobs. It's a whitespace control character, whose precise meaning is, as far as I know, left to the implementation. In the same way that a horizontal tab (HT) -- what you'd generally think of us a tab -- means "advance the cursor some amount of space forward on the line," a vertical tab would mean "advance the cursor some amount of space downward on the page." I don't have a copy of the ASCII Standard in front of me so I can't say more, but it's not used a lot of these days. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Fifteen minutes / To show the world -- Nik Kershaw From mike at mhuffman.com Sat Jan 24 12:55:12 2004 From: mike at mhuffman.com (Mike Huffman) Date: 24 Jan 2004 09:55:12 -0800 Subject: Program Python in VIM References: <871xpsc5zf.fsf@tulip.whu.ca> <40103ee7.108130723@news.blueyonder.co.uk> <3ae9c53d.0401230913.64c7150d@posting.google.com> Message-ID: <3ae9c53d.0401240955.153f19db@posting.google.com> Scott F wrote in message news:... > This should do it. > > map :w:!python % It does indeed, Thanks! Unfortuantely I do not use vi consistently enough to ever get beyond the basics. Had some false starts finding a good key to map that worked on all my vi installations (Linux, Cygwin, Windows console); settled on Ctrl-K: unused and easy to type. Actually, at the moment I am using the maping for Perl, but don't tell anyone :-) Mike From francisgavila at yahoo.com Mon Jan 19 23:09:06 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 19 Jan 2004 23:09:06 -0500 Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> Message-ID: <100pahdc7d98q58@corp.supernews.com> Wayne Folta wrote in message ... >John, > [snippage] >(Actually, now that I reread it, I should've said "pure OO", which I >believe is more reflective of their statements. And this has some basis >in fact, I believe, if you look at the v1 of Ruby and Python and what >is first-class and what is not.) [snippage] >Again, as you yourself say, they chose to subclass protocol services >off of a class 'protocol' and Python did not. In fact, Python chose to >not subclass POP3 from anything. Why? Because of the culture, in my >opinion. Ruby emphasizes OO and that it's "pure OO" (their opinion) and >so an implementation that involves a Smalltalk-ish subclassing of >everything recommends itself. > >Python has a different culture where such strict tree-like class >structure does not recommend itself. Python's "batteries included" >philosophy resulted in a more straightforward and (mostly) better >documented way to do it. > >Intellectually, I prefer Ruby. Ruby and Smalltalk intrigue me. But the >"pure OO" approach (my words this time) is annoying, and even at some >point inconsistent, as I mentioned in my paragraph about 0.step(). I >feel like Python has got the right balance where it's OO and pretty >much fully so, but not fanatically so. And it's what I've adopted. [snippage] Some time ago I wrestled with the Ruby-Python claim-counterclaim to "purity" in http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=vug18vkm jpiice%40corp.supernews.com&rnum=1&prev=/groups%3Fq%3D%2522Francis%2BAvila%2 522%2Bruby%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3Dvug18vkmjpii ce%2540corp.supernews.com%26rnum%3D1 (Whew) Anyway, as yet I fail to see how one can be considered more "pure" than the other. Ruby prefers subclassing, but this seems cultural rather than technical. Further, Python can be said to be more "pure", in the naive sense that everything that's first class is an object, and more entities are first class in Python (e.g. methods). I don't think this is a *good* argument, but it's not a ludicrous one, because it at the very least illustrates that we don't know what the heck "pure" means in this context. To me, the argument that there is a direct correspondence between "OO purity" and "similarity to SmallTalk" begs the question, because it presupposes that SmallTalk is pure OO. But there's nothing about SmallTalk, aside from the historical accident of being one of the first languages to use objects pervasively, which suggests to me that its is the "purest" way of doing OO. Rather, OO is too general a concept to admit of a single paradigm which is imitated to greater or lesser degrees in one or another language. The difference between Ruby and Python already illustrates that OO does not admit of a single paradigm, because of the attribute/message distinction. Which is more pure? It's like asking whether meat as food is more pure than vegetables. Of course, this is just my current thinking on the subject. If someone presents an argument that Ruby is more pure which I find compelling (Leaving aside the old CPython wart of unsubclassable base types.), I'll certainly repent my assessment. But I'll still prefer Python, because using 'impure OO' doesn't bother me one bit. ;) -- Francis Avila From miki.tebeka at zoran.com Thu Jan 22 02:35:19 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 21 Jan 2004 23:35:19 -0800 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: Message-ID: <4f0a9fdb.0401212335.481c6679@posting.google.com> Hello Rodrigo, > >>> a = range(8) > >>> for b in a: > if b == 4: > a.remove(b) > else: > print b try: a = range(8) for b in list(a): # Iterate over a shallow copy if b == 4: a.remove(b) else: print b 0 1 2 3 5 6 7 HTH. Miki From not at all.com Tue Jan 13 17:36:41 2004 From: not at all.com (G.I.L) Date: Wed, 14 Jan 2004 00:36:41 +0200 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <40047290$1@news.012.net.il> Brandon J. Van Every wrote: > "Brandon J. Van Every" > wrote in message news:bsd101$c1oj1$1 at ID-207230.news.uni-berlin.de... >> I am >> >> - *TENTATIVELY* - >> >> (operative word) undertaking the project of porting the GPL open >> source game "Freeciv" to Python. Freeciv is, in essence, an almost >> straight clone of Sid Meier's Civilization II, albeit with better >> cross-platform and multiplayer support. www.freeciv.org > > Here's a postmortem. Short version: I've canned the project. Many > of you will say "I told you so," but at least I almost have a VS .NET > 2003 build to show for it. Actually, it's you who said "told you so", since most of your stories revolve around unfinished projects and utter failures. Brandon, why the fuck on Earth couldn't you spend that exact amount of time doing what you did BEFORE posting and arguing with the entire newsgroup? It was an unbelievable waste of time, since you've managed to convice (maybe still wrongfully) all the people that you are completely clueless. The single most problematic issue you have is the belief that one can rely on failures to pave the "right new way"(tm). Wrong. It can also lead to endless new shitty ones. Listen to a .02$ piece of advice: since your pioneering ways have been completely fruitless (at least commercially-wise), why not concentrate on succeeding where other people normally do, and THEN prove there's another and better way to achieve success? I see your point in many of the issues you raised. But the only reason I don't compare myself to you, is that I have a shitload of games to prove my point. I've never had a major failure, so I never needed to use one to leverage my projects. All the things I learned from, were simply bad habits, mostly coding habits. I constantly evolve, in small steps, from one success to another. That's how it should be. You do the math. g From usenet at -OBFUSCATION-joefrancia.com Wed Jan 14 13:49:07 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Wed, 14 Jan 2004 18:49:07 GMT Subject: Printing to console (No Scroll) In-Reply-To: References: Message-ID: Totte Karlsson wrote: > Hi, > How can I print to the console without having it scrolling to a new line for > each print statement? > I want to print a count down in the console, but for each count it scrolls > the screen (of course). > > Is there another way? > > Here is the simple script for now > > print "Closing window in :" > for second in range(10): > time.sleep(1) > print `10-second` +" seconds" > > thanks > /totte This works for me: import time, sys for second in range(10): time.sleep(1) sys.stdout.write(`10-second` + " seconds ") sys.stdout.flush() From candiazoo at comcast.net Fri Jan 23 13:30:06 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 23 Jan 2004 13:30:06 -0500 Subject: Seem to be having trouble with Python/Bethon. References: Message-ID: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> No takers, eh? :/ I can't be the only python user on BeOS... The only thing I can think of is that I am running "bone". Mike From cjw at sympatico.ca Mon Jan 26 17:56:41 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 26 Jan 2004 17:56:41 -0500 Subject: Newbie : innerproduct function from Numarray In-Reply-To: References: Message-ID: <40159B29.3020603@sympatico.ca> Ohkyu Yoon wrote: > I have two vectors that have about 2000 elements. > I need to calculate the innerproducts of those vectors 2000 times where > one of them cycles left(ie 1234, then 2341, then 3412, etc) > Basically, I want to calculate A*x, where A is a left-circulant cyclic > matrix, > and x is a vector. > > I tried it two ways. > vector1 & vector2 are lists. > > 1) > from Numarray import innerproduct > output = [] > temp = vector1 + vector1 # temp is twice the length of vector1 > for i in range(2000): > output.append(innerproduct(temp[i:(i+2000)],vector2) > 2) > output = [] > temp = vector1 + vector1 > for i in range(2000): > sum = 0 > for j in range(2000): > sum += temp[i+j] * vector2[j] > output.append(sum) > > I thought the first method using Numarray should be faster. > But it looks like the second method is faster. > Am I doing anything wrong? > Do you guys know any faster way to do this? > > Thank you. > > You might consider something like the following: # ohkyu.py a sliding cross-product import numarray as N _nc= N.numarraycore _nt= N.numerictypes import numarray.random_array.RandomArray2 as _ra # The sliding array a= _nc.zeros(shape= (2, 10), type= _nt.Float64) b= _nc.arange(10, shape= (10,), type= _nt.Float64) # data for the sliding array a+= b # the data from b is broadcast to both rows print a # to show the 'wraparound' a.ravel() # the second row is appended to the first c= _ra.random(shape= (10,)) # data for the fixed array for i in range(10): z= _nc.dot(a[i:i+10], c) print i, z I would be interested to know how the time compares. Colin W. From tiny_one at NOSPAM.comcast.net Fri Jan 9 09:04:10 2004 From: tiny_one at NOSPAM.comcast.net (kaeli) Date: Fri, 9 Jan 2004 08:04:10 -0600 Subject: [OT] Database reporting software References: Message-ID: In article , shoot at the.moon enlightened us with... > > I could contemplate web based or application based report generation, > but are there easy to use draggy-droppy report designing applications > around? Just the names would enable me to look them up. > WebFocus. Easy to use and can export the reports as Excel, HTML, etc. A bit pricey, but some of the best reporting software out there. DBMSs tend to have their own reporting tools, but IMO, they aren't that great. Trust me, writing your own is not easy. Cross-tabulations (pivot tables, crosstabs) are common things in reports and aren't easy to write well/flexibly. Third party software to do reports is used by almost everyone. (I wrote a small crosstab class, but it would have to be beefed up considerably to be flexible for general use) More options if you Google for "database report generation" (no quotes). -- -- ~kaeli~ A backward poet writes... inverse. http://www.ipwebdesign.net/wildAtHeart http://www.ipwebdesign.net/kaelisSpace From tismer at stackless.com Thu Jan 29 21:36:51 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 30 Jan 2004 03:36:51 +0100 Subject: Update to the Stackless Pages -- thanks for so much input! Message-ID: <4019C343.7040000@stackless.com> Dear friends, there have been so many changes, additions, contributions and discussion of Stackless in the last few days, that I did an update of the website and created new binaries as well. There also were some kind people who sent some money via PayPal. I would like to thank these, and encourage others to follow their example. Everybody is listed in the sponsors page. There is a good chance for Stackless 3.0 for Python 2.3.3 to appear in the first days of February. Thanks to all contributors who helped in any way! cheers - chris http://www.stackless.com/ -- 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 dave at pythonapocrypha.com Fri Jan 9 17:50:11 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 9 Jan 2004 15:50:11 -0700 Subject: OT: There's a monkey on my keyboard, Re: Straw poll on Python performance (was Re: Python is far from a top performer ...) Message-ID: <027c01c3d702$f0aef490$6401fea9@YODA> > Dave wrote: > > I program in Python full-time and each spend approximately zero hours > I swear I can't type today. Anyway, that was supposed to be "each WEEK spend...". From crap at crud.com Fri Jan 23 01:56:03 2004 From: crap at crud.com (Moosebumps) Date: Fri, 23 Jan 2004 06:56:03 GMT Subject: Batch commands on Windows Message-ID: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> So, after reading some messages about os.system, and looking at the popen stuff and trying it a bit, I still have not found a way to keep a command window open for several commands (on Windows 2000/XP), while seeing the normal output in a command window. All I want to do is do what a batch file does, but I want to actually have functions and associative arrays and all the other niceties of python. What's the deal with that? I thought Python started out as a scripting language. And that seems like the most basic thing that a scripting language should do. I just want to list the commands, not deal with capturing the output and redirecting it and all that. It's not just because I'm too lazy, it's because most of my co-workers don't know Python and I want to make the transition easier and sell them on it. This seems like an enormous deficiency. Does anyone know if this can be done? If not, that's a point for perl, *gasp* : ) Which we _were_ using, but which I object to for reasons I won't go into. I have noticed this tendency for really good software to be deficient in some obvious area. Python has amazed me in many respects, but every so often I encounter something like this which is pretty disappointing. And yes I have read PEP 324, but it doesn't seem to make mention anything like this. Another example is Perforce, which is absolutely outstanding for 99% of things, but then you encounter some glaring hole. Most software is just mediocre all around. thanks, MB From haim at babysnakes.org Sun Jan 18 11:05:08 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Sun, 18 Jan 2004 18:05:08 +0200 Subject: newbie question about compression and ascii Message-ID: Hi I'm a real newbie, so sorry if this is a trivial question. I'm writing a script that collect a list of files and creates a zipfile from these files. when running it on linux everything works fine, but when I'm running it on windows I get this error when running the command: myZip.write(file) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa8 in position 10: ordinal not in range(128) the file variable contains: u'C:\\Document and Settings\\haim\etc...'. is there a way to solve this? thanx -- Haim From googlegroups at thuswise.com Mon Jan 5 10:22:30 2004 From: googlegroups at thuswise.com (Dave) Date: 5 Jan 2004 07:22:30 -0800 Subject: Python for Embedded Devices? References: <221e7b06.0401041537.2896b22d@posting.google.com> <4f0a9fdb.0401042307.1f6bd4e8@posting.google.com> Message-ID: <33b7435c.0401050722.3b01a3d0@posting.google.com> What about cases where the OS shields you from porting issues? This is a question which interests me at the moment, as I'm considering some future embedded work. Python is available as a package for NetBSD. To what extent does this mean that, if you can install NetBSD, you can run a Python interpreter? http://www.netbsd.org celebrates the fact that it targets SBCs and some handheld devices. Has anyone out there any experience of Python on NetBSD on embedded platforms? Here's hoping, Dave. From mwh at python.net Wed Jan 14 06:29:56 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 14 Jan 2004 11:29:56 GMT Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <400413E0.5C691A56@engcorp.com> <7xr7y3mzsl.fsf@ruckus.brouhaha.com> <400444A0.717BA7A3@engcorp.com> <7xk73vzlen.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Peter Hansen writes: > > > Python has no support for macros or aliases, and it would be silly > > > to add some special kludge for input(). The user needs to be able > > > to redefine the function and so forth too. > > > > Sure it does: > > > > def input(*args): > > return eval(raw_input(*args)) > > For it to be an alias, that definition would have to be injected into > the module that input is actually called from, not run in a separate > module. The problem with doing things this way is that it's not easy to get Python-defined functions into an extension module. Nothing deep. > How the heck does input get at the environment of its caller, anyway? > Through the frame object chain? Yes. The function you are seeking is called PyEval_MergeCompilerFlags. > I guess the obvious fix is for the future division flag to be part of > the environment, so evaling in the caller environment is done according > to the flag. I'm not sure what you mean here. eval() already respects future division, as does execfile() and compile(). input() just got overlooked when this stuff got added (back in the 2.1 era for nested scopes, though the details have changed intermittently over the intervening vwersions). > Someone has already checked a fix into sourceforge, but I haven't > looked at it and don't know if it works that way or some other way. Wouldn't checking have taken about as much time as writing the above post? It's a very simple patch... Cheers, mwh -- All obscurity will buy you is time enough to contract venereal diseases. -- Tim Peters, python-dev From Pieter.Claerhout at Creo.com Wed Jan 28 05:44:30 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 28 Jan 2004 11:44:30 +0100 Subject: Cross-version extension modules? Message-ID: <490316A24CC5D411ACD700B0D078F7F003915E2A@cseexch01.cse.creoscitex.com> Normally, it doesn't change between micro versions. pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Peter Astrand [mailto:peter at cendio.se] Sent: 28 January 2004 11:43 To: python-list at python.org Subject: RE: Cross-version extension modules? On Wed, 28 Jan 2004, Pieter Claerhout wrote: > extension modules in Python are always linked to a specific version of > Python. You might perform some tricks with writing a pure Python module > about your extension that, based on the version of the python interpreter, > loads a different version of your extension. This is e.g. the way the Python > drivers for SapDB work. Thanks. Is PYTHON_API_VERSION guaranteed to increase only when the Python major or minor version increases, or can it change between micro versions as well? /Peter > -----Original Message----- > From: Peter Astrand [mailto:peter at cendio.se] > Sent: 28 January 2004 10:40 > To: python-list at python.org > Subject: Cross-version extension modules? > > > > If I build a extension module with Python 2.2 and then loads it with 2.3, > I get: > > RuntimeWarning: Python C API version mismatch for module _foo: This > Python has API version 1012, module _foo has version 1011. > > How fatal is this? Is it safe to use the module anyway? If not, is it > possible to build the module differently, so that it actually is safe to > use it with different versions of Python? > > -- Peter ?strand www.thinlinc.com Cendio www.cendio.se Teknikringen 3 Phone: +46-13-21 46 00 583 30 Link?ping -- http://mail.python.org/mailman/listinfo/python-list From NAVMSE-SRV003 at techblu.com Thu Jan 29 08:35:58 2004 From: NAVMSE-SRV003 at techblu.com (Anti Virus Administrator) Date: Thu, 29 Jan 2004 05:35:58 -0800 Subject: Norton AntiVirus detected and quarantined a virus in a message you sent. Message-ID: Recipient of the infected attachment: SRV003, First Storage Group\Mailbox Store (SRV003), Dennis Lacar/Inbox/Employment Subject of the message: ERROR One or more attachments were quarantined. Attachment lvfpu.zip was Quarantined for the following reasons: Virus W32.Novarg.A at mm was found. Virus W32.Novarg.A at mm was found in lvfpu.doc .exe. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcfletch at rogers.com Mon Jan 5 16:05:26 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 05 Jan 2004 16:05:26 -0500 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <3FF9D196.9060402@rogers.com> John Roth wrote: >"Just" wrote in message >news:just-CC8B2B.17325205012004 at news1.news.xs4all.nl... > > >>In article , >> "John Roth" wrote: >> >> ... >>>15. Should files and directories be the same >>>class. >>> >>>Probably not. While they share a lot of common >>>functionality (which should be spelled out as an >>>interface) they also have a lot of dissimilar >>>functionality. Separating them also makes it easy >>>to create objects for things like symbolic links. >>> >>> >>But what about paths for not-yet-existing files of folders? I don't >>think you should actually _hit_ the file system, if all you're doing is >>path.join(). >> >> > >I agree here. I haven't looked at any of the candidate implementations >yet, so I don't know what they're doing. I'm thinking of a >three class structure: the parent class is just the path manipulations; >it has two subclasses, one for real files and one for real directories. >That way they can not only inherit all of the common path manipulation >stuff, but the developer can instantiate a pure path manipulation >class as well. > >There might also be a mixin that encapsulates the stuff that's common >to real files and directories like accessing and changing dates and >permissions. > >I'm sure there are use cases that will throw a curve at that structure >as well. > > My implementation combines the two into a single class. Here's the logic: * There is no necessary distinction between files and directories at the path level o Particularly with upcoming ReiserFS 4, where structured storage shows up, it's possible to have files behaving much like directories. o Zip files also come to mind if we have virtual file system support eventually * These objects represent paths, not the things pointed to by the paths. o They allow you to operate on the path, which is "almost" the filesystem, but not quite. o In the space of "paths", there's no distinction between a file and a directory, really. o Even a path that traverses a few symbolic links, and drops into a zip-file is still just a path, it's a way of specifying something, similar to a "name" or "location" class. o You can find out what the path-object points to via the path methods, but the path itself isn't those objects. * Don't want to have to explicitly cast your paths to file/directory to get the basic file/directory operations when joining paths. o Mix-ins require changing the class of the instance by somehow figuring out that it's a file, that requires a file-system access (to what may be a non-existent or very expensive-to-access file). o There's not much of a conflict between the file/directory path operations Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From salgado at freeshell.org Sun Jan 25 10:13:48 2004 From: salgado at freeshell.org (Guilherme Salgado) Date: Sun, 25 Jan 2004 13:13:48 -0200 Subject: trouble w/ unicode file In-Reply-To: References: Message-ID: <1075043628.18837.17.camel@maluf.alcatraz> On Sun, 2004-01-25 at 06:54, Serge Orlov wrote: > "Guilherme Salgado" wrote in message news:mailman.752.1074995324.12720.python-list at python.org... > > Hi there, > > > > I have a python source file encoded in unicode(utf-8) with some > > iso8859-1 strings. I've encoded this file as utf-8 in the hope that > > python will understand these strings as unicode () > > strings whithout the need to use unicode() or u"" on these strings. But > > this didn't happen. > > You hoped, but you forgot to pray Why do you think Python > should behave this way? There is (an experimental?) option -U that Ok, ok. I'll remember to pray next time. :-) I need to store unicode strings(declared in files) in ZODB, but i don't want to use u"" around all my strings (cause most of them are latin-1), so i think storing the file as unicode will work. Is there a better way for doing this? > forces all string literals to be unicode. Obviously if you use this option > your sources won't be easily distributable to other people > [...] > > > Am I expecting something that really shoudn't happen or we have a bug? > > We have a bug here as well. But in your code. The coding must > be the same as the coding of your source file. bar.py must be: > #-*- coding: latin-1 -*- > x = '????????????' > print x, type(x) > I didn't understand this (even after some pray) :-) My file is encoded in utf-8, look: $ file bar.py bar.py: UTF-8 Unicode text Why should i declare it as latin1 encoded though? []'s Guilherme Salgado -- This email has been inspected by Hans Blix, who has reported that no weapons of mass destruction were used in its construction. Read his report here: From michael at foord.net Fri Jan 16 03:44:32 2004 From: michael at foord.net (Fuzzyman) Date: 16 Jan 2004 00:44:32 -0800 Subject: working on multiple files in IDLE References: Message-ID: <8089854e.0401160044.647e8021@posting.google.com> "Moosebumps" wrote in message news:... > So say I am working on two separate .py files in IDLE that are part of the > same program. Does anyone have problems where when you modify one file, and > then run the other, the changes you made in the first aren't updated? > > I usually just close all the files, and restart IDLE, but this is a pain. > Maybe because I always use right click -> edit with IDLE (on Windows). That > starts up a separate Python Shell too, which I always close. > > MB The latest version of IDLE was *supposed* to fix this by restarting the IDLE session when you run the script. Unfortunately they didn't get it working on the windows version because it uses the same socket when you run multiple versions......... The result is that IDLE is virtually unuseable for serious work on windows... :-( There *is* a way round it...... If you edit your file association for .py and .pyw files (from an explorer window menu select tools and folder options - then choose file types). Remove the -n from the command line that IDLE is launched with.. this allows IDLE to be launched with a subprocess... *HOWEVER* if you do this you can only open one version of IDLE at a time the second and third modules/scripts that you edit must be opened using the 'open' or 'open module' option..... If a second shell window opens it will hang......... I have two file associations - one 'Edit with IDLE Subprocess' and one 'Edit with IDLE No Subprocess'... the two co-exist quite happily even when run simultaneously........... For files edited on IDLE *with* a subprocess - it will restart the session whenever you run the script...... which re-imports all the modules and therefore includes your changes..... bit of a bodge though.... Fuzzy From google at axiomatize.com Thu Jan 15 17:24:54 2004 From: google at axiomatize.com (Laurent Therond) Date: 15 Jan 2004 14:24:54 -0800 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> Message-ID: <265368cb.0401151424.3cd7ede6@posting.google.com> I forgot to ask something else... If a client and a server run on locales/platforms that use different encodings, they are bound to wrongly interpret string bytes. Correct? From none at none.com Mon Jan 12 12:34:37 2004 From: none at none.com (Derek) Date: Mon, 12 Jan 2004 12:34:37 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: "Jacek Generowicz" wrote: > > > I would also add that while Lisp has been a favorite in > > the AI community, you will find that most AI techniques > > generalize to most any programming language. I spent > > a good deal of time in grad school and on my first job > > doing AI programming in C++. The only time I used Lisp > > was in introductory classes, mostly to write elegant -- > > but toy -- programs. > > Lest Derek give the impression that Lisp is in any way a > "toy" language, or that it somehow sacrifices practicality > for elegance, I feel honour bound to point out that it > is actually the most powerful and expressive programming > language known to man, and excells in solving problems > which are often considered too hard to be solved in other > languages. I meant no disrespect to Lisp. My intention was only to point out that it's quite possible to carry out AI programming in other languages, albeit less miraculously. :) From aaron at reportlab.com Mon Jan 12 09:58:28 2004 From: aaron at reportlab.com (Aaron Watters) Date: 12 Jan 2004 06:58:28 -0800 Subject: Databases: Which one's right for me? References: Message-ID: <9a6d7d9d.0401120658.5b9ee522@posting.google.com> "Tim Peters" wrote in message news:... > [Aaron Watters] > > Does zodb support the strictest isolation levels? > > I'm almost certain it doesn't, but I'm not a DB expert. Please take this to > a ZODB list, as previously suggested. > > > If so how? If not what does it support exactly? > > I pointed you to Jeremy's relevant blog entry last time... Reading the blog it seems you are right. I wish zodb would be a bit more careful in its claims. When you say "zodb supports the ACID properties of transactions" this has a precise meaning which vanishes when you redefine all the letters. In particular it suggests that zodb would be good for something like an accounting or banking application which would require strict transaction isolation (serializability). The looser definition could lead to fairly unpleasant difficulties (law suits, jail time...). Sorry, had to complete my thought on clp. -- Aaron Watters === so you better start swimming or you'll sink like a stone for the times, they are a-changing. --Dylan From Johan.Vervoort at utimaco.be Wed Jan 21 11:18:07 2004 From: Johan.Vervoort at utimaco.be (Johan.Vervoort at utimaco.be) Date: Wed, 21 Jan 2004 16:18:07 GMT Subject: Reading BLOB References: <400e3510.18785312@news.eunet.be> <400E8AB0.9D4DEB79@engcorp.com> Message-ID: <400ea2c0.46864796@news.eunet.be> This is the sample code: It should dump all the certificates to the certs directory... What I suspect is that python thinks that the certif field is a STRING and it's truncated when the first '\0' occurs... (The data is stored completely in the database as an equivalent C-program works fine...) Sample output: >>> reload (Test) [('csernum', 'STRING', 80, 80, 0, 0, 0), ('certif', 'STRING', 0, 2147483647, 0, 0, 0)] csernum certif import dbi, odbc def ReadCmail(): result = { 'Result' : 'OK' } # Microsoft Visual FoxPro ODBC DNS # Database type: Free table directory dbc = odbc.odbc('CEC') cursor = dbc.cursor() query = "SELECT CSERNUM,CERTIF FROM C_MAIL" cursor.execute(query) row = cursor.fetchone() for row in iter(cursor.fetchone, None): # Dump certif to file FileName="C:\\CERTS\\%s.crt" % row[0] CertFile = open(FileName, "wb") CertFile.write(row[1]) CertFile.close() print cursor.description for tup in cursor.description: print tup[0] cursor.close() dbc.close() return result ReadCmail() On Wed, 21 Jan 2004 09:20:32 -0500, Peter Hansen wrote: >Johan Vervoort wrote: >> >> How can I read a binary value from a blob via ODBC (Microsoft VFP >> driver-win32all)? The value seems to be truncated at the first '\0' > >Maybe posting a very small snippet of code which reproduces the >problem would help get you responses. I can't help, as I don't >know what VFP driver-win32all is, but if there was example code I >might be able to see the problem anyway, and others more expert in >this area would likely see the problem right away. > >-Peter From jepler at unpythonic.net Sat Jan 17 18:28:48 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 17 Jan 2004 17:28:48 -0600 Subject: rfc822.py date parsing problem In-Reply-To: <41886.207.172.179.21.1074381320.squirrel@li4-142.members.linode.com> References: <41886.207.172.179.21.1074381320.squirrel@li4-142.members.linode.com> Message-ID: <20040117232848.GB23442@unpythonic.net> Probably some message has an invalid date in a header. In 2.2, I can get that exception by passing an invalid string to parsedate_tz: >>> import rfc822 >>> rfc822.parsedate_tz(" ") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/rfc822.py", line 861, in parsedate_tz if data[0][-1] in (',', '.') or data[0].lower() in _daynames: IndexError: list index out of range guess_delivery_time() should probably recover from this exception, but I don't know what exactly would be appropriate. Jeff From jacek.generowicz at cern.ch Tue Jan 13 04:05:14 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2004 10:05:14 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <87hdz0g2zk.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Jacek Generowicz writes: > [...] > > If you want to perform miracles, then learn Lisp. If you > > merely want to write programs that rock, then learn Python. > [...] > > ...and then somebody argues that macros aren't a programming language > feature, but a harmful means of inventing new languages, and then we > get into that endless macro thread again... Well they're all Nazis. From tim.golden at viacom-outdoor.co.uk Wed Jan 21 04:49:19 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Jan 2004 09:49:19 -0000 Subject: CD Insert Notification in WinXP Message-ID: >Hi, > >I'm using Python 2.3 on a Win XP box, and I'm trying to find >if there's >a library of some sort that will give you a callback (or something >comparable) when a new disc is inserted into a CD Rom drive. >I've done a >little googling and nothing's come up, so I'm not holding my breath. :) > Initial response, prior to further investigation: use PyGame (http://pygame.org). It's quite lightweight and gives you a lot of control. It doesn't, as far as I know, give you a call back, but its CD object gives you an is_empty function which you could poll as and when. Check out http://pygame.org/docs/ref/CD.html Don't be put off by the "gamey" nature of the toolkit. I've used it here for several apps, because of the degree of control it gives. I haven't used the CD lib, admittedly, except to play around with, but you can import what you need and leave the rest. 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 alanmk at hotmail.com Mon Jan 19 07:02:33 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 19 Jan 2004 12:02:33 +0000 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> <7934d084.0401181808.6e698042@posting.google.com> Message-ID: <400BC759.72FE1FF2@hotmail.com> [Andrae Muys] > I'm curious to know how a Queue.Queue() provides the same > functionality? I have always considered a Queue.Queue() to be an > inter-thread communcation primitive. Not exactly. Queue.Queue is a *thread-safe* communication primitive: you're not required to have seperate threads at both ends of a Queue.Queue, but it is guaranteed to work correctly if you do have multiple threads. >From the module documentation """ The Queue module implements a multi-producer, multi-consumer FIFO queue. It is especially useful in threads programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python. """ http://www.python.org/doc/current/lib/module-Queue.html > serialise() (at least the > corrected version discussed later in this thread) is strictly a > synchronisation primitive. Just as Queue.Queue is a synchronisation primitive: a very flexible and useful primitive that happens to be usable in a host of different scenarios. I think I'm with Aahz on this one: when faced with this kind of problem, I think it is best to use a tried and tested inter-thread communication paradigm, such as Queue.Queue. In this case, Queue.Queue fits the problem (which is just a variation of the producer/consumer problem) naturally. Also, I doubt very much if there is much excessive resource overhead when using Queue.Queues. As you've already seen from your first cut of the code, writing thread-safe code is an error-prone process, and it's sometimes difficult to figure out all the possibile calling combinations when multiple threads are involved. But if you'd used Queue.Queue, well this whole conversation would never have come up, would it ;-) regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From rodrigob at elo.utfsm.cl Tue Jan 27 09:24:46 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Tue, 27 Jan 2004 11:24:46 -0300 Subject: names proposals => Searching a name for a new program References: <40153d2a_2@nova.entelchile.net> Message-ID: <401670d4$1_2@nova.entelchile.net> (repeated the message with the hope it get out my local ISP news server) Hi, I'm finishing an open source crossplatform pure python collaborative text edition software, similar to SubEthaEdit. Essencially it is a stripped down version of LeoN (take a look at http://ryalias.freezope.org/souvenirs/leon) Actually I'm searching a names for such software. I would like to have a descriptive name, not things like 'yasu' (yet another sofware unamed), etc... My first idea was MultiEdit, but that name was already took. So now I have in my list: PluriPen Chalks Quills PluriQuills PluriChalk 'Chalks' is my favourite, but I think it can be done better. Any sugestion ? RodrigoB. From Z_kline at hotmail.com Sun Jan 25 21:18:22 2004 From: Z_kline at hotmail.com (Zachary) Date: Sun, 25 Jan 2004 18:18:22 -0800 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: "Josiah Carlson" wrote in message news:bv1pgj$ctl$3 at news.service.uci.edu... > > > Either that or Microsoft. ;-) Or he's plain stupid. > > > > Mikl?s > > Never underestimate the power of stupidity (or ignorance, or denial, or...). > > Speaking of which... > http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html > > - Josiah Amazing! I didn't know he could completely miss the point so much. From ajsiegel at optonline.com Thu Jan 22 20:46:48 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 23 Jan 2004 01:46:48 GMT Subject: [Numpy-discussion] Status of Numeric References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> <400fe3c5$0$3036$61fed72c@news.rcn.com> Message-ID: On Thu, 22 Jan 2004 09:48:46 -0500, "Edward C. Jones" wrote: >Arthur wrote: >> >> Couldn't one argue that - for example - in 3d graphic applications the >> performance as to short arrays is crucial. > >In some numerical / graphing packages, there are specialized, fast, >fixed-size arrays for sizes less than 4 by 4. The problem is having at one's disposal all the other good shit functionality - technical term - that something like Numeric brings to the table for operating on arrays. At least in how I have used it, where the 3d drawing might in fact boil down to a short one-dimensionall vector, but the computations that get me to the content of that vector might involve something quite more than that. Certainly I don't deal in 2000 element arrays, but on the other hand the standard graphics matrix library doesn't quite cut it either . Numeric has been quite the perfect thing. I think this must be true for a wide assortment of visualization applications. Art From francisgavila at yahoo.com Fri Jan 9 16:09:43 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 9 Jan 2004 16:09:43 -0500 Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: Jens Thiede wrote in message ... >I found the querk in my code: > >a = [1, 2, 3]; >b = a; >b.append(4); > >b == [1, 2, 3, 4]; # As it should. >a == [1, 2, 3, 4]; # - Why? > >One would think that b is a referance to a - however I know it's not. Ordinarily I would write a big custom-made explaination complete with examples. However: http://starship.python.net/crew/mwh/hacks/objectthink.html This is good enough. -- Francis Avila From loic at yermat.net1.nerim.net Tue Jan 20 15:53:27 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Tue, 20 Jan 2004 21:53:27 +0100 Subject: an example of a singleton design pattern in python? In-Reply-To: References: Message-ID: Daniel Ortmann a ?crit : > Hello, > > Does anyone have an example of a singleton design pattern in python? > > Thanks! > http://www.python.org/cgi-bin/moinmoin/SingletonProgramming Look for links too on page : http://www.python.org/cgi-bin/moinmoin/PatternProgramming Hope it will help ! Yermat From zorlord at zorlord.karoo.co.uk Tue Jan 6 04:36:47 2004 From: zorlord at zorlord.karoo.co.uk (greg) Date: Tue, 6 Jan 2004 09:36:47 -0000 Subject: Probles parsing a text file References: <4f0a9fdb.0401052354.549cece4@posting.google.com> Message-ID: thanks Miki. what would you suggest somthing like if line[:8] == "setVar1": #do somthing elif line[:8] == "setVar2": #do somthing else but this would be extreamly slow if there server.cfg has many directives in it then when the last directive is found (eg: setVar117) and this is the 116th elif then it will have to check through if line[:8] == "setVar1": #do somthing elif line[:8] == "setVar2": #do somthing else elif line[:8] == "setVar3": #do somthing elif line[:8] == "setVar4": #do somthing else elif line[:8] == "setVar5": #do somthing ............... .......... ..... elif line[:8] == "setVar117": #execute code for 117 what do you think "Miki Tebeka" wrote in message news:4f0a9fdb.0401052354.549cece4 at posting.google.com... > Hello, > > > heres my text file(well the first two lines of it) > > > > ######################################### > > # Default BMUS server CFG file # > ... > > i heres the script that im using to parse the file > ... > Try: > #!/usr/bin/env python > try: > fo = open("server.cfg") > print "Reading server CFG file" > for line in fo: > line = line.strip() # Strip white spaces > if (not line) or line.startswith("#"): > continue > eval(line) # *** UNSAFE *** > print "line executed" > except IOError, e: > print "Can't read server CFG (%s)" % e > > Note that using "eval" is very unsafe. Someone might place > 'shutil.rmtree("/")' inside the CFG file. > > > many thnas for your help > No problem. > > Miki From newz at rekon.org.NOSPAM Sat Jan 17 18:15:01 2004 From: newz at rekon.org.NOSPAM (Wil Schultz) Date: Sat, 17 Jan 2004 15:15:01 -0800 Subject: Best way to do this? Message-ID: <100jg9er3qak890@corp.supernews.com> I am reading the "Non-Programmers Tutorial For Python" by Josh Cogliati http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html One of the exercises asks for a program to ask for a password three times. Surprisingly this took me much longer that it probably should have so I am curious if the following is the easiest way this is done. Thanks much! ************************************************* #!/usr/local/bin/python count = 0 password = "null" while count < 3: count = count + 1 password = raw_input("what's the pass: ") if password == "mypass": print "Access Granted" count = 3 else: if count < 3: print "Try Again" else: print "Too Bad" ************************************************* -- Wil my 2? "When everything seems to be going well, you have obviously overlooked something." From mcfletch at rogers.com Wed Jan 28 15:56:02 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 28 Jan 2004 15:56:02 -0500 Subject: C API: how to tell if x is a new style instance? In-Reply-To: <20040128184040.GD11485@foof.i3.cz> References: <20040128184040.GD11485@foof.i3.cz> Message-ID: <401821E2.1070106@rogers.com> Well, I don't actually know how to check for the spiritual state of a new-style class, but here's how to tell if an instance is an instance of a new-style class: * Note that a new-style class is a sub-class of type, while old-style classes are not * Check if isinstance( instance.__class__, type ) * HTH, Mike Michal Vitecek wrote: > hello everyone, > > i've tried to find a way to determine in the python C-API if x is an > instance of a (damned) new style class, but failed :/ > > can someone please tell me how this could be accomplished? > > thank you, > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From nhodgson at bigpond.net.au Sun Jan 18 06:51:23 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sun, 18 Jan 2004 11:51:23 GMT Subject: Retrive unicode keys from the registry References: <1xpzaa8i.fsf@python.net> <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> <40086EE5.7020708@v.loewis.de> Message-ID: <%quOb.17356$Wa.7471@news-server.bigpond.net.au> Martin v. L?wis: > Too bad. Perhaps we should link Python with MSLU? I don't have any experience with it and fear it would introduce a new class of bug where the wide API is incompletely supported. Neil From a.schmolck at gmx.net Wed Jan 21 15:57:53 2004 From: a.schmolck at gmx.net (A.Schmolck) Date: 21 Jan 2004 20:57:53 +0000 Subject: Need help with Python class idioms References: Message-ID: tad at tadland.net (Tad Marko) writes: > Can anyone suggest a more Pythony way to do the following? > > Thanks, > Tad > > #!/bin/env python > > class A: > def __init__(self): > self.mandatoryVar1 = None > self.mandatoryVar2 = None > > def setMV1(self, mv1): > self.mandatoryVar1 = mv1 > > def setMV2(self, mv2): > self.mandatoryVar2 = mv2 > > def saveToDB(self, db): > if self.mandatoryVar1 == None: > raise Exception, "Mandatory Var 1 not set." > if self.mandatoryVar2 == None: > raise Exception, "Mandatory Var 2 not set." > > # Using db, do whatever saving stuff is needed. class A(object): def saveToDB(self, db): # Using db, do whatever saving stuff is needed. 'as From paul at fxtech.com Thu Jan 22 09:46:04 2004 From: paul at fxtech.com (Paul Miller) Date: Thu, 22 Jan 2004 08:46:04 -0600 Subject: Looking for advice: supporting multiple embedded interpreters Message-ID: <6.0.1.1.2.20040122084447.02f56ec0@mail.fxtech.com> Some background first - we have some software that embeds a Python interpreter into a host application. Scripts are loaded dynamically and used. But we want to support the ability to edit scripts while the app is running. This means we have to "unload" the script and cause a reload. Normal module reloading tricks don't work because if you try to reimport a script that imports another script, and if the nested script is changed, it might not be reloaded itself. Also, we have 2 parts of the software, each using Python for its own set of scripts. We don't want scripts loaded into each parts to "see" scripts loaded into the other part. Ideally, we would like multiple "instances" of a Python interpreter to manage this. So, for Python 2.2, I came up with a system that works. When we need a new self-contained Python interpreter, I use Py_NewInterpreter(), swap it in using PyThreadState_Swap, load my built in modules, and swap it back out. When I need to run some code in that interpreter, I swap it back in, load the module I need, call methods in it, and swap it back out. When I'm done with the interpreter, I swap it back in and call Py_EndInterpreter. When I want to force a reload of all the script code in a given interpreter, I just delete the interpreter, create a new one, and load the scripts into that one. This has worked flawlessly. And each "part" of my application can use a different interpreter without modules and globals in each one interfering with the other. Now, with Python 2.3, this code doesn't seem to work anymore. Someone told me it is likely because of the extensive rewrite of GUSI or whatnot. It is important to note that I'm NOT really doing any threading. I just was self-contained interpreters for the above reasons. What I am wondering is if there a reliable method in 2.3 that does what I need? It has recently come to my attention that Lutz Paelike is in exactly the same situation I am in, so I don't think this is a fringe concept. From swalters_usenet at yahoo.com Sun Jan 18 04:22:33 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 09:22:33 GMT Subject: Web Form Error Handling Techniques References: Message-ID: | Sean Abrahams said | > def insertData(data): > > # test data for validity > if not data['name'].isalpha(): > raise InvalidDataError(data['name'], "Name contains non-alpha > characters") > if not data['age'].isdigit(): > raise InvalidDataError(data['age'], "Age contains non-digit > characters") > > sql = """ > INSERT INTO people (name, age) VALUES ('%s', '%s') > """ % (data['name'], data['age']) > > executeSQL(sql) > > I should first check to see if the data is valid, meaning that the > name contains only alpha characters and the age only containing > numeric characters. > > If I raise an exception, how would one handle the reprinting of the > web form with a red * next to the field that contains invalid data? If > one field is in error, I can see that upon receiving an exception you > can have your code just reprint the web form with the red star, but > what about when both fields are in error, do you have the exception > create a list which then your code checks to see if it exists and then > loops through it to know what fields are in error? So, what you're saying is that you wish to have the exception pass information on which, of each piece, of the data is invalid? Test it all, and then raise an error based on *all* the data that is invalid. For instance: ------ class InvalidDataError(Exception): """InvalidDataError Attributes: values - a list of tuples of the form: (name, data, offense) Where name is the name of the field causing problems Data is the data the field contained. Offense is a string describing the problem encountered. """ def __init__(self, value): self.value = value def __str__(self): return str(value) def insertData(data): errors = [] if not data['name'].isalpha(): errors.append(('name', data['name'], "Name contains non-alpha characters")) if not data['age'].isdigit(): errors.append(('age', data['age'], "Age contains non-digit characters")) if len(errors): raise InvalidDataError(errors) sql = """ INSERT INTO people (name, age) VALUES ('%s', '%s') """ % (data['name'], data['age']) executeSQL(sql) good={"name":"bob", "age":"12343"} bad={"name":"bob#", "age":"14"} worse={"name":"bob", "age":"ni!"} ugly={"name":"v@$$#", "age":"ni!"} def test(data): try: insertData(data) except InvalidDataError, e: print "Data: %s failed with errors:"%(str(data)) for x in e.value: name, data, problem = x print "Field \"%s\" had bad data \"%s\" and reported \"%s\" as the problem."%(name, data, problem) print else: print "Good %s found to be A-Ok!"%(str(data)) print test(good) test(bad) test(worse) test(ugly) ------ Now, with that code, you can format your user response any way you want. User defined exceptions can toss around any type of data. See section 8.5 of the tutorial for examples: http://www.python.org/doc/current/tut/node10.html Also, one other test that needs to be performed is to check whether the data dictionary passed to insertData contains each of the fields required. One checks this with data.has_key('name'). If you get passed a bad piece of data, then you can handle it gracefully. Personally, I would create a different exception for that because the cause could be either programmer error, or bad data being passed to the program. Personally, though, I wouldn't wait until just before inserting the data to check it's validity. I prefer to catch invalid data as *early* as possible. When I'm writing CGI and other web scripts, the outline of my program looks like this: Check for the existence and validity of each piece of data. If error exists: Generate and return an error page to the user. Else: Handle the data and generate a response page for the user. It's a good habit to check the validity of each piece of data as soon as it's received. This lets you separate problems where the user sent you bad data, and problems where you messed up the data along the way. If the user passed you decent data, then the only error they should see is some form of "Internal Server Error." HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From anton at vredegoor.doge.nl Mon Jan 12 20:03:31 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 13 Jan 2004 02:03:31 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <4003444f$0$136$3a628fcd@reader1.nntp.hccnet.nl> "Bicho Verde" wrote: > I just have this idea that I would like to contribute to the curve of >accelarated exponential progress (technological singularity), artificial >intelligence and so on. From that point of view there is much to do... But >can I stand for it and where to start? > Anyone would help me and give me some hints? http://www.nickbostrom.com Anton From newsgroups at jhrothjr.com Thu Jan 8 07:34:12 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Jan 2004 07:34:12 -0500 Subject: Descriptor puzzlement Message-ID: Using Python 2.2.3, I create this script: [beginning of script] class AnObject(object): "This might be a descriptor, but so far it doesn't seem like it" def __init__(self, somedata): self.it = somedata def __get__(self, obj, type=None): print "in get method" return self.it def __set__(self, obj, it): print "in set method" self.somedata = it return None ## def foo(self): ## return 1 class AnotherObject(object): def __init__(self): self.prop = AnObject("snafu") myClass = AnotherObject() print myClass.prop myClass.prop = "foobar" print myClass.prop [end of script] Then I execute it: C:\Documents and Settings\John\My Documents\Projects\AstroPy4>b C:\Documents and Settings\John\My Documents\Projects\AstroPy4>python b.py <__main__.AnObject object at 0x0086D248> foobar It doesn't look like the descriptor protocol is getting invoked at all. What's happening here? John Roth From rroberts at adobe.com Fri Jan 9 20:46:42 2004 From: rroberts at adobe.com (Read Roberts) Date: Fri, 09 Jan 2004 17:46:42 -0800 Subject: Help in unwrapping a PyObject* returned by an embedded Python function Message-ID: Environment: Mac OSX 10.2.4, vanilla Python 2.3.2 install Why does PyArg_ParseTuple fail to parse a return value which is a tuple? When inside a C extension function, I call a Python function : pyStringResult = PyEval_CallObject(pyEN_callback, arglist); The Python function runs just fine, and returns a string value. The following works fine, where name is (char**). from Python callback function: return myString in calling C function: *name = PyString_AsString(pyStringResult); However, the following does not work: from Python callback function: return (myString) in calling C function: if (!PyArg_ParseTuple(pyStringResult, "s", name)) { dbprintf(4, "c: failed to parse return value\n"); PyErr_Clear(); } PyArg_ParseTuple fails, and returns NULL. How come? By the documentation, I would think that PyArg_ParseTuple would parse any Python tuple object. -- ----------------------------------------------------------------------------------------- Read K. Roberts rroberts at adobe.com Adobe Systems San Jose TW12 (408)-536-4402 on Weds San Francisco (415) 642-5642 Mon, Tues, Thurs, Fri From jblazi at hotmail.com Mon Jan 12 10:08:35 2004 From: jblazi at hotmail.com (jblazi) Date: Mon, 12 Jan 2004 16:08:35 +0100 Subject: Further problems wirh Emacs Python mode Message-ID: The Python mode for Emacs works nicely on my own machine but it does not work entirely correctly in my school. We use a Novell network and that may cause some problems. Shen I am editing a Python program and type C-c C-c, the second window with the caption is displayed (The Emacs window is tiled), but the print output does not appear. When my Python program is for example print 'hallo' nothing is displayed in the Python Output Window. (On my machine at home I see 'Hallo' (without the 's). I should like to add this: I usually start Python programs on the school systems by typing test.py (for example) at the command line. Then the Python interpreter is automativally started and test.py is executed. This does not work with the Python mode package (CPython?) and so I wrote a batchfile python.py, that contains the only line %1. Has anybody an idea, what goes wrong? -- TIA, jb ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From francisgavila at yahoo.com Sun Jan 4 11:32:07 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 4 Jan 2004 11:32:07 -0500 Subject: Parametrized inheritance References: <2AJJb.725692$HS4.5422608@attbi_s01> Message-ID: #quote# Dan Bullok wrote in message ... Mike C. Fletcher wrote: > You can find more information about these kinds of patterns by searching > for "Mix-In Class" and/or "Multiple Inheritance". Python 2.2 changed how > multiple inheritance graphs are constructed in Python, BTW. If you used > old-style classes the mro would have been [MySub, Sub, Base, MyBase, Base] > IIRC. Well, I thought of doing this, but after looking up resolution order (sec 9.5.1 of the tutorial) I found that resolution is done "depth-first, left-to-right", In my example, that would have given [MySub, Sub, Base, MyBase, Base], but, I checked, using mro(), and found that it was indeed [MySub, Sub, MyBase, Base], just as I needed it. (thanks for the mro() tip - didn't know about that one). Unless I've gone crosseyed (possible, it's late), this is NOT depth-first, left-to-right. So is the tutorial out of date? #endquote# I just looked and, yes indeed, it is out of date (file a bug report). Python 2.2 used this mro, which was changed in 2.3. 2.3 uses a so-called 'C3' mro, which is a bit more complex. See http://www.python.org/2.3/mro.html. The best documentation on Python classes WRT the new-style changes is an essay by Guido at http://www.python.org/2.2.2/descrintro.html. It says 2.2, but it mentions 2.3 changes as inline addendums. Odd thing is, filename is "descriptor intro" yet it doesn't mention descriptors. There's a good reference on the madness that is descriptors at http://users.rcn.com/python/download/Descriptor.htm. -- Francis Avila From skip at pobox.com Thu Jan 29 10:35:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 29 Jan 2004 09:35:17 -0600 Subject: isinstance() bug In-Reply-To: <20040129083746.GA27504@foof.i3.cz> References: <20040129083746.GA27504@foof.i3.cz> Message-ID: <16409.10293.242424.825038@montanaro.dyndns.org> >>> it's my belief that if i'm instantiating a class from the same >>> location no matter how i imported its definition, its instances are >>> always of the same class. >> Your belief is incorrect. 'package.module.A' and 'module.A' are >> distinct classes. Michal> could you elaborate further why do you consider the current Michal> behaviour to be correct? you've only described how it works Michal> currently. i'd be interested what's the reasoning behind that. It's not necessarily a bug. More likely it's a feature. It does what you expect -- if your mental model of how things work corresponds to how things really work. ;-) Michal> i'm inclined to think that the current behaviour is a Michal> side-effect of the implementation (perhaps to which some got Michal> used to?). Before Python had packages this sort of thing occurred much less frequently. If CPython's behavior was changed now (I don't know if Jython's behavior is the same) the change might raise subtle, hard-to-find errors. Maybe you can solve it by adding a shadow dictionary keyed by inode number. It would probably need to be exposed in sys as something like sys.module_inodes, so that programmers can explicitly force module deletion from the runtime. Any place sys.modules is tweaked sys.module_inodes would have to be as well. Skip From jjl at pobox.com Mon Jan 5 11:13:55 2004 From: jjl at pobox.com (John J. Lee) Date: 05 Jan 2004 16:13:55 +0000 Subject: RELEASED: allout-vim 031229 References: Message-ID: <87d69yqsos.fsf@pobox.com> Fran?ois Pinard writes: > [Alexander Schmolck] > > Fran?ois Pinard writes: > > > > In French, we easily use "formidable" to describe a girl who is > > > wonderfully sympathetic and/or attractive. > > > I think sympathetic is another of those false friends :) > > Indeed, thanks!! I just looked it up in a dictionary... [...] Fran?ois, your English is good enough to be comprehensible 99% of the time, and bad enough to be endearing. If you get any better at it, people will start to take all your words seriously, and *then* you'll be in trouble <0.5 wink>. Of course, you don't always get the whole truth from dictionaries. I remember my sister and I laughing at the translation in our school French textbook of "zut" as "bother". "Bother" must be the mildest swearword (if you can call it that) in the English language -- comically so. We were of the opinion that a word that's so clearly designed to be spat must be at least two notches up in vulgarity. :-) (Now, how do I make a transparent pretence of remaining OT...) Thankfully, Python doesn't have that problem. No, actually, a *real* OT comment: I'm pretty sure I've seen two big pieces of code, by two French authors, in which the word "eventually" is used all over the place, in a way that clearly means something to French people . "eventually" --> "finally", perhaps? I don't think it's as simple as that, though. One example: http://pybliographer.org/ John From james at logicalprogression.net Fri Jan 23 09:36:19 2004 From: james at logicalprogression.net (James Henderson) Date: Fri, 23 Jan 2004 14:36:19 +0000 Subject: C compilers In-Reply-To: References: Message-ID: <200401231436.19383.james@logicalprogression.net> On Friday 23 January 2004 1:13 pm, Lucas Raab wrote: > I realize that this is a Python newsgroup, but do any of you know any good > C/C++ compilers?? I'm interested in imbedding C with Python. > > Thanks This would have been less OT if you'd asked what compilers you can build Python with. Then I would have directed you to the README that comes with the Python distribution. Without knowing your platform it would be hard for anyone - on any newsgroup - to help you further. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From rmkrauter at yahoo.com Wed Jan 21 18:23:12 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed, 21 Jan 2004 18:23:12 -0500 Subject: Assignment to slice In-Reply-To: <20040121130236.D8E3.JCARLSON@uci.edu> References: <20040121130236.D8E3.JCARLSON@uci.edu> Message-ID: <1074727392.4458.47.camel@vaio> I'm just surprised that nobody thinks it's unusual. >>> x = [] >>> x[4] = 5 Python says "Wrong! Can't do that! I'm quitting now!" >>> x = [] >>> x[4:5] = [1,2,3,4,5] Python says "Ok. Cool. Those indices don't exist in x so I'll just stick your list at the beginning, and the indices you used in the slice have nothing to do with where the elements end up, since they don't exist in the list anyway." To me that doesn't look much different than if python were to do this: (not real code obviously) >>> x = [] >>> x[4] = 5 >>> x [5] Python says "Well, x[4] doesn't exist so you must have meant x[0]." That would make no sense. So why does it make sense to do that same exact thing if you're assigning to a slice, instead of an element? That's what I see as inconsistent; not that python does not behave just like perl. I'm sure that a little more time will reveal this 'inconsistency' as a shortcoming in the wiring of my brain, and not a weird python idiosyncrasy. It's cool to hear other people's take on it. Thanks alot. Rich On Wed, 2004-01-21 at 16:09, Josiah Carlson wrote: > > Instead python will just tack stuff on to the front of > > the array. Which, I still believe, is totally > > inconsistent. But what do I know? I have about 5 > > minutes of python experience. > > > Oh well. Maybe my problem is that I'm using perl as my > > model of consistency. Plus, it's a minor issue anyway. > > I just need to be aware of it, and not try to write > > perl code in python. I need to learn to write python > > code in python. > > There are a few choices that one can make when allowing slice reading > and writing in sequences. Python made one: never cause an exception for > integer arguments, and certain indices map to the same location. Perl > made another: extend the sequence if necessary to fill it out. > > Both are consistent and predictable. Python does it one way, Perl does > it another. Heck, Python has variable definitions that are done one way, > Perl has variable definitions that are done another. They were choices > made during the creation that fit a paradigm. > > Expecting Python to behave like Perl is like expecting your mother to > pee standing up; without alteration, it's not gonna happen. > > - Josiah -------------- next part -------------- An HTML attachment was scrubbed... URL: From candiazoo at comcast.net Sat Jan 24 23:17:36 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Sun, 25 Jan 2004 04:17:36 GMT Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> <1074926701.236022@yasure> Message-ID: Don! You've done great work. I suppose I can try rebuilding after switching back to net_server. I have 2.2.2 w/0.5.0 and that failed as well, btw. I apologize for not providing more information, I did not seek to irritate you. :/ (as you sound in your response) and I appreciate all the work you've done. Neither did I mean to imply that I was not sure if I wanted to use Python/Bethon. I love Python, and I love BeOS. Bethon seems to be the way to go, altho' I need to learn Bethon. So, anyway, I will try switching back to net_server, building 0.5.1 for 2.2.2 and give it another go. Mike In message <1074926701.236022 at yasure>, "Donn Cave" wrote: > Quoth Zoo Keeper : > | No takers, eh? :/ > | > | I can't be the only python user on BeOS... > | > | The only thing I can think of is that I am running "bone". > > Well, at least now we know one thing about your setup. > > In later versions, a Python class can definitely inherit > from BWindow. If you have the 0.5.1 distribution, the > programs in "test" do it that way, and they work. Earlier > versions, before 0.5.0, can't do this (and neither can > older versions of Python.) It is certainly possible to > mess up the BeOS libraries while trying to improve them, > though, as demonstrated by the 3rd party "Developer Edition". > That certainly could be your problem. > > You're not the only Python user on BeOS, but they are few. > Given the level of general interest, I think you'd have > better odds posting to comp.sys.be.programmer. > > As for what I read as your implicit question, will you be > sorry you chose to develop your application in Python with > a Bethon UI - it depends on the details. The functions > available here are numerous but not nearly the whole Be API, > and there are whole areas of functionality that it will > probably never get into. It's pretty useful for casual > stuff, but probably not for real hard core polished > applications. Distribution will be a harder, too, than > a straight C++ program. > > Donn Cave, donn at drizzle.com From __peter__ at web.de Sun Jan 4 16:09:35 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jan 2004 22:09:35 +0100 Subject: Tkinter.Menu() Question References: <4a_Jb.8099$6B.48@newsread1.news.atl.earthlink.net> Message-ID: Adonis wrote: > I wish to create a popup menu from a list, when it is created they all > show the same label from the list: > > Months = [0, 'January', 'February', 'March', 'April', 'May', 'June', > 'July', 'August', 'September', 'October', 'November', > 'December'] > > def _Menu_Click(self, month): > print month > > menu = Menu(fraMain, tearoff=0) > > for Month in Months[1:]: > menu.add_command(label=Month, command=lambda : _Menu_Click(Month)) > > When the menu calls _Menu_Click(...) it always prints 'December' > > Now my understanding is the when an object is created and it is > replicated, whichever of the modified replications affects all of the > objects, being that they are just mere references to the original (my > wording might be off, correct me if I am wrong). How do I avoid this for > what I am trying to achieve? (I made some bogus changes so I could ensure it works) from Tkinter import * Months = [0, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] root = Tk() class DontCare: def _Menu_Click(self, month): print month dc = DontCare() mb = Menubutton(root, text="so what") mb.pack() menu = mb["menu"] = Menu(mb, tearoff=0) for Month in Months[1:]: menu.add_command(label=Month, command=lambda m=Month: dc._Menu_Click(m)) root.mainloop() Note how the instance (dc) is provided with the method (_Menu_Click) in the lambda (in your real code you will most likely have to replace dc with self). The real trick is to provide the loop variable Month as the default value for m in the lambda. m will be bound to the same string as Month when the lambda is *created*. If you don't do this, the value of the variable Month will be looked up when the lambda is *called*, which will be always "December" after the for loop is terminated. Peter From ashleylloyd at hotmail.com Fri Jan 9 09:34:30 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Fri, 09 Jan 2004 14:34:30 +0000 Subject: Debugging Python Message-ID: Thanks very much for your help. Have a good weekend! Cheers Ashley >From: "Mike C. Fletcher" >To: Ashley Lloyd , Python List > >Subject: Re: Debugging Python >Date: Fri, 09 Jan 2004 09:06:33 -0500 > >Standard module pdb is popular (and what I use, though I also do lots of >print-statement debugging too). There's also a win32db (or something like >that) in PythonWin. Some of the IDE's have integrated debuggers which are >normally very similar to pdb. I think HapDebugger is about the only truly >"different" debugging system, in that it's an out-of-process (and IIRC, >remote) debugging mechanism that relies on a patched version of Python. > >BTW, the Agile Programmer types have been known to suggest that debuggers >are entirely unnecessary, as everything should be caught by more and more >fine-grained unit-tests. Seems like a nice way to go, IMO. > >HTH, >Mike > >Ashley Lloyd wrote: > >>What do people generally use to debug their Python programs? I haven't >>seen anything out there that walks through the code, but perhaps I'm >>looking in the wrong places? > >_______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > _________________________________________________________________ Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo From skip at pobox.com Thu Jan 22 21:50:18 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 22 Jan 2004 20:50:18 -0600 Subject: HDD Stress Test with Python In-Reply-To: References: Message-ID: <16400.35818.996805.854108@montanaro.dyndns.org> Bart> A bit off topic, but here goes: Does this look like a reasonable Bart> hard drive stress-test? ... Bart> fp1 = os.popen("/sbin/newfs /dev/disk0s3", "r") ... Bart> fp2 = os.popen("/sbin/newfs /dev/disk0s5", "r") ... My guess is that newfs isn't all that random in its behavior, nor that it touches all that much of the disk. I think it mostly lays down inode structure. I doubt it even zeroes out the data chunks. You might want to do something like build multiple copies of some huge program (Emacs? GCC? Gimp? Darwin kernel?) in parallel, while constantly creating and deleting a bunch of large files stuffed with random bits. Skip From a.schmolck at gmx.net Fri Jan 9 07:06:21 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 09 Jan 2004 12:06:21 +0000 Subject: Object-based inheritance in Python References: Message-ID: Tobias Windeln writes: > Maybe there is a way to hand over self to the delegatee object. [...] > class Child: > def __init__(self, delegatee): > self.__dict__['delegatee'] = delegatee Can't you just use this pattern: self.__dict__['delegatee'] = delegatee(self) ? 'as From mwilson at the-wire.com Wed Jan 28 11:29:18 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 28 Jan 2004 11:29:18 -0500 Subject: How does compare work? References: <40158680$0$7044$ba620e4c@news.skynet.be> <20040126235704.GD13453@siliconimage.com> Message-ID: In article , Gerrit Holl wrote: >Inyeol Lee wrote: >> (This unusual definition of comparison was used to simplify the >> definition of operations like sorting and the in and not in operators. >> In the future, the comparison rules for objects of >> different types are likely to change.) >> """ > >When comparing mixed types becomes illegal, does that mean sorting a >sequence of mixed types becomes illegal as well? Or will sort be a >special case? Presumably there'd be a whole new set of comparisons that would support inter-type < (e.g. for sorts) and == (e.g. for dicts). Even then, what about PEP 326, which presumes to define highest and lowest objects that can be compared with anything? Regards. Mel. From try_vanevery_at_mycompanyname at yahoo.com Tue Jan 13 22:00:43 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 19:00:43 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Dan Olson" wrote in message news:pan.2004.01.14.01.17.00.970198 at fakeemail.com... > > As a person heavily involved in the pseudo-commercial Linux game industry > and a Linux user in general, I must say that I agree with your general > assessment that Linux users do far too little to make sure that their > applications run and run well on Windows. Yeeeeeeeey! agreement of some kind from some quarter. > That said, I disagree that Open Source projects have little to no value in > commercial projects. There are countless examples that could be pointed > out, but I'll just point out one of them: OpenAL. I did mention there are exceptions, but they are few and far between. OpenAL is once again not a game project. Generally speaking, there is no critical mass of Open Source development in the Windows world. The vast majority of Open Source developers are Linuxers, and carry with them Linux-y baggage about how software "should" be developed. Their notions of "should," both ideologically and practically, lead to Windows build procedures being rather shoddy. > Here is my future advice: get a month and a half into a project before > announcing it. I'm curious what sky is going to fall if I don't follow your advice? Really, so many engineers have this "I want everybody to shut up" mentality. It's not like when I first spoke, that I promised anyone anything, or was particularly looking for help (unless someone with a very similar agenda had happened along). Rather I offered up a set of ideas for people to kick at. Thanks, one and all, for whatever small amount of intellectual labor you performed for me at the time. > Not only will you have people not saying "I told you so" > if you scrap it, but people will in general be more interested in your > project when you have something to show for it. Dude, when you "are interested" in Ocean Mars, I will be worth millions of dollars. You are never going to be interested in it before then. So why should I care if you are interested or not, right now? The only thing people like you respect is money and success. I am different, I respect the honest attempts. That's the "what it means to be an indie developer" conversation I think is worth having. Your kind of conversation, that "you are only allowed to publically demonstrate success," is a conversation I think worth ignoring. It's bullshit: the vast majority of us do *not* succeed all the time, or even a lot of the time. We fear to admit this because we don't want to look stupid. But, at this point in my career I'm quite beyond that fear. > Are you planning to make your vs.net version of FreeCiv available? Others > might be interested in continuing the work. Yes, I do. The question is whether I can get the freeciv.org people to put it in their source pool or not. > Cygwin is a horrible horrible > way to run things on Windows, and I'd like to take this time to insult the > mothers of everyone who has ever made their Linux application run on > Windows using only Cygwin. I am not sure how I feel about it. I think it only bothers me when they claim to be cross-platform in theory, and the Windows build simply does not work in practice. A working Windows build should be easy to obtain all the dependencies for, and it should just build. When it doesn't do that, when you have to chase all over Hell's green acre to find the libraries, and then the build simply coughs and gags and dies, I'm not even slightly amused at how "cross-platform" some Linuxer is claiming things to be. Linux == grungy OS for people who mostly don't care about good deployment and ease-of-use practices. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA When no one else sells courage, supply and demand take hold. From ramen at lackingtalent.com Sat Jan 17 16:54:21 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 17 Jan 2004 21:54:21 -0000 Subject: Does anyone else not find the fun in programming...? References: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> Message-ID: In article <4004f5ac$0$69931$edfadb0f at dread12.news.tele.dk>, Max M wrote: > But I also have a hobby creating music with algorithmic composition > techniques in Python. And that is *fun* What Python libraries do you use to do algorithmic composition? I played around with Snack (for Tcl) awhile back but couldn't get decent realtime performance so I gave up on the idea for the time being. I'm very interested to hear what sort of techniques you use. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From tweedgeezer at hotmail.com Tue Jan 27 16:18:43 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Jan 2004 13:18:43 -0800 Subject: I support PEP 326 References: Message-ID: <698f09f8.0401271318.21c9ca72@posting.google.com> Gary Robinson wrote in message news:... > I've recently had a couple of cases of needing exactly what it proposes, and > having to kluge around the fact that it's not there. It's a great idea. > > If there anywhere else I should be expressing my opinion on this, let me > know. I'm also in support of this PEP, and have cases in which I would use the new singletons. The biggest reason I believe the PEP should be accepted is that you simply *can't* "roll your own" in a heterogenous environment. If I have my Min/Max objects and you have your Min/Max objects, someone's objects simply aren't going to work as expected. I'm in favor of Minimum and Maximum, though, if only for ease in discussing Python: the capital isn't obvious both verbally or at the beginning of a properly written sentence. Jeremy From python at quixs.com Wed Jan 14 12:34:49 2004 From: python at quixs.com (Lars Heuer) Date: Wed, 14 Jan 2004 18:34:49 +0100 Subject: wxPython worries In-Reply-To: <40055e11$0$282$4d4ebb8e@news.nl.uu.net> References: <40055e11$0$282$4d4ebb8e@news.nl.uu.net> Message-ID: <375234841.20040114183449@quixs.com> Hello Guyon, > I've got the same worries, but I'm still not really convinced... > boa-constructor is nice... but not there yet There's another free tool: wxGlade http://wxglade.sourceforge.net/ Commercial tools: wxDesigner: http://www.roebling.de/ DialogBlocks: http://www.anthemion.co.uk/dialogblocks/ Maybe some of these tools fit your needs. I've no deep experience with them all. :) HTH, Lars From artur_spruce at yahoo.com Thu Jan 22 17:19:31 2004 From: artur_spruce at yahoo.com (AdSR) Date: 22 Jan 2004 14:19:31 -0800 Subject: Error under Cygwin - threading module Message-ID: Hello, Nothing relevant found on Google for this, so I'm asking here. I wrote a short script that launches several threads (parallel download using urllib.urlretrieve in this case). Sometimes when I launch my script under Cygwin, I get strange error messages like: 2 [win] python 1912 Winmain: Cannot register window class Sometimes all of the threads run OK, otherwise after the "correct" ones finish the console stops responding anyway. No problems directly under Windows, and /lib/python2.3/test/test_threading.py works fine too. What is wrong? Here is the script: ---- wp_retr.py ---- #!/usr/bin/env python """Retrieve files from the list, give new names if present in list.""" from __future__ import division import re import urllib import threading import time import sys class Download: def __init__(self, url, name): self.url = url self.name = name self.last_check = 0.0 class DownloadBag: def __init__(self, downloads): self._downloads = [] for url, name in downloads: self._downloads.append(Download(url, name)) def start(self): threads = [] for d in self._downloads: p = self._createProgress(d) thargs = (d.url, d.name, p) th = threading.Thread(target=urllib.urlretrieve, args=thargs) threads.append(th) th.start() return threads def _progress(self, download, blocks, blk_size, total): t = time.time() if t - download.last_check > 5: if total != -1: print "%s -> %s: %2.1f%%" % (download.url, download.name, blocks*blk_size/total*100) else: print "%s -> %s: %d bytes" % (download.url, download.name, blocks*blk_size) download.last_check = t def _createProgress(self, download): def progf(blocks, blk_size, total): self._progress(download, blocks, blk_size, total) return progf if __name__ == "__main__": spcre = re.compile(r"(.*?)\s+(.*)$") slashre = re.compile(r"(?:.*)/(.*?)$") f = file(sys.argv[1]) #"filelist.txt") filelist = [] for line in f: line = line.strip() m = spcre.match(line) if m: url, name = m.groups() else: m = slashre.match(line) if m: url, name = line, m.group(1) else: print "Incorrect line format:\n%s" % line continue filelist.append((url, name)) f.close() db = DownloadBag(filelist) threads = db.start() for t in threads: t.join() ---- and here is an example input file (run as python filelist.py filelist.txt): ---- filelist.txt ---- http://www.gnu.org/software/bash/manual/bashref.html http://www.gnu.org/software/make/manual/html_mono/make.html ---- TIA, AdSR From tchur at optushome.com.au Thu Jan 15 16:20:35 2004 From: tchur at optushome.com.au (Tim Churches) Date: 16 Jan 2004 08:20:35 +1100 Subject: Why gmp is not in the standard library? In-Reply-To: <4f0a9fdb.0401150211.615a7f45@posting.google.com> References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: <1074201635.1875.32.camel@emilio> On Thu, 2004-01-15 at 21:11, Miki Tebeka wrote: > Which made me think why Python don't use gmp as it's primary math > package - we'll get fast results, a lot of number types and much more. > > Can't think of any reason why Python is implementing its own long > numbers... > Can you enlighten me? As others have said, re-engineering Python to use GMP numeric types would be a huge undertaking. But I think there is a case to be made for including gmpy as a library in the standard Python distribution. It is very small and doesn't take long to compile, but is incredibly useful. Of course, someone would need to prepare Python-style docs, and someone would need to track GMP development and update the version included with Python at each release (the current gmpy developers perhaps) - thus I suspect it is more a resourcing issue than anything else. However, if some dead wood is ever removed from the Python standard library, I would love to see gmpy take its place. Thanks to the gmpy (and GMP) developer, BTW. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From cleroy at saros.fr Fri Jan 9 10:13:02 2004 From: cleroy at saros.fr (chriss) Date: Fri, 09 Jan 2004 16:13:02 +0100 Subject: problem with a python service Message-ID: Hello everybody! I'm very bad in English but I'm going to try to explain my problem. I have a python program and this program is a service. chronologically: 1. I install my program like service -> it's ok 2. I start the service -> it's ok 3. I stop the service -> it's ok 4. I remove the service -> it's ok 5. I install a new version of my program like service -> it's ok 6. i try to start my new service but it don't start. If I remove the new service and I install the old service I don't arrive to start my old service. If I launch my program like a process, the program start. Is it possible that the service is badly remove? How to make to check it? I install my service with the command: "myService.py --startup auto --interactive install" I remove my service with the command: "myService.py remove" I start my service with the command: "net start pampa" (pampa is the service name) I stop my service with the command: "net stop pampa" Here the code of my service: import win32serviceutil, win32service import pywintypes, win32con, winerror from win32event import * from win32file import * from win32pipe import * from win32api import * from ntsecuritycon import * import log import PampaClient import time class PampaService (win32serviceutil.ServiceFramework): _svc_name_ = 'Pampa' _svc_display_name_ = 'Pampa Client pour WinNT' def __init__ (self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) SetEvent(self.hWaitStop) def SvcDoRun(self): import servicemanager servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' Youpi ?') ) programmePrincipal = PampaClient.PampaClient() try : programmePrincipal.main() except : shutDownThread = programmePrincipal.getShutDownThread() shutDownThread.setService(self) while 1: rc = WaitForMultipleObjects((self.hWaitStop,), 0, 1000) if rc==WAIT_OBJECT_0: break self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' Arret en cours') ) shutDownThread.shutDown() finir while shutDownThread.isAlive(): time.sleep(2) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ' Youpiiiii c\'est fini') ) if __name__=='__main__': win32serviceutil.HandleCommandLine(PampaService) thank you in advance for your reponses, Christophe From bart_nessux at hotmail.com Fri Jan 16 08:32:06 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 16 Jan 2004 08:32:06 -0500 Subject: python & mathematical methods of picking numbers at random In-Reply-To: <59idnYa3_eQMtJrd4p2dnA@comcast.com> References: <59idnYa3_eQMtJrd4p2dnA@comcast.com> Message-ID: Terry Reedy wrote: > "Bart Nessux" wrote in message > news:bu6rvn$njg$1 at solaris.cc.vt.edu... > >>Jeff Epler wrote: >> >>>But why are *you* using >>> random.sample(range(len(x)), 25) >>>instead of >>> random.sample(x, 25) >>>? > > >>Because it works and it's fast and len(count) changes every drawing. > > > I think you missed Jeff's point, which is that you are repeating part of > the work that sample tries to do for you. From the Lib Ref: > " > sample(sequence, k): Return a k length list of unique elements chosen from > the population sequence. Used for random sampling without replacement. New > in version 2.3. > > Returns a new list containing elements from the population while leaving > the original population unchanged. The resulting list is in selection order > so that all sub-slices will also be valid random samples. This allows > raffle winners (the sample) to be partitioned into grand prize and second > place winners (the subslices). > " > When you get the sample from range(n), you have to use them as indexes into > x to get the actual list of names. But the indexing and extraction is what > sample would do if you gave it x instead of range(x)! Ahh, I see what you mean. From webmaster at beyond-thoughts.com Tue Jan 6 04:23:14 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Tue, 06 Jan 2004 10:23:14 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <3FFA7E82.4020609@beyond-thoughts.com> John Roth wrote: > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q > > Frankly, I like the idea. It's about time that all of the file > and directory stuff in the os module got objectified > properly (or at least with some semblance of OO propriety!) > Great I've been thinking of something like this, while I've been writing a "File-Class" (I'll open a thread for this ...) [1] I think Path being a subclass of str is odd. There are a lot of string-operations that don't fit to path (some of them should be implemented in a different way e.g. __mul__ if at all). However the point with the old os function etc. is very sound. So it might be a good idea to have Path being a subclass of str *for transition*. But finally all those functions should call str(argument) instead of of demanding a str-object as argument (if they don't already today). This determines Path.__str__ to return a valid path-string. Path's constructor should be able to use such a string. (when there are Path-Classes for other stuff like URLs we maybe need a factory ...) [21] I think file-paths and directory-paths shouldn't be the same class (they have different meaning. Think about a "walk"-function for dirs) But it might be hard if the path doesn't exist, how to decide whether it's a file-path or a dir-path? You could do the follwing (for Unixes): if its string-representation ends with '/' it's a directory otherwise it's a file. Bash is autocompleting this way but "cd /home" is valid to and would cause trouble with this algorithm. (If the path exists it's easier) file-path and directory-path should have a common superclass. There seems to be a distinction between existing and non-existing paths. Probably a lot of things shared between file-paths and directory-paths are valid for non-existing-paths. "about a path object that happens to have the ability to do file system operations in appropriate circumstances" [John Roth] This is a good thing but I think there are problems: maybe the given path does not exist. This takes me to my last point: What about invalid paths? Should Path-Class take care of always being a valid path (this doesn't necessarily mean a path of an existing file/directory) Especially if someone uses string-methods on a Path-object there could arise invalid paths, even if finaly the path is valid again. The validity of filesystem-paths is os/filesystem dependendt. Christoph Becker-Freyseng From no at spam.invalid Mon Jan 5 13:53:51 2004 From: no at spam.invalid (Russell E. Owen) Date: Mon, 05 Jan 2004 10:53:51 -0800 Subject: Tkinter and OS X 10.3? References: <7ba1cb43.0312301205.30156acf@posting.google.com> Message-ID: In article <7ba1cb43.0312301205.30156acf at posting.google.com>, parki at whatevernot.com (Brian Parkinson) wrote: >I have tried to get Tkinter working on my Mac (OS X 10.3). I installed >MacPython 2.3 and the TclTkAquaBI-8.4.2.0.dmg. > >When I type: > >import Tkinter >r = Tkinter.Tk() > >I get a window all right, but clicking on the window causes the >following error: > >SetFrontProcess failed,-606 > >the window can't properly get focus. > >Had same problem when I tried the example Tk application that comes >with nltk (Natural Language Toolkit). > >Any ideas? You are almost certainly typing python instead of pythonw at the terminal prompt. This results in exactly the error described. (I'm not sure why there are two commands instead of python doing whatever extra magic pythonw does.) -- Russell From q2n8byu02 at sneakemail.com Tue Jan 6 22:09:19 2004 From: q2n8byu02 at sneakemail.com (Ivan Nestlerode) Date: 6 Jan 2004 19:09:19 -0800 Subject: KeyboardInterrupt and threading References: Message-ID: "Paul McGuire" wrote in message news:... > Is the signal module not available to you? > > Assuming you have access to the signal module: > 1. Create a boolean that you can periodically test for in your thread code, > to see if you should keep processing. This may be a global singleton, a > global boolean, or something, but it needs to be visible to both the main > thread and the threaded code. You probably have some compute intensive > loops such as: > while( prime_factors < 1e15 ): > or > while( optimization != converged ): > or even just > while( True ): > > Change these to reference the "keep processing" flag. > while( keep_processing and prime_factors < 1e15 ): > or > while( keep_processing and optimization != converged ): > or even just > while( keep_processing ): # no need to 'and' with True > > 2. Create a signal handler to trap for SIGINT. In the signal handler, set > the "keep-processing" bit to False: > > > > Now your main thread will get the ^C interrupt and clear the > "keep_processing" flag, which will eventually get picked up by your worker > thread the next time it tests for it. > > HTH, > -- Paul I do have the signal module (Python 2.3.2 on Linux), but unfortunately, even registering a signal handler doesn't fix the problem where busy non-main threads prevent Ctrl-C from working. Here is another code snippet using a signal handler (this code is very similar to the code from my second post). If the main thread's loop has the print statement, everything works fine. If it is commented out (as written here), Ctrl-C is ignored completely and the program just keeps running. Why won't this work? Is this a bug? Thanks, -Ivan #!/usr/bin/python from signal import signal, SIGINT from threading import Event, Thread from time import sleep class CpuHogThread(Thread): def __init__(self): Thread.__init__(self) self.counter = 0 self.stopEvent = Event() def join(self): self.stopEvent.set() Thread.join(self) def run(self): try: while not self.stopEvent.isSet(): self.counter += 1 except KeyboardInterrupt: print 'CPU hog subthread caught KeyboardInterrupt' def handler(signal, frme): stopEvent.set() print 'main thread SIGINT handler' t.join() print 'CPU hog subthread joined at counter %d' % t.counter return 0 if __name__ == '__main__': stopEvent = Event() signal(SIGINT, handler) t = CpuHogThread() t.start() print 'CPU hog subthread spawned' try: while not stopEvent.isSet(): sleep(2) # without the next print, Ctrl-C is completely ignored #print 'still sleeping' except KeyboardInterrupt: print 'main thread caught KeyboardInterrupt' t.join() print 'CPU hog subthread joined at counter %d' % t.counter From claird at lairds.com Mon Jan 5 11:45:18 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 05 Jan 2004 16:45:18 -0000 Subject: Python for Embedded Devices? References: <4f0a9fdb.0401042307.1f6bd4e8@posting.google.com> <33b7435c.0401050722.3b01a3d0@posting.google.com> Message-ID: In article <33b7435c.0401050722.3b01a3d0 at posting.google.com>, Dave wrote: >What about cases where the OS shields you from porting issues? > >This is a question which interests me at the moment, as I'm >considering some future embedded work. > >Python is available as a package for NetBSD. To what extent >does this mean that, if you can install NetBSD, you can run >a Python interpreter? . . . I'm quite confident that a good NetBSD installation will be able to run (core) Python nicely. Was that your question? While I haven't used NetBSD myself on any interesting hard- ware, all my experience tells me the combination will be robust. -- Cameron Laird Business: http://www.Phaseit.net From pycon at python.org Mon Jan 26 10:02:13 2004 From: pycon at python.org (Aahz) Date: Mon, 26 Jan 2004 10:02:13 -0500 Subject: PyCon sprints: sign up now! Message-ID: <20040126150212.GA26785@panix.com> We're starting the process of pulling PyCon sprints together, and we want to know whether *you* are going to volunteer. The PSF is sponsoring the sprints, so all registered PyCon attendees can work on sprints for free. To let the sprint organizers know who's interested, sign up on the sprint wiki: http://www.python.org/cgi-bin/moinmoin/SprintPlan2004 PS: Don't forget to register! Early bird ends Jan 31! PPS: Donate money to the PSF at http://www.python.org/psf/donations.html PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. We're looking for volunteers to help run PyCon. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From wweston at att.net Wed Jan 28 10:22:05 2004 From: wweston at att.net (wes weston) Date: Wed, 28 Jan 2004 15:22:05 GMT Subject: Confused about a list.sort() In-Reply-To: References: Message-ID: Amy, Switch from windoze to linux and provide screen dumps. wes at linux:~> python Python 2.3.3c1 (#3, Dec 26 2003, 16:36:50) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> list = [3,9,2] >>> list.sort() >>> list [2, 3, 9] Amy G wrote: > I have a list of numbers... actully I have two lists, List 1 is a list of > number strings and List2 is one of numbers. > > List 1 example: > List1 = [ '20040124123000', '20040124123001', '20040125012456'] > > List 2 example: > List2 = [ 20040124123000L, 20040124123001L, '20040125012456L] > > When I try either: > List1 = List1.sort ... or > List2 = List2.sirt > > and then... > print List1... or > print List2 > > I get None. > > Why is this? > How do I remedy this problem? > > From afriere at yahoo.co.uk Wed Jan 14 22:46:02 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 14 Jan 2004 19:46:02 -0800 Subject: best book References: Message-ID: <38ec68a6.0401141946.70fa3aa5@posting.google.com> Terry Carroll wrote in message news:... > On Thu, 15 Jan 2004 03:32:31 +0530, km wrote: > My favorite to start is O'Reilley's "Learning Python." > > Try to borrow it, rather than buy it, though, or at least buy a used copy. The problem with that is that a used or borrowed copy is unlikely to be the (new) 2nd edition, (see http://www.oreilly.com/catalog/lpython2/) which covers up to Python 2.3. (The older version is badly outdated). Besides which, if you actually buy a copy they might consider a 3rd edition at some time in the future. From DavidSegall at nowhere.net Fri Jan 9 11:05:58 2004 From: DavidSegall at nowhere.net (David Segall) Date: Fri, 09 Jan 2004 16:05:58 GMT Subject: [OT] Database reporting software References: Message-ID: Steve Horsley wrote: >I have an existing system working on MS Access, and software that >regularly logs events into it (and deletes old events after a year). > >Now need to move to real servers, probably Solaris though possibly >Linux. Modifying the software to update the database (maybe mySQL or >Oracle) contents is easy enough, but how do I produce reports >(statistics and summaries) on the database contents? > >I could contemplate web based or application based report generation, >but are there easy to use draggy-droppy report designing applications >around? Just the names would enable me to look them up. > >I am struggling with OpenOffice.org at the moment, trying to see if it >can do what I'm looking for, but it doesn't seem to be able to do GROUP >BY and SUM() - simple aggregation stuff. > >All suggestions would be very welcome. > >Steve If your new database has an ODBC driver the easiest solution would be to keep your existing Access reporting by linking the tables to an Access database running on a Windows machine. Oracle definitely provides an ODBC driver as does the open source PostrgreSQL. I don't know about mySQL. If that is not desirable then Crystal Reports (http://www.businessobjects.com/products/reporting/crystalreports/default.asp) may be the answer. I hate coding reports using Crystal Reports but I'm sure that you can, eventually, produce any conceivable report using it. I don't think it is available under Linux or Solaris but it could connect from a Windows machine to a database running on a Linux or Solaris server. If you want a machine and operating system independent report writer the most polished open source, portable solution I have come across is the combination of iReport (http://ireport.sourceforge.net/) and JasperReports (http://sourceforge.net/projects/jasperreports/). From paul.moore at atosorigin.com Tue Jan 6 18:05:50 2004 From: paul.moore at atosorigin.com (Paul Moore) Date: Tue, 06 Jan 2004 23:05:50 +0000 Subject: PEP 324: popen5 - New POSIX process module References: Message-ID: <65fou181.fsf@yahoo.co.uk> Peter Astrand writes: >> I've read the PEP, and I'd like to help with an implementation for >> Windows, if no-one else is doing it. > > Help is always appreciated. I haven't got very far yet. It might be useful > to look at http://starship.python.net/~tmick/#process as well (but we > should really try to get a smaller code base than this). I've got a (so far *very* basic) implementation which works. I'll have a think about some of the issues which came up when I was writing it, and write up some notes. Paul -- This signature intentionally left blank From michael at foord.net Tue Jan 13 03:53:03 2004 From: michael at foord.net (Fuzzyman) Date: 13 Jan 2004 00:53:03 -0800 Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> <871xq8ri6h.fsf@pobox.com> <87eku7y9zj.fsf@pobox.com> Message-ID: <8089854e.0401130053.4c776e8f@posting.google.com> Thanks to all who posted help. I think theres more than enough to get me through this - when I get a chance I'll sit and have a play. I'm sure I'll have more questions....... Thanks Fuzzy jjl at pobox.com (John J. Lee) wrote in message news:<87eku7y9zj.fsf at pobox.com>... > Samuel Walters writes: > > > |Thus Spake John J. Lee On the now historical date of Fri, 09 Jan 2004 > > 20:16:54 +0000| > > > > > or again, you can set .addheaders on OpenerDirector (which will cause > > > those headers to be added to all requests). > > (just to clarify, I meant an OpenerDirector instance, not the class > itself) > > > > This, however, does not stop the original User-agent header to be sent, > > and google still filters out the request. Instead, it just causes a > > second user-agent to be sent. > > No, it does stop them being sent. Perhaps you mutated the base class > .addheaders by mistake (using .append(("User-agent", "blah")), for > example)? Don't do that! Mutating class attributes is a bad idea. > > > > Here is the very bad code I used to solve this problem. There are better > > ways, I assure you, but it should point you in the right direction. You > [...] > > No need to assure me of *that* . You can call a base class > constructor directly, you know. And clobbering the base class' > constructor is another very bad idea. > > > John From abulka at netspace.net.au Mon Jan 5 21:48:32 2004 From: abulka at netspace.net.au (Andy Bulka) Date: 5 Jan 2004 18:48:32 -0800 Subject: UML tools for python References: <13dc97b8.0312301543.39192aa2@posting.google.com> Message-ID: <13dc97b8.0401051848.11205ed4@posting.google.com> Alexandre Fayolle wrote in message > Well, I think the first thing you could do if you have specific problems > with any of the tools you mention is getting in touch with the > developers, and try to talk with them. Since we've never heard of your > problems with pyreverse, there's hardly any chance that we will do > anything for you. I *have* reported numerous problems with pyreverse to your mailing list. Why do you say I haven't? Specifically: Jun 2003 DOCTYPE XMI directive and MSXML3 parser Feb 2003 Running the latest version locks up when no -d option Feb 2003 Pyreverse 0.4.2 requires logilab.common and optik.OptionParser ? Dec 2002 Fwd: [Gentleware #12069] Poseidon - version 1.5 XMI import prob. and many more before that. And I appreciate you guys responding - great! > But just saying "all existing tools suck, we (i.e., I) need someone to > build some cool free tool with " won't get you > anywhere. The purpose of my post was not an idle 'newbie' post - I have been watching this area for a number of years and have provided the urls in this thread - partly as a service to the python community and also, yes, as a bit of a complaint about the limitations of each of the existing tools. As for contributing something myself: - A source forge project I set up quite a while ago but its just an idea at this stage http://sourceforge.net/projects/pyidea/ - A robust python parser written by me which doesn't rely on the fragility of __import__ see PyNSource http://www.atug.com/andypatterns/pynsource.htm - A Delphi (windows only) GUI front end to PyReverse currently unreleased - My post in this thread researching and listing all UML tools for python that I know. Hopefully people will get ideas from this. Anyway - ideally I was hoping for a robust discussion by senior Python people on what they may be using with regards to UML and what their feelings are about the situation. UML is very important yet there is no GUI driven two-way tool for python programmers. Surely serious, larger scale, software development in Python would want to be using UML as part of the process? Andy Bulka http://www.atug.com/andypatterns From stach at fr.USUN.pl Fri Jan 9 18:11:01 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Sat, 10 Jan 2004 00:11:01 +0100 Subject: Python is far from a top performer according to benchmark test... References: Message-ID: "JanC" wrote in message news:Xns946BE66E88E82JanC at 213.119.4.35... > "Krzysztof Stachlewski" schreef: > > I think all (or at least most) of the tested compilers, VMs, etc. were > written in C/C++, and thus are using libraries written in C/C++... Well, yes. Whether or not you can say that a piece of code is *really* implemented in a chosen language and not in "the language that this language is implemented in" ;-) is a matter of scale. I just think that the Numeric package is not the best example of the speed of Python itself. Stach From bhan at andrew.cmu.edu Wed Jan 14 13:54:57 2004 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Wed, 14 Jan 2004 13:54:57 -0500 (EST) Subject: Scripts for parsing Received: headers in emails Message-ID: A while ago I asked if anyone knows a module for parsing Received: headers in emails. Apparently my guess was wrong (that someone already wrote it in Python). I got an email pointing me to Spambayes project, however the tokenizer doesn't seem like doing a lot on the Received headers (especially when comparing to SpamAssassin's code). So I wrote a small set of scripts for doing this: http://www.cs.cmu.edu/~benhdj/Code/receivedDB.v0_1-20040114.tar.gz It's based on SpamAssassin's Received.pm script, but I separated patterns from the code. Patterns of all known headers are kept in a text database file so new entries can be added without touching anything else. I hope this is useful to someone else too - and of course any patch to increase the coverage of the database is welcome! Ben From aahz at pythoncraft.com Fri Jan 9 13:34:06 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2004 13:34:06 -0500 Subject: Tcl/Tk Support References: Message-ID: In article , Diego.andrade wrote: > >Im not a Python programer, but I need to use Python on some aplications CVS >related. Im trying to install ViewCVS who need Tkinter library. But It >doesnt Work. Im using RedHat 9 Default Installation, to test if Tcl/Tk >suport for Python is working I Type in the Python console import tkinter and >received the following output: > >[root at Diego-Linux root]# 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 tkinter >Traceback (most recent call last): >File "", line 1, in ? >ImportError: No module named tkinter >>>> What happens when you type "import Tkinter" (note initial capital) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From guettli at thomas-guettler.de Thu Jan 15 02:25:31 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 15 Jan 2004 08:25:31 +0100 Subject: best book References: Message-ID: Am Thu, 15 Jan 2004 03:32:31 +0530 schrieb km: > Hi all, > > What is the best book to start with python ? i am have been working since 1 yr with Perl. Since you already know perl, I suggest the Python Cookbook. A lot of examples! thomas From elainejackson7355 at home.com Sun Jan 25 22:59:04 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 26 Jan 2004 03:59:04 GMT Subject: quick question about IDLE Message-ID: I've noticed that the menu in IDLE sometimes has an item called "Shell" with a submenu that offers the opportunity to "Restart Shell". But at other times "Shell" isn't there. Can anybody clue me in about this? TIA. Peace From not at all.com Thu Jan 15 06:25:17 2004 From: not at all.com (G.I.L) Date: Thu, 15 Jan 2004 13:25:17 +0200 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <40051cb3$1@news.012.net.il> Message-ID: <40067838$1@news.012.net.il> Brandon J. Van Every wrote: > "G.I.L" wrote in message > news:40051cb3$1 at news.012.net.il... >> Brandon J. Van Every wrote: >>> "G.I.L" wrote in message >>> news:40047290$1 at news.012.net.il... >>>> It >>>> was an unbelievable waste of time, since you've managed to convice >>>> (maybe still wrongfully) all the people that you are completely >>>> clueless. >>> >>> Why, because I turned around a project in 3 weeks while having the >>> flu half the time? >> >> No, because you dumped the project because it was boring. > > You're a fool then. What's your school of advice, keep working on > things no matter how much of a boring waste of time they become? No, you should evaluate the gain/loss ratio on every project you consider working on. You seemed to give it all justifications before starting to work on it, and can it completely after a very short amount of time. Either you haven't gone deep enough, and you haven't discovered the interesting bits, or you're a very shallow professional to have missed the boring parts of the project. What would your advice be? Start wasting time and money on things and can them if they appear to be boring? How about minimizing the loss by completing something which would give you something in return, such as a non-crashing port? >> This may kill any credit you may have had with people. > > Getting "credit" was a goal? News to me. It's you who wanted to give advice to other people. Do you really believe anyone would follow your advice after THIS??? >>> You try to do something big, you put your money on the line to do >>> it, you fail or don't entirely succeed, you give postmortem, you >>> lay all your cards out for others to examine... *then* I will worry >>> about your opinion. >> >> You state that you will follow only those who fail after putting >> their own money on projects? > > Read it again, and put up or shut up. If you don't have the balls to > allow postmortems of your *own* projects, don't expect me to care > about your flak. Wow, you do have a thick skin, dontcha? How about listening to advice from others for a change? Is it just possible that you're trying to discovering the right trail on the wrong road? Ok, I'll bite. I just invested 0$ on a 3D shooter. I started working on it, and the math was too hard. I gave up after 5 minutes. Do I qualify? g From tzot at sil-tec.gr Tue Jan 13 12:36:51 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 13 Jan 2004 19:36:51 +0200 Subject: Tix and Grid widget Message-ID: It seems strange that so many people have requested for the functionality of a grid widget (like the wxTable, I believe, in wxWindows), and none has offered to add the necessary code in Tix.py to make it available (for those who have installed tix, of course). Apart from the http://www.python.org/doc/life-preserver/ documentation (the Tkinter quick reference), the Tix.py and Tkinter.py files from the source tree, and http://tix.sourceforge.net/man/html/TixCmd/tixGrid.htm (the tixGrid manual page), does anyone have any other hints for resources that might help me update Tix.py ? Thanks in advance. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From swalters_usenet at yahoo.com Thu Jan 8 23:41:42 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 04:41:42 GMT Subject: Lua: further investigation and comparisons with Python and Forth References: Message-ID: |Thus Spake John Benson On the now historical date of Thu, 08 Jan 2004 19:54:12 -0800| > Before reading about Open Firmware, I had assumed that Forth had > completely dropped out of sight. Anyone else aware of counterexamples? I know that Sun systems have a forth based boot system. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From Pieter.Claerhout at Creo.com Sun Jan 11 10:25:09 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Sun, 11 Jan 2004 16:25:09 +0100 Subject: Oracle to Mysql (dates) Help please Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D6D@cseexch01.cse.creoscitex.com> What your seeing in the insert statement is not a string, but is a DateTime object, which needs to be converted to the correct representation for the target database. Prepared statements are the best option here. With prepared statements, the data conversion happens automagically. The code will then look as follows: ## BEGIN CODE import cx_Oracle import MySQLdb tabellen = [ 'machine' ] connO = cx_Oracle.connect( 'bla/bla' ) cursO = connO.cursor() connM = MySQLdb.Connect( 'localhost', db='bla' ) cursM = connM.cursor() for tabel in tabellen: print tabel cursO.execute( 'select * from ' + tabel ) results = cursO.fetchall() cursM.execute_many( 'insert into ' + tabel + ' values ( %s,%s,%s,%s,%s )', results ) # END CODE A few notes: - This uses the execute_many function which will speed up the insert process quite a lot. - Instead of fetching one record at a time, all records are fetched at once. - The number of "%s" in the insert statement will depend on the number of columns in the target table. You could look at the first row of the results variable to know how many columns there are in the table. - The type of placeholders in the SQL statement depend on the database. More info on execute_many and other can be found on: http://www.python.org/peps/pep-0249.html (look for paramstyle and execute_many). Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: duikboot [mailto:ad at ad.nl] Sent: 11 January 2004 14:32 To: python-list at python.org Subject: Oracle to Mysql (dates) Help please Hi all, I'm trying to export a view tables from a Oracle database to a Mysql database. I create insert statements (they look alright), but it all goes wrong when I try to execute them in Mysql, because the dates must have quotes on each side. I just don't know how make the dates right. Well I'll just show you the code and some insert statements it generates. Could anyone please help me? Thanks, Arjen ####Code#### import cx_Oracle tabellen=["machine"] con_oracle=cx_Oracle.connect("bla/bla") c_oracle=con_oracle.cursor() import MySQLdb my=MySQLdb.Connect("localhost", db="bla") my_mysql=my.cursor() for tabel in tabellen: print tabel c_oracle.execute("select * from %s" % tabel) a_oracle=c_oracle.fetchone() #file=open("%s.sql" % tabel, 'w') while a_oracle != None: b=str(a_oracle) ins="insert into %s values %s;\n" % (tabel, b) #file.write(ins) my_mysql.execute(ins) #print ins a_oracle=c_oracle.fetchone() file.close() con_oracle.close() my.close() ##insert statement### insert into machine values ('230KM', ' ', '230KM', 1980-01-01 00:00:00, 2035-01-01 00:00:00, 1, 100, 'asap', 'NO', 0, 0, 'corrugator', 2003-12-04 06:00:00, 1970-01-01 01:00:00, ' ', 'normal', 0.0, 0.0, 7, ' ', ' ', 'normal', ' ', ' ', 'A', 2003-12-04 09:42:14, 82766); -- http://mail.python.org/mailman/listinfo/python-list From omission9 at invalid.email.info Sat Jan 24 03:49:25 2004 From: omission9 at invalid.email.info (omission9) Date: Sat, 24 Jan 2004 08:49:25 GMT Subject: efficient matching of elements a list Message-ID: Suppose I have a lists of tuples A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)] and an int i=1 What is the fastest way in python to get out all the tuples from the list whose first element is equal to i? A have a very large list and a simple for a in A_LIST: if a[0]==i: #We have a match!! Seems to be very slow and there must be some super quick pythonic way to do this maybe? Any avice would be much appreciated!! From garbagecollector86 at hotmail.com Wed Jan 28 19:08:14 2004 From: garbagecollector86 at hotmail.com (Tom Hanks) Date: 28 Jan 2004 16:08:14 -0800 Subject: getting files over ftp References: <560d84ab.0401281049.18d377f3@posting.google.com> Message-ID: <3b6f03cd.0401281608.3f6fb23a@posting.google.com> heavens7s at hotmail.com (Joe) wrote in message news:<560d84ab.0401281049.18d377f3 at posting.google.com>... > How can you grab files over an ftp connection using ftplib? I can > make the connection, browse to the directory, view directory, but > can't copy over the files. > > Thanks def ftp_download(host, user, pswd, ftpdir, filename): """Downloads a single file from an FTP server""" ftp = ftplib.FTP() ftp.connect( host ) ftp.login ( user , pswd ) ftp.cwd ( ftpdir ) f = file( filename , "wb" ) ftp.retrbinary("RETR " + filename, f) From james at logicalprogression.net Wed Jan 21 12:07:24 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 17:07:24 +0000 Subject: problems iterating over a files lines In-Reply-To: <200401211627.55109.james@logicalprogression.net> References: <2835a96b.0401210800.4b89d878@posting.google.com> <200401211627.55109.james@logicalprogression.net> Message-ID: <200401211707.24684.james@logicalprogression.net> On Wednesday 21 January 2004 4:27 pm, James Henderson wrote: > If you used file.read().splitlines() instead you would avoid the extra > blank line. Or even file.readlines(). D'oh! Though this keeps the newlines on the end of each file. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From merkosh at hadiko.de Mon Jan 19 11:14:33 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Mon, 19 Jan 2004 17:14:33 +0100 Subject: subclassing "file" Message-ID: Hi, when extending a build in class, what does the constructor __init__(...) have to return? and how does the constructor call its base-class construtor? (or is this done automatically?) I want to derive from "file" to create a class that reads record from a binary file: class myFile(file): def __init__(self, filename, mode="r", bufsize=-1): ....?... just calling the basename and the constructor does not work: >>> f = myFile("testfile") >>> f ', mode '' at ...> What am I missing? Thanks for your comments Ciao Uwe From richie at entrian.com Thu Jan 29 07:39:13 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 29 Jan 2004 12:39:13 +0000 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? In-Reply-To: References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: [Rune] > It's important to notice here that I'm not interested if the user has > already pressed shift or ctrl. I'm only interested in knowing if he is > currently holding down one of these keys. [Thomas] > No idea about linux, but on windows you use win32api.GetKeyState(). You mean GetAsyncKeyState: "The GetAsyncKeyState function determines whether a key is up or down at the time the function is called" Not GetKeyState: "The key status returned from this function changes as a thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware." ...assuming, Rune, that you *really do* want the current state. If your program is event driven, and you're responding to Shift+Click or Ctrl+Drag or similar, then you want GetKeyState. Imagine the machine is running very slowly. I Shift+Click your app and release the Shift key before your app responds. You call GetAsyncKeyState and see that Shift is not pressed. Had you used GetKeyState, it would tell you that the Shift key was pressed at the time of the click. -- Richie Hindle richie at entrian.com From andymac at bullseye.apana.org.au Tue Jan 6 17:22:17 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 7 Jan 2004 09:22:17 +1100 (EST) Subject: PEP 324: popen5 - New POSIX process module In-Reply-To: <16E1010E4581B049ABC51D4975CEDB8803060D8E@UKDCX001.uk.int.atosorigin.com> References: <16E1010E4581B049ABC51D4975CEDB8803060D8E@UKDCX001.uk.int.atosorigin.com> Message-ID: <20040107091635.S36986@bullseye.apana.org.au> On Tue, 6 Jan 2004, Moore, Paul wrote: > From: Peter Astrand [mailto:astrand at lysator.liu.se] > > The only drawback with "process" is that it is already in use by > > http://starship.python.net/~tmick/#process. > > Ah. I wasn't aware of that module. I wonder whether Trent would be willing > to combine his code and yours somehow, and donate the name? There might be some logic to making this a subpackage of os (os.process ?), which already has a doc subsection for process management functions, rather than a separate top level module (like popen2). -- 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 mir4uu at yahoo.com Fri Jan 9 11:49:10 2004 From: mir4uu at yahoo.com (mir nazim) Date: 9 Jan 2004 08:49:10 -0800 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> Message-ID: <425cc8d1.0401090849.27bf0d3e@posting.google.com> thanks a lot for he4lping me out. keep ideas flowing. its really cool group. thanks again. From xpythonist at yahoo.com.br Thu Jan 22 05:30:08 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Thu, 22 Jan 2004 07:30:08 -0300 (ART) Subject: python said : "1, 2, 3, 6, 7, manbo !" In-Reply-To: <4f0a9fdb.0401212335.481c6679@posting.google.com> Message-ID: <20040122103008.75711.qmail@web21504.mail.yahoo.com> Or, more idiomatically, a = range(8) for b in a[:]: ... :) Aloysio --- Miki Tebeka escreveu: > Hello Rodrigo, > > >>> a = range(8) > > >>> for b in a: > > if b == 4: > > a.remove(b) > > else: > > print b > try: > a = range(8) > for b in list(a): # Iterate over a shallow copy > if b == 4: > a.remove(b) > else: > print b > 0 > 1 > 2 > 3 > 5 > 6 > 7 > > HTH. > Miki > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis! http://br.geocities.yahoo.com/ From mcfletch at rogers.com Fri Jan 9 08:50:57 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 08:50:57 -0500 Subject: debugging makes a person a better programmer In-Reply-To: <3ffea564$0$296$ba620e4c@news.skynet.be> References: <3ffea564$0$296$ba620e4c@news.skynet.be> Message-ID: <3FFEB1C1.2000700@rogers.com> broebel wrote: >I'm just wondering, > >people tell me that helping to debug someone elses program is a really good >way to learn to understand the language it's programmed in. > > One of the reasons that "debugging as learning" is often useful is that many modern systems are large, complex collections of loosely coupled components. Zope, for instance, is almost impossible to grok fully without spelunking through with a debugger to see what actually happens with the security machinery, the traversal machinery, etceteras. The debugging gives you a guide to "where to start reading the code". Keep in mind that in these situations, you're not actually looking for bugs, you're just using the debugging tool to figure out what's going on under the covers. As to the actual suggestion of trying to fix bugs to learn. It can be a good way, but it really does need a mentor to make it an efficient operation. If you want to pursue it, look at the bug-tracker for the project in which you're interested (this is particularly easy with SourceForge-hosted projects), and choose something that seems small. Email the developers of the project to let them know you'll be playing with the bug, (let them know that you're a new-ish developer). Depending on the maturity and size of the projects, you may even find "how to get started hacking on X" documentation hanging around. Otherwise you'll often need to talk with the developers to make any real headway. The developers of the project may even have a suggestion for what bug would be an appropriate first step. If you're lucky, the developers will have failure-case code available (i.e. unit-tests) so that you can know when you've succeeded :) . >My question is: from wich point of can someone start to try to help a >programmer by debugging or testing a program. > >If indeed you already need a profound knowledge of the language than how can >you learn something about it? except for the fact that you see other >possibilities of way to programm. > > One of the ways that people often suggest is to read (and then play with) small samples of really well-written code. The Python Cookbook (both the dead-trees and the online versions) is designed for this kind of learning. This code will tend to have fairly low defect rates, but it is, in essence, a collection of the "verse literature" (poetry) of the language (where projects such as Zope or Twisted is the "prose literature", i.e. long-form/novels). Personally, I'd suggest studying short-form examples of the art first (i.e. poetry), they tend to be easier to keep entirely within the mind, and will tend toward more varied expressions of what can be done. Once you've been exposed to the possibilities, try spelunking through the larger and more heavily structured projects (e.g. Twisted, Zope). Have fun, and good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From __peter__ at web.de Tue Jan 6 04:14:58 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Jan 2004 10:14:58 +0100 Subject: tuple.__hash__() References: Message-ID: Thomas Guettler wrote: > I want to unique a list of tuples. Since > __hash__ returns a 32 bit integer, there > could be a situtation where two different tupples > return the same value. Maybe you can decorate/uniquify/undecorate? >>> items = [t1, t2, t1, t1] >>> di = [(id(i), i) for i in items] >>> from sets import Set >>> si = Set(di) >>> ui = [i[1] for i in si] >>> ui [(1, 2, 3), (1, 2, 3)] > Is there a dictionary type which uses __cmp__() like > btrees in the standard library? I don't understand. For the above example an algorithm based on __cmp__() would return a list with a single item which does not seem to be what you want. Peter From exarkun at intarweb.us Fri Jan 23 10:31:10 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 23 Jan 2004 10:31:10 -0500 Subject: Is twistedmatrix.com dead? In-Reply-To: <182bcf76.0401230624.7e468275@posting.google.com> References: <182bcf76.0401230624.7e468275@posting.google.com> Message-ID: <20040123153110.GA1911@intarweb.us> On Fri, Jan 23, 2004 at 06:24:17AM -0800, Paul Moore wrote: > I haven't been able to get through to twistedmatrix.com for a few days > now. I know they had a problem a couple of days ago, but is there > still a problem, or has something at between me and them simply failed > to notice they are back? Expect it back late monday or early tuesday. Jp > > Thanks, > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From aa at bb.cc Tue Jan 27 10:11:19 2004 From: aa at bb.cc (Ladvánszky Károly) Date: Tue, 27 Jan 2004 15:11:19 GMT Subject: Problem with RE matching backslash Message-ID: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> What is the correct way to match/search a backslash with regular expressions? print re.match('\\m', '\\m').group(0) raises an error while print re.search('\\m', '\\m').group(0) yields 'm' print re.search('\\m', '\m').group(0) yields 'm' print re.search('\\m', 'm').group(0) yields 'm' Any helpful comment on this would be appreciated, K?roly From swalters_usenet at yahoo.com Thu Jan 8 13:25:33 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Thu, 08 Jan 2004 18:25:33 GMT Subject: What psyco is goot at [Was: Rookie Speaks] References: <3FFC9855.3070901@lawson.com> <3FFC9A22.3020507@lawson.com> Message-ID: |Thus Spake Jacek Generowicz On the now historical date of Thu, 08 Jan 2004 11:43:01 +0100| > Samuel Walters writes: > >> If you'd like to see an example of both the psyco and profile modules >> in action, let me know and I'll give you some more understandable code >> that I once wrote to see what types of things psyco is good at >> optimizing. > > I think this is generally interesting, and would be curious to see it, > if you'd care to share. Sure thing. The functions at the top are naive prime enumeration algorithms. I chose them because they're each of a general "looping" nature and I understand the complexity and methods of each of them. Some use lists (and hence linearly indexed) methods and some use dictionary( and hence are has bound). One of them, sieve_list is commented out because it has such dog performance that I decided I wasn't interested in how well it optimized. These tests are by no means complete, nor is this probably a good example of profiling or the manner in which psyco is useful. It's just from an area where I understood the algorithmic bottlenecks to begin with. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" from math import sqrt def primes_list(Limits = 1,KnownPrimes = [ 2 ]): RetList = KnownPrimes for y in xrange(2,Limits + 1): w = y p, r = 0,0 for x in RetList: if x*x > w: RetList.append(w) break p,r = divmod(y,x) if r == 0: w = p return RetList def primes_dict(Limits = 1,KnownPrimes = [ 2 ]): RetList = KnownPrimes RetDict = {} for x in KnownPrimes: RetDict[x] = 1 w = x + x n = 2 while w <= Limits + 1: RetDict[w] = n w += x n += 1 p, r = 0,0 for y in xrange(2, Limits + 1): for x, z in RetDict.iteritems(): if x*x > y: RetDict[y] = 1 break p,r = divmod(y,x) if r == 0: RetDict[y] = p break return RetList def sieve_list(Limits = 1, KnownPrimes = [ 2 ]): RetList = KnownPrimes CompList = [ ] for y in xrange(2, Limits + 1): if y not in CompList: w = y n = 1 while w <= Limits: CompList.append(w) w += y n += 1 return RetList def sieve_list_2(Limits = 1, KnownPrimes = [ 2 ]): SieveList = [ 1 ]*(Limits ) RetList = [ ] for y in xrange(2, Limits + 1): if SieveList[y-2] == 1: RetList.append(y) w = y + y n = 2 while w <= Limits + 1: SieveList[w - 2] = n w += y n += 1 return RetList def sieve_dict(Limits = 1, KnownPrimes = [ 2 ]): SieveDict = { } RetList = KnownPrimes for x in KnownPrimes: SieveDict[x] = 1 w = x + x n = 2 while w <= Limits + 1: SieveDict[w] = n n += 1 w += x for y in xrange(2, Limits + 1): if not SieveDict.has_key(y): RetList.append(y) w = y n = 1 while w <= Limits + 1: SieveDict[w] = n w += y n += 1 return RetList if __name__ == "__main__": import sys import profile import pstats import psyco #this function wraps up all the calls that we wish to benchmark. def multipass(number, args): for x in xrange(1, number + 1): primes_list(args, [ 2 ]) print ".", sys.stdout.flush() primes_dict(args, [ 2 ]) print ".", sys.stdout.flush() #Do not uncomment this line unless you have a *very* long time to wait. #sieve_list(args) sieve_dict(args, [ 2 ]) print ".", sys.stdout.flush() sieve_list_2(args, [ 2 ]) print "\r \r%i/%i"%(x, number), sys.stdout.flush() print "\n" #number of times through the test passes = 5 #find all primes up to maximum maximum = 1000000 #create a profiling instance #adjust the argument based on your system. pr = profile.Profile( bias = 7.5e-06) #run the tests pr.run("multipass(%i, %i)"%(passes,maximum)) #save them to a file. pr.dump_stats("primesprof") #remove the profiling instance so that we can get a clean comparison. del pr #create a profiling instance #adjust the argument based on your system. pr = profile.Profile( bias = 7.5e-06) #"recompile" each of the functions under consideration. psyco.bind(primes_list) psyco.bind(primes_dict) psyco.bind(sieve_list) psyco.bind(sieve_list_2) psyco.bind(sieve_dict) #run the tests pr.run("multipass(%i, %i)"%(passes,maximum)) #save them to a file pr.dump_stats("psycoprimesprof") #clean up our mess del pr #load and display each of the run-statistics. pstats.Stats('primesprof').strip_dirs().sort_stats('cum').print_stats() pstats.Stats('psycoprimesprof').strip_dirs().sort_stats('cum').print_stats() From ykingma at accessforall.nl Sat Jan 17 14:37:54 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 17 Jan 2004 20:37:54 +0100 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> <40083eac$0$321$e4fe514c@news.xs4all.nl> <40086C6E.8536542C@hotmail.com> Message-ID: <40098f12$0$320$e4fe514c@news.xs4all.nl> Alan, you wrote: > [Andrae Muys] >>>> Found myself needing serialised access to a shared generator from >>>> multiple threads. Came up with the following >>>> >>>> def serialise(gen): >>>> lock = threading.Lock() >>>> while 1: >>>> lock.acquire() >>>> try: >>>> next = gen.next() >>>> finally: >>>> lock.release() >>>> yield next > > [Ype Kingma] >>> Is there any reason why the lock is not shared among threads? >>> From the looks of this, it doesn't synchronize anything >>> between different threads. Am I missing something? > > [Jeff Epler] >> Yes, I think so. You'd use the same "serialise" generator object in >> multiple threads, like this: >> >> p = seralise(producer_generator()) >> threads = [thread.start_new(worker_thread, (p,)) >> for t in range(num_workers)] > > Hmm. I think Ype is right: the above code does not correctly serialise > access to a generator. Well, I just reread PEP 255, and I can assure you a was missing something... > The above serialise function is a generator which wraps a generator. > This presumably is in order to prevent the wrapped generators .next() > method being called simultaneously from multiple threads (which is > barred: PEP 255: "Restriction: A generator cannot be resumed while it > is actively running") > > http://www.python.org/peps/pep-0255.html > > However, the above implementation re-creates the problem by using an > outer generator to wrap the inner one. The outer's .next() method will > then potentially be called simultaneously by multiple threads. The I agree (after rereading the PEP.) > following code illustrates the problem > > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > import time > import thread > import threading > > def serialise(gen): > lock = threading.Lock() > while 1: > lock.acquire() > try: > next = gen.next() > finally: > lock.release() > yield next > > def squares(n): > i = 1 > while i < n: > yield i*i > i = i+1 > > def worker_thread(iter, markers): > markers[thread.get_ident()] = 1 > results = [] ; clashes = 0 > while 1: > try: > results.append(iter.next()) > except StopIteration: > break > except ValueError, ve: > if str(ve) == "generator already executing": > clashes = clashes + 1 > del markers[thread.get_ident()] > print "Thread %5s: %d results: %d clashes." % (thread.get_ident(),\ > len(results), clashes) > > numthreads = 10 ; threadmarkers = {} > serp = serialise(squares(100)) > threads = [thread.start_new_thread(worker_thread,\ > (serp, threadmarkers)) for t in xrange(numthreads)] > while len(threadmarkers.keys()) > 0: > time.sleep(0.1) > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > I believe that the following definition of serialise will correct the > problem (IFF I've understood the problem correctly :-) > > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > import time > import thread > import threading > > class serialise: > "Wrap a generator in an iterator for thread-safe access" > > def __init__(self, gen): > self.lock = threading.Lock() > self.gen = gen > > def __iter__(self): > return self > > def next(self): > self.lock.acquire() > try: > return self.gen.next() > finally: > self.lock.release() Looks like a candidate for inclusion in a standard library to me. > def squares(n): > i = 1 > while i < n: > yield i*i > i = i+1 > > def worker_thread(iter, markers): > markers[thread.get_ident()] = 1 > results = [] ; clashes = 0 > while 1: > try: > results.append(iter.next()) > except StopIteration: > break > except ValueError, ve: > if str(ve) == "generator already executing": > clashes = clashes + 1 > del markers[thread.get_ident()] > print "Thread %5s: %d results: %d clashes." % (thread.get_ident(),\ > len(results), clashes) > > numthreads = 10 ; threadmarkers = {} > serp = serialise(squares(100)) > threads = [thread.start_new_thread(worker_thread,\ > (serp, threadmarkers)) for t in xrange(numthreads)] > while len(threadmarkers.keys()) > 0: > time.sleep(0.1) > #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > Also, I don't know if I'm happy with relying on the fact that the > generator raises StopIteration for *every* .next() call after the > actual generated sequence has ended. The above code depends on the > exhausted generator raising StopIteration in every thread. This seems > to me the kind of thing that might be python-implementation specific. > For example, the original "Simple Generators" specification, PEP 255, > makes no mention of expected behaviour of generators when multiple > calls are made to the its .next() method after the iteration is > exhausted. That I can see anyway? Am I wrong? Quoting from PEP 234: http://www.python.org/peps/pep-0234.html "Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? ... Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration." Thanks to all for the help, Ype From joshway_without_spam at myway.com Fri Jan 9 15:56:26 2004 From: joshway_without_spam at myway.com (JCM) Date: Fri, 9 Jan 2004 20:56:26 +0000 (UTC) Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: Jens Thiede wrote: > I found the querk in my code: > a = [1, 2, 3]; > b = a; > b.append(4); > b == [1, 2, 3, 4]; # As it should. > a == [1, 2, 3, 4]; # - Why? > One would think that b is a referance to a - however I know it's not. Rather, a and b hold references to the same object--the list created by the expression [1, 2, 3]. > Without changing a thing from above, the following is true: > b = []; > b.append(5); > a == [1, 2, 3, 4]; > b == [5]; > How do I avoid accedentaly modifying variables, is this a bug? If not > why not? Assignment rebinds variables to different objects, so b now holds a reference to the list created by the expression []. From martin at v.loewis.de Sat Jan 3 19:33:09 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 04 Jan 2004 01:33:09 +0100 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: Sean R. Lynch wrote: > Well, I'm providing a same_type function that compares types. What else > do you want to do with type()? The other option is to go the Zope3 route > and provide proxies to the type objects returned by type(). I don't know what is needed, but I know that existing code will break when it did not strictly need to - no existing code uses your function. If you think your users can accept rewriting their code - fine. Regards, Martin From dave at pythonapocrypha.com Fri Jan 2 15:57:31 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 2 Jan 2004 13:57:31 -0700 Subject: Can this be reversed (Tkinter)? References: <002d01c3d171$df2920b0$5501a8c0@markxp> Message-ID: <06a901c3d173$0a7e27f0$6401fea9@YODA> > I am looking at the format used by root.geometry(). The string returned > from root.geometry() is "%dx%d+%d+%d". Is there a quick and painless > way to extract the values from that string (i.e., "100x150+25+25" => > (100,150,25,25))? How about: s = '100x150+25+25' import re reg = re.compile('(\d+)x(\d+)\+(\d+)\+(\d+)') [int(x) for x in reg.match(s).groups()] -Dave From spamtrap at bigfoot.com Mon Jan 12 06:56:00 2004 From: spamtrap at bigfoot.com (zde) Date: Mon, 12 Jan 2004 12:56:00 +0100 Subject: wrapping C pointers Message-ID: <40028B50.90007@bigfoot.com> Hi, What's the preferred way to wrap handles to C structures in python? (opaque 32-bit pointers with LSBs=00, that python should never deref) Convert directly to PyLong? (seems most natural, although python longs are quite heavy-weight). Shift right and convert to PyInt? (might result in a bit smaller & faster python object, but does it really pay off?) Convert to hexadecimal string? (looks horrible, but SWIG uses that by default, and the author claims it's faster than embedding the pointer inside CObjects. (?!?) CObject? Would provide type information + simple-to-add C methods, but I don't really need that right now, especially if it's slower than hexadecimal strings.. Anyone ran some tests? What python types people use in their wrappers? Thanks.. -- Zdenek From maxm at mxm.dk Sun Jan 18 07:23:11 2004 From: maxm at mxm.dk (Max M) Date: Sun, 18 Jan 2004 13:23:11 +0100 Subject: Does anyone else not find the fun in programming...? In-Reply-To: References: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> Message-ID: <400a7a92$0$205$edfadb0f@dread12.news.tele.dk> Dave Benjamin wrote: > In article <4004f5ac$0$69931$edfadb0f at dread12.news.tele.dk>, Max M wrote: > What Python libraries do you use to do algorithmic composition? I played > around with Snack (for Tcl) awhile back but couldn't get decent realtime > performance so I gave up on the idea for the time being. I'm very interested > to hear what sort of techniques you use. First of I don't use realtime... I create lists of notes:: class Note: def __init__(self, time=0, pitch=64, velocity=64, duration=96): self.time = time self.pitch = pitch self.velocity = velocity self.duration = duration def __str__(self): r = [] a = r.append a('time %s' % self.time) a('pitch %s' % self.pitch) a('velocity %s' % self.velocity) a('duration %s' % self.duration) return '\n'.join(r) That are then converted into midi files by a very simple wrapper layer. This simple structure makes it extremely simple to create transformations on a list of notes. I considder each list a "part" like you see it in Cubase/Logic. The idea is then to create a personal library of transformations and generators that expres your own musical style. I also have a few routines for repeating/extending/sequencing these parts. I import these midi files into software like Cubase, or Reason or Orion. Where they drive either hardware or software synths. I like to fiddle around with the sounds manually by twiddleling the knobs. But I don't change the mnusic manually in the sequencer software. Rather i change the software and genereate a new midi file, that I reload. It is a bit like writing code generators. And it is completely flexible, creative and fun due to the ease of Python. regards Max M From giles_brown at hotmail.com Wed Jan 28 14:58:36 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 28 Jan 2004 11:58:36 -0800 Subject: Help with Extension Class Crash References: <57de9986.0401280544.37d56ebb@posting.google.com> Message-ID: <57de9986.0401281158.41fd421@posting.google.com> giles_brown at hotmail.com (Giles Brown) wrote in message news:<57de9986.0401280544.37d56ebb at posting.google.com>... > Hello folks, > Can anyone help? Yes I can. You used the wrong HEAD macro. You need a different macro for a variable size object you idiot! Sheesh. Giles From kristian.ovaska at helsinki-nospam.fi.invalid Fri Jan 16 12:20:03 2004 From: kristian.ovaska at helsinki-nospam.fi.invalid (Kristian Ovaska) Date: Fri, 16 Jan 2004 17:20:03 GMT Subject: do loop References: <3064b51d.0401160536.5d80fa97@posting.google.com> Message-ID: <0o5g009j960v8dk477637l3046b8lv1v9g@4ax.com> beliavsky at aol.com: >In a Python 'for' loop, one can change the value of looping variable, [...] >Is there a way to write a loop in Python that enforces this >constraint? Should such functionality be added to the language? In Python, "for i in range(3)" produces a sequence [0, 1, 2] and binds each element to i in turn. It's the sequence that drives the loop; i is more like a placeholder, and you are free to bind some other value to it if you wish - it doesn't change loop semantics. So, it makes no sense to restrict i. -- Kristian Ovaska - http://www.cs.helsinki.fi/u/hkovaska/en/ From not at existing.ru Fri Jan 23 10:59:42 2004 From: not at existing.ru (bva) Date: Fri, 23 Jan 2004 16:59:42 +0100 Subject: viewcvs install error on solaris In-Reply-To: <400821B5.F7B7AB1B@attglobal.net> References: <4007e92d$0$325$ba620e4c@news.skynet.be> <400821B5.F7B7AB1B@attglobal.net> Message-ID: <401144f8$0$766$ba620e4c@news.skynet.be> I'm less than a newbie in Python. Do you have to download these modules seperately or do they come with the default python install? Jack J. Woehr wrote: > bva wrote: > > >>Hello, >> >>While trying to install viewcvs on a solaris 5.9 machine I get the >>following error message: >> >>Traceback (most recent call last): >> File "./viewcvs-install", line 35, in ? >> import compat >> File "./lib/compat.py", line 20, in ? >> import urllib >> File "/usr/local/lib/python2.2/urllib.py", line 26, in ? >> import socket >> File "/usr/local/lib/python2.2/socket.py", line 41, in ? >> from _socket import * >>ImportError: No module named _socket >> >>Python is installed on the machine. Can anybody tell me what I'm doing >>wrong or what I've forgotten? >> > > > Apparently, there's a module named "socket" that you don't have installed. > > > -- > Jack J. Woehr # Ceterum censeo > PO Box 51, Golden, CO 80402 # in herbas belli > http://www.softwoehr.com # ab idem desistamus. > > > From dietrich at zdome.net Sun Jan 25 04:35:28 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 25 Jan 2004 01:35:28 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: <4012FEB1.5000106@prescod.net> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> <4012FEB1.5000106@prescod.net> Message-ID: On Jan 24, 2004, at 3:24 PM, Paul Prescod wrote: > function random_sword_magic_power(quality): > return choose_random_assoc( > selector = (quality, (poor, medium, good)), > properties = { (5, 0, 0): glows_in_the_dark(), > (3, 3, 0): magically_silent(), > (1, 5, 1): elemental_power( > choice([earth, water, air, fire]) > (0, 2, 4): magical_keen_edge(), > (0, 0, 2): ????} > > I don't follow what you are doing with the last line so I didn't > duplicate it. The last line recursively calls random_sword_magic_power() twice and concatenates the results. It's something that I used a lot in this program, which I originally wrote in Python, but I was completely baffled trying to implement this part. The reason you can't do it with a dict or list in Python is that the list is always evaluated, and recurses infinitely. A dict isn't appropriate because there would be duplicate keys. Think of it as three tables collapsed into one, the 'poor', 'medium', and 'good' tables, where the relative probabilities for each table fall on a different column. So.... (choose-random-assoc color (red green) ((2 1) foo) ((1 1) bar)) ...has a 2/3 chance of producing 'foo' when color=red, but only 1/2 when color=green. My original point was that Python is not completely agnostic. There's a method to programming in Python, and some patterns just don't fit that method. I anticipated people asking for examples, and I expected that a couple of my examples would fall flat. While Python is a fantastic general-purpose language, it will often be beaten by application-specific languages, but only in their domain. I purposefully didn't use any examples of application-specific languages because people would tell me that I were not being fair. I still have no idea how to express the function in Python without adding "crutches". From quentel.pierre at wanadoo.fr Sat Jan 10 08:25:46 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 10 Jan 2004 14:25:46 +0100 Subject: Asynchronous HTTP server in standard library ? Message-ID: Python standard library provides two modules for asynchronous socket programming : asyncore and asynchat. Several web servers have been built upon these modules (medusa being the best-known I suppose) and are famous for their performance level Unfortunately no example of use is provided in the standard library (whereas the more "classic" SocketServer is illustrated by BaseHTTPServer, SimpleHTTPServer, etc). I think it would be useful if Python came with a simple HTTP server written with these modules, to help beginners understand how use them I've written one, which handles GET and POST requests. It's inspired by (and partly copied from) the http subset of medusa, only reduced to less than 200 lines. It's called SimpleAsyncHTTPServer and published on Active State Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259148 Any thoughts ? Pierre From aahz at pythoncraft.com Sun Jan 18 19:04:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 18 Jan 2004 19:04:39 -0500 Subject: threads and loops References: Message-ID: In article , python-list wrote: > >I'm starting to work with threads, but I'm a little confused. I think >I understand the concepts, but not the controls. Why doesn't something >like this work: Rather than answering your question directly, I'll tell you to look at my slides at http://www.pythoncraft.com/OSCON2001/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From engsolnorm at ipns.com Sun Jan 25 14:38:50 2004 From: engsolnorm at ipns.com (engsol) Date: Sun, 25 Jan 2004 11:38:50 -0800 Subject: Python and writing a CSV file References: <20040121232549.GA28328@mail.theserver.ath.cx> <009501c3e07e$80b62e30$97443d42@homebass1> <16399.7079.192926.761791@montanaro.dyndns.org> <000c01c3e2b7$a6eabcc0$97443d42@homebass1> Message-ID: On Sun, 25 Jan 2004 12:05:23 -0600, Skip Montanaro wrote: > > Kevin> Thanks for responding. Currently we do not have Python 2.3 > Kevin> installed on our server, is there another way to perform this > Kevin> task with another module or without a module? Thanks! > >The Object Craft module does write CSV files. When we wrote the module >included with 2.3, we conciously tried to keep it compatible with 2.2, so >you might well be able to just download it and compile it with 2.2 like any >other third-party module. If that fails, let me know and I'll see if I >can't steer you in the right direction. > >Failing all that, if your data is very well-behaved, you can write valid CSV >data quite easily. Given a list of lists like so: > > data = [ > [1, 2, 4, "My data"], > ["abc", "def", "ghi"], > ["234234234", 1.2e7, "!@##%^*"], > ] > >you should be able to write it to sys.stdout with something like (untested): > > for row in data: > row = [str(e) for e in row] > print '"' + '","'.join(row) + '"' > >Note that the data above doesn't include quotation marks in any of the >fields, the separator is always a comma, and all output will be fully >quoted. Also, it assumes you're on Windows where you'll automatically get >CRLF terminators. > >You should be able to fairly easily extend the above code to handle those >situations. > >Skip > Great timing! I was about to post a question regarding CSV files. I bread-boarded a small test script to learn how the csv thing works, and it seems to work well. The script is: import csv writer = csv.writer(file('csv_test.CSV', 'w')) list_1 = ['a','b','c'] list_2 = ['d','e','f'] list_3 = list_1 + list_2 for ix in range(3): print list_3 writer.writerow(list_3) stdout reports: ['a', 'b', 'c', 'd', 'e', 'f'] ['a', 'b', 'c', 'd', 'e', 'f'] ['a', 'b', 'c', 'd', 'e', 'f'] but the csv file shows: a,b,c,d,e,f a,b,c,d,e,f a,b,c,d,e,f So the question is, where does the extra crlf in the csv file come from? And how do I get rid of it? Thanks, Norm From peter at engcorp.com Mon Jan 12 16:32:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 16:32:22 -0500 Subject: How to call a system command with flexibility on Windows References: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> Message-ID: <40031266.B76A5B6F@engcorp.com> Nicolas Fleury wrote: > > I have a hard time trying to call a system command with the following > capability on Windows: > - Redirection of stdout and stderr. > - Have the return code. > > The documentation seems to say it's only possible on Unix, have I missed > something. Thx for your help. It can be done on Windows, although at the very least you cannot redirect stderr properly from the command line on Win98.... not sure about other issues. I'm pretty sure return codes are available with os.system() under Windows, but I rarely use them and forget any relevant details. -Peter From graham__fawcett at hotmail.com Fri Jan 30 14:46:55 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 30 Jan 2004 11:46:55 -0800 Subject: Building a Course Management System Message-ID: My employer (University of Windsor, Canada) has given me the go-ahead to prototype a CMS (Course Management System, not Content Management), written in Python, to be released under an open-source license (choice of license is TBA). Course Management is a rather broad domain, covering content management, communications tools (e.g., announcements, mail, chat, discussion), assessment (quizzes, surveys, assignments, gradebook), activity tracking, etc. Ideally a good CMS will be portal-based, to aid in managing information- and work-flow. Open-source is finally making headways into the course-management domain, one that has been predominantly commercial for some time. There are a few open-source CMS initiatives out there: Moodle and LogiCampus (both of which are written in PHP) come to mind. We've played with the PHP projects, and though they have some fine features, they also have some drawbacks (PHP as a language choice being among them, but also a number of less-than-ideal design choices, IMO). Needless to say, I'm very excited at the prospect of designing and building such a prototype, and even more excited about the opportunity to open-source it. But for my employer's sake, I must be diligent and survey existing projects, and community interest in such a project. -- Are there other Python-based CMS (Course management systems) that I've overlooked? (Zope4Edu came to mind, but it's commerical, I think; at least, there's no public CVS that I can find.) -- Is there anyone out there who would like to collaborate on a new Python-based CMS? (We do have some specific requirements, and so I might be somewhat inflexible about early design decisions, but there is plenty of room at the party for other designers, programmers, artists and writers.) We're especially interested in partnerships with other academic institutions, though that's not a constraint. Although a formal timeline hasn't been set, I expect that the prototype will be about an eight-week project, starting some time within the next month. At the end of the project, we must produce a useable system with enough functionality to allow for experimentation and beta-testing. In the release-early-release-often spirit, I would hope to publish an early-alpha version within the first week or two of development. Some features will be specific to our needs, but I hope to keep it largely generic. (For those wondering why Python was specified, when little else has been formalized yet: simply put, I get to choose the tools for the prototype, and I choose Python. If I had twice as much time, I'd write it in Java.) I'd encourage any interested people to contact me by e-mail at . (I respect if no one gets excited over a vapourware announcement, but I'd love to have a list of people to contact when the alpha is out.) Regards, -- Graham From syver at inout.no Fri Jan 16 11:42:59 2004 From: syver at inout.no (Syver Enstad) Date: 16 Jan 2004 17:42:59 +0100 Subject: Very strange unicode behaviour References: Message-ID: Thomas Heller writes: > > Is this behaviour the same on Python 2.3? > > No, it behaves correctly as it seems: That's a relief. See my later post to see why the first report I gave was *very* confusing. From swalters_usenet at yahoo.com Thu Jan 15 01:18:51 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Thu, 15 Jan 2004 06:18:51 GMT Subject: best application framework for developing web application References: <14ba0c0.0401142201.68faebcf@posting.google.com> Message-ID: | aj said | > hi > i am a newbi to python and developing a web application what do u all > think is the best application framework for developing web application in > python. I want a framework that supports templates,database connectivity, > is available for both unix and windows ,and ofcourse is easy to learn. > Zope > Quixote > Draco or others Participate in the ongoing discussion of that topic: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&th=c8dbc563a0c82b6f&rnum=1 HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From jjl at pobox.com Wed Jan 14 21:01:46 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 02:01:46 +0000 Subject: I come not to bury C++, but to praise it... References: Message-ID: <87ad4qrmut.fsf@pobox.com> "Derek" writes: [...] > Maybe I didn't make myself clear. I counted the ease with which > memory can be corrupted in C++ as a minus for C++ and a plus for > Python. I agree with you. No, you don't (assuming I understand Jp's post), because... > On the flip side, C++ can catch errors immediately that Python will > not complain about until runtime, and in this imperfect world tests > may not catch all such errors up front. In this respect I consider > C++ safer. ...you made no evaluation of the relative importance of these two qualities (memory-safety and static type-safety). Nor of the fact that C++ comes unavoidably packaged with the more-lines-of-code-per- function-point anti-feature -- KIS! John From http Tue Jan 13 14:08:58 2004 From: http (Paul Rubin) Date: 13 Jan 2004 11:08:58 -0800 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <400413E0.5C691A56@engcorp.com> Message-ID: <7xr7y3mzsl.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > Well, the documentation for "input()" says "Equivalent to > > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/ > > equivalent...." > > I remember reading that too, and just assumed that at this point > it was in fact *implemented* that way, as a simple alias. Maybe > it should be... Python has no support for macros or aliases, and it would be silly to add some special kludge for input(). The user needs to be able to redefine the function and so forth too. From bart_nessux at hotmail.com Mon Jan 12 11:59:53 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Mon, 12 Jan 2004 11:59:53 -0500 Subject: Why learn Python ?? In-Reply-To: References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Ville Vainio wrote: > Learn Python first, the ease of programming can quite possibly inspire > you to create something interesting. This is true. Learn Python and *then* learn other languages. Learn as many languages as you like. Python will teach you how to think when writing programs. This thought process will be the same for C, C++, Perl, etc. As a bonus, Python can be applied to solving real-world problems as well. So, you get the best of both worlds: 1. A theorhetical language that easily teaches the concepts of modern computer programming. 2. A practical language that is actually useful for doing things. Python is also easy to read compared to other languages. It's much easier to learn. Its syntax doesn't get in the way of learning like C ++, or other language's syntax can. It's fun too. Best of luck, Bart From none at none.com Wed Jan 14 13:02:50 2004 From: none at none.com (Derek) Date: Wed, 14 Jan 2004 13:02:50 -0500 Subject: I come not to bury C++, but to praise it... References: Message-ID: "Jp Calderone" wrote: > > I also use C++ and Python as my main languages and I > > agree with your comments. However, I don't agree that > > Python is inherently "safer" than C++. At best I see > > it as a tie. For example, C++ let's you corrupt memory > > among other "unsafe" things, most of which can be avoided > > by using standard containers, smart pointers, etc. > > Python lets you do "unsafe" things such as passing an > > object to a function when it makes no sense to do so, > > which can lead to nasty runtime surprises. > > A traceback is *much* less nasty than memory corruption. > One stops the program immediately and shows you exactly > where the problem lies, the other may let the program run > for quite a long time before simply causing the process to > die, leaving few clues as to the source of the problem. > > Python may not be *completely* safe (indeed, memory > corruption is still possible due to bugs in the interpreter > and extension modules), but it is quite a bit safer than > C++. Maybe I didn't make myself clear. I counted the ease with which memory can be corrupted in C++ as a minus for C++ and a plus for Python. I agree with you. On the flip side, C++ can catch errors immediately that Python will not complain about until runtime, and in this imperfect world tests may not catch all such errors up front. In this respect I consider C++ safer. From jzgoda at gazeta.usun.pl Sat Jan 17 09:30:36 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 17 Jan 2004 14:30:36 +0000 (UTC) Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> Message-ID: Frank Bechmann pisze: > btw.: there is even a python port for the AS/400, but even if CL as > ugly as a nightmare it can't be beaten in terms of productivity on an > AS/400. Yes, htpp://www.iseriespython.com/. Discovery of existence of Python for iSeries made me switch back to AS/400 from Unix. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From jepler at unpythonic.net Wed Jan 21 10:59:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Jan 2004 09:59:59 -0600 Subject: newbie: prefix operator "**" In-Reply-To: References: Message-ID: <20040121155959.GB18498@unpythonic.net> On Wed, Jan 21, 2004 at 10:33:49AM -0500, Christian Jauvin wrote: > Hello, > > I am playing with some classes in the Tkinter module > to learn some GUI basics. Take a look at the Tutorial, section 4.7.2. The ** prefix for an argument means that it accepts arbitrary keyword arguments. http://python.org/doc/tut/node6.html#SECTION006720000000000000000 Example: def f(**kw): print kw >>> f(a=1, b=2) {'a': 1, 'b': 2} Tkinter uses this to pass the keyword arguments along to the next level, eventually to the Tk command to create or configure a widget. Jeff From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jan 26 19:35:40 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 27 Jan 2004 01:35:40 +0100 Subject: ANN: Snakelets 1.22 (simple-to-use web app server with dynamic pages) Message-ID: <4015b25b$0$323$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.22 is available. Snakelets is a Python web application server, mainly for educational purposes (but it works fine, mind you). This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). It is possible to run Snakelets off a CD (read-only mode). Snakelet's focus is on understanding the way dynamic web sites are created and make this process as easy as possible, while still providing a rich and powerful server environment. It's released under the open-source MIT Software license. You can download from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). Most relevant changes since 1.21: - all Ypages can be precompiled at startup to check for errors - compiled Ypages can be written to a file, to aid debugging - small Ypage parser fixes - fixed some threading issues - fixed small virtualhost issue, improved config checks To start, edit the vhost config file (see docs) and then run serv.py script, or the monitor.py script if you want to start it as a daemon (on Unix). Enjoy, --Irmen de Jong. From llothar at web.de Thu Jan 29 21:05:59 2004 From: llothar at web.de (Lothar Scholz) Date: 29 Jan 2004 18:05:59 -0800 Subject: Webhosting with Python References: <8089854e.0401290012.465ba364@posting.google.com> <2004012913401516807%kevin@sborg> Message-ID: <6ee58e07.0401291805.6878bf2a@posting.google.com> Kevin Ballard wrote in message news:<2004012913401516807%kevin at sborg>... > So, then, how do *they* plan to make money off of that? I think it's possible. The speed of the free site is very slow (i looked at the give link). If you calculate that 1/2 of the given transfer rate is really used and you get a server from rackshack.net (700GB for 99$) you can make 600$ per server. That's quite reasonable if it is run by a student or someone who only want to get a few bucks and has more time then money. Oh yes, the banner and site layout is 59$ template from "www.templatemonster.com" so i think it's a small one person company. From rainerd at eldwood.com Tue Jan 13 18:49:28 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 13 Jan 2004 23:49:28 GMT Subject: I come not to bury C++, but to praise it... References: Message-ID: Derek wrote: > You also seem to have a narrow view of C++ as a strictly OO language > when in fact it supports several programming paradigms (write whatever > you want: template metaprograms, modules, procedures, classes, etc.). C++ is rather similar to Python in this respect. ;-) I currently have two languages that I regularily use: C++ and Python. C++ produces faster programs, gives direct access to the hardware, and has many third-party libraries that Python doesn't have. Python is more concise, more flexible, safer, and has its own set of libraries that C++ doesn't have. Both have their place. None of the other languages I've looked at (with the possible exception of Common Lisp) seem to offer me anything that I can't find in either Python or C++, and many of them (Java in particular) are far too restrictive for my taste. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From peter at engcorp.com Tue Jan 13 14:28:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jan 2004 14:28:21 -0500 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> Message-ID: <400446D5.1265452A@engcorp.com> Donn Cave wrote: > > In article <40041576.D070723E at engcorp.com>, > Peter Hansen wrote: > > Basically, as a software engineer ... I find Python to be hands down > > *the* best language I've encountered for use in serious work. I can't > > actually think of another which excels on so many fronts. > > But your list describes the perfect hacker language, at > least on some counts. I'm nominally a Software Engineer > myself, but I have no formal CS education and have never > worked on a large project, so I feel right at home with > the hacker culture here. But help me out here, suppose > we're going to go in and develop one of those massive > projects - I don't know, say the IRS needs a new computer > system - what on that list would we care about? Never having done a new system for the IRS (yet? ;-) I can't really say, but I do some pretty hard core stuff and Python fits the bill for me better than past attempts... > Maybe vague promises like high productivity and ease of > testing would be attractive, but anyone can say that for > some ideal context. Perhaps, but it's also pretty easy to quantify, at least in the non-scientific fashion which I've attempted to use for that. > Library support is probably not even on the charts. Very few systems cannot benefit from good library support. Presumably the IRS requires networking, some user interface capabilities, probably a bunch of database interfaces, really sophisticated testing, and these days maybe even some standardization in the area of, say, XML or something like that. > I would think a major consideration at > the outset of a project like this would be whether the > code that all these teams is writing will eventually come > together and work like it's supposed to, and from that > point of view it's tempting to look for some support for > architectural consistency, like "interfaces" and that sort > of thing. I agree, though I personally find it much more effective to use good tests for this kind of thing. Interfaces don't cut it when there's not a simple caller-callee relationship between things. I have lots of components which are separated by various other kinds of interfaces, such as a particular file format, or XML, or some custom network protocol. Need tests to check both sides of those equations. -Peter From roy at panix.com Thu Jan 8 09:24:58 2004 From: roy at panix.com (Roy Smith) Date: Thu, 08 Jan 2004 09:24:58 -0500 Subject: Looking for help with regular expressions- not Python Specific References: <8d3e714e.0401072114.5bf3fba7@posting.google.com> Message-ID: cappy2112 at yahoo.com (Tony C) wrote: > But I would like to find a mailing list or newsgroup where I can ask > questions about regexps (when things don't work), not specifically > dealing with Python. When I have Python-regexp questions, I'll post > them here of course. I don't know of any regex-specific newsgroups or mailing lists, but most old unix hands are pretty good at them, so asking in comp.unix.questions might be worth trying. Perl makes extensive use of regex, so I'll bet you'll find some regex gurus on comp.lang.perl too. Try doing a search on groups.google.com for regex and see what newsgroups pop up the most with recent dates, then ask your questions there. Keep in mind that there are many different regex libraries out there, and they don't all accept exactly the same syntax. Python and Perl use the same library (I believe). But, on the other hand, we're a pretty friendly group on comp.lang.python, and I know there's a bunch of regex wizards who hang out here as well, so why not just ask here. One Python-specific tip is to get into the habit of ALWAYS using the r'' style raw strings for regex. It makes life so much simplier. Joe Francia wrote: > First, be sure you actually need regexes. See if you can achieve the > same results using string methods. String methods are faster to run, > easier to write, and much easier to debug. Regex's are an extremely powerful tool, and anybody who's serious about programming (especially if you do text processing) should have a solid mastery of them. That being said, Joe is certainly right about them not always being the best tool for the job. Chainsaws and scalpels are both useful cutting tools, but hardly interchangable in all applications. Regex's can lead to extremely fast and compact code, but then can also lead to stuff which is impossible for anybody to understand 6 months later. Also, Joe's comment that string methods are faster to run is a half-truth. Regex's get compiled. If you use the all-in-one step regex methods, you compile the expression every time you use it. Compiling is expensive. But, if you pre-compile the expression, using it is very fast. Doing the compile step once, and re-using the result can be very fast. A single regex that looks for a complex pattern may well be faster than a series of string methods tied together with conditional logic. Your mileage may vary, so if speed is important to you, try different ways and profile it. In any case, for the vast majority of stuff, speed is just not an issue, and you should pick your weapon based more on clarity and simplicity of the resulting code than on raw speed. From newsgroups at jhrothjr.com Tue Jan 20 19:04:31 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jan 2004 19:04:31 -0500 Subject: always the same object References: Message-ID: <100rgj1etbcqr9d@news.supernews.com> "Uwe Mayer" wrote in message news:bukbuo$rqp$1 at news.rz.uni-karlsruhe.de... > Hi, > > I am using struct.unpack() quite often. unpack() returns a tuple, however a > tuple with always the same id(), which is AFAIK the memory location of the > structure. > > I found myself working with above tuple, initialising other data structures, > etc... and when I tried to change one list element, suddenly all list > elements change => so they all contain the identical object The biggest problem people have with lists is attempting to reuse one rather than starting with a new one. For example, this ***WILL NOT*** work: class Fubar: aList = [None, None, None] def addToList(self, something): aList[:3] = something on the other hand, this will work: class Good: def __init__(self): self.aList = [None, None, None] def addToList(self, something): aList[:3] = something > Now what are the rules when Python re-uses an old object (as with > struct.unpack() ) and when does it create new objects? As far as lists are concerned, list literals ([...]) always return a new list. > And what ist the proposed solution for dealing with this situation, i.e. how > do I create a true copy of what struct.unpack() returns me? See above. John Roth > > Thanks in advance > Ciao > Uwe From teengo at yahoo.com Tue Jan 13 16:07:19 2004 From: teengo at yahoo.com (Ticachua) Date: 13 Jan 2004 13:07:19 -0800 Subject: How to intercept a keypress using python? References: Message-ID: Tim Golden wrote in message news:... > >-----Original Message----- > >From: teengo at yahoo.com [mailto:teengo at yahoo.com] > >Sent: 12 January 2004 17:51 > >To: python-list at python.org > >Subject: How to intercept a keypress using python? > > > > > >Hello all, > > > >Does anyone know how to intercept user's keypress or > >mouseclick in Python? > >I'd like to write a small tool (Python-based preferrably) running on > >Windows to capture the user's keypresses and mouseclicks and write > >them to a file. > > > >Thanks for your help. > >-- > > Check out: > http://mail.python.org/pipermail/python-list/2003-November/195739.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 > ________________________________________________________________________ Thanks a bunch Tim. From miki.tebeka at zoran.com Mon Jan 12 03:37:42 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 12 Jan 2004 00:37:42 -0800 Subject: script to translate from compiler AST References: Message-ID: <4f0a9fdb.0401120037.13686194@posting.google.com> Hello Andrey, > I'm looking for a script to translate from 'compiler' AST to py source > and executable code. > > Google search reveals hardly useful links. > > Is there something like that or it is left as an exercise for a curious > developer? Have you looked at the parser module? (http://www.python.org/doc/current/lib/module-parser.html) it does have some functions operating on AST. The is also a visitor patter support in the compiler module. HTH. Miki From jepler at unpythonic.net Sun Jan 18 13:07:39 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Jan 2004 12:07:39 -0600 Subject: re question - finiding matching () In-Reply-To: <4f0a9fdb.0401180751.4b66d974@posting.google.com> References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: <20040118180739.GA24401@unpythonic.net> Regular Expressions cannot perform the simple task of matching an arbitrary number of parentheses. You could write an expression that will work as long as the nesting isn't more than N levels, but the expression quickly becomes very painful. Instead, you can use some method to split the string into parts: one part for "(", one for ")" and one for any other sequence of characters: tokenize_re = re.compile("\(|\)|[^()]*") Now, use this expression to tokenize your input string: >>> tokens = tokenize_re.findall("add((2 * 2), 100)") >>> print tokens ['add', '(', '(', '2 * 2', ')', ', 100', ')'] To match your language, the first token must be 'add': if tokens[0] != 'add': # no match The second token must be '(': if tokens[1] != '(': # no match Now, start scanning and counting parens, until you get back to 0 nesting_level = 0 for t in tokens[1:]: if t == ')': nesting_level -= 1 if nesting_level == 0: # End of desired string else if t == '(': nesting_level += 1 # if you end the loop without reaching nesting_level 0 # then there were not enough close-parens # no match You could also implement this part recursively (as you likely would if you were actually compiling the string into bytecode). Jeff From rodrigob at elo.utfsm.cl Wed Jan 21 15:55:49 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Wed, 21 Jan 2004 17:55:49 -0300 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: Message-ID: <400ee387$1_1@nova.entelchile.net> (corrected the identation) > At the python2.3.2 prompt > > >>> a = range(8) > >>> for b in a: > ...........if b == 4: > ................a.remove(b) > ...........else: > ................print b > > > 0 > 1 > 2 > 3 > 6 > 7 > > > Why 5 does not appear ? (this was the source of a deep bug in a 4000+ > lines networked program...) > > RodrigoB > From jdhunter at ace.bsd.uchicago.edu Wed Jan 14 23:19:14 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 14 Jan 2004 22:19:14 -0600 Subject: Numeric Python and C In-Reply-To: (Ognen Duzlevski's message of "Wed, 14 Jan 2004 19:17:55 +0000 (UTC)") References: Message-ID: >>>>> "Ognen" == Ognen Duzlevski writes: Ognen> Hi, can someone explain how to change a value within an Ognen> array from a C function? Warning: I am not a Numeric C API guru. For 1D arrays I use the following macro // get x[i] from a 1d array of type xtype #define get1d(x,i,xtype) \ *(xtype *)(x->data+i*x->strides[0]) You can assign to the return value of this, as in count = 0; while ((row = mysql_fetch_row(res)) != NULL) { get1d(p,count,float) = atof(row[0]); get1d(v,count,int) = atoi(row[1]); ++count; } where p and v are 1D numeric arrays. You'll have to do a bit more work for 2D arrays, but this may speed you on your way.... JDH From __peter__ at web.de Wed Jan 21 22:44:51 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 22 Jan 2004 04:44:51 +0100 Subject: Identifing current function References: Message-ID: Brian Donovan wrote: > Is there a way to identify the current function. For example: >>> import inspect >>> def whoami(): return inspect.stack()[1][3] ... >>> class A: ... def someMethod(self): print whoami() ... def anotherMethod(self): print whoami() ... >>> def someFunc(): ... print whoami() ... a = A() ... a.someMethod() ... a.anotherMethod() ... >>> someFunc() someFunc someMethod anotherMethod >>> Seems to work. No warranty, though. Peter From none at none.com Sat Jan 10 04:22:18 2004 From: none at none.com (Eli Pollak) Date: Sat, 10 Jan 2004 20:22:18 +1100 Subject: need help translating a PHP for statement to python References: Message-ID: Haha ... you must be originally a perl coder. Who else writes attricious code like this if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) If I was hiring you, I'd fire you on the spot. Secondly, here is what I came up with. Not sure what '1E7' is though. And change 'intval' to 'int' if you want to cast something to an int in python x,y = cx-cy-1,0 while y <= cy: prd = q * y_ar[y] + car - ((car = int(prd / 1E7)) * 1E7); if (bar = ((x_ar[x] -= prd + bar) < 0)) x_ar[x] += 1E7; x,y = x+1,y+1 Eli > I'm translating some PHP scripts to Python and have hit a roadblock > with a for statement. If someone could explain to me how one should > translate the multiple increment, evaluations, etc. in the first line > I would appreciate it deeply ... > > for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { > $prd = $q * $y_ar[$y] + $car; > $prd -= ($car = intval($prd / 1E7)) * 1E7; > if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7; > } > > thanks, > > Davis From aahz at pythoncraft.com Sun Jan 4 19:42:23 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2004 19:42:23 -0500 Subject: Proposal: new peps always in clpa References: Message-ID: In article , Gerrit Holl wrote: >Aahz wrote: >> In article , >> Gerrit Holl wrote: >>> >>>would it be a good idea to automatically sumbit all new peps to >>>comp.lang.python.announce? After all, each PEP is an announcement and >>>may be important to the entire Python community. Another possibility >>>would be to python-dev, but since c.l.py.announce has a broader public, >>>I'd prefer the first one. What do you think? >> >> That's a good idea, but c.l.py.announce needs to have its Followup-To: >> set to c.l.py. I think I asked for that once before, but didn't get a >> response. > >I think Followup-To: should be set to c.l.py for _any_ posting in >c.l.py.announce, not only for peps, but that is another issue >altogether. Exactly. But currently most announcements to c.l.py.announce don't spawn discussion, so it hasn't been a critical issue; until Followup-To is fixed, I'm opposed to requiring PEPs to be posted there. Note that it's not trivial, because c.l.py.a has a gateway to an e-mail list, where Reply-To: should be set. It'll likely require some Mailman work -- and c.l.py.a hasn't even been upgraded to current Mailman yet. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From jcarlson at nospam.uci.edu Tue Jan 27 17:40:39 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 27 Jan 2004 14:40:39 -0800 Subject: I support PEP 326 In-Reply-To: <698f09f8.0401271318.21c9ca72@posting.google.com> References: <698f09f8.0401271318.21c9ca72@posting.google.com> Message-ID: > I'm also in support of this PEP, and have cases in which I would use > the new singletons. > > The biggest reason I believe the PEP should be accepted is that you > simply *can't* "roll your own" in a heterogenous environment. If I > have my Min/Max objects and you have your Min/Max objects, someone's > objects simply aren't going to work as expected. > > I'm in favor of Minimum and Maximum, though, if only for ease in > discussing Python: the capital isn't obvious both verbally or at the > beginning of a properly written sentence. Unfortunately, I have a feeling that the PEP may be killed because there doesn't seem to be a location/name that is agreeable to those with voting power in python-dev. A new module included into the standard library seems to be the easiest way to get it into Python. However, considering that you cannot guarantee that the Max/Min will get their __cmp__ method called (when comparing against user-defined classes), you cannot guarantee the ordering. If it were to get special treatment, by including it as a pseudo-builtin (always in Python, but doesn't have a name in __builtin__), it is a 5 line modification to PyObject_Compare in object.c to guarantee the orderings with Max/Min: http://mail.python.org/pipermail/python-dev/2004-January/042275.html That email also makes a case for min() and max() returning the minimum and maximum object respectively, whose string representations would be 'min()' and 'max()' respectively. It would result in the overloading of the min and max functions, but there is no general consensus in python-dev; some people like it due to its similarity to using int(), list(), dict(), float(), str(), long(), etc., but others (including Guido himself) think that min() and max() /should/ produce TypeErrors. I'm thinking that maybe it should produce a warning for a release or two (that it used to produce a TypeError, unless 'from future import extremes' is at the beginning of a script), but in Python 2.5 or 2.6 remove the warning. Yeah. If someone has a strong opinion either way, perhaps you should comment in python-dev. If anyone has a better name/location suggestion, (that is not listed as an option in the current or previous versions in CVS: http://python.org/peps/pep-0326.html http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/peps/pep-0326.txt?content-type=text%2Fplain&rev=1.2 ), you suggestions are definitely appreciated. Thank you, - Josiah From michael at stroeder.com Fri Jan 23 05:54:03 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 23 Jan 2004 11:54:03 +0100 Subject: ANN: python-ldap-2.0.0pre19 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.0pre19 2004-01-22 Changes since 2.0.0pre18: Modules/: * LDAPObject.c: Most deprecated functions of OpenLDAP C API are not used anymore. * functions.c: Removed unused default_ldap_port(). * constants.c: Removed unused or silly constants AUTH_KRBV4, AUTH_KRBV41, AUTH_KRBV42, URL_ERR_BADSCOPE, URL_ERR_MEM * errors.c: Fixed building with OpenLDAP 2.2.x (errors caused by negative error constants in ldap.h) ldap.ldapobject.LDAPObject: * Removed unused wrapper methods uncache_entry(), uncache_request(), url_search(), url_search_st() and url_search_s() * New wrapper methods for all the _ext() methods in _ldap.LDAPObject. ldap.modlist: * Some performance optimizations and simplifications in function modifyModlist() From jacek.generowicz at cern.ch Mon Jan 12 10:13:52 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Jan 2004 16:13:52 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: "Derek" writes: > I would also add that while Lisp has been a favorite in the AI > community, you will find that most AI techniques generalize to most > any programming language. I spent a good deal of time in grad school > and on my first job doing AI programming in C++. The only time I used > Lisp was in introductory classes, mostly to write elegant -- but > toy -- programs. Lest Derek give the impression that Lisp is in any way a "toy" language, or that it somehow sacrifices practicality for elegance, I feel honour bound to point out that it is actually the most powerful and expressive programming language known to man, and excells in solving problems which are often considered too hard to be solved in other languages. If you want to perform miracles, then learn Lisp. If you merely want to write programs that rock, then learn Python. :-) If, however, masochism is more you bent, then I thoroughly recommend C++. -- Greenspun's Tenth Rule of Programming: 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." From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Sat Jan 24 05:58:43 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 24 Jan 2004 12:58:43 +0200 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: >>>>> "Ganesan" == Ganesan R writes: Ganesan> is nearly 6 times slower in python (8 time slower with Ganesan> Python 2.2) using fileinput. Every appears to know that Ganesan> fileinput is slower and avoid it when performance is a Ganesan> concern; but even manually doing the equivalent is slower Ganesan> in python. I've simply switched back to using perl for my A while back someone fixed his python script to use normal files instead of stdin, and the Python version proved to be even faster than the Perl version. Have you tried that? -- Ville Vainio http://tinyurl.com/2prnb From jason at tishler.net Tue Jan 27 09:46:36 2004 From: jason at tishler.net (Jason Tishler) Date: Tue, 27 Jan 2004 09:46:36 -0500 Subject: Error under Cygwin - threading module In-Reply-To: References: Message-ID: <20040127144636.GA1204@tishler.net> AdSR, On Thu, Jan 22, 2004 at 02:19:31PM -0800, AdSR wrote: > Nothing relevant found on Google for this, so I'm asking here. I wrote > a short script that launches several threads (parallel download using > urllib.urlretrieve in this case). Sometimes when I launch my script > under Cygwin, I get strange error messages like: > > 2 [win] python 1912 Winmain: Cannot register window class > > Sometimes all of the threads run OK, otherwise after the "correct" > ones finish the console stops responding anyway. FWIW, I cannot reproduce the above problem under: $ cygcheck -cd cygwin python Cygwin Package Information Package Version cygwin 1.5.5-1 python 2.3.2-1 and Windows 2000 SP4 What Cygwin, Python, Windows versions are you using? Have you tried a recent Cygwin snapshot? Some pthread bugs have been fixed since 1.5.5-1. > No problems directly under Windows, What does the above mean? Under Win32 Python? Or, under cmd.exe? > What is wrong? Sorry, I don't know. 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 CousinStanley at hotmail.com Wed Jan 7 08:07:23 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 7 Jan 2004 06:07:23 -0700 Subject: compileall binaries don't run!? References: <798d4337.0401062132.1e82ee65@posting.google.com> Message-ID: | ... | And the output looks fine, resulting in a bunch of pyc files. | | Then I try running the pyc file eg.: | | /home/me/mySourceDir/doodad.pyc | | But get the following error: | bash: ./doodad.pyc: cannot execute binary file Daniel .... As the .pyc files are not stand-alone executables, you might try passing the path of the compiled file to the Python interpreter .... python /home/me/mySourceDir/doodad.pyc -- Cousin Stanley Human Being Phoenix, Arizona From mcfletch at rogers.com Sun Jan 25 17:49:37 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 25 Jan 2004 17:49:37 -0500 Subject: MySQL insert query problem In-Reply-To: References: Message-ID: <40144801.3010305@rogers.com> Did you by any chance declare the field to be 19 characters wide when creating the database? Truncating to the length of the field is, I think, normal SQL practise. Just a thought, Mike Lol McBride wrote: ... >varchar field in a database I'm using. The query being sent to the MySQL >server by my program is : INSERT INTO analysis (DrawNumber,pool1)VALUES >(847, ' (4, 8, 21, 24, 39, 44) ' ) ; > >But the field pool1 actually contains (4, 8, 21, 24, 39, i.e it is >missing the final digits ( 44 ) > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mark at mceahern.com Sun Jan 18 12:46:42 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 18 Jan 2004 11:46:42 -0600 Subject: xml.dom.minidom childnodes In-Reply-To: <400abcab$0$780$ba620e4c@news.skynet.be> References: <400abcab$0$780$ba620e4c@news.skynet.be> Message-ID: <1074448002.18656.33.camel@dev.internal> On Sun, 2004-01-18 at 11:04, Vincent De Baere wrote: > As you can see in the xml file, there is a newline after the (root) > documentelement. I guess that's why I need to use menurootchildren[1] > instead of menurootchildren[0] to access the first child. Why not use getElementsByTagName and punt on the whole variable whitespace as childNodes business? Cheers, // m From FBatista at uniFON.com.ar Fri Jan 30 13:21:11 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 30 Jan 2004 15:21:11 -0300 Subject: PEP 327: Decimal Data Type Message-ID: Stephen Horne wrote: #- My concern is that many people will use a decimal type just #- because it #- is there, without any consideration of whether they actually need it. Speed considerations are raised. You'll *never* get the performance of using floats or ints (unless you have a coprocessor that handles this). #- I don't know what the solution should be, but I do think it needs to #- be considered. (In my dreams) I want to "float" to be decimal. Always. No more binary. Maybe in ten years the machines will be as fast as is needed to make this posible. Or it'll be implemented in hardware. Anyway, until then I'm happy having decimal floating point as a module. . Facundo From bobx at linuxmail.org Thu Jan 15 19:50:35 2004 From: bobx at linuxmail.org (Robert) Date: Fri, 16 Jan 2004 00:50:35 GMT Subject: wxPython worries In-Reply-To: References: Message-ID: What is needed is a good "Programming wxPython"! From http Tue Jan 6 19:09:13 2004 From: http (Paul Rubin) Date: 06 Jan 2004 16:09:13 -0800 Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> Message-ID: <7xd69wy5zq.fsf@ruckus.brouhaha.com> Ville Vainio writes: > Paul Rubin writes: > > > > The above code works, but I don't like making two read() calls. Any > > > way to avoid it, or a more elegant syntax? Thanks. > > > > You can make it even uglier: > > > > f = file(filename, 'rb') > > while 1: > > data = f.read(1024) > > if len(data) <= 0: > > break > > someobj.update(data) > > f.close() > > > > There's been proposals around to add an assignment-expression operator > > like in C, so you could say something like > > > > f = file(filename, 'rb') > > while len(data := f.read(1024)) > 0: > > someobj.update(data) > > f.close() > > It's funny, but I find the first version much more readable than the > second one. Especially if I consciously forget the "do lots of stuff > in condition part of while" indoctrination from C. If there is lots of > stuff in while you have to stare at it a bit more, and it becomes > "idiomatic", something you learn, perhaps even cookbook stuff, instead > of obvious-as-such. Idioms exist because they're useful, and there's already plenty of them in Python, like ''.join(stringlist) or "for i in xrange(n)" etc. Maybe the condition in the while statement makes that statement twice as hard to read. However, the example as a whole can still be easier, simply because it's shorter. Version 1: Statement Reading difficulty ========= ================== f = file(filename, 'rb') 1 while 1: 1 data = f.read(1024) 1 if len(data) <= 0: 1 break 1 someobj.update(data) 1 f.close() 1 Total reading difficulty: 7 Now the second version: Statement Reading difficulty ========= ================== f = file(filename, 'rb') 1 while len(data := f.read(1024)) > 0: 2 someobj.update(data) 1 f.close() 1 Total reading difficulty: 5 I got through college on a version of this reasoning. I was a math major. I had friends studying history and literature who said "that's a hard subject", but I thought they were crazy. But in a normal math class, there's one textbook that you use for the whole semester, and you cover maybe half the chapters in it. I was able to keep up. But in a literature course, you usually have to read a different entire book from cover to cover EVERY WEEK. I took a couple classes like that and barely survived. Yes, it takes a lot more effort to read a page of a math book than a page of a novel. When you compare the total reading load though, math was a much easier major than literature or history. It's the same with programs. I'd rather read 5 lines of tight code that each actually does something, than 3 pages of loose code (the kind that's usually written in Java) that spastically meanders trying to do the same thing, even if the individual loose lines are easier to read than the tight lines. From mhammond at skippinet.com.au Fri Jan 30 19:09:53 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 31 Jan 2004 11:09:53 +1100 Subject: pythonwin woes In-Reply-To: References: Message-ID: oliver wrote: > Hi, > > I am trying my hands on the latest verion of pythonwin extension with > python 2.3.3 , and run into *semi-fatal* problem: the run command > ignores the modifications I made to the source code, and *always* > show me results given by that outdated source: it feels like it just > use that cached .pyc!!! > > I wonder if the other pythonwin users had experienced the same > problem, or did I miss anything here. There is no such problem in IDLE > though. The difference will be that Pythonwin runs all programs "in process". When you run a program for the second time, all of the 'import' statements are still using the same module they imported before. The solution is generally to *reload* the modules you change, before you run the main script. Pressing Ctrl+I will do that for you - it will reload the module if it was previously imported. After doing that, your main script should see the new modules. IDLE runs all programs in a new, external Python process, so never sees this issue. In lots of ways, I like the way Pythonwin does it - keeping that state around can be very useful - eg, after the program has terminated, you can still see the objects etc. Mark. From EP at zomething.com Sat Jan 3 02:01:15 2004 From: EP at zomething.com (EP) Date: Fri, 02 Jan 2004 23:01:15 -0800 Subject: Speed? In-Reply-To: Message-ID: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> On questions of the suitability of Python for CGI, embedded apps, etc., execution speed comes to mind. I previously read some comparisons which did not show Python in a good light in this regard: i.e. Python is slow compared to Perl, C++, Java. http://www.flat222.org/mac/bench/ Is there more authoritative and current information IRT speed comparisons? Is newer Python any faster? Also, if Python is a bit slower in execution than some alternative languages, what do others do in practice to speed it up, and how much of that optimization do they do? Or is a slower speed to be accepted like one learns to accept that their lovely bride takes a long time getting ready to go out ? TIA, Eric P.S. I tried to replicate the simple "console test" with Python 2.3 on my PC. Using the Windows command prompt, on a reasonably modern PC (128MB RAM, 1.3 AMD chip), I clocked 72.45 seconds to print the numbers up to 999,999, which is more than 3x as long as the results reported in the link given. Then running the same program out of IDLE I clocked 627.48 seconds printing the numbers only up to 99,999. Perhaps that's a caution about launching any large processes out of IDLE? Here's the test script: import time def loop_time(): start=time.time() for x in xrange(1000000): print x end=time.time() exectime=end-start return exectime nada=raw_input('Press return when ready') run=loop_time() print 'Timed loop ran for: '+str(run)+' seconds' From crawley.storm.nospanatallever at ntlworld.com Thu Jan 29 18:00:16 2004 From: crawley.storm.nospanatallever at ntlworld.com (Crawley) Date: Thu, 29 Jan 2004 23:00:16 +0000 Subject: win32com support Message-ID: Im trying to produce a small Visual Studio Addin. Taking the OutlookAddin example and changing the registry place it installs too, everything works ok. Examples in C++ show that in the OnConnection method I have to registry my commands and also pass an instance of my sub class of ICommands. The C code looks like this: IApplication* pApplication = NULL; pApp->QueryInterface(IID_IApplication, (void**) &pApplication) CCommandsObj::CreateInstance(&m_pCommands); m_pCommands->AddRef(); m_pCommands->SetApplicationObject(pApplication); pApplication->SetAddInInfo((long) AfxGetInstanceHandle(), (LPDISPATCH) m_pCommands, -1, -1, m_dwAddin)); So far Im trying something like this: self._command = VCCmd(application) application.SetAddInInfo(AfxGetInstanceHandle(), self._command, - 1, -1, addin ) with VCCmd defined like: class VCCmd: _com_interfaces_ = ['_ICommands'] _public_methods_ = [] _application = None def __init__( self, app ): self._application = app print "VCCmd __init__" Needless to say, its not working, so questions. 1) AfxGetInstanceHandle dosent appear to exist in the win32api... so how do I call it. 2) am I defining VCCmd correctly to be a subclass of ICommands 3) am I correct in thinking i dont have to explicitly 'cast' application into an IApplication instance Many thanks for any light you may be able to shed on the subject Rich From adim at logilab.fr Tue Jan 27 12:34:07 2004 From: adim at logilab.fr (Adrien Di Mascio) Date: Tue, 27 Jan 2004 17:34:07 +0000 (UTC) Subject: descriptors and old-style classes Message-ID: Hi, I've recently discovered that descriptors can be used with old-style classes if they don't define a __set__ method (and this would be why class and static methods are usable with old-style classes). I understand why the __set__ method is not called with old-style classes, but I don't understand why __get__ *is* called. I thought the transformation from : a.x into : type(a).__dict__['x'].__get__(a, type(a)) was done in object.__getattribute__ (or type.__getattribute__), but then this does not explain why this also seems to work with old-style classes. Could someboby help me here ?? Cheers, Adrien. -- Adrien Di Mascio LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From usenet_spam at janc.invalid Fri Jan 9 15:28:42 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 09 Jan 2004 20:28:42 GMT Subject: Python Utils - A simple config file parser and output object References: <8089854e.0401070044.1e8116ad@posting.google.com> <8089854e.0401090212.4826925d@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) schreef: > I have to use google groups to post these messages as our work > firewall block nntp.... I'm thinking of building a newsgroup reader > that uses google groups via http but provides a better interface... > anyone interested ?? Some news servers allow connections on port 80 or other alternatives. (The free news.readfreenews.net server does, but it doesn't allow posting,) Also comp.lang.python is linked to the python mailing list: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From cookedm+news at physics.mcmaster.ca Sun Jan 11 18:03:10 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 11 Jan 2004 18:03:10 -0500 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: At some point, Samuel Walters wrote: > > Whether one uses Fortran, Python, or any other language, all primitives > are eventually implemented in either C or assembly. At some point or > another, we end up scraping bare metal and silicon to get our answers. > The question then becomes, "How easily can I extend this language to fit > my needs." NumPy is evidence that at least a few people said "Easily > enough." I don't know how extensible Fortran is, but I would guess "very" > since I've heard of it being applied in many domains other than numerical > processing. (OpenFirmware, for example.) You're confusing Fortran with Forth, which is a stack-based language, much like Postscript, or RPL used on HP 48 calculators. These days, I doubt Fortran is used for anything but numerical processing. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newz at wilcomm.net.NOSPAM Thu Jan 1 07:16:43 2004 From: newz at wilcomm.net.NOSPAM (Wil Schultz) Date: Thu, 01 Jan 2004 04:16:43 -0800 Subject: Where to go from here? newbee In-Reply-To: References: Message-ID: If you are sure you're up to it, here's a good place to start... http://www.ibiblio.org/obp/thinkCSpy/ Wil my 2? "When everything seems to be going well, you have obviously overlooked something." Richard wrote: > Just downloaded python for the fun of it. > What do I run to begin coding with? > Version 2.3.3 > > When I run the "command line" thing, I get a dos window. > Now what? > > The built in tutor explains some basics about programming but zilch on where > to begin. > > > BTW, you have 357 days left to do your christmas shopping. > > > From michele.simionato at poste.it Sun Jan 25 05:51:41 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 25 Jan 2004 02:51:41 -0800 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: <95aa1afa.0401250251.30810821@posting.google.com> xah at xahlee.org (Xah Lee) wrote in message news:<7fe97cc4.0401242131.22acf485 at posting.google.com>... Please, at least don't cross-post (and don't make me to cross post). _____________________ /| /| | | ||__|| | Please do not | / O O\__ | feed the | / \ | Trolls | / \ \|_____________________| / _ \ \ || / |\____\ \ || / | | | |\____/ || / \|_|_|/ | _|| / / \ |____| || / | | | --| | | | |____ --| * _ | |_|_|_| | \-/ *-- _--\ _ \ | || / _ \\ | / ` * / \_ /- | | | * ___ c_c_c_C/ \C_c_c_c____________ From james at logicalprogression.net Thu Jan 15 09:13:27 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 15 Jan 2004 14:13:27 +0000 Subject: TUPLE & LIST In-Reply-To: <%7xNb.55$Uw3.50@newsr2.u-net.net> References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <200401151413.28003.james@logicalprogression.net> On Thursday 15 January 2004 2:08 pm, Yomanium Yoth Taripo? II wrote: > HI, > > 1) what are the differences between list and tuple? > 2) how to concatenate tuple and list? no method, no op?ator? > 3) im looking the fucking manual, and cant add value in my tuple, when it > already created :/ > how to do it? > > thx. 3) is your answer to 1) ! -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ From mxlaym009 at hotmail.com Sun Jan 11 18:39:20 2004 From: mxlaym009 at hotmail.com (M. Laymon) Date: Sun, 11 Jan 2004 23:39:20 GMT Subject: Python installation breaks Outlook Express Message-ID: I just installed Python 2.3.3 under Windows XP professional. After I did, my wife tried to access her email using Outlook Express and got the error messages: Your server has unexpectedly terminated the connection. Possible causes for this include server problems, network problems, or a long period of inactivity. Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net', Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F Your server has unexpectedly terminated the connection. Possible causes for this include server problems, network problems, or a long period of inactivity. Account: 'incoming.verizon.net', Server: 'incoming.verizon.net', Protocol: POP3, Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F (No comments about Outlook, please.I have tried to get her to use a different email program, but she likes Outlook.) I checked the settings, then recreated her account in Outlook, but nothing worked. My Mozilla Thunderbird email client worked fine. Since the only thing I had done recently was to install Python. I used system restore to go back to the point before installing Python. After I did, Outlook started working again. Has anyone else seen this behavior ? Thanks. M. Laymon From luszczek1 at netscape.net Sat Jan 3 22:47:56 2004 From: luszczek1 at netscape.net (luszczek1 at netscape.net) Date: Sat, 03 Jan 2004 22:47:56 -0500 Subject: Advanced (?) compiling, freezing, translating Python Message-ID: <312735AC.3841CC26.0331AA34@netscape.net> Hi, here's my problem: - I know it will take me 10 times as long to write a code in C than in Python - I need the speed of the C version - my program cannot depend/require on Python interpreter/libraries/modules Is there a way to write Python program that almost looks like (say) C and then transoform it into C. Transformation should be intelligent - I don't want dynamic objects with dictionaries of methods. I'm willing to provide type descriptions so when I say: myList = [0] * 100 I get in C: int *myList; myList = calloc(100, sizeof(int)); I'm aware of projects like Pyrex, Psyco, and Pypy but their scope is too broad: they are about Python in its entirety and dynamism. There was also discussion some time back about adding static typing to Python. This is not what I'm thinking about either. I gave C as an example, but what I meant was translating Python into another language with some additional guidance (command-line optons or "header files"). I believe that Python is rich enough to express most of semantics of most of languages. For example, C++ templates are included in Python by default: In Python: def sum(aList): v = 0 for e in aList: v += e In C++: template sum(Vector aList) {...} In case anybody would care, even primitive data types from C/C++ like float, short, etc. can be emulated in Python with array module. I don't see equivalence to C++ reference, value, and pointer semantics, but most folks can live without it. Does anything like this exist? Would anybody find it useful? With compiler module now in standard Python, it seems like an easy job. Or am I missing something? Peter __________________________________________________________________ New! Unlimited Access from the Netscape Internet Service. Beta test the new Netscape Internet Service for only $1.00 per month until 3/1/04. Sign up today at http://isp.netscape.com/register Act now to get a personalized email address! Netscape. Just the Net You Need. From tim at remove_if_not_spam.digitig.co.uk Sun Jan 11 18:45:48 2004 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Sun, 11 Jan 2004 23:45:48 +0000 Subject: Division oddity Message-ID: If I do from __future__ import division then eval(1/2) gives me 0.5 as expected. But if I do print input("enter a sum: ") and enter 1/2 as the sum I get 0 as if I hadn't done the import. I thought input was supposed to give the same behaviour as an eval on raw input -- why the difference here? From jepler at unpythonic.net Thu Jan 8 17:06:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 8 Jan 2004 16:06:54 -0600 Subject: Strings with null bytes inside sqlite In-Reply-To: References: Message-ID: <20040108220654.GE14102@unpythonic.net> It depends on the structure of the string, but using s.encode("string-escape") / e.decode("string-escape") may give better performance and better storage characteristics (if your data is mostly ASCII with a few NULs included). If chr(0) is the only problem value, then creating your own encoder/decoder may be better, translating '\0' -> '\\0' and '\\' -> '\\\\'. Jeff From tim.one at comcast.net Mon Jan 12 10:45:56 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 12 Jan 2004 10:45:56 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401120658.5b9ee522@posting.google.com> Message-ID: [Aaron Watters] > Reading the blog it seems you are right. I wish zodb would be > a bit more careful in its claims. When you say "zodb supports > the ACID properties of transactions" this has a precise meaning > which vanishes when you redefine all the letters. I haven't made a claim about what ZODB does, I've just pointed you to what others have said about it. I'm not sure what you're referring to here, but guess it's probably taken from: http://zope.org/Wikis/ZODB/FrontPage/guide/node3.html If so, the meanings it intends for each letter are given there. I don't think its Isolation means that two programs or threads running in two different transactions cannot see each other's changes until they commit their transactions. misrepresents what ZODB does. > In particular it suggests that zodb would be good for something > like an accounting or banking application which would require strict > transaction isolation (serializability). The looser definition > could lead to fairly unpleasant difficulties (law suits, jail > time...). Sorry, had to complete my thought on clp. Would the text above imply "strict transaction isolation (serializability)" to such a programmer? If so, it probably ought to change. From M.Boeren at guidance.nl Mon Jan 19 07:44:11 2004 From: M.Boeren at guidance.nl (Marc Boeren) Date: Mon, 19 Jan 2004 13:44:11 +0100 Subject: Oracle to Mysql, I'm (still) lost... Message-ID: <7BE0F4A5D7AED2119B7500A0C94C58AC3D6F0C@DELLSERVER> Hi, instead of > cursMy.execute("insert into %s values %s", (tabel, a_oracle)) Try: sql = "insert into "+ tabel +" values (" comma = "" for value in a_oracle: sql+= comma + "%s" comma = ", " sql+= ")" or better: sql = "insert into %s values (" % tabel sql+= ", ".join(["%s"] * len(a_oracle)) sql+= ")" cursMy.execute(sql, a_oracle) which does the same thing. Your original sql-statement looked (for the execute call) like it needed two (sql-style)parameters, when in fact it needs as much parameters as there are fields in the table. And, the table-name is not an sql-parameter, it is just something that needs filling in... Hope this helps, Cheerio, Marc. From skchim0 at engr.uky.edu Sun Jan 25 22:20:12 2004 From: skchim0 at engr.uky.edu (satish) Date: Mon, 26 Jan 2004 03:20:12 +0000 Subject: Too many indices Message-ID: <200401260320.12070.skchim0@engr.uky.edu> Hi all, I tried to run a small script when I got the following IndexError. Can someone help me in explaining this error ? Traceback (most recent call last): File "satish.py", line 36, in ? mesh = Mesh(db['x'], db['y'], db['z']) File "/usr/lib/python2.2/site-packages/LESTool/CFD_database.py", line 208, in __getitem__ self.readCoords() File "/usr/lib/python2.2/site-packages/LESTool/CFD_database.py", line 239, in readCoords self.data[cgns.x] = MA.array(self.data['coordinates'][0,:,:,:]) IndexError: too many indices Thanks Regards, Satish -- SATISH KUMAR CHIMAKURTHI Graduate Teaching Assistant CFD GROUP UNIVERSITY OF KENTUCKY LEXINGTON KENTUCKY - 40508 Email: skchim0 at engr.uky.edu Mobile: 859-312-8425 From deets_noospaam at web.de Sun Jan 4 08:11:22 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 04 Jan 2004 14:11:22 +0100 Subject: how to make a code object a function Message-ID: Hi, I've got code objects that are created from strings at runtime that look like this: def p_op1(_, args): _.add_dependency('p_op1') As you migth guess, p_op1 is supposed to become an instance method. Now how do I make this code object a function-object that can be set into the instances __dict__ to make it a callable method? Thanks for any advice, Diez B. Roggisch From peter at engcorp.com Tue Jan 27 17:41:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Jan 2004 17:41:32 -0500 Subject: makeExe.py References: <4016E237.97F88A36@engcorp.com> Message-ID: <4016E91C.8F3FE795@engcorp.com> Also just stumbled across this, which works in a similar fashion (faking the sys.argv list before calling setup() directly. ftp://pygame.org/pub/pygame/pygame2exe.py (This one is customized for pygame programs, but might give you some good ideas too.) -Peter From ralph at sluiters.de Wed Jan 7 01:59:32 2004 From: ralph at sluiters.de (Ralph Sluiters) Date: Wed, 7 Jan 2004 07:59:32 +0100 Subject: Problem: 'Threads' in Python? References: Message-ID: You did everything, but not answer my question. I know what cookies are, but I don't need cookies here. And you said in your answer "start background process", that was my question. How can I start a background process. But I've solved it now, Ralph From jepler at unpythonic.net Thu Jan 29 12:00:38 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 29 Jan 2004 11:00:38 -0600 Subject: isinstance() bug In-Reply-To: References: Message-ID: <20040129170037.GF18498@unpythonic.net> On Wed, Jan 28, 2004 at 09:08:00PM +0100, Michs Vitecek wrote: > On Wed, 28 Jan 2004 11:32:19 -0600 Skip Montanaro wrote: > >You need to compare inode numbers to see if you have the same or different > >files. > > > > >>> import stat > > >>> os.stat(a.__file__)[stat.ST_INO] > > 37041L > > >>> os.stat(b.__file__)[stat.ST_INO] > > 37041L > > > > this could also be used to verify whether the imported module, class etc. > comes from the same file without messing with the absolute path and > problems related to it. really a good idea, Skip. I'd have to come out on the -1 side. First, because it adds complications to the interpreter simply to notify a programmer of an avoidable problem that should be caught by testing. Second, I'm not convinced that you won't create some other kind of problem through cleverness. For instance, it's perfectly legitimate to use module-level variables to hold state, and it's perfectly legitimate for two packages to both contain the same sub-package (for instance, of modules A and B both use the same non-standard module, they can bundle it inside their respective namespaces). But on systems with a small read-only filesystem, it's also perfectly legitimate to make these two copies of the same file actually hard-links to the same file. You've just broken this arrangement. Third, I'm not convinced that using inode numbers is guaranteed to work. In Unix, it at least needs to be the tuple (inode, device), because the same inode number can appear on multiple devices. Are you sure that Python will *never* encounter a system with a bug or limitation that can make two different files return the same inode number from os.stat()? (for instance, if an NFS server uses a 64-bit-inode filesystem but must generate 32-bit inodes for clients because of NFS protocol limitations; or if a filesystem doesn't really have the concept of an inode number, like FAT/VFAT filesystems) Fourth, what is the "inode" or "device" of a module loaded from a ZIP archive (possible in Python today), or from a URL (possible with the right import hook, though probably a bad idea)? Fifth, will it work right if the 'a.m' and 'm' refer to the same file, but the sequence of actions look like this in the interactive console: >>> import a.m # edit m.py in an editor, save >>> import m The editor session might change the inode of m.py, meaning that m is not a.m. Or, if not, then it will see that a.m is the same as m, so the imported m will not contain the changes from the editor session. Sixth, will it work right in the presence of reload()? >>> import a.m >>> import m # edit m.py here, and assume there is no inode number change >>> reload(a.m) Is m reloaded too? What is "correct" in this case? So I guess that makes me at least -6 if I get a vote for each problem I can imagine. Jeff From ogger at ya.com Fri Jan 2 14:56:01 2004 From: ogger at ya.com (Ogger) Date: 2 Jan 2004 11:56:01 -0800 Subject: Firing events in local server (CLSCTX_LOCAL_SERVER) Message-ID: <56536fdf.0401021156.1c71986b@posting.google.com> Hello, I'm trying to develop a COM local server with python using Mark Hammond's win32 extensions, but I have problems when I want to fire an event. The COM server has a worker thread and I want to fire an event from this worker thread passing an argument to the event that is another automation server (served from the same local server). The error message is (translated from spanish): Ignoring COM error to connection. - -2147417842, The application called an interface that was in a buffer for a different subprocess. I have tried many options, like: changing in win32com/server/localserver.py the property sys.coinit_flags to CLSCTX_LOCAL_SERVER, using CoMarshalInterThreadInterfaceInStream to pass the interface to the worker thread, without success. Can anybody explain me what is happen? From webmaster at beyond-thoughts.com Sun Jan 11 04:07:15 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Sun, 11 Jan 2004 10:07:15 +0100 Subject: PRE-PEP: new Path class; more links In-Reply-To: References: Message-ID: <40011243.1060404@beyond-thoughts.com> I've found some links that might be interresting. http://www.w3.org/2000/10/swap/uripath.py http://dev.w3.org/cvsweb/2000/10/swap/uripath.html?rev=1.9 [the doc for it] Links of the operator.attrgetter / "groupby" iterator discussion in python-dev (Jp Calderone posted a hint on it already --- I chose some exemplary posts) http://mail.python.org/pipermail/python-dev/2003-December/040614.html http://mail.python.org/pipermail/python-dev/2003-December/040628.html http://mail.python.org/pipermail/python-dev/2003-December/040643.html Christoph Becker-Freyseng From jcarlson at uci.edu Tue Jan 20 17:04:10 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 14:04:10 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> Message-ID: <20040120135921.1C3F.JCARLSON@uci.edu> > The instructions that came with SpamBayes says it. THey say to either run > the setup.py file in the Python GUI (IDLE) or froma command prompt. I have > tried both to no avail... If you are in windows and your associations are correct, try: setup.py install - Josiah From seefeld at sympatico.ca Wed Jan 7 03:02:10 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 07 Jan 2004 03:02:10 -0500 Subject: debugging memory management via C API Message-ID: <3FFBBD02.3010501@sympatico.ca> hi there, I'm writing some C python extension and I'd like to debug the memory management, i.e. run some tests to see whether I did the ref counting correctly, etc. What's the suggested way to do that via the C API ? Is there some function which I could call at the very end of an application that will collect some statistics about the memory (de)allocations done associated with PyObject construction/destruction ? Thanks, Stefan From jepler at unpythonic.net Tue Jan 20 18:50:36 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Jan 2004 17:50:36 -0600 Subject: always the same object In-Reply-To: References: Message-ID: <20040120235036.GA27049@unpythonic.net> If you included some code, maybe we'd be able to help you. >>> struct.unpack("2i", " "*8) (538976288, 538976288) struct.unpack returned a tuple. The tuple happens to be immutable, and all the things it contains are immutable. So there's no way to change ever change the value of this object. As far as I know, this would be true for any struct format you care to choose. (You could change the "value" of an immutable object if it contains some mutable objects, like this: a = ([],) b = ([],) assert a == b a[0].append(0) assert a != b a and b go from equal to unequal, even though a and b are both immutable) Jeff From theller at python.net Wed Jan 7 09:19:36 2004 From: theller at python.net (Thomas Heller) Date: Wed, 07 Jan 2004 15:19:36 +0100 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> Message-ID: <65fnon7r.fsf@python.net> Jacek Generowicz writes: > I always wonder whether I should post concise articles, or wordy ones, > covering all possbile assumpitons and misconceptions. > > It appears that, usually, I get the balance hopelessly wrong :-( Or, > Note, I did NOT say "How do I ...", I said "Where do I find > [...] documentation ...". [...] > I am NOT interested in a recipe posted here. I want to know where to > find the official instructions on how it is done, so that I can show > newbies how to find the information themselves. > > "Give a man a fish, and he can eat for a day. Teach a man to fish ...", > and all that. > > If these instructions are, as it seems, absent, then I would > appreciate advice on what I can do to make them appear in the > appropriate place, and what the appropriate place might be. So why don't you try to find out yourself??? Thomas From carroll at tjc.com Fri Jan 9 14:48:39 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri, 09 Jan 2004 19:48:39 GMT Subject: Unicode and exception strings References: Message-ID: <291uvv8qajta6n5qum3c6mtq8nhlrh9puu@4ax.com> On Fri, 09 Jan 2004 19:44:21 GMT, Terry Carroll wrote: >In one program I have that occasionally runs into a line that includes >some (UTF-8) Unicode-encoded Chinese characters , I have something like >this: Sorry, a stray parenthesis crept in here (since this is a pared down version of my actual code). It should read: try: _display_text = _display_text + "%s\n" % line except UnicodeDecodeError: try: # decode those UTF8 nasties _display_text = _display_text + "%s\n" % line.decode('utf-8') except UnicodeDecodeError: # if that still doesn't work, punt # (I don't think we'll ever reach this, but just in case) _display_text = _display_text + "%s\n" % repr(line) > I don't know if this will help you or not. From ville.vainio at spamster_tut_remove.fi Tue Jan 6 16:52:30 2004 From: ville.vainio at spamster_tut_remove.fi (Ville Vainio) Date: 06 Jan 2004 23:52:30 +0200 Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > > The above code works, but I don't like making two read() calls. Any > > way to avoid it, or a more elegant syntax? Thanks. > > You can make it even uglier: > > f = file(filename, 'rb') > while 1: > data = f.read(1024) > if len(data) <= 0: > break > someobj.update(data) > f.close() > > There's been proposals around to add an assignment-expression operator > like in C, so you could say something like > > f = file(filename, 'rb') > while len(data := f.read(1024)) > 0: > someobj.update(data) > f.close() It's funny, but I find the first version much more readable than the second one. Especially if I consciously forget the "do lots of stuff in condition part of while" indoctrination from C. If there is lots of stuff in while you have to stare at it a bit more, and it becomes "idiomatic", something you learn, perhaps even cookbook stuff, instead of obvious-as-such. > but that's the subject of holy war around here too many times ;-). Don't > hold your breath waiting for it. Probably true. Instead of ":=", I wouldn't mind getting rid of expressions/statements difference as a whole. -- Ville Vainio http://www.students.tut.fi/~vainio24 From jepler at unpythonic.net Tue Jan 13 16:01:57 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 13 Jan 2004 15:01:57 -0600 Subject: Does anyone else not find the fun in programming...? In-Reply-To: References: Message-ID: <20040113210157.GD6601@unpythonic.net> >>> "fun" in "programming" 0 # DANGIT >>> "programming".find("fun") -1 # ARGARGHARGH >>> "programming".index("fun") ValueError: substring not found in string.index # F***! >>> assert "programming" is "fun" AssertionError # I'm going home Jeff From gerrit at nl.linux.org Thu Jan 29 15:57:38 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 29 Jan 2004 21:57:38 +0100 Subject: read() on tempfile In-Reply-To: References: Message-ID: <20040129205738.GA2867@nl.linux.org> cherico wrote: > from tempfile import * > > f = NamedTemporaryFile () > f = write ( 'test' ) > print f.read () #here print nothing Strange, it should raise an Exception. I guess you typed it over? 'write' should give a NameError. You want to do f.write, not f=write. After that, you first want to seek to 0. Gerrit. -- 268. If any one hire an ox for threshing, the amount of the hire is twenty ka of corn. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From reply.in.the.newsgroup at my.address.is.invalid Thu Jan 8 17:56:55 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 08 Jan 2004 23:56:55 +0100 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> Message-ID: <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> broebel: >first problem is the fact that I started out with a little program who was >part of a course but the problem is when I launch the program. I don't have >the time to see the result because the screen closes immediately. >Can anyone explain what's happening. The program started, did what it had to do and then terminated :-) "1 How do I run a Python program under Windows?" http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-under-windows -- Ren? Pijlman From nid_oizo at yahoo.com_remove_the_ Mon Jan 12 13:46:33 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 12 Jan 2004 13:46:33 -0500 Subject: Why learn Python ?? In-Reply-To: <40029dad$0$28706$a729d347@news.telepac.pt> References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Bicho Verde wrote: > Anyone would help me and give me some hints? - C# is like a MS-specific Java. - C++ is for system programming where performance is important. I love C++ but I think it was Herb Sutter (a C++ guru) who described C++ as a "last resort language" and I must agree. - Perl is also a very nice language, but I would suggest to basically see it as a parsing language and Perl 6 will make perl even better in that domain with built-in support for grammars. And knowing a parsing language is a very good thing. However, for other than that, even if Perl has all the functionality, Python is cleaner, simpler and more structured and elegant. If you're interested in AI, I strongly suggest to look at functional languages like Lisp dialects. Don't be afraid to learn many languages, that's the way you will learn what is strong about each of them, and that we basically need them all;) Regards, Nicolas From ohgoddearlord at yahoo.com Tue Jan 6 13:45:59 2004 From: ohgoddearlord at yahoo.com (John) Date: 6 Jan 2004 10:45:59 -0800 Subject: os.system always opens new window on Windows XP/2000 Message-ID: Can anyone tell me how to run a bunch of commands in the same command line window? When I do this: system("command1") system("command2") ... it opens a new window for every system call. The alternative I can think of is to write out the command to a batch file and run that, but I'm wondering if there is a better way to do it. Partly it is annoying to have 20 cmd windows flash on the screen, but also I don't think it works if I do something like this: system("set envvar=hi") since I think the envvar does not persist once the command window is closed. thanks! From tzot at sil-tec.gr Sat Jan 10 12:33:16 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 10 Jan 2004 19:33:16 +0200 Subject: Yet another RE question References: Message-ID: On Sat, 10 Jan 2004 10:36:07 +0200, rumours say that "Bogdan Marinescu" might have written: [snip: this is about a simple compiler of a small language, and Python follows Perl re symantics instead of POSIX: a|ab always matches 'a' even if 'ab' would match in the search string] >This is quite annoying for me; while some solutions to this problem exists and they are shown in the Spark documentation, I have some background with lex/yacc and I would really like to use the "lex" semantics (longest match). Is there a package for Python that implements this behaviour? AFAIK no, there is no such package. However, you can do the following things: - reorder alternations (sp?) to be longest first Substitute "ab|a" for "a|ab" - the (?!...) operator might help The re "if(?![a-z_0-9])" would match the 'if' and would ignore all identifiers starting with 'if'. HTH. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From FBatista at uniFON.com.ar Wed Jan 28 14:44:41 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 28 Jan 2004 16:44:41 -0300 Subject: FRE: PEP 326 is D-E-A-D (was Re: How does compare work?) Message-ID: Aahz wrote: #- >Even then, what about PEP 326, which presumes to define highest and #- >lowest objects that can be compared with anything? #- #- What about it? ;-) #- #- (Guido just posted a Pronouncement rejecting it.) Can't find it at http://www.python.org/doc/essays/pepparade.html I'm looking in the wrong place? Thanks. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From i18n-nb-admin at lister.ping.uio.no Mon Jan 26 19:35:09 2004 From: i18n-nb-admin at lister.ping.uio.no (i18n-nb-admin at lister.ping.uio.no) Date: Tue, 27 Jan 2004 01:35:09 +0100 Subject: Your message to i18n-nb awaits moderator approval Message-ID: <20040127003509.9901.40898.Mailman@cappuccino.ping.uio.no> Your mail to 'i18n-nb' with the subject HELLO Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From newsgroups at jhrothjr.com Tue Jan 20 11:31:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jan 2004 11:31:46 -0500 Subject: converting base class instance to derived class instance References: <930ba99a.0401200413.5fae6fb9@posting.google.com> Message-ID: <100qm0soklj3439@news.supernews.com> "Sridhar R" wrote in message news:930ba99a.0401200413.5fae6fb9 at posting.google.com... > Consider the code below, > > class Base(object): > pass > > class Derived(object): > > def __new__(cls, *args, **kwds): > # some_factory returns an instance of Base > # and I have to derive from this instance! > inst = some_factory() # this returns instance of Base > return inst # Oops! this isn't an instance of Derived > > def __init__(self): > # This won't be called as __new__ returns Base's instance > pass __new__ can return an instance of any class it pleases. It's not restricted to returning an instance of the class it happens to be in, nor is it restricted to returning a newly created instance, for that matter. It can do the entire construction job without using the __init__ method. However, I don't think that's the best solution. If your factory is going to return instances of several different classes, I think it's best that it be an explicit factory method or function, not something that magically happens in a class constructor. I'd rather not have to deal with programs where class constructors pass me instances of classes other than the one I'm calling. If you want to do a little bit of deep magic, a factory function can create an instance by calling object(), plug in whatever attributes it wants and then change the __class__ attribute to whatever class it wants before it returns the newly minted instance. It doesn't have to go near anything that resembles a constructor (other than calling object() to get a new instance, of course.) > The constraint is there is some factory function that creates an > instance of Base class. So I _can't_ call "Base.__init__(self)" in > Derived.__init__ func, as their will be _two_ instances (one created > by Derived.__init__ and other created by the factory function) > > Simply I want to get a derived class object, but instead of allowing > _automatic_ creation of Base instance, I want to use _existing_ Base's > instance, then use this as a Derived's instance. > > Will metaclass solve this problem? Wrong tool. Metaclasses are used to set up classes, not to set up instances. John Roth From lbates at swamisoft.com Thu Jan 29 11:19:47 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 29 Jan 2004 10:19:47 -0600 Subject: Printing/updating output to the screen References: <40192945$1@nntphost.cis.strath.ac.uk> Message-ID: Daniel, Here is an example progressbar class that I use in my programs. -Larry class progressbarClass: def __init__(self, finalcount): import sys self.finalcount=finalcount self.blockcount=0 self.block="*" self.f=sys.stdout # # If the final count is zero, don't start the progress gauge # if not self.finalcount : return self.f.write('\n------------------ % Progress -------------------1\n') self.f.write(' 1 2 3 4 5 6 7 8 9 0\n') self.f.write('----0----0----0----0----0----0----0----0----0----0\n') return def progress(self, count): if (count > self.finalcount): count=self.finalcount if (self.finalcount != 0) : percentcomplete=int(round(100*count/self.finalcount)) if (percentcomplete < 1): percentcomplete=1 else: percentcomplete=100 blockcount=int(percentcomplete/2) if (blockcount > self.blockcount): for i in range(self.blockcount,blockcount): self.f.write(self.block) self.f.flush() if (percentcomplete == 100): self.f.write("\n") self.blockcount=blockcount return if __name__ == "__main__": from time import sleep pb=progressbarClass(8) count=0 while count<9: count+=1 pb.progress(count) sleep(0.2) pb=progressbarClass(100) pb.progress(20) sleep(0.2) pb.progress(47) sleep(0.2) pb.progress(90) sleep(0.2) pb.progress(100) print "testing 1:" pb=progressbarClass(1) pb.progress(1) "Daniel Pryde" wrote in message news:40192945$1 at nntphost.cis.strath.ac.uk... > Hi there. I hope this isn't a stupid question to ask, but does anyone > know how to print out a string without moving to a new line each time > and simply updating the first line. An example would be, if I wanted to > have a percentage progress counter that was constantly updating. I'm > unsure how to do this without printing to a brand new line. Any help > would be greatly appreciated. Thanks. > > Daniel > From tim.one at comcast.net Sun Jan 11 13:30:29 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 11 Jan 2004 13:30:29 -0500 Subject: pydoc patch for Subversion In-Reply-To: <20040111090645.GA2398@omnifarious.org> Message-ID: [Eric Mathew Hopper] > I have a patch that allows pydoc to deal with Subversion > (http://www.subversion.tigris.org) style version strings. That's good, but please upload it to Python's patch manager: http://sf.net/tracker/?group_id=5470&atid=305470 Mailing lists, and Ping's inbox , are black holes for patches. From dallasm at aiinet.com Fri Jan 23 14:04:03 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Fri, 23 Jan 2004 14:04:03 -0500 Subject: Sending Through ^] Through telnetlib Message-ID: > "John Abel" wrote in message > news:mailman.687.1074866920.12720.python-> list at python.org... > > > I have written a script that makes a > telnet connection, runs various > > commands, and returns the output. That was the easy bit :) > However, to > > close the session, I need to send ^] followed by quit. I've tried > > sending chr(29), which is the ascii equivalent, but that > doesn't seem to > > work. Is there something I'm missing? > > > > Any pointers would be much appreciated. > > > > Thanks > > > > J > > > FYI the telnetlib (as of 2.2.1, not sure past that) does not support all telenet commands. If you want to send a special command, you need to access the raw socket and send the extened options list character and the command character. Ex: to send a Telnet BREAK telnetCon.get_socket().send(chr(255)+chr(243)) So maybe trying telnetCon.get_socket().send(chr(255)+chr(29)) Will work fo you? --- Dallas S. Mahrt> From danb_83 at yahoo.com Sat Jan 31 04:01:41 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 31 Jan 2004 01:01:41 -0800 Subject: PEP 327: Decimal Data Type References: Message-ID: Josiah Carlson wrote in message news:... > > (In my dreams) I want to "float" to be decimal. Always. No more binary. I disagree. My reasons for this have to do with the real-life meaning of figures with decimal points. I can say that I have $1.80 in change on my desk, and I can say that I am 1.80 meters tall. But the two 1.80's have fundamentally different meanings. For money, it means that I have *exactly* $1.80. This is because "dollars" are just a notational convention for large numbers of cents. I can just as accuately say that have an (integer) 180 cents, and indeed, that's exactly the way it would be stored in my financial institution's database. (I know because I used to work there.) So all you really need here is "int". But I do agree with the idea of having a class to hide the decimal/integer conversion from the user. On the other hand, when I say that I am 1.80 m tall, it doesn't imply that humans height comes in discrete packets of 0.01 m. It means that I'm *somewhere* between 1.795 and 1.805 m tall, depending on my posture and the time of day, and "1.80" is just a convenient approximation. And it wouldn't be inaccurate to express my height as 0x1.CC (=1.796875) or (base 12) 1.97 (=1.7986111...) meters, because these are within the tolerance of the measurement. So number base doesn't matter here. But even if the number base of a measurement doesn't matter, precision and speed of calculations often does. And on digital computers, non-binary arithmetic is inherently imprecise and slow. Imprecise because register bits are limited and decimal storage wastes them. (For example, representing the integer 999 999 999 requires 36 bits in BCD but only 30 bits in binary. Also, for floating point, only binary allows the precision-gaining "hidden bit" trick.) Slow because decimal requires more complex hardware. (For example, a BCD adder has more than twice as many gates as a binary adder.) > In my dreams, data is optimally represented in base e, and every number > is represented with a roughly equivalent amount of fudge-factor (except > for linear combinations of the powers of e). > > Heh, thankfully my dreams haven't come to fuition. Perhaps we'll have an efficient inplementation within the next 102.1120... years or so ;-) > While decimal storage is useful for...money Out of curiosity: Is there much demand for decimal floating point in places that have fractionless currecy like Japanese Yen? > Perhaps a generalized BaseN module is called for. People > could then generate floating point numbers in any base (up to perhaps > base 36, [1-9a-z]). If you're going to allow exact representation of multiples of 1/2, 1/3, 1/4, ..., 1/36, 1/49, 1/64, 1/81, 1/100, 1/121, 1/125, 1/128, 1/144, etc., I see no reason not to have exact representations of *all* rational numbers. Especially considering that rationals are much easier to implement. (See below.) > ... Of course then you have the same problem with doing math on two > different bases as with doing math on rational numbers. Actually, the problem is even worse. Like rationals, BaseN numbers have the problem that there are multiple representations for the same number (e.g., 1/2=6/12, and 0.1 (2) = 0.6 (12)). But rationals at least have a standardized normalization. We agree can agree that 1/2 should be represented as 1/2 and not -131/-262, but should BaseN('0.1', base=2) + BaseN('0.1', base=4) be BaseN('0.11', 2) or BaseN('0.3', 4)? The same potential problem exists with ints, but Python (and afaik, everything else) avoids it by internally storing everything in binary and not keeping track of its representation. This is why "print 0x68" produces the same output as "print 104". BaseN would violate this separation between numbers and their notation, and imho that would create a lot more problems than it solves. Including the problem that mixed-based arithmetic will require: * approximating at least one of the numbers, in which case there's no advantage over binary, or * finding a "least common base", but what if that base is greater than 36 (or 62 if lowercase digits are distinguished from uppercase ones)? From skip at pobox.com Mon Jan 5 07:07:13 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 5 Jan 2004 06:07:13 -0600 Subject: Is it bug or feature in sre? In-Reply-To: References: Message-ID: <16377.21361.749300.297850@montanaro.dyndns.org> >>> re.compile("(?P[A-Z]*)?") Roman> Traceback (most recent call last): ... Roman> sre_constants.error: nothing to repeat Roman> I wonder why I can't do this? Is there some reason why "(?P[A-Z]*)" or "(?P[A-Z]+)?" isn't sufficient? You specified the zero-or-more repetition inside the group. There's nothing else to have zero-or-one of. Roman> I guess it's of terrible style, but is this behaviour intentional Roman> or not? I suspect it's intentional, since Fredrik went to the trouble of raising an exception with a useful error message. Roman> Probably it is good idea to mention this in Python update path Roman> documents. Otherwise some old programs will mysteriously fail. What were you converting from, an older version of sre, pre, regex, or (shudder) regexp? Skip From robin at jessikat.fsnet.co.uk Mon Jan 12 04:18:26 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 12 Jan 2004 09:18:26 +0000 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Message-ID: In article <7xeku5vrn8.fsf at ruckus.brouhaha.com>, Paul Rubin writes >Tim Rowe writes: >> If I do from __future__ import division then eval(1/2) gives me 0.5 as >> expected. But if I do print input("enter a sum: ") and enter 1/2 as >> the sum I get 0 as if I hadn't done the import. I thought input was >> supposed to give the same behaviour as an eval on raw input -- why the >> difference here? > >The input function is calling eval from the context of the module >where 'input' itself is defined. If you use "from __future__ import >division" in module A and have "print 3/2" in module B, the value of >3/2 in module B shouldn't be affected by the input, since module B >may depend on integer division having the old behavior. > >The result is a little bit surprising at first glance though, so it >should probably be documented. I get this in pythonwin with 2.3.2 PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> from __future__ import division >>> eval('1/2') 0.5 >>> In python I get 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. >>> from __future__ import division >>> eval('1/2') 0.5 >>> so I guess pythonwin is broken in this respect. -- Robin Becker From exarkun at intarweb.us Fri Jan 9 19:57:40 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 9 Jan 2004 19:57:40 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: <3FFF26A1.943DEA84@engcorp.com> References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <20040110005740.GA4681@intarweb.us> On Fri, Jan 09, 2004 at 05:09:37PM -0500, Peter Hansen wrote: > Iwan van der Kleyn wrote: > > > > In other words: it would be nice if Python on average would run faster > > so the need for optimisation would lessen. > > I disagree with the above. My opinion has long been that Python runs > adequately fast and that few people should need to spend much time on > optimization. Maybe that sort of view should be put to the test. > > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) > No. Jp From lubowiecka at go2.pl Mon Jan 26 02:08:26 2004 From: lubowiecka at go2.pl (Sylwia) Date: 25 Jan 2004 23:08:26 -0800 Subject: problems with registering PythonService.exe Message-ID: Hi! I have the following problem :( After registering the "PythonService.exe" executable... C:\Python23\Lib\site-packages\win32>PythonService.exe -register I got the following error message: ============================================================================== "Registering the Python Service Manager... Fatal Python error: PyThreadState_Get: no current thread This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information." ============================================================================== What may be wrong ?:( I have win32all-157 installed on my computer... I will be grateful for any hints. Thank you in advance, Sylwia From support at more-it.net Wed Jan 28 16:30:47 2004 From: support at more-it.net (support at more-it.net) Date: Wed, 28 Jan 2004 22:30:47 +0100 Subject: Virus Alert Message-ID: <200401282130.i0SLUlS08708@securemail.more-it.net> The mail message (file: data.pif) you sent to john at orion.de contains a virus. (on securemail.more-it.net) From paradisejourney at hotmail.com Thu Jan 15 01:01:54 2004 From: paradisejourney at hotmail.com (aj) Date: 14 Jan 2004 22:01:54 -0800 Subject: best application framework for developing web application Message-ID: <14ba0c0.0401142201.68faebcf@posting.google.com> hi i am a newbi to python and developing a web application what do u all think is the best application framework for developing web application in python. I want a framework that supports templates,database connectivity, is available for both unix and windows ,and ofcourse is easy to learn. Zope Quixote Draco or others From maxk at NtOoSuPrAoM.edu Fri Jan 16 04:00:40 2004 From: maxk at NtOoSuPrAoM.edu (Maxim Khesin) Date: Fri, 16 Jan 2004 09:00:40 GMT Subject: SimpleXMLRPCServer Message-ID: Hi, the typical usage of SimpleXMLRPCServer registers some class with the server instance and then jumps into a serve-forever loop, e.g. server = SimpleXMLRPCServer(('', 8000)) server.register_instance(MyClass()) server.serve_forever() is there a way to process actions other than XML-RPC requests using SimpleXMLRPCServer? Is is possible to do something like server = SimpleXMLRPCServer(('', 8000)) server.register_instance(MyClass()) while(1) if(checkSomeCondidion()): server.serve_once() else: server.stop() thanks, max From oliver.schoenborn at utoronto.ca Wed Jan 21 13:31:01 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Wed, 21 Jan 2004 13:31:01 -0500 Subject: [Numpy-discussion] Status of Numeric References: Message-ID: "Paul Dubois" wrote in message news:mailman.533.1074574795.12720.python-list at python.org... > Having two array classes around is a terrible idea. Once you have two > popular array classes the entire world bifurcates. This plot package I second that vehemently. > I only suggested we do numarray because Numeric was, by general > agreement, unmaintainable. It was hard to work on and lacked the kind > of robustness necessary to get permission to put it in the core. We all > agreed Numeric would cease. Let's stick to the plan. However, I think experience has shown that users tend to go for better performance rather than better design. So why couldn't Numeric be redesigned for maintainability, but keep the algorithms that make it more performant than numarray? Does the interface need to change? Oliver From t-meyer at ihug.co.nz Tue Jan 20 22:37:11 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 21 Jan 2004 16:37:11 +1300 Subject: Installing SpamBayes In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1304BA3C39@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130467785B@its-xchg4.massey.ac.nz> [Josiah Carlson] > If you are in windows and your associations are correct, > try: setup.py install [Dog] > That didnt work either and the file assoc. are correct. In this sort of situation, it really helps to be more specific. What happened when you tried this? Did you get an error message? What was it? How do you know that the file associations are correct? Have you tried executing other python files? What version of Windows are you using? Is Python on your path? =Tony Meyer From skip at pobox.com Wed Jan 28 11:05:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 10:05:07 -0600 Subject: r prefix bug ... or my lack of understanding? In-Reply-To: References: Message-ID: <16407.56755.65025.785344@montanaro.dyndns.org> Bill> Thanks I looked at faqs.org did not see it. That's because the Python FAQ is not posted to this list/newsgroup. It's only available on the web. I think faqs.org just culls FAQs from postings. Skip From donn at u.washington.edu Wed Jan 14 12:34:07 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 14 Jan 2004 09:34:07 -0800 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> Message-ID: In article <100aq779r2h2c9e at corp.supernews.com>, claird at lairds.com (Cameron Laird) wrote: > In article , > Derek wrote: > . > . > . > >I also use C++ and Python as my main languages and I agree with your > >comments. However, I don't agree that Python is inherently "safer" > >than C++. At best I see it as a tie. For example, C++ let's you > >corrupt memory among other "unsafe" things, most of which can be > >avoided by using standard containers, smart pointers, etc. Python > >lets you do "unsafe" things such as passing an object to a function > >when it makes no sense to do so, which can lead to nasty runtime > >surprises. > > We disagree on some matters. > > I *do* regard Python as inherently safer than C++, and much more so. > My aim for now is not to persuade you to my view, but only to make > it explicit. Memory management, and mismanagement, as mundane as it > is, is so poorly applied in so much of the C++ code I see, that it > swamps all other dimensions of comparison between the two languages. > I quite agree with you that competent C++ programmers should exploit > smart pointers and so on. My experience is that, somehow, C++ as > it's generally practiced appears to have barriers to their use. > > I don't understand your last sentence, and, given my own focus on > reliability, I very much want to understand it. Are you alluding > precisely to Python's dynamic typing, and observing that, as earlier > is better, C++'s compile-type checks beat Python's run-time checks? Your wording is precise enough that your question could have been better. Note "compile type checks" vs. "run-time checks" - a difference not only in when, but what. There's more to it than "earlier is better". Donn Cave, donn at u.washington.edu From michael at foord.net Tue Jan 6 07:24:04 2004 From: michael at foord.net (Fuzzyman) Date: 6 Jan 2004 04:24:04 -0800 Subject: YAPLP - Yet Another Python Links Page Message-ID: <8089854e.0401060424.12465fcb@posting.google.com> As part of a python project I've been working on ( atlantibots - www.atlantibots.org.uk )I've collected Python and programming links.... for what it's worth I thought I'd make them publicly available.... http://www.voidspace.org.uk/coollinks/python_links.shtml 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.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. --- 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 http Tue Jan 13 14:41:20 2004 From: http (Paul Rubin) Date: 13 Jan 2004 11:41:20 -0800 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <400413E0.5C691A56@engcorp.com> <7xr7y3mzsl.fsf@ruckus.brouhaha.com> <400444A0.717BA7A3@engcorp.com> Message-ID: <7xk73vzlen.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > Python has no support for macros or aliases, and it would be silly > > to add some special kludge for input(). The user needs to be able > > to redefine the function and so forth too. > > Sure it does: > > def input(*args): > return eval(raw_input(*args)) For it to be an alias, that definition would have to be injected into the module that input is actually called from, not run in a separate module. How the heck does input get at the environment of its caller, anyway? Through the frame object chain? I guess the obvious fix is for the future division flag to be part of the environment, so evaling in the caller environment is done according to the flag. Someone has already checked a fix into sourceforge, but I haven't looked at it and don't know if it works that way or some other way. From gandalf at geochemsource.com Fri Jan 16 06:57:02 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 16 Jan 2004 12:57:02 +0100 Subject: Python Message-ID: <4007D18E.1040005@geochemsource.com> Is there a public list where we can bless, praise and vaunt the most advanced state-of-the-art programming language of the world? (Poetic question from a spirited Python believer) From alexander.dejanovski at laposte.net Wed Jan 21 05:53:45 2004 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Wed, 21 Jan 2004 11:53:45 +0100 Subject: Retic SOAP tester 0.2 released Message-ID: <5.1.0.14.2.20040121114749.02c426f8@127.0.0.1> Just released Retic SOAP tester 0.2. New features : SOAP messages exchanged are now pretty-printed and syntax-colored for better legibility. Downloads : http://sourceforge.net/projects/retic/ ================================================================================ Retic SOAP tester is a GUI tool written in Python (wxPython) that is capable of parsing WSDL files and sending SOAP requests without any programming. Retic SOAP tester comes into two distributions : win32 exe (thanks to py2exe) and Python src (wxPython 2.4 and PyXML 0.8.3 required). ================================================================================ Enjoy !! From tzot at sil-tec.gr Thu Jan 8 12:02:57 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 08 Jan 2004 19:02:57 +0200 Subject: Bits from Numbers. References: <3ffcb189$1@nntp0.pdx.net> Message-ID: On Wed, 07 Jan 2004 16:36:43 -0800, rumours say that sdd might have written: >I am whacking away at some code to view numbers as bit sequences. >While this is not complete, I'd appreciate some feedback from anyone >who is interested in looking at it: > http://members.dsl-only.net/~daniels/bits.html Is it similar to BitDecoder which you can find at the Python Package Index? http://www.python.org/pypi?:action=display&name=BitDecoder&version=0.5.1 If yes, perhaps you should contact its author and then co-operate on it. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jmdeschamps at cvm.qc.ca Sat Jan 3 16:39:42 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 3 Jan 2004 13:39:42 -0800 Subject: SMTP - Topic & add files References: <1073137983.983243@news.liwest.at> Message-ID: <3d06fae9.0401031339.7a2dcdb5@posting.google.com> "EsC" wrote in message news:<1073137983.983243 at news.liwest.at>... > Hy! > > probably a dummy question, but i don't > know how to set a Topic-Text and add > Files to an email ... > > i use the SMTPLIB module and the > function/method: .sendmail(from,to,msg) > > but how can i set a topic Text? > is there an other function/method, or > must it be encoded within the message-text? > > thanks for your help > EsC its in the msg parameter of sendmail such as : yourSmtp = smtplib.SMTP('yourMailServer.org') #envoi un message #ARGUMENTS from sendMail #from: your own client adress #to: the intended recipient's adress #msg: what will really show...in different fields monSmtp.sendmail("From: ownMail at yourMailServer.org", "To: recipientAdresse at hisServer.org", "From:joe\r\nTo: Owner \nSubject: 3 weeks left" + "\n\nTopic text of the message! ") on Windows, may differ slightly on Linux :) Good messaging, JM From aaron at reportlab.com Mon Jan 12 12:26:36 2004 From: aaron at reportlab.com (Aaron Watters) Date: Mon, 12 Jan 2004 12:26:36 -0500 Subject: Databases: Which one's right for me? References: <9a6d7d9d.0401120658.5b9ee522@posting.google.com> <1073924765.6341.387.camel@localhost.localdomain> Message-ID: <4002D8CC.4060701@reportlab.com> re: jeremy's reply... I find the Gray and Reuter definition confusing. To my mind isolation means serializability and if you don't have serializability (at least as an option) you don't have isolation. Transactions don't have to be complex to cause serious problems in read-committed mode: the classic example is a debit of $1000 for checking account 123 running at the same time as a credit for $4000 for checking account 123. If both transactions run at the same time and read the same previous (committed) balance and they both complete but the first one completes last then the customer is screwed to the tune of $4000. This is only the simplist problem -- for transactions involving complex data structures the problems can be much more subtle than that (and more difficult to correct). -- Aaron Watters === in theory, theory is the same as practice. in practice, it's more complicated than that. From aahz at pythoncraft.com Tue Jan 27 01:11:20 2004 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2004 01:11:20 -0500 Subject: Single and double asterisks preceding variables in function arguments References: Message-ID: In article , anton muhin wrote: > >See item 7.5 in Language Reference. In short: * declaries list of >additional parameters, while ** declares map of additional parameters. Actually, ``*`` forces creation of a tuple: >>> def foo(*bar): ... print type(bar) ... >>> l = [1,2,3] >>> foo(*l) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From skip at pobox.com Sat Jan 10 15:05:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 14:05:21 -0600 Subject: Setting up test for XML-RPC In-Reply-To: References: Message-ID: <16384.23297.521353.200475@montanaro.dyndns.org> >> You should be able to build a server and a client with just the >> standard Python distribution. MB> Really? That would be awesome. But I don't see how that MB> works... what do you enter for the URL? (right now it is just MB> http://localhost, but obviously I would need to specify 20 different MB> machines for my system. They are just bare Windows XP Pro machines MB> with a default installation. They're "Windows Server" machines, I MB> don't think. Doesn't matter. Suppose you ran the server on win.foobar.tv, listening to port 1234. In the client you'd call ServerProxy like so: server = ServerProxy("http://win.foobar.tv:1234") print server.exanples.echo("My dog has fleas") Skip From http Sat Jan 3 01:18:56 2004 From: http (Paul Rubin) Date: 02 Jan 2004 22:18:56 -0800 Subject: Text-to-HTML processing program References: Message-ID: <7xwu89pnan.fsf@ruckus.brouhaha.com> philh at invalid.email.address (phil hunt) writes: > Does anyone know of a text-to-HTML processing program, ideally > written in Python because I'll probably be wanting to make small > modifications to it, which is simple and straightforward to use > and which uses a simple markup language (something like Wikipedia > markup would be ideal)? I really wish Wikipedia, BBCodes, and all that would just use regular HTML instead of continually inventing new "simplified" markup codes for users to remember. The one thing they do that's useful is convert blank lines to

. From yshurik at fhb.kiev.ua Sat Jan 17 05:51:00 2004 From: yshurik at fhb.kiev.ua (yshurik) Date: Sat, 17 Jan 2004 12:51:00 +0200 Subject: PyQt forum Message-ID: Hi all. If you are working with PyQt the forum can be useful - http://www.thekompany.com/support/forum/index.php (PyQt forum) -- Best regards From flemming at bjerke.dk Wed Jan 28 23:41:19 2004 From: flemming at bjerke.dk (flemming at bjerke.dk) Date: 29 Jan 2004 04:41:19 -0000 Subject: I have changed my e-mail address Message-ID: <20040129044119.14293.qmail@dmerhverv.org> Send mail til: flem[SLET DETTE]@bjerke.dk Send mail to: flem[DELETE THIS]@bjerke.dk I close flemming at bjerke.dk. Flemming From eric.brunel at N0SP4M.com Thu Jan 29 09:43:09 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Thu, 29 Jan 2004 15:43:09 +0100 Subject: Rookie question about data types (hashtables) References: Message-ID: Steve D. Perkins wrote: [snip] > What I would LIKE to have is a hashtable-like structure that lets me > retrieve multiple values based on a partial key. AFAIK, if you can do queries on a "hashtable-like structure" with a partial key, it cannot be a real hashtable... > I want to have a text > field for the user to type in a Spanish word, and a box below containing > a list of English words. With each character that the user types, I > would like to narrow down the words listed in the box below. That is, > when you type the letter "a" the box will contain all English words > starting with the letter "a". When you then type "n", the box will > narrow further and contain all words starting with "an", etc... until > you've narrowed it down to appropriate word. I'd use a Python dictionary indexed not on words, but on letters in the word. So, for a dictionary translating english words into french, you'd have for example: dictionary['m']['o']['n']['d']['a']['y']['translation'] = 'lundi' (NB: having 'translation' as the last key is to solve the problem of words included in another; see 'sun' and 'sunday'. BTW, any key that is not a single character can be used...) Here is an example implementation: -------------------------------------------------------- def addWord(myDict, originalWord, translatedWord): d = myDict for c in originalWord: if not d.has_key(c): d[c] = {} d = d[c] d['translation'] = translatedWord def _allTranslations(rootWord, d): res = [] for c in d.keys(): if c == 'translation': res.append((rootWord, d[c])) else: res += _allTranslations(rootWord + c, d[c]) return res def getTranslations(myDict, word): d = myDict for c in word: if not d.has_key(c): return [] d = d[c] return _allTranslations(word, d) -------------------------------------------------------- And then you'd do: frenchDict = {} ## Week days addWord(frenchDict, 'monday', 'lundi') addWord(frenchDict, 'tuesday', 'mardi') # ... addWord(frenchDict, 'sunday', 'dimanche') ## Months addWord(frenchDict, 'january', 'janvier') addWord(frenchDict, 'february', 'fevrier') # ... addWord(frenchDict, 'december', 'decembre') print getTranslations(frenchDict, 'wednesday') print getTranslations(frenchDict, 'ju') print getTranslations(frenchDict, 's') I don't know how it scales up for big dictionaries, not to mention huge ones... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From peter at engcorp.com Tue Jan 20 11:47:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jan 2004 11:47:11 -0500 Subject: I come not to bury C++, but to praise it... References: <20040114153516.GA16224@intarweb.us> Message-ID: <400D5B8F.8C597B9E@engcorp.com> Derek wrote: > > "Oren Tirosh" wrote: > > A traceback is also much less nasty than deciphering a > > 1000-character long compiler error message reported in > > code that uses a heavily templated library. > > Absolutely correct. But remember that ugly template-related compiler > error messages are a reflection of current compiler technology, not a > fundamental limitation of C++. I suspect future compilers will make > debugging templates much easier. I believe I heard that claim, almost verbatim, sometime around the last time I was actively using C++, which was about a decade ago... -Peter From ecocozza at hotmail.com Tue Jan 20 10:44:25 2004 From: ecocozza at hotmail.com (eric cocozza) Date: Tue, 20 Jan 2004 10:44:25 -0500 Subject: Python work needed... please respond privatly Message-ID: Hi, I just moved a python program to a new server, and I'm getting path errors. It relys on the pear library and a image processing one. Please respond with cost based on 1/hr of work, and please accept paypal, or other simple form of payment. Thanks! -Eric From mir4uu at yahoo.com Sat Jan 3 11:26:52 2004 From: mir4uu at yahoo.com (mir nazim) Date: 3 Jan 2004 08:26:52 -0800 Subject: Python for Embedded Devices? References: Message-ID: <425cc8d1.0401030826.59a9d4ca@posting.google.com> brandon6684 at yahoo.com (Brandon) wrote in message news:... > Java seems to have taken off as the platform and language of choice > for many embedded devices. Would it be feasible for Python(perhaps > running on an embedded version of Linux) to act in such a capacity. > Most of my experience with Python has been with Unix-type scripting > tasks and using it when it is an applications built in scripting, but > I know some people try to use to build larger complex applications. Is > the Python interpreter portable and good enough to be used in resource > constrained devices like cell phones? Why only embeded devices? It should possible to create complete J2EE like platform for python for creating complex applications. [ i m no expert. lokking for a simple discussion.] From adonisv at REMOVETHISearthlink.net Sun Jan 11 13:49:58 2004 From: adonisv at REMOVETHISearthlink.net (Adonis) Date: Sun, 11 Jan 2004 18:49:58 GMT Subject: Moving widgets in Tkinter Message-ID: I wish to manually move widgets in Tkinter, now I have successfully done it, but with odd results, I would like to move the widgets with a much smoother manner, and better precision. Any help is greatly appreciated. -- here is snip of working code: from Tkinter import * class blah: def MoveWindow(self, event): self.root.update_idletasks() self.f.place_configure(x=event.x_root, y=event.y_root-20) def __init__(self): self.root = Tk() self.root.title("...") self.root.resizable(0,0) self.root.geometry("%dx%d%+d%+d"%(640, 480, 0, 0)) self.f = Frame(self.root, bd=1, relief=SUNKEN) self.f.place(x=0, y=0, width=200, height=200) self.l = Label(self.f, bd=1, relief=RAISED, text="Test") self.l.pack(fill=X, padx=1, pady=1) self.l.bind('', self.MoveWindow) self.f.bind('', self.MoveWindow) self.root.mainloop() x = blah() From max at alcyone.com Mon Jan 19 14:54:20 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 19 Jan 2004 11:54:20 -0800 Subject: Delayed evaluation and setdefault() References: Message-ID: <400C35EC.AF2DFADD@alcyone.com> Leo Breebaart wrote: > So I guess my question is twofold: one, do people think > differently, and if so why?; and two: is there any elegant (or > other) way in which I can achieve the delayed evaluation I desire > for setdefault, given a side-effect-having b()? The setdefault method of dictionaries is just a normal method in Python; only the builtin `and' and `or' operators have special short-circuiting behavior. That is to say, there are no builtin functions or methods in Python which are "special forms." It's true that the kind of thing you want to do (lazy evaluation in some incidental context) is common, but it would not be a good idea to start selectively adding special forms to the language since it would greatly complicate things. Right now if I see this.that(something, theOther()) I can immediately tell what gets evaluated or called and when. I don't need to know that there are special cases in some things that look like method/function calls but actually might be special forms, and that's a good thing. As for your particular solution, you're much better off implementing the lazy evaluation you want yourself, rather than wishing there were special language support for it for that particular method (or a very small subset of methods/functions). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The critical period in matrimony is breakfast-time. -- A.P. Herbert From Pieter.Claerhout at Creo.com Wed Jan 28 04:44:11 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 28 Jan 2004 10:44:11 +0100 Subject: Cross-version extension modules? Message-ID: <490316A24CC5D411ACD700B0D078F7F003915E29@cseexch01.cse.creoscitex.com> Peter, extension modules in Python are always linked to a specific version of Python. You might perform some tricks with writing a pure Python module about your extension that, based on the version of the python interpreter, loads a different version of your extension. This is e.g. the way the Python drivers for SapDB work. You can download them from: http://www.sapdb.org/7.4/sap_db_downloads.htm Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Peter Astrand [mailto:peter at cendio.se] Sent: 28 January 2004 10:40 To: python-list at python.org Subject: Cross-version extension modules? If I build a extension module with Python 2.2 and then loads it with 2.3, I get: RuntimeWarning: Python C API version mismatch for module _foo: This Python has API version 1012, module _foo has version 1011. How fatal is this? Is it safe to use the module anyway? If not, is it possible to build the module differently, so that it actually is safe to use it with different versions of Python? -- Peter ?strand www.thinlinc.com Cendio www.cendio.se Teknikringen 3 Phone: +46-13-21 46 00 583 30 Link?ping -- http://mail.python.org/mailman/listinfo/python-list From jjl at pobox.com Tue Jan 6 11:28:34 2004 From: jjl at pobox.com (John J. Lee) Date: 06 Jan 2004 16:28:34 +0000 Subject: Why does this fail? References: Message-ID: <878yklavnx.fsf@pobox.com> "Dave Murray" writes: > New to Python question, why does this fail? [...] > def Checkit(URL): [...] (already answered six times, so I won't bother...) You might want to have a look at the unittest module. Also (advert ;-), if you're doing any kind of web scraping in Python (including functional testing), you might want to look at this little FAQ (though it certainly doesn't nearly cover everything relevant): http://wwwsearch.sf.net/bits/clientx.html BTW, in response to another question in this thread (IIRC), and entirely contrary to my previous assertion here , it appears that HTMLParser.HTMLParser is a bit more finicky with HTML than is sgmllib/htmllib (htmllib is a thin wrapper over sgmllib). I hope to investigate and fix that -- HTMLParser.HTMLParser knows about XHTML, so in that respect is a better choice than sgmllib/htmllib. If you want to process junk HTML, though (or perhaps even valid HTML that the library you're using doesn't like), look at mxTidy or uTidylib. I should link to those on my FAQ page... John From theller at python.net Sat Jan 10 16:13:40 2004 From: theller at python.net (Thomas Heller) Date: Sat, 10 Jan 2004 22:13:40 +0100 Subject: scanning c-code References: Message-ID: <4qv35wxn.fsf@python.net> "tm" writes: > Hello, > > I have to to scan c-code, look for a c-struct variable(declaration) and > represent the struct in a tree-graphic. > Are there modules for scanning c-code and graphictools for the > representation stuff. > What would you advise as a starting point... Simon Burton's cdecl.py: Thomas From bkelley at wi.mit.edu Thu Jan 15 15:27:24 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 15 Jan 2004 15:27:24 -0500 Subject: Why gmp is not in the standard library? In-Reply-To: References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <4006f74a$0$567$b45e6eb0@senator-bedfellow.mit.edu> Skip Montanaro wrote: > Bdb's license is not GPL: > > http://www.sleepycat.com/download/oslicense.html I stand corrected, it makes perfect sense that the Berkeley DB should be released using the Berkeley license :) I don't know why I thought otherwise. That being said, wasn't there some issue with making the Python License GPL compatible for issues like these? > Skip > From Z_kline at hotmail.com Mon Jan 19 08:00:03 2004 From: Z_kline at hotmail.com (Zachary) Date: Mon, 19 Jan 2004 05:00:03 -0800 Subject: overwrite private method... (of wxColumnSorterMixin class) References: Message-ID: "Florian Preknya" wrote in message news:bugj2p$vqj$1 at nebula.dnttm.ro... > Is there a posibility to overwrite a private method (one that starts with > __ ) ? I read that they are just formely private, they are prefixed with the > class name to have an obtured visibility, so maybe it's a trick here... > > More details... > I use wxPython, more specifically the wxColumnSorterMixin class. I want to > overwrite the __OnColClick event handler to behave on my way: I want the > sorting feature will affect only some columns, not all columns and that > event handler is the key. The problem is that the event chain is skiped in > the __OnColClick method, so I cannot receive the event anymore. So, my idea > was to overwrite the __OnColClick method in the mixin subclass. Is this > possible? Or, are they other solutions for this ? > > Thanks, > Florian. > > What you read is true, so far as I know. It is possible to override them, as Python doesn't have a notion of encapsulation, again, as far as I know. You can probably get away with this. From davecook at nowhere.net Mon Jan 26 10:04:51 2004 From: davecook at nowhere.net (David M. Cook) Date: Mon, 26 Jan 2004 15:04:51 GMT Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: In article , Josiah Carlson wrote: > Speaking of which... > http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html I'm still flabbergasted that this is on whitehouse.gov and not on whitehouse.org. Dave Cook From jcarlson at nospam.uci.edu Fri Jan 30 22:23:13 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 19:23:13 -0800 Subject: PEP 327: Decimal Data Type In-Reply-To: <401B1A87.639CD971@easystreet.com> References: <6ltk10h30riel0lghd18t5unjco2g26spi@4ax.com> <401B1A87.639CD971@easystreet.com> Message-ID: > If python adds decimal data, it probably ought to be consistent with C > and C++. Otherwise, the C and C++ guys will have a dreadful time > writing emulation code to run on computers built to support python. Now that's a "Python will take over the world" statement if I ever heard one. But seriously, processor manufacturers build processors and compilers for Fortran, C, and C++. If a manufacturer starts paying attention to where Python is going (for things other than scripting their build-process), I'm sure Guido would like to know. - Josiah From graham at rockcons.co.uk Sun Jan 4 14:27:03 2004 From: graham at rockcons.co.uk (Graham Nicholls) Date: Sun, 04 Jan 2004 19:27:03 +0000 Subject: Launching pdb from within a script References: Message-ID: Graham Nicholls wrote: > Peter Otten wrote: > >> Graham Nicholls wrote: >> >>> A year or so ago, I was given a really useful answer to a question posed >>> here, which showed me how to start the debugger from withing a script. >> >> Are you looking for pdb.set_trace()? >> >> Peter > I think so, thanks! > Graham Or maybe not. I'm sure I was able to print the value of variables like this: except : pdb.set_trace() run the program: error message (Pdb) d (not sure why!) (Pdb) print dentry.path (Pdb) more debugging here But pdb complains that there are no such variables. It may be that I had to add some incantation around the script startup - I just can't remember (and its frustrating!). Thanks Graham -- #include From jdhunter at ace.bsd.uchicago.edu Sat Jan 3 11:17:13 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 03 Jan 2004 10:17:13 -0600 Subject: Graph in wxPython In-Reply-To: ("Cousin Stanley"'s message of "Sat, 3 Jan 2004 06:40:17 -0700") References: Message-ID: >>>>> "Cousin" == Cousin Stanley writes: Cousin> John .... Perhaps I can add another verse to that song Cousin> I've been writing called The Cousin> GTK/PyGtk/wGlade/Wx/MatPlotLib Blues .... Cousin> You know a couple of verses already .... :-) >>>> import matplotlib >>>> >>>> matplotlib.use( 'WX' ) Cousin> unrecognized backend WX. Use one of PS, GD, GTK, Template Looks like you're using an older version of matplotlib. The WX backend is a fairly recent addition. Make sure you are using 0.40. Hope this helps, JDH From hawkfish at trustedmedianetworks.com Mon Jan 12 13:14:27 2004 From: hawkfish at trustedmedianetworks.com (Richard Wesley) Date: 12 Jan 2004 13:14:27 EST Subject: Standalone ZPT and Batch Message-ID: I am busy converting a single Zope page to a Python cgi using the standalone ZPT implementation from sourceforge. Most of it seems to work just fine, but I am finding that although the Batch object is available and ported(?), it does not seem to work. Whenever I try to access batch/next/first with a short list, the renderer complains that next.first is not defined. The ZPT codes looks like this ... batch python:modules['ZUtils'].Batch(...); next batch/next ... Looking at Batch.py, it appears that Batch.next is actually a LazyNextBatch object, which only defines the Zope-specific __of__ operator. This makes sense, but I am rather surprised that standalone ZTP does not handle this correctly in Expressions.py Anyone have any suggestions about how to fix this? TIA, -- - rmgw ---------------------------------------------------------------------------- Richard Wesley Trusted Media Networks, Inc. "There's nothing intellectual about wandering around Italy in a big shirt, trying to get laid." - Rowan Atkinson, "Black Adder:Ink and Incapability" From ketulp_baroda at yahoo.com Sat Jan 10 06:44:21 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda) Date: Sat, 10 Jan 2004 11:44:21 -0000 Subject: What is best for web application development?? Message-ID: i am developing a web application and i am really confused on what should i use. should i use just python and use the cgi module availabe. Or should i use application like WebWare.Also there is PSP available. I am really confused and need help From runed at stud.cs.uit.no Wed Jan 28 14:03:45 2004 From: runed at stud.cs.uit.no (Rune) Date: 28 Jan 2004 11:03:45 -0800 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? Message-ID: <6ed33425.0401281103.61987e72@posting.google.com> Hey I'm trying to build a gui application and need to know if the user is actually holding down the shift or ctrl key. That is, if the user currently is holding down the shift key. In pseudo code this will boil down to something like this: def test: if user presses shift: return SHIFT_IS_PRESSED elif user presses ctrl: return CTRL_IS_PRESSED else return false It's important to notice here that I'm not interested if the user has already pressed shift or ctrl. I'm only interested in knowing if he is currently holding down one of these keys. (I have looked into msvcrt and the like but have found no answer..) The function should also work in both windows and Linux. Any help is appriciated :) From netquest at sympatico.ca Tue Jan 27 03:19:24 2004 From: netquest at sympatico.ca (KNS) Date: Tue, 27 Jan 2004 00:19:24 -0800 Subject: winapi: mouseclick In-Reply-To: References: Message-ID: Just to add some clarification, this is in fact a Python question. I'm just working within the Windows environment. And, now that I'm here, I'm certain this is child's play for many of you, so a bit of help would be most welcomed. Thanks. KNS wrote: > > Hello, > > Can someone please suggest how to test for a mouse click using > the WinAPI? I have dispatched a windows application and would > like to detect any mouseclicks (and keyboard entry for that matter)... > > Thanks. > From Pieter.Claerhout at Creo.com Thu Jan 22 05:52:15 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 22 Jan 2004 11:52:15 +0100 Subject: Importing database: newbie issue Message-ID: <490316A24CC5D411ACD700B0D078F7F003915DDD@cseexch01.cse.creoscitex.com> I would read in the file line by line and then extract the parts I need, provided the database file is a text file. A small example: ### CODE SAMPLE f = open( 'MyDatabaseFile', 'r' ) data = f.readlines() f.close() for record in data: field1 = record[32:32+12] field2 = record[50:50+8] ### END Hope this answers your question. cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Angelo Secchi [mailto:secchi at sssup.it] Sent: 22 January 2004 11:55 To: python-list at python.org Subject: Importing database: newbie issue Hi, I have a database with a fixed format structure (i.e. i know the starting point and the length of each of the field composing the database) and I would like to extract from it only few fields (ex the one starting from the 32nd position with length 12...). What is the best way to do that? Thank a -- http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Wed Jan 28 10:34:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 09:34:20 -0600 Subject: I support PEP 326 In-Reply-To: References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> <20040128041023.2EB9225B353@bonanza.off.ekorp.com> <20040128090205.GA3086@nl.linux.org> Message-ID: <16407.54908.798846.778336@montanaro.dyndns.org> Josiah> I know you commented on the flat namespace of __builtin__, but Josiah> I've not seen any comments on PEP 326. http://mail.python.org/pipermail/python-dev/2004-January/042308.html I guess I don't sort() stuff enough... Skip From tim.one at comcast.net Mon Jan 19 12:05:27 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 19 Jan 2004 12:05:27 -0500 Subject: secure unpickle? In-Reply-To: <871xpwxe5g.fsf@pobox.com> Message-ID: [Gandalf] > ... >> I'm using this module (based on the documentation you mentioned): >> ... [John J. Lee] > What does this have to do with the question? He was worried about > security of pickle, not asking how to call dumps() and loads(). Look at Gandalf's code again. The pickler is unremarkable, but the unpickler contains the assignment: p.find_global = None As his loads docstring said, "this function will not unpickle globals and instances" as a result. From __peter__ at web.de Wed Jan 28 17:14:07 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jan 2004 23:14:07 +0100 Subject: Nested lists or conditional logic? References: Message-ID: Here's another odd one: from itertools import islice ITEMSINBATCH = 3; ARBITRARYNUM = 11; sample = ["item #%d" % i for i in range(ARBITRARYNUM)] def batches(s, n): it = iter(s) n -= 1 def batch(next): yield next for item in islice(it, n): yield item while True: yield batch(it.next()) for batch in batches(sample, ITEMSINBATCH): for item in batch: print item print "summary" The client code is as clean as you can get... Peter From vincent at visualtrans.de Sun Jan 4 10:08:43 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 4 Jan 2004 16:08:43 +0100 Subject: importing References: <231bc96c.0401031249.12cff6d7@posting.google.com> Message-ID: "vincent wehren" schrieb im Newsbeitrag news:bt9a52$nug$1 at news4.tilbu1.nb.home.nl... | "Boomer" schrieb im Newsbeitrag | news:231bc96c.0401031249.12cff6d7 at posting.google.com... | | Hi all, | | I'm new to python which explains my problems with this. I'm trying | | to import a .csv file(from excel) into some fields on my company's | | software system(which interfaces to an sql database. Each row in this | | .csv file needs to be split into smaller strings and each respective | | string applied to it's field in the software then it's saved and the | | next row starts, here's the code I've come up with so far. | | | | f=open ("book1.csv", "r") | | s=f.readline () | | while s != "": | | print s | | l = s.split(s,",",(11)) | | PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0]) | | PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}") | | PlayIt.SetFieldContent ("SY012ADM1", "001bez", l[1]) | | PlayIt.SetFieldContent ("SY012ADM1", "005agr", l[2]) | | PlayIt.SetFieldContent ("SY012ADM1", "006agr", l[3]) | | PlayIt.SetFieldContent ("SY012ADM1", "009kst", l[4]) | | PlayIt.SetFieldContent ("SY012EHM1", "005laeh", l[5]) | | PlayIt.SetFieldContent ("SY012EHM1", "006lauf", l[6]) | | PlayIt.SetFieldContent ("SY012EHM1", "011vkuf", l[7]) | | PlayIt.SetFieldContent ("SY012SDM1", "012fest", l[8]) | | PlayIt.SetFieldContent ("SY012PRM1", "001tpr", l[9]) | | PlayIt.SetFieldContent ("SY012PRM1", "002wpr", l[10]) | | PlayIt.SetFieldContent ("SY012PRM1", "003plpr", l[11]) | | PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}") | | s=f.readline () | | f.close () | | | | here's the error | | | | Traceback (innermost last): | | File "", line 5, in ? | | AttributeError: 'string' object has no attribute 'split' | | | | the furthest I get is when I remove the s.split all together then I | | can actually watch it import the first field correctly and switch | | focus to the second field where it prints a comma and then hangs and | | eventually gives the | | argument 3: expected string list found | | Someone told me I need to import the string module using "import | | string" somewhere in my code, but when I do this I get an error | | stating that no such module exists. I run this as script inside a | | macro from another program and I believe the version of python this | | program uses is 2.2.1. | | Hi "Boomer" | | if you are using version V3.91 or lower of your companies software, the | embedded Python will still be at 1.52. If it is V4.20 it'll be Python 2.2.2. | Since I know that the Python standard library is not shipped with the | software you are referring to, you need to either install Python (in the | version corresponding to your version) on your local machine, or an | accessible share and set your environment properly. | | Looking at your example I am pretty confident that your are using V391 which | embedds 1.52. As a quick fix: check if either "string.pyc" or "string.py" | lives in your w32 directory or - if you are executing via Just for the record, I mean the w32 directory of the ERP system you are referring to! Vincent Wehren a .pli file - in | the directory "playit.exe" lives in. If that is not the case, get either | module in the correct version and copy it to the directories just described. | This will fix your problem (until you try to import another module | ofcourse). | | HTH | | Vincent Wehren | | | | | | | | | | | | | | | | | | | Does anyone have any ideas? Any help would be wonderful!!! | | From andrew-pythonlist at puzzling.org Wed Jan 21 05:52:15 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 21 Jan 2004 21:52:15 +1100 Subject: twistedmatrix.com - time out error In-Reply-To: References: Message-ID: <20040121105215.GA6651@frobozz> On Wed, Jan 21, 2004 at 11:42:52AM +0100, Nuff Said wrote: > I am trying to download Twisted form www.twistedmatrix.com since > maybe 2 days, but I always get a time out error from the server. Yeah, there's some sort of hardware fault with the server, apparently. > Is there a mirror resp. another 'official' download site for Twisted? > (Or: does someone know what's going on with twistedmatrix.com?) http://twisted.sf.net/ should have the most recent releases (including documentation). You ought to be able to use Google's cache to read the website, if you're desperate to read the marketing material ;) -Andrew. From engsolnom at ipns.com Thu Jan 1 13:54:43 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Thu, 01 Jan 2004 10:54:43 -0800 Subject: Where to go from here? newbee References: <1koon5kaqkghf.211m8yj2j32t$.dlg@40tude.net> Message-ID: Richard, Being a newbie to Python myself, I can relate. One way...assuming windows Click on the python command line thing you evidently found. This gives you a dos box showing the Python prompt...>>> Just type Python commands: print "Hello World", for example Control Z to exit Another way.... Bring up a 'real' dos box, cd to Python23, or whatever your install named it, and enter python This again shows the Python prompt >>> >From the dos prompt, you can run a Python script by entering: python myscript.py where myscript is a text file with an extension of py, and located in the C:\python23 dir. If you make a sub-directory myfiles (adviable) under C:\python23, to hold your test scripts, you need to enter: python myfiles\myscript.py A third way... Use a text editor to manage files and directories, and which may be able to launch dos commands. There are dozens of editors out there, some good, some not so good. I use PFE, and have for years. Hope this helps a bit. Norm On Thu, 1 Jan 2004 09:45:00 -0600, "Richard" wrote: > Jules Dubois wrote: > > > On Wed, 31 Dec 2003 23:22:43 -0600, in article > > , Richard wrote: > > >> Just downloaded python for the fun of it. > >> What do I run to begin coding with? > >> Version 2.3.3 > > > Yes, unless you have some reason to use an older release. > > >> When I run the "command line" thing, I get a dos window. > >> Now what? > > > Type some commands and see how the interpreter works. > > > Go to http://www.cs.unm.edu/~ej and click on these links. > > > Python Hacking I (Just do it!) > > Python Hacking II (types, functions, exceptions) > > Python Hacking III > > > Type the commands and see what happens. > > > Go to http://www.python.org/ and find some more advanced tutorials. > >Ok. Now I'm slowly understanding. I guess you could say that python is >similar to visual basic and c++ in coding. >I have a program written in python which has several "py" files included. >How do I view these for the coding examples? > From wrbt at email.com Thu Jan 29 16:26:48 2004 From: wrbt at email.com (Larry) Date: 29 Jan 2004 13:26:48 -0800 Subject: Color count in PIL References: <2ec1bc1c.0401271443.15f56742@posting.google.com> Message-ID: <2ec1bc1c.0401291326.5602aee2@posting.google.com> wrbt at email.com (Larry) wrote in message news:<2ec1bc1c.0401271443.15f56742 at posting.google.com>... > I've been walking up, down, and around instances in the object model > of PIL trying to figure out how to easily calculate how many unique > colors are used in an image, specifically a bitmap (mode "P"). Am I > missing something? > > Thanks python friends! So far I have: colors=len(sets.Set(list(im.getdata()))) That makes me want to throw up. From venkataraju at nospam2me.sbcglobal.net Tue Jan 20 16:22:05 2004 From: venkataraju at nospam2me.sbcglobal.net (Venkat Venkataraju) Date: Tue, 20 Jan 2004 21:22:05 GMT Subject: Python T-shirt In-Reply-To: References: Message-ID: <1_gPb.32556$P%1.25715272@newssvr28.news.prodigy.com> > The code on the back of it was written by a very cool guy.. I don't > remember who. Thanks, anyways! :) I lookup and it is written by Fredrik Lundh (fredrik_lundh_at_ivab.se) Venkat From daniels at dsl-only.net Tue Jan 6 13:50:10 2004 From: daniels at dsl-only.net (sdd) Date: Tue, 06 Jan 2004 10:50:10 -0800 Subject: metadocumentation (keyword help) In-Reply-To: References: Message-ID: <3ffb0edf$1@nntp0.pdx.net> Jp Calderone wrote: > On Tue, Jan 06, 2004 at 03:27:06PM +0100, Jacek Generowicz wrote: > >>Where can I find concise, clear documentation[*] describing what one has >>to do in order to enable Python's internal help to be able to provide >>descriptions of Python keywords ? > > > "Quote them" > > help('if') > > Jp > > Or simply use help() and interactively enter lines. From capitanmutanda at hotmail.com Thu Jan 29 03:57:14 2004 From: capitanmutanda at hotmail.com (Capitan Mutanda) Date: 29 Jan 2004 00:57:14 -0800 Subject: browsing IIS Metabase? Message-ID: Hello! I'm studing Python and would like to do some learning on the job. I have the need to read and write IIS Metabase, but could not find any examples. Anybody can suggets a metabase browser? TIA /CM From jeremy+plusnews at jeremysanders.net Fri Jan 23 07:58:21 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Fri, 23 Jan 2004 12:58:21 +0000 Subject: Psyco distutils problem Message-ID: Hi - I'm trying to build a Psyco rpm on Fedora 1. I try the command xpc5:~/psyco-1.1.1> python setup.py bdist_rpm this fails with: ... copying dist/psyco-1.1.1.tar.gz -> build/bdist.linux-i686/rpm/SOURCES building RPMs rpmbuild -ba --define _topdir /home/jss/psyco-1.1.1/build/bdist.linux-i686/rpm --clean build/bdist.linux-i686/rpm/SPECS/psyco.spec error: File /home/jss/psyco-1.1.1/build/bdist.linux-i686/rpm/psyco/psyco-1.1.1.tar.gz: No such file or directory error: command 'rpmbuild' failed with exit status 1 If I then copy the missing file it fails with ... + unset DISPLAY + env 'CFLAGS=-O2 -g -pipe -march=i386 -mcpu=i686' python setup.py build Traceback (most recent call last): File "setup.py", line 83, in ? execfile(os.path.join(SOURCEDIR, 'files.py'), data) IOError: [Errno 2] No such file or directory: 'c/files.py' error: Bad exit status from /home/jss/psyco-1.1.1/build/bdist.linux-i686/rpm/tmp/rpm-tmp.23601 (%build) RPM build errors: Bad exit status from /home/jss/psyco-1.1.1/build/bdist.linux-i686/rpm/tmp/rpm-tmp.23601 (%build) error: command 'rpmbuild' failed with exit status 1 So it looks like some files aren't being copied. I'm a distutils newbie, so can someone suggest whether this is a Psyco problem, a Fedora problem, an RPM problem or what? Just doing setup.py bdist does actually work. Thanks Jeremy From michael at telcopartners.com Sat Jan 24 15:53:27 2004 From: michael at telcopartners.com (Michael Spencer) Date: Sat, 24 Jan 2004 12:53:27 -0800 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: [Fixed top-posts: please add future comments at the bottom] > > > > > > > > Amy G wrote: > > > > I have seen something about this beofore on this forum, but my google > > search > > > > didn't come up with the answer I am looking for. > > > > > > > > I have a list of tuples. Each tuple is in the following format: > > > > > > > > ("data", "moredata", "evenmoredata", "date string") > > > > > > > > The date string is my concern. This is the date stamp from an email. > > > > The problem is that I have a whole bunch of variations when it comes > to > > the > > > > format that the date string is in. For example I could have the > > following > > > > two tuples: > > > > > > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 > > 03:15:06") > > > > > > > > I know there is some way to use the date string from each of these to > > get a > > > > date usable by python, but I cannot figure it out. > > > > I was trying to use time.strptime but have been unsuccesful thus far. > > > > > > > > Any help is appreciated. > > > > > > "wes weston" wrote in message > > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net... > > > Amy, > > > I hope there is a better way but, if you go here: > > > > > > http://www.python.org/doc/current/lib/datetime-date.html > > > > > > The new datetime module may help. This and the time mod > > > should get you where you want to go. > > > > > > list = strdate.split(", ") > > > daystr = list[0] > > > daynum = int(list[1]) > > > monthstr = list[2] > > > year = int(list[3]) > > > #funct to get a month int is needed > > > > > > d = datetime.Date(y,m,d) > > > > > > wes > > > > > > --------------------------------------- > > > > > > > > "Amy G" wrote in message > news:PRgQb.16209$AA6.9881 at fed1read03... > > No it won't. Unfortunatly I don't necessarily have a comma delimited date > > string. Thanks for the input though. > > > > The following three date strings is another example of the various date > > formats I will encounter here. > > > > Thursday, 22 January 2004 03:15:06 > > Thursday, January 22, 2004, 03:15:06 > > 2004, Thursday, 22 January 03:15:06 > > > > All of these are essentially the same date... just in various formats. I > > would like to parse through them and get a comparable format so that I can > > display them in chronological order. > > > > > > "Amy G" wrote in message news:n7iQb.16224$AA6.5862 at fed1read03... > Okay. I fixed the problem somewhat. I moved the dateutil directory over to > /usr/local/lib/python2.2/site-packages and I can now import dateutil. But a > call like this: > > from dateutil.parser import parse > > results in this error: > > ImportError: cannot import name parse > > I can 'from dateutil.parser import *' but cannot use parse after that. > I can also 'from dateutil import parser' but that doesn't help either. > > Sorry for my inexperience here. Thanks for all of the help already. > Amy: The docstring of the dateutil package: """ Copyright (c) 2003 Gustavo Niemeyer This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer " __license__ = "PSF License" notes that it requires the datetime module (new in Python 2.3). It appears that you are using 2.2. Can you install 2.3.3? If you need to stick with 2.2, the question of using datetime in 2.2 was answered in http://groups.google.com/groups?q=python+2.2+datetime&hl=en&lr=&ie=UTF-8&selm=mailman.1043334342.25146.python-list%40python.org&rnum=2 with a pointer to a "workalike" module, see: http://cvs.zope.org/Zope3/src/datetime/ I have not tested whether this works with dateutil Cheers Michael From owner-mutt-users at mutt.org Mon Jan 26 23:00:41 2004 From: owner-mutt-users at mutt.org (owner-mutt-users at mutt.org) Date: 27 Jan 2004 04:00:41 -0000 Subject: mutt-users@mutt.org: Non-member submission from python-list@python.org Message-ID: <20040127040041.15623.qmail@agent57.gbnet.net> Your submission to the list has been forwarded to the list owner for approval because you do not seem to be on that list. If you want to join the list, send email to , with "subscribe mutt-users" in the message text (not the subject). From rune.froysa at usit.uio.no Fri Jan 9 07:18:39 2004 From: rune.froysa at usit.uio.no (Rune Froysa) Date: 09 Jan 2004 13:18:39 +0100 Subject: Unicode and exception strings Message-ID: Assuming an exception like: x = ValueError(u'\xf8') AFAIK the common way to get a string representation of the exception as a message is to simply cast it to a string: str(x). This will result in an "UnicodeError: ASCII encoding error: ordinal not in range(128)". The common way to fix this is with something like u'\xf8'.encode("ascii", 'replace'). However I can't find any way to tell ValueErrors __str__ method which encoding to use. Is it possible to solve this without using sys.setdefaultencoding() from sitecustomize? Regards, Rune Fr?ysa From NAIGIMSESRIMAIL at gims.com Tue Jan 27 05:19:27 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Tue, 27 Jan 2004 12:19:27 +0200 Subject: ALERT - GroupShield ticket number OA1430_1075198765_ESRIMAIL_3 w as 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: Michael G. A. Sung Sent: -1897042688,29615427 Subject: PAP connection Attachment Details:- Attachment Name: ATT09057.txt File: ATT09057.txt 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: 1891 bytes Desc: not available URL: From a at a.invalid Thu Jan 8 13:34:38 2004 From: a at a.invalid (Timo Virkkala) Date: Thu, 08 Jan 2004 20:34:38 +0200 Subject: Cheetah - Test suite failures Message-ID: I tried to install Cheetah (0.9.15) and ran into trouble. When running the test suite, I get 61 failures and 57 errors. Most of the errors are "ImportError: No module named temp", with some "TypeError: update() takes exactly one argument (0 given)". The full output of the test suite is at (URL: http://www.cs.helsinki.fi/u/tjvirkka/out.txt ) I'd hate to spend hours debugging this thing, so I thought to ask here if someone has any ideas what's causing this.. -- Timo Virkkala From bkelley at wi.mit.edu Tue Jan 6 09:56:48 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 06 Jan 2004 09:56:48 -0500 Subject: Test if IDLE is a mature program In-Reply-To: References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com><99dce321.0312311130.5b7c7c8a@posting.google.com><3ff49f0e.776954150@news.blueyonder.co.uk> Message-ID: <3ffacc43$0$572$b45e6eb0@senator-bedfellow.mit.edu> Andrew Dalke wrote: > > Or tried to save to a file named "prn" or "aux" under MS Windows ;) Or even worse, "aux.jar" or "aux.py". Talk about headaches. > Andrew > dalke at dalkescientific.com > > From martin at v.loewis.de Fri Jan 2 06:36:51 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 02 Jan 2004 12:36:51 +0100 Subject: Python 2.3.3 compilation problem In-Reply-To: References: Message-ID: <3FF557D3.50500@v.loewis.de> Zdenda wrote: > Compiling /usr/local/lib/python2.3/xml/sax/handler.py ... > Compiling /usr/local/lib/python2.3/xml/sax/saxutils.py ... > Compiling /usr/local/lib/python2.3/xml/sax/xmlreader.py ... > Compiling /usr/local/lib/python2.3/xmllib.py ... > Compiling /usr/local/lib/python2.3/xmlrpclib.py ... > Compiling /usr/local/lib/python2.3/zipfile.py ... > make: *** [libinstall] Error 1 > > Have somebody any idea where is error? It's an error further up in the output, probably caused by some erroneous file in /usr/local/lib/python2.3. Regards, Martin From francisgavila at yahoo.com Sat Jan 10 11:06:08 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 10 Jan 2004 11:06:08 -0500 Subject: Writing Files References: Message-ID: <10008pk9gov3c78@corp.supernews.com> Lucas Raab wrote in message ... >What is the best way to go about writing to files?? Whenever I insert a >statement to write results to a file there's nothing in it. Any >suggestions?? Don't forget to close and/or flush your file.... -- Francis Avila From mi-mal at o2.pl Mon Jan 12 05:32:54 2004 From: mi-mal at o2.pl (Mimal) Date: Mon, 12 Jan 2004 11:32:54 +0100 Subject: CGI module problem: duplicated output In-Reply-To: References: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> Message-ID: > How about renaming it to mimal_cgi.py! For a second I thought: "That's it!" Unfortunately, that doesn't seem to help. I renamed the file and I got the same. :-( -- Mimal From jdhunter at ace.bsd.uchicago.edu Sat Jan 3 02:03:18 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 03 Jan 2004 01:03:18 -0600 Subject: Graph in wxPython In-Reply-To: ("Oh Kyu Yoon"'s message of "Wed, 31 Dec 2003 19:31:15 -0800") References: Message-ID: >>>>> "Oh" == Oh Kyu Yoon writes: Oh> Does anyone know how to implement plots from scipy, chaco, etc Oh> into wxPython widget? matplotlib has a wxpython plotting backend, which supports interactive data exploration and hardcopy save to a variety of output formats -- http://matplotlib.sourceforge.net Here's a sample script: import matplotlib matplotlib.use('WX') from matplotlib import plot, show plot([1,2,3]) show() You can use matplotlib interactively from the python shell, in batch python scripts, or embed it in wxpython application window. Or you can use it offline w/o a GUI environment to make hardcopy plots in PNG, PS or other formats. See the example examples/embedding_in_wx.py for demo code showing how to embed matplotlib figures into wx apps. matplotlib also supports GTK, PS and GD. biasedly-yours, JDH From adalke at mindspring.com Fri Jan 16 02:53:04 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 16 Jan 2004 07:53:04 GMT Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <878yka2sze.fsf@pobox.com> <100bbekd61fbl53@corp.supernews.com> <100d4ljnic3l465@corp.supernews.com> Message-ID: JanC: > But Netscape was largely based on Mosaic anyway; being developed by the > same developers. The beta I was talking about above still has a Mosaic > logo. ;-) While it had many of the same developers, as I recall, none of the code was shared. They were planning to call it Netscape Mosaic but that was changed before the final release. Also, and again pulling out some old memory here, Netscape paid UIUC a chunk of money just in case there was some accidental copyright transfer because of not doing a pure clean-room reimplementation. I think that was mentioned in the IPO prospectus... but I'm not going to try and dig it up now. Andrew dalke at dalkescientific.com From godoy at ieee.org Thu Jan 15 15:23:26 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 15 Jan 2004 18:23:26 -0200 Subject: wxwindows question References: Message-ID: On Thursday 15 January 2004 11:29 Jason Tesser wrote in : > Have you developed many apps that run on both Linux and Windows?? I don't know how many is 'many', but *I*, alone, have written 17 programs with it in the last 6 months. From concept programs (that might evolve into something else) to business systems. A partner of mine has written almost half of it in the same period while also learning Python... Of those apps I've written 6 rely heavily on database (PostgreSQL) and there are 3 that are in use everyday by lots of people in two different companies. As I said in another message, all development and debugging done by me is done on a Linux box and these companies run both Windows and Linux (being, for now, Windows the most used). I'm still learning a lot being my last lessons on printing (two months ago) and graphics (I'm only needing it now, so I'm studying it while doing lots of other things). Printing was the hardest thing I had to do up to now, but people from the wxPython mailing list help a lot and the documentation, besides not being the best thing that exists, is also very useful and direct to the point. wxWindows, the base of wxPython, is also free and is being adopted by companies such as Borland, what might make the quality improve a lot and make things more efficient. Developers of wxWindows and wxPython are very fast and responsive. Be seeing you, -- Godoy. From CousinStanley at hotmail.com Sat Jan 3 16:18:25 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 3 Jan 2004 14:18:25 -0700 Subject: Graph in wxPython References: Message-ID: | Looks like you're using an older version of matplotlib. | | The WX backend is a fairly recent addition. | | Make sure you are using 0.40 John .... I've got MatPlotLib 0.30 installed here on 2003-10-21 .... I'll look for 0.40 .... Thanks for the update .... -- Cousin Stanley Human Being Phoenix, Arizona From jepler at unpythonic.net Tue Jan 20 19:57:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Jan 2004 18:57:49 -0600 Subject: Pyrex without Python (was Re: calling Pyrex results from C) Message-ID: <20040121005749.GA27424@unpythonic.net> Perhaps I should take the advice given elsewhere to ask on a pyrex mailing list, but I thought I'd try here first. As I mentioned in another thread a few weeks ago, a current hobby is writing code for small embedded processors, where "small" means 1k-4k instructions and 128-1k bytes data. C is a fine language for this as long as you don't use FP arithmetic or much of the standard library. I wish I could write my code in Pyrex, of course keeping to 'int8_t' and 'int16_t' as only basic data types, but it inevitably makes Python API calls. How close to impossible would it be to make Pyrex emit Python-free code if there are only 'cdefs'? Are there any obvious gotchas in Pyrex-generated code if 'int' is a 16-bit datatype? Is there some reason that large stack frames and/or calls to malloc() would be unavoidable in Pyrex? Jeff From skip at pobox.com Sat Jan 24 14:09:47 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 24 Jan 2004 13:09:47 -0600 Subject: utf8 encoding problem In-Reply-To: References: <20040122103549.GA5620@wiggy.net> Message-ID: <16402.49915.534545.987590@montanaro.dyndns.org> >> Luckily that is not true, otherwise it would be completely impossible >> to have websites using non-ascii input. To be specific, the encoding >> used for HTML forms is determined by: [algorithm omitted] Martin> As Denis explains, it is true. See 17.13.4 Sorry, but I'm coming to this discussion late. See "17.13.4" of what document? Thx, Skip From claird at lairds.com Tue Jan 13 12:49:33 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 13 Jan 2004 17:49:33 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> Message-ID: <1008btdlo4li1b1@corp.supernews.com> In article <40041576.D070723E at engcorp.com>, Peter Hansen wrote: >Donn Cave wrote: >> >> Python has the advantage of a clean start, but >> from a software engineering standpoint it really seems like a >> hacker language. > >Ohh.... nice controversial statement. :-) > >I would strongly disagree with the above statement for a number >of reasons, including (random thoughts): > > - packages > - interactive interpreter > - no static typing > - high productivity > - ease of testing > - flexibility > - extremely broad library support > - low learning curve > >and probably a dozen others. I think this has all been discussed before, >though, so I won't belabour the point. Basically, as a software engineer >(nominally a "Systems Design Engineer") I find Python to be hands down >*the* best language I've encountered for use in serious work. I can't >actually think of another which excels on so many fronts. . . . >From a Python standpoint, "software engineering" has made a nice start, but it needs to catch up with hacker insights. -- Cameron Laird Business: http://www.Phaseit.net From ericjnilsen at earthlink.net Tue Jan 6 14:52:54 2004 From: ericjnilsen at earthlink.net (EricN) Date: 6 Jan 2004 11:52:54 -0800 Subject: help needed with class and method confusion References: <20040106102232.19889.00002028@mb-m01.aol.com> Message-ID: Here's one way to do it (undoubtedly there are other ways as well). Sorry, I couldn't loop the moons. Probably a programmer more clever than I could write a factory pattern for it. class Moon: def __init__(self, name, diameter = 0.0, planet = "unknown"): self.NAME = name self.DIAMETER = diameter self.HOMEPLANET = planet def setMoonName(self, name): self.NAME = str(name) def getMoonName(self): return self.NAME def setMoonDiameter(self, diam): self.DIAMETER = float(diam) def getMoonDiameter(self): return self.DIAMETER def setMoonHomePlanet(self, planet): self.HOMEPLANET = str(planet) def getMoonHomePlanet(self): return self.HOMEPLANET if __name__ == "__main__": moons = [] Io = Moon("Io", 1.0, "Jupiter") moons.append(Io) Europa = Moon("Europa", 2.0, "Jupiter") moons.append(Europa) Ganymeade = Moon("Ganymeade", 3.0, "Jupiter") moons.append(Ganymeade) Titan = Moon("Titan", 3.0, "Saturn") moons.append(Titan) for x in range(len(moons)): print moons[x].getMoonName() print moons[x].getMoonDiameter() print moons[x].getMoonHomePlanet() print From http Thu Jan 15 04:12:07 2004 From: http (Paul Rubin) Date: 15 Jan 2004 01:12:07 -0800 Subject: Safe prime numbers in Python References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> Message-ID: <7xad4pbmoo.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > def safe_primes(last=1): > while True: > next = gmpy.next_prime(last) > if gmpy.is_prime((next-1)/2): > yield next > last = next > > Seems to work fairly well. This doesn't generate a random prime, since the choice of primes by next_primes is not uniform. A simple, reasonably fast way to generate these primes randomly is Generate random r, where r==3 (mod 4), i.e. r = 4n+3 for some n Compute s = (r-1)/2 Do fast crude tests on BOTH r and s for primality, i.e. check for small prime divisors (3,5,7,...). If either one has a small divisor throw both away and generate a new pair. This lets you discard most candidate pairs quickly. Now do a more through test (Miller-Rabin or whatever) to make sure r,s are really prime. As mentioned, I have some code around that I'll post when I can find it. It's pretty straightforward and can generally find a pair within a minute or so (maybe less, I don't really remember) on my p3-750. From roy at panix.com Thu Jan 22 21:13:31 2004 From: roy at panix.com (Roy Smith) Date: Thu, 22 Jan 2004 21:13:31 -0500 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: In article <401081A1.E4C34F00 at alcyone.com>, Erik Max Francis wrote: > Gary Robinson wrote: > > > I've recently had a couple of cases of needing exactly what it > > proposes, and > > having to kluge around the fact that it's not there. It's a great > > idea. > > > > If there anywhere else I should be expressing my opinion on this, let > > me > > know. > > Seems quite reasonable to me. The only issue I'd take with it is the > choice of Min and Max for the names of the singletons; they're a little > too close to the functions min and max, which obviously they're both > likely to be used with. I would suggest something a little more verbose > such as Minimum and Maximum, or if you want to get silly, Infimum and > Supremum. I suppose you could special-case min() and max() to return the appropriate singletons if called with no arguments. There's something very nice about that. There's also something very ugly about it. I'm having a hard time deciding which is stronger :-) From gregadelliot at hotmail.com Thu Jan 22 10:51:09 2004 From: gregadelliot at hotmail.com (jeff) Date: 22 Jan 2004 07:51:09 -0800 Subject: performing action on set of charecters Message-ID: hiya, Ive a load of binary in a file. Its 3 bit (2^3) and i wanna convert it to an integer. ive tried using theintergar = string.atoi(thebinary, 2), but that doesnt take it as 3 bit binary it has no spaces it it, so im a bit stuck as to how to do this with python, cheers greg From jjl at pobox.com Mon Jan 19 16:16:48 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Jan 2004 21:16:48 +0000 Subject: secure unpickle? References: <871xpwxe5g.fsf@pobox.com> Message-ID: <87vfn7abb3.fsf@pobox.com> Gandalf writes: > John J. Lee wrote: > > >Gandalf writes: > >[...] > > > >>I'm using this module (based on the documentation you mentioned): > >> > >[...snip...] > > > >What does this have to do with the question? He was worried about > >security of pickle, not asking how to call dumps() and loads(). > > > Well, in that case, get my humble apologies. It was an honest question (even though I didn't expect a useful answer ;-). I now see (thanks to Tim's post) you *did* have an answer in there. John From sholden at holdenweb.com Fri Jan 9 10:10:55 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 9 Jan 2004 10:10:55 -0500 Subject: FW: [zpugdc-gen] PyCon 2004 Message-ID: MessageBill reminds me to remind you that PyCon 2004 early-bird registration ends soon. PyCon is shaping up, and registrations are coming in. Still room for sprints on new topics, though - talk to Jeremy Hylton about them. Still time to send in your paper, too. This year we are also looking for good educational papers, as we have encouraged students to attend with a $50 discount, and they need good learning materials. Still a week before the final paper submission deadline, so go for it! regards -- Steve Holden http://www.holdenweb.com/ ReportLab Enterprise Publishing Solutions http://www.reportlab.com/ Telephone: +1-800 494 3119 Fax: +1 703 278 8289 PyCon DC 2004 George Washington University, March 24-26 -----Original Message----- From: dc-gen-admin at lists.zpug.org [mailto:dc-gen-admin at lists.zpug.org]On Behalf Of Barr Bill P Sent: Friday, January 09, 2004 9:22 AM To: 'dc-gen at lists.zpug.org' Subject: [zpugdc-gen] PyCon 2004 Just a reminder that PyCon 2004 early-bird registration ends on Jan. 31. It's only $175.00! http://pycon.org/dc2004/ -- Bill Barr "MDA is doing for design what UML has done for Java." -Allan Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: From alessandro at sephiroth.it Sun Jan 18 08:30:24 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Sun, 18 Jan 2004 13:30:24 GMT Subject: wxpython toolbar separator and windows xp Message-ID: Hi to all. Using wxpython i can't see toolbar separators (only a space between buttons) under windows xp, is that a os problem ? -- Alessandro From peter at engcorp.com Tue Jan 6 08:44:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 08:44:08 -0500 Subject: Speed? References: Message-ID: <3FFABBA8.3A24716F@engcorp.com> EP wrote: > > On questions of the suitability of Python for CGI, embedded apps, etc., > execution speed comes to mind. I previously read some comparisons which > did not show Python in a good light in this regard: i.e. Python is slow > compared to Perl, C++, Java. > > http://www.flat222.org/mac/bench/ > > Is there more authoritative and current information IRT speed comparisons? > > Is newer Python any faster? > > Also, if Python is a bit slower in execution than some alternative > languages, what do others do in practice to speed it up, and how much of > that optimization do they do? Or is a slower speed to be accepted like one > learns to accept that their lovely bride takes a long time getting ready to > go out ? I would question the wisdom of using any generic benchmark (such as the "console output test" you included) to make decisions about adoption of key technologies. Identify the core characteristics of your intended application, code up a simple benchmark which contains representative code, and see how it stacks up against the competition. We did this with Python on one embedded system we were considering, with a benchmark that included threading, memory allocation and releasing, some simple math, and lots of string operations. The results told us much more than PyStone or something similar would have, and gave us much more confidence in the results. And with Python, of course, it's almost trivial to do this kind of thing, compared to some other languages. Sigh. -Peter From Bill.Scherer at verizonwireless.com Wed Jan 28 08:44:58 2004 From: Bill.Scherer at verizonwireless.com (Bill Scherer) Date: Wed, 28 Jan 2004 08:44:58 -0500 Subject: Compiling DCOracle2 on RH Linux 8.0 In-Reply-To: References: <8725c51c.0401241912.316a7cfc@posting.google.com> Message-ID: <4017BCDA.5050401@VerizonWireless.com> Ron Reidy wrote: >dripton at wizard.net (David Ripton) wrote in message news:<8725c51c.0401241912.316a7cfc at posting.google.com>... > > >>reidyre at yahoo.com (Ron Reidy) wrote in message news:... >> >> >> >>>I am trying to compile DCOracle2 on RedHat 8.0 and make is giving me >>>the following error: >>> >>>gcc -pthread -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes >>>-I/usr/local/include/python2.3 -I/usr/local/include/python2.3 @DEFS@ >>>-I/oracle/app/oracle/9i/rdbms/demo >>>-I/oracle/app/oracle/9i/network/public >>>-I/oracle/app/oracle/9i/plsql/public >>>-I/oracle/app/oracle/9i/rdbms/public -DORACLE9i -c ././dco2.c -o >>>./dco2.o >>>gcc: cannot specify -o with -c or -S and multiple compilations >>> >>> >>>Did I do something wrong? >>> >>> >>No. The DCOracle2 build process isn't very robust. >> >>Look at src/Makefile. Find a line that says "DEFS=%DEFS" and change >>it to "DEFS=-fno-strict-aliasing" >> >> > >David, > >Thanks. That worked well. Now, how do I install it? The only copies >of dco2.so that exist are in the directory tree where I built the >library. In searching for any kind of install directios, I found >nothing like 'make install', etc. > Ron - At the same sevel as the src folder where you built dco2.so, you should find a DCOracle2 folder. Put dco2.so in that folder, and copy that folder into your $PYTHONPATH (site-packages/ would do fine). Then you should be able to start your python and import DCOracle2. HTH, Bill > >Thanks you your help. > > From km at mrna.tn.nic.in Sat Jan 17 12:08:08 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 17 Jan 2004 22:38:08 +0530 Subject: yield Message-ID: <20040117170808.GA21486@mrna.tn.nic.in> Hi all, i didnt understand the purpose of 'yield' keyword and the concept of 'generators' in python. can someone explain me with a small example how generators differ from normal function calls? kindly enlighten regards, KM From donn at u.washington.edu Fri Jan 2 16:56:00 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 02 Jan 2004 13:56:00 -0800 Subject: Problem building on BeOS... References: <8zjJb.725764$Tr4.1845399@attbi_s03> Message-ID: In article <8zjJb.725764$Tr4.1845399 at attbi_s03>, Zoo Keeper wrote: > Is there a way to strip'em? I see "cr nl". :/ Certainly. From the Terminal shell (where you ran "od"), $ tr -d '\r' < oldfile > newfile or if you want to use a more complicated procedure (and untested) #!/bin/sh # case $# in 0) echo Usage: strip file [file ...] >&2 ;; esac new=uncr.$$ for file do tr -d '\r' < $file > $new if cmp $file $new > /dev/null 2>&1 then rm $new else save=$file.dist test -e $save || mv $file $save mv $new $file fi done Donn Cave, donn at u.washington.edu From hungjunglu at yahoo.com Fri Jan 9 14:46:23 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Jan 2004 11:46:23 -0800 Subject: Object-based inheritance in Python References: Message-ID: <8ef9bea6.0401091146.6a86ac0a@posting.google.com> Stephan Diehl wrote in message news:... > Tobias Windeln wrote: > > > > I'm looking for suggestions on object-based inheritance > > in Python. Automatic forwarding (often called delegation) > > in Python is easy: > > > > Have a look at Hans Nowaks 'selfish' implementation: > http://zephyrfalcon.org/download/selfish-0.4.2.zip > > This is a pythonesque interpretation of the 'self' language by Sun. > By the way, if you are googling, you want probably look for 'prototype based > languages'. Seems like prototype-based languages are catching up the attention of people. I have looked at them recently. My feeling is that somehow main development stopped around 1997. I have looked at Io (I know it's born in 2002, but the ideas come from before), but I just get the feeling that Io is not "clean" enough. Anyway, I think that instead of designing final languages, it's a better idea to make *prototype* languages (sorry for the pun) and experiment with various features. One problem I've seen in Io is that they started to write software, when the language itself is not well-defined yet. And so, you make changes to the language, and you have to make corrections to large body of existing code. And, also, once too much code is written with existing language, it becomes really hard to make language changes later: too much work to update legacy packages. There are a few problems with current programming languages that only come to bite you at large scale projects (Multiple Inheritance, Metaprogramming, AOP, Multiple Version handling, Transactional/Incremental programming with real-time rollback/undo, ideas from Functional languages, etc.) And my experience has been that the more complex your project becomes, the more you wish you had a simple, clean, solid, powerful theoretical foundation for your programming language. Prototype-based seems the right direction to go, but I am kind of disappointed at all existing prototype-based languages out there. Somehow something happened in 1997 that stopped research in this direction. And now the prototype-based languages seem so much behind. It's like time has been frozen for 6 years. regards, Hung Jung From martin at v.loewis.de Fri Jan 2 12:41:13 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 02 Jan 2004 18:41:13 +0100 Subject: Problem building on BeOS... In-Reply-To: References: Message-ID: Zoo Keeper wrote: > For some reason, the Python preprocessing balks on the "\" line continuation > character. Any ideas/thoughts? Is it just that my version of gcc is not > supported? Yes, in combination with the way your source files are structured. It appears that the line ending convention differs in your source files from the line endings that gcc expects. E.g. the source files may have \r\n at the end of a line, whereas your gcc may expect only \n. As a result, \\\r\n is treated as an escaped \r, which gives a stray \. I don't know what line ending convention your system uses, or where you got the sources from, but it appears you need to convert them. Later versions of gcc support "universal text mode". Regards, Martin From LittleDanEhren at yahoo.com Sat Jan 31 14:34:28 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 31 Jan 2004 11:34:28 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: <711c7390.0401311134.26cd0a11@posting.google.com> > I think I get the idea. Let's see: > > P = Object clone do( # saw do() used in iolanguage mail archive > allocated = 0 > init = method( > id := allocated # semi-colons required? > allocated += 1 > ) > howMany = method(return allocated) > ) > > x := P clone > y := P clone > write("allocated? ", P howMany()) > # output ... > # allocated? 2 > > Correct? > No, init and allocated should have used :=, even though init has special meaning. I don't really know why you have the howMany method since it doesn't really do anything (everything is public and methods can be called with just references), and all clones of P will dynamically inheret allocated. Also, when initializing variables, their scope must be specified (which is the whole reason for the difference between := and =), so id := allocated should probably be self id := allocated. self, along with a few other variables, is implicitly sent to all functions (and do). > Thanks for making me aware of this language, it has some > interesting ideas. I'm not annoyed by the difference between := > and =. I understand the issue(s) they're trying to solve: you don't > need to declare local variables, or use self, explicitly. I don't have > a problem with that. I imagine it could lead to subtle bugs (if you > update a slot when you meant to set a new one), but that is only > speculation on my part. Actually, the whole scoping model is really that you're working in transparent objects with inheretance, even for things like the global scope and the scope of functions. > > I'm not a fan of the parenthesis (which might be expected from > a Python user - love that significant whitespace ;). At first I didn't like them easier, and with the syntax of most languages, there really isn't any advanatage, but Io code by convention can be much more dense (while still readible). For example, Io doesn't have a ternary operator (like Python), but the flow control function if can be used like one. For example: x := if(Nil, 1, 0) would set x to 0. Note that only Nil (and things that emulate Nil) are false in the context of if. > I'm also not a > big fan of 'clone', I'd rather see 'new', but I do understand why > 'clone' is more apt. Of course, in this language, you could always > just say > > Object new = Object getSlot("clone") > P = Object new > ... > > I can appreciate the flexibility of that. Yeah, that is an advantage. That way of using 'new' will be inhereted dynamically for all objects. Daniel Ehrenberg From steve at ferg.org Thu Jan 8 18:20:00 2004 From: steve at ferg.org (Stephen Ferg) Date: 8 Jan 2004 15:20:00 -0800 Subject: what is Python's module search path? References: Message-ID: Thanks. It says """When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. ... When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation-dependent default.""" Is the installation-dependent default path on Windows usually Lib/site-packages? If so, then it looks like my original search order was wrong, and the correct search order (on Windows) is: --------------------------------------------------------- * Python's built-in modules, including modules in the standard library * the directory from which your main module was loaded * in directories in PYTHONPATH * in the /python23/Libs/site-packages directory -------------------------------------------------------- Is that correct? Part of what is confusing me is that Lib/site-packages is pretty poorly documented. From news at grauer-online.de Sun Jan 25 09:35:27 2004 From: news at grauer-online.de (Uwe Grauer) Date: Sun, 25 Jan 2004 15:35:27 +0100 Subject: My Python cannot find wxPython In-Reply-To: <692feddd.0401241448.447817e2@posting.google.com> References: <692feddd.0401221457.18d40480@posting.google.com> <692feddd.0401241448.447817e2@posting.google.com> Message-ID: Equis Uno wrote: > ... > > Next, I downloaded boa-constructor-0.2.3.src.zip > Get Boa from cvs on sf.net. Actual version is 0.2.8 Uwe From bogdanal at b.astral.ro Sat Jan 10 03:36:07 2004 From: bogdanal at b.astral.ro (Bogdan Marinescu) Date: Sat, 10 Jan 2004 10:36:07 +0200 Subject: Yet another RE question Message-ID: <002b01c3d754$cbe9d5b0$a3e3a4d5@darkore> Hello all, First I want to apologize if this was already discussed before, I can't find an answer anywhere right now. I'm writing a simple compiler for a small language using Spark (http://pages.cpsc.ucalgary.ca/~aycock/spark/). And I just found out that the regular expressions in Python follow the Perl semantics (first-then-longest) instead of the POSIX semantics (longest match). This is quite annoying for me; while some solutions to this problem exists and they are shown in the Spark documentation, I have some background with lex/yacc and I would really like to use the "lex" semantics (longest match). Is there a package for Python that implements this behaviour? Thank you, Bogdan -------------- next part -------------- An HTML attachment was scrubbed... URL: From NAVExchangeprotection at pantheon1.com Mon Jan 26 21:24:40 2004 From: NAVExchangeprotection at pantheon1.com (NAV for Exchange) Date: Mon, 26 Jan 2004 20:24:40 -0600 Subject: Norton AntiVirus detected a virus in a message you sent. The infected attachment was deleted. Message-ID: <2FD388D0DD3CD04280A70646799A413E07C5BB@zeus.pantheon1.com> Recipient of the infected attachment: ZEUS, First Storage Group\Mailbox Store (ZEUS), Jon Stagman/Deleted Items Subject of the message: Error One or more attachments were deleted Attachment file.zip was Deleted for the following reasons: Virus W32.Novarg.A at mm was found in file.scr. From guido at python.org Mon Jan 5 12:44:19 2004 From: guido at python.org (Guido van Rossum) Date: Mon, 05 Jan 2004 09:44:19 -0800 Subject: PyCon Reminder: Proposal deadline 1/15 Message-ID: <200401051744.i05HiJN08590@c-24-5-183-134.client.comcast.net> This is a reminder that the deadline for sending proposals for presentations at PyCon DC 2004 is January 15, 2004. We are interested in any and all submissions about uses of Python and the development of the language. Since there is expected to be a strong educational community presence for the next PyCon, teaching materials of various kinds are also encouraged. You can submit your proposal at: http://submit.pycon.org/ For more information about proposals, see: http://www.pycon.org/dc2004/cfp/ If you have further questions about the submission web interface or the format of submissions, please write to: pycon-organizers at python.org We would like to publish all accepted papers on the web. If your paper is accepted and you prepare an electronic presentation (in PDF, PythonPoint or PowerPoint) we will also happily publish that on the web site once PyCon is over. If you don't want to make a formal presentation, there will be a significant amount of Open Space to allow for informal and spur-of-the-moment presentations for which no formal submission is required. There will also be several Lightning Talk sessions (five minutes or less). About PyCon: PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. PyCon DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. We're looking for volunteers to help run PyCon. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ Pictures from last year's PyCon: http://www.python.org/cgi-bin/moinmoin/PyConPhotos I'm looking forward to seeing you all in DC in March!!! --Guido van Rossum (home page: http://www.python.org/~guido/) From kkto at csis.hku.hk Wed Jan 14 20:36:17 2004 From: kkto at csis.hku.hk (Isaac To) Date: Thu, 15 Jan 2004 09:36:17 +0800 Subject: confusion about Exception Mechanism References: Message-ID: <7ik73uouwe.fsf@enark.csis.hku.hk> >>>>> "Zachary" == Zachary writes: Zachary> Hello, I'm relatively new at Python, and am slightly confused Zachary> about how the try...except mechanism is supposed to work. I am Zachary> just not sure how it would be used, as it just seems that it is Zachary> another sort of loop. Is their any sort of example I could Zachary> look at, that has an example of how it is applied? I haven't Zachary> really seen any such full example. How you think that exception is a kind of loop? E.g., documentation where you get that idea? If any documentation leads you to think that way, the documentation must be clarified (e.g., by modifying it). Regards, Isaac. From jdhunter at ace.bsd.uchicago.edu Tue Jan 27 22:56:59 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 27 Jan 2004 21:56:59 -0600 Subject: Upgrading Python on Red Hat 7.2? In-Reply-To: (Leif K-Brooks's message of "Wed, 28 Jan 2004 02:59:46 GMT") References: Message-ID: >>>>> "Leif" == Leif K-Brooks writes: Leif> I have an ancient server with Red Hat 7.2 and Python Leif> 1.5.2. I want to install mod_python, but I'll need a version Leif> of python from some time after the stone age to do Leif> that. Up2date is broken (missing Python module, go figure), Leif> so I can't use that. The latest RPMs seem to be for Red Hat Leif> 9, will they work with 7.2? If not, will building from Leif> source make versioned binaries only (/usr/bin/pythonX.X Leif> instead of /usr/bin/python)? The default build > ./configure > sudo make install will install to /usr/local/ and thus will not overwrite /usr/bin/python. JDH From jepler at unpythonic.net Sun Jan 18 16:15:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Jan 2004 15:15:59 -0600 Subject: parse binary file in python? In-Reply-To: References: Message-ID: <20040118211559.GC20915@unpythonic.net> Python's primary tool for this is the "struct" module. See the stanard library documentation for more info. Also, remember always to open files in binary mode ("rb") so that people running on windows don't get bizarre failures. Jeff From bart_nessux at hotmail.com Thu Jan 15 15:31:49 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 15 Jan 2004 15:31:49 -0500 Subject: python & mathematical methods of picking numbers at random In-Reply-To: <7xd69largm.fsf@ruckus.brouhaha.com> References: <7xd69largm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Bart Nessux writes: > >>I am using method 'a' below to pick 25 names from a pool of 225. A >>co-worker is using method 'b' by running it 25 times and throwing out >>the winning name (names are associated with numbers) after each run >>and then re-counting the list and doing it all over again. >> >>My boss thinks that 'b' is somehow less fair than 'a', > > > Both are the same, as you can see by calculating the probability of > any given name being selected. What is the application, and the > computer environment? You may also need to worry about correlations > in the underlying Mersenne Twister PRNG. If the application is > something where randomness is very important (you're picking winners > for a big lottery or something) then you should use a better RNG. We're raffling off crock-pots... that's why I think this is OK for our purposes. From bokr at oz.net Thu Jan 8 14:14:18 2004 From: bokr at oz.net (Bengt Richter) Date: 8 Jan 2004 19:14:18 GMT Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> <246a4e07.0401062301.880cb64@posting.google.com> Message-ID: On 6 Jan 2004 23:01:36 -0800, frank at chagford.com (Frank Millman) wrote: >Samuel Walters wrote in message news:... >> >> What exactly *is* a vertical tab? I don't think I've ever seen it on a >> keyboard or used in the wild. I think I may have seen it on the >> keybindings for a mainframe terminal I once used, but I didn't really dig >> too deep because, as far as operating the mainframe was concerned, I was a >> well trained monkey who could check and restart failed jobs. >> >> Inquiring minds want to know. >> >> Sam Walters > >I could be wrong, but I seem to remember reading years ago that >vertical tabs were used to control line printers - you could force the >printer to skip straight to a line number instead of issuing a series >of line feeds. > IIRC some line printers had a punched tape loop that could be punched to indicate stops for VT and FF. And if the tape broke you wound up with the rest of your box of fanfold paper all over the floor, since normal gravity was not enough to refold the amazing spew of output. Add multipart with carbon paper etc for extra fun. Regards, Bengt Richter From CousinStanley at hotmail.com Fri Jan 9 20:18:24 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 9 Jan 2004 18:18:24 -0700 Subject: Problem with OpenGL.GLUT References: <7447dd2a.0401071402.2c0737e6@posting.google.com> <87oetchk33.fsf@hugin.valhalla.net> Message-ID: Sean .... The link that Mike Fletcher posted .... http://pyopengl.sourceforge.net/documentation/installation.html Leads ultimately to the one you posted .... http://www.xmission.com/%7Enate/glut.html I now have a glut32.dll that works fine with Python 2.3 / PyOpenGL .... Thanks for the info .... -- Cousin Stanley Human Being Phoenix, Arizona From me at privacy.net Wed Jan 14 17:21:22 2004 From: me at privacy.net (James Keasley) Date: 14 Jan 2004 22:21:22 GMT Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 In article , Brandon J. Van Every wrote: > Agreed, and more specifically, there is a huge *cultural divide* between > most OSS developers and proprietary commercial developers who simply want to > add some OSS "to get the boring bits over with." Yeah, it indicates that you are a lazy cunt who wants to get something for nothing, if you want to use someone elses work that you haven't commissioned from them, find what you want from someone who isn't fussed, and has used the BSD license, people who have used the GPL have done so cos they *don't* want some software company ripping off their hard work and not contributing anything back. > In fact, one can identify the locus of problems by simply asking, "How many > OSS game developers are willing to work on something with a BSD license?" > Precious few. Most BSD licenses out there are not game software. BSD is a > good indicator that someone cares about commercial concerns. So is the use of the GPL, the people who use that care that commercial concerns can't come along, take their hard work, file off a few serial numbers and flog for $BIG_NUM. If that pisses you off what of it, I suspect that the writers of the software care about as much as I do. - -- James jamesk[at]homeric[dot]co[dot]uk I replaced the headlights on my car with strobe lights. Now it looks like I'm the only one moving. (Steven Wright) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFABcDhqfSmHkD6LvoRAgWgAJ0RTeUPOoKU2eemXbm0NHSNmrmHXgCfRW8r toJ+B4HTbZrv1LnBpLyuOzE= =Mk4Y -----END PGP SIGNATURE----- From gerrit at nl.linux.org Sat Jan 3 16:09:49 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 3 Jan 2004 22:09:49 +0100 Subject: importing In-Reply-To: <231bc96c.0401031249.12cff6d7@posting.google.com> References: <231bc96c.0401031249.12cff6d7@posting.google.com> Message-ID: <20040103210948.GA772@nl.linux.org> Boomer wrote: > here's the error > > Traceback (innermost last): > File "", line 5, in ? > AttributeError: 'string' object has no attribute 'split' You are probably running an ancient Python version. Try upgrading to Python 2.3. If you can't, try to import string and use string.split. If this doesn't work, please send the error message to the list... yours, Gerrit. -- 15. If any one take a male or female slave of the court, or a male or female slave of a freed man, outside the city gates, he shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From aahz at pythoncraft.com Mon Jan 12 23:42:29 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Jan 2004 23:42:29 -0500 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: In article , Frithiof Andreas Jensen wrote: > >That, in my opinion, is wrong: Fortran is successful because it was there >first! Which brings up the obvious question: why isn't Lisp successful? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From max at alcyone.com Thu Jan 8 06:50:04 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 08 Jan 2004 03:50:04 -0800 Subject: Why " ".some_string is often used ? References: Message-ID: <3FFD43EC.BC8240F9@alcyone.com> John Roth wrote: > And I agree, it's not entirely obvious why it's a string > method rather than a list method, since it operates on > a list, not on a string. The only explanation that makes > sense is that, as a list method, it would fail if the list > contained something other than a string. That's still > not very friendly, though. On the contrary, I think that's the best reason. Lists have nothing to do with strings, and so very string-specific methods (discounting system-wide things such as str or repr) being included in lists is not the right approach. Furthermore, the methods associated with a list tend to become the "pattern" that sequence types must fulfill, and it sets a terribly bad precedent to attach whatever domain-specific application that's needed into a sequence type just because it's easiest on the eyes at the moment. The .join method is inherently string specific, and belongs on strings, not lists. There's no doubting that seeing S.join(...) for the first time is a bit of a surprise, but once you understand the reasoning behind it, it makes perfect sense and makes it clear just how much it deserves to stay that way. And above all, of course, if you think it personally looks ugly, you can from string import join or write your own join function that operates over sequences and does whatever else you might wish. That's what the flexibility is there for. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Life is not a spectacle or a feast; it is a predicament. -- George Santayana From raims at dot.com Mon Jan 19 09:22:08 2004 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 19 Jan 2004 15:22:08 +0100 Subject: Tkinter References: Message-ID: <87oet0ow6n.fsf@mobile.foo> km writes: > Is there any good online tutorial which is a good intro for Tkinter > programming in Python ? http://www.pythonware.com/library/an-introduction-to-tkinter.htm -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From theller at python.net Mon Jan 12 16:27:28 2004 From: theller at python.net (Thomas Heller) Date: Mon, 12 Jan 2004 22:27:28 +0100 Subject: py2exe, Inno Setup, and tkinter References: Message-ID: Anthony Baxter writes: > I'm trying to use py2exe and Inno Setup to build an installer for > shtoom, which uses tkinter. > > If I take the py2exe generated directory, and run the executable from > there, it works fine. > > If I add all the files in the directory to an installer (including > the tk-8.4 and tcl-8.4 directories), it builds an installer fine. > > But when I run the installer, and install to, say c:/Program Files/Shtoom, > running the program fails with > Traceback (most recent call last): > File "", line 78, in ? > File "", line 75, in main > File "", line 66, in findUserInterface > File "", line 33, in tryTkInterface > File "shtoom\ui\tkshtoom.pyc", line 23, in main > File "shtoom\ui\tkui\main.pyc", line 11, in __init__ > File "Tkinter.pyc", line 1564, in __init__ > _tkinter.TclError: Can't find a usable init.tcl in the following directories: > {c:/Program Files/lib/tcl8.4} {c:/Program Files/lib/tcl8.4} c:/lib/tcl8.4 {c:/Program Files/library} c:/library c:/../tcl8.4.3/library > > This probably means that Tcl wasn't installed properly. > > The init.tcl is actually in C:/Program Files/Shtoom/tcl8.4. Why is > it not looking in the correct location? How can I fix this? Are you sure your installer reproduces the same directory structure as the dist directory has? I would expect the init.tcl in this directory: c:/Program Files/shtoom/tcl/tcl8.4/init.tcl Thomas From admin2 at enabled.com Fri Jan 16 12:54:44 2004 From: admin2 at enabled.com (Noah) Date: Fri, 16 Jan 2004 09:54:44 -0800 Subject: cannot find input file: Modules/Setup.config.in Message-ID: <20040116175444.M21972@enabled.com> freeBSD 4-8 STABLE cant install Python-2.3.3 configure: creating ./config.status config.status: creating Makefile.pre config.status: creating Modules/Setup.config config.status: error: cannot find input file: Modules/Setup.config.in clues please? - Noah From Z_kline at hotmail.com Wed Jan 14 20:31:41 2004 From: Z_kline at hotmail.com (Zachary) Date: Wed, 14 Jan 2004 17:31:41 -0800 Subject: confusion about Exception Mechanism Message-ID: Hello, I'm relatively new at Python, and am slightly confused about how the try...except mechanism is supposed to work. I am just not sure how it would be used, as it just seems that it is another sort of loop. Is their any sort of example I could look at, that has an example of how it is applied? I haven't really seen any such full example. Thanks, And Sorry for the newbie Question, Zack From deets_noospaam at web.de Wed Jan 14 08:43:01 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 14 Jan 2004 14:43:01 +0100 Subject: passing callback function to c-extension Message-ID: Hi, I'm currently writing my first c-extension module. First of all: distutils and the tutorial for embedding/extending rock! Great work, guys. However, I didn't find a hint how to pass a python callback function. Googling didn't turn out much useful stuff, so I'd be glad if someone could post a hint on how to do this. Regards, Diez From mwilson at the-wire.com Thu Jan 22 10:07:44 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 22 Jan 2004 10:07:44 -0500 Subject: Identifing current function References: Message-ID: In article , Ben Finney wrote: >On Thu, 22 Jan 2004 02:21:54 GMT, Brian Donovan wrote: >> Is there a way to identify the current function. For example: >> >> class A: >> def B(self): >> print current_function_name > >Functions, like all objects, have no inherent name. Names are bound to >objects; each object can have zero, one or more names bound to it. None >of the names has any particular status as "the" name of the object. Functions, classes and modules do have a __name__ attribute. This is often (but not necessarily) the same as the name the thing goes by in a namespace that knows it. It might or might not be the name the O.P. wants. Regards. Mel. From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 23 05:04:47 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 23 Jan 2004 11:04:47 +0100 Subject: cgi concurrency approaches? References: <7x7jzjgso7.fsf@ruckus.brouhaha.com> Message-ID: <66s11056aptit3vd2inv3p3r07v95k52ha@4ax.com> Paul Rubin : >I'm wondering if folks here have favorite lightweight ways of dealing >with concurrency in cgi's. Take a simple case: > >You want to write a cgi that implements a simple counter. The first >time it's called, it prints "1". The next time, "2", etc. [...] >Anyone have some simpler approaches? Use mod_python and keep the counter in a Python variable (if the value needs not be persistent). http://www.modpython.org/ -- Ren? Pijlman From dkuhlman at rexx.com Sun Jan 4 19:42:59 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 04 Jan 2004 16:42:59 -0800 Subject: Progress indicator during FTP upload References: <20040104221012.0cc111a3.no.spam@box> Message-ID: Christophe Delord wrote: > On Sun, 04 Jan 2004 19:31:34 +0100, Frantisek Fuka wrote: > >> My application uses ftplib to upload files to remote server. What >> is the cleanest way to provide progress indicator for long files? >> What exactly should I override in the ftplib (I am not very >> proficient in the FTP protocol)? >> > > Hello, > > To update my web site I wrote a script in wich I have overriden > ftplib.FTP to print a dot when a block of bytes is sent. Here is > my dot_FTP class : Slick. Thank you. Dave [snip] -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From graham at rockcons.co.uk Sun Jan 4 14:20:12 2004 From: graham at rockcons.co.uk (Graham Nicholls) Date: Sun, 04 Jan 2004 19:20:12 +0000 Subject: Launching pdb from within a script References: Message-ID: Peter Otten wrote: > Graham Nicholls wrote: > >> A year or so ago, I was given a really useful answer to a question posed >> here, which showed me how to start the debugger from withing a script. > > Are you looking for pdb.set_trace()? > > Peter I think so, thanks! Graham -- #include From tcdelaney at optusnet.com.au Sat Jan 24 02:29:56 2004 From: tcdelaney at optusnet.com.au (Tim Delaney) Date: Sat, 24 Jan 2004 18:29:56 +1100 Subject: C compilers References: Message-ID: <40121ef3$0$14480$afc38c87@news.optusnet.com.au> "Gerrit Holl" wrote: > Lucas Raab wrote: > > I realize that this is a Python newsgroup, but do any of you know any good > > C/C++ compilers?? > > yes Now now Gerrit - you know you should always include the link in such a response ... http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From jeremy at alum.mit.edu Thu Jan 22 14:13:34 2004 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: Thu, 22 Jan 2004 14:13:34 -0500 Subject: I support PEP 326 In-Reply-To: <40100B15.7060308@prescod.net> References: <40100B15.7060308@prescod.net> Message-ID: <1074798814.27007.148.camel@localhost.localdomain> On Thu, 2004-01-22 at 12:40, Paul Prescod wrote: > As a matter of style wouldn't it be nice to refer to PEPs both by number > and by name? It is just a minor oversight but there is a tendency of > communities to migrate to refering to things just by numbers in a way > that excludes newcomers or hobbiests. > > NOT directed at you in particular Gary! What's PEP 326 again? Jeremy From theller at python.net Thu Jan 8 04:15:01 2004 From: theller at python.net (Thomas Heller) Date: Thu, 08 Jan 2004 10:15:01 +0100 Subject: "Interrupted function call" exception while relogging :( References: Message-ID: <4qv6n6ne.fsf@python.net> lubowiecka at go2.pl (Sylwia) writes: > Hi! > > I need your help... > > I have the following problem. I've implemented the python Windows > Service which behaves like a log supervisor. If the space > > used by log files is bigger than a given upper limit, then it starts > to delete log files until the space is less than a given > > lower limit. I configured the service to start up automatically on > system boot. The script checks the space used by log files > > every 1000 secs. After analyse of the space, it falls asleep > (time.sleep(1000)). Everything works OK, except one thing... > > Since the service is not tied to the user ID of the person starting > it, the service should remain open even when that person > > who started it logs off. So I made an experiment and relogged. After > that it turned out that the service stopped working. The > > Event Viewer returned the error: > > "SvcDoRun > time.sleep(1000) > exceptions.IOError: [Errno 4] Interrupted function call > " > I use Window XP OS and Python and Python 2.3.2 Just an idea: you could try to use win32api.Sleep() instead. Thomas From mwh at python.net Mon Jan 5 12:12:53 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 5 Jan 2004 17:12:53 GMT Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: Ype Kingma writes: > Marco Bubke wrote: > > > Hi > > > > There is the Lock object in the threading module. > > But there is no medode there I could aquire a scoped > > lock like: > > > > mutex = threading.Lock() > > my_lock = mutex.scoped_acquire() # maybe scoped_lock() > > #now this stuff is locked > > > > del mylock > > > > #the lock is released. > > > > def do_domething: > > my_lock = mutex.scoped_acquire() > > #now this stuff is locked > > #the lock is released after its out of scope > > > > > > I have written this my own but I'm not sure there is a drawback > > because its looks so convinent. So I wonder why its not in > > the module? > > Some reasons: > - What should happen when an exception happens during the locked stuff? > - It is possible pass a reference to the lock during the locked stuff, > so although the lock goes out of local scope, there still might be > a reference to it. > - The moment that __del__() is called is not guaranteed. > > You can also do it like this: > > mutex = threading.Lock() > mutex.acquire() > try: > # now this stuff is locked > finally: > mutex.release() # explicit is better than implicit This is the way to do it today. There's PEP 310 which, if accepted, makes this at least shorter to write... (and PEP 310 references a lengthy discussion about whether using __del__ like this is wise). Cheers, mwh -- 3. Syntactic sugar causes cancer of the semicolon. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From christoph at mmc-startup.com Thu Jan 15 15:01:36 2004 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Thu, 15 Jan 2004 21:01:36 +0100 Subject: needed PyXPCOM tutorial. In-Reply-To: <425cc8d1.0401150908.287de0d8@posting.google.com> References: <425cc8d1.0401150908.287de0d8@posting.google.com> Message-ID: <4006F1A0.9050801@mmc-startup.com> mir nazim wrote: >hi >i m in need of a PyXPCOM tutorial. it should explain using python >(instead of JavaScript) for creating apps. if any body can point me to >some web resources or a printed book . >thankz > > Maybe those will help (check 3! They've some more links) http://lxr.mozilla.org/seamonkey/source/extensions/python/xpcom/ http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/ http://pygecko.sourceforge.net/ http://xul.sourceforge.net/ http://luxor-xul.sourceforge.net/ http://www.thomas-schilz.de/MozPython/ (the downloads-dirctory contains installers for upgrading Mozilla to Python-Interpretability) Christoph Becker-Freyseng From Pieter.Claerhout at Creo.com Tue Jan 13 09:30:27 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 13 Jan 2004 15:30:27 +0100 Subject: Make a function call itself after set amount of time Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D86@cseexch01.cse.creoscitex.com> Bart, have a look at the TaskKit subpart of WebWare (http://webware.sourceforge.net/). You can use it run periodic tasks. Pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Bart Nessux [mailto:bart_nessux at hotmail.com] Sent: 13 January 2004 15:24 To: python-list at python.org Subject: Make a function call itself after set amount of time How do I make a function call itself every 24 hours. Also, is there a way to start the program automatically w/o depending on the OS functions like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and xp. Below is an example of what I'm trying to do. TIA def ipconfig_email(): from email.MIMEText import MIMEText import smtplib import time import os u = "user name" #Change This to user's name. f = "my-email-addy" t = "my-email-addy" fp0 = os.popen("ipconfig /all", "r") fp1 = os.popen("psinfo -d -s", "rb") msg = MIMEText(fp0.read() + fp1.read()) fp0.close() fp1.close() msg["Subject"] = "%s's IPconfig Report" % u msg["From"] = f msg["To"] = t h = "my.smtp.server" s = smtplib.SMTP(h) s.sendmail(f, t, msg.as_string()) s.quit() time.sleep(86400) #24 hour sleep HOW_DO_I_CALL_THE_FUNCTION_AGAIN? ipconfig_email() -- http://mail.python.org/mailman/listinfo/python-list From theller at python.net Fri Jan 30 13:14:52 2004 From: theller at python.net (Thomas Heller) Date: Fri, 30 Jan 2004 19:14:52 +0100 Subject: newbie py2exe difficulty References: Message-ID: "Mike C. Fletcher" writes: [a great detailed explanation how to run the py2exe setup script snipped] Mike, I took the freedom to enter this text in the py2exe wiki: Thanks, Thomas From mcherm at mcherm.com Thu Jan 8 08:15:09 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 8 Jan 2004 05:15:09 -0800 Subject: PRE-PEP: new Path class Message-ID: <1073567709.3ffd57dda8cb0@mcherm.com> > > Another Point: > > Should Path be immutable like string? > > I have though about this, too. It should certainly not be fully mutable, > because if a path changes, it changes. But maybe we could have a > .normalise_inplace() which mutates the Path? What consequences would > this have for hashability? > > I like paths to be hashable. so they probably should be immutable. I agree... paths should be immutable. Instead of .normalize_inplace() which changes the behavior of the Path, how about .get_normalized_string() (please find a better name) which allows access to the normalized version without mutating the Path object? (Or perhaps it should be .get_normalized_Path()... I'm not sure.) -- Michael Chermside From amy-g-art at cox.net Tue Jan 27 12:45:16 2004 From: amy-g-art at cox.net (Amy G) Date: Tue, 27 Jan 2004 09:45:16 -0800 Subject: Too many indices References: Message-ID: Posting your script would be helpful. "satish" wrote in message news:mailman.790.1075105274.12720.python-list at python.org... Hi all, I tried to run a small script when I got the following IndexError. Can someone help me in explaining this error ? Traceback (most recent call last): File "satish.py", line 36, in ? mesh = Mesh(db['x'], db['y'], db['z']) File "/usr/lib/python2.2/site-packages/LESTool/CFD_database.py", line 208, in __getitem__ self.readCoords() File "/usr/lib/python2.2/site-packages/LESTool/CFD_database.py", line 239, in readCoords self.data[cgns.x] = MA.array(self.data['coordinates'][0,:,:,:]) IndexError: too many indices Thanks Regards, Satish -- SATISH KUMAR CHIMAKURTHI Graduate Teaching Assistant CFD GROUP UNIVERSITY OF KENTUCKY LEXINGTON KENTUCKY - 40508 Email: skchim0 at engr.uky.edu Mobile: 859-312-8425 From aaron at reportlab.com Sun Jan 11 20:12:46 2004 From: aaron at reportlab.com (Aaron Watters) Date: 11 Jan 2004 17:12:46 -0800 Subject: Databases: Which one's right for me? References: Message-ID: <9a6d7d9d.0401111712.22a74be7@posting.google.com> "Tim Peters" wrote in message news:... > [Aaron Watters] > > BTW, I would like to see somewhere an explanation of how > > ZODB concurrency control and recovery work. Please inform if > > there is some information. I'm not encouraged by the fact that > > in what documentation I can find the definitions are not the > > standard ones. > > Of course you're much more likely to get a useful discussion of this on a > ZODB list, like . > > "The standard" ones aren't all that standard. ANSI SQL-92 defines multiple > isolation levels, and they've been (I think) fairly critiqued as incomplete > and partly ambiguous; e.g., > > A Critique of ANSI SQL Isolation Levels > Hal Berenson, et al. > http://citeseer.nj.nec.com/berenson95critique.html Some SQL isolation levels are hacks to allow long running transactions, etcetera. If you keep to the strictest isolation level you get the classical behaviour which has been studied and elaborated by many very smart people over the last several decades and which is very well understood. Does ZODB support the strictest isolation levels? If so how? If not what does it support exactly? -- Aaron Watters === We'll make our way across the galaxy And head back home on the L.I.E. -- "Laser show", Fountains of Wayne From aaron at reportlab.com Sun Jan 11 12:58:16 2004 From: aaron at reportlab.com (Aaron Watters) Date: 11 Jan 2004 09:58:16 -0800 Subject: Databases: Which one's right for me? References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: <9a6d7d9d.0401110958.693e30d1@posting.google.com> Rene Pijlman wrote in message news:... > Marc: > >Basically I need a db that will travel with my executable script and > >faithfully store and edit the data needed in that script. > > Have a look at ZODB. > > Introduction: > http://www.python.org/workshops/2000-01/proceedings/papers/fulton/zodb3.html BTW, I would like to see somewhere an explanation of how ZODB concurrency control and recovery work. Please inform if there is some information. I'm not encouraged by the fact that in what documentation I can find the definitions are not the standard ones. For example zodb.pdf: """ Isolation means that two programs or threads running in two different transactions cannot see each other's changes until they commit their transactions. """ Database System Concepts, 4th edition, Silberchatz, Korth, Sudarshan p.566 """ Isolation: Even though multiple transactions may execute concurrently the system guarantees that for every pair of transactions Ti and Tj it appears to Ti that either Tj finished executing before Tj started or Tj started executing after Ti finished. """ The zodb definition is far weaker than the standard one (at least in this document). Maybe they really meant something different? For an example of what I'm looking for please see the xsdb documentation http://xsdb.sourceforge.net/concurrency.html or the gadfly documentation http://gadfly.sourceforge.net/recover.html -- Aaron Watters === ...and somewhere in the eprom that hacker he switched context but in is cryptic code I found a statement I could parse: you got to know when to kludge up know when to core dump know when to single step know when to "run" you never count your source lines while your sittin' at the keyboard there'll be time enough for metrics when the hackings done. The Hacker (with apologies to The Gambler) From fredrik at pythonware.com Thu Jan 29 19:27:58 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 30 Jan 2004 01:27:58 +0100 Subject: Color count in PIL References: <2ec1bc1c.0401271443.15f56742@posting.google.com> Message-ID: "Larry" wrote: > I've been walking up, down, and around instances in the object model > of PIL trying to figure out how to easily calculate how many unique > colors are used in an image, specifically a bitmap (mode "P"). Am I > missing something? colors = len(filter(None, im.histogram())) From bkelley at wi.mit.edu Fri Jan 9 23:06:16 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Sat, 10 Jan 2004 04:06:16 GMT Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: <3FFF36A1.40303@v.loewis.de> References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> Message-ID: Martin v. Loewis wrote: > Brian Kelley wrote: > >> Essentially, everything looks like this >> _("STRING") >> >> I got to thinking that this is python, I shouldn't have to do this. >> Why not have a mechanism to capture this data at compile time? > > > Precisely because it is Python you should have to do this. The language > that looks like line noise is a different one... > > Explicit is better than implicit. > Simple is better than complex. I suppose we see a little differently here. What I am suggesting I think is still explicit, the major difference is that when the code is compiled the internationalization tables are generated. I don't see too much difference between using _("STRING") to indicate a string to be internationalized and i"STRING" Except that the later will be automatically noticed at compile time, not run-time. I have also played with international("STRING") >> if a value exists in the international table for >> the given string, the string is converted to the current locale. > > Using what textual domain? > I am using the same mechanism as gettext but tying it into the "import locale" mechanism. >> Now, I don't know if this is a good idea or not, and I may be >> reinventing some wheels, but it has some appealing characteristics and >> ties in with the gettext system really well. Of course, I'm a bit >> leary with changing the python parser but I was uncomfortable with the >> two step process of writing the code, then passing it through a source >> analyzer so that it could be internationalized. > > What is your problem with that technique? You have to extract the > strings *anyway*, because the translators should get a list of the > strings to translate, and not need to worry with your source code. I think this happens fine in both cases. The mechanism for internationalizing with wxPython just didn't feel, well, pythonic. It felt kind of tacked into place. Of course I feel the same way about most C macros :) >> So, am I being silly, redundant or just plain different? > > I do wonder what kind of application are you looking at. How > many strings? How many different translators? How often do > the strings change? Are the strings presented to the immediate > user of the application sitting in front of the terminal where > the application is running, or are there multiple simultaneous > accesses to the same application, e.g. through a Web server? The number of strings doesn't really matter I think as long as you can automatically generate the ones that need to be translated. Both mechanisms do this. I hadn't previously thought about multiple simultaneous users but this could fit in nicely. After some experimentation with the string classes, it turns out that as long as the __repr__ of the string stays unchanged, i.e. in this case the original english version, then the __str__ of a string (the locale specific changes) can change willy-nilly and not affect things like dictionaries and class name lookups. Perhaps I am optimizing the wrong end of the stick. I could change the gettext _("STRING") functionality to (mostly) do what I want without the need for parser changes. However, I was entranced by the thought of writing (in normal python) raise Exception(i"You shouldn't reach this exception at line %s"%line) and automatically generating the translation files at compile time. Of course this is different than raise Exception(_("You shouldn't reach this exception at line %s"%line)) which generates them at run-time or by using the source code-analyzer. I personally think the first one is slightly more explicit. Perhaps raise Exception( internationalize("You shouldn't reach this exception at line %s"%line) ) would be better. Compile-time generation just feels safer to me. The code-analyzer might miss special cases and what not, but if it is generated at compile time it will work all the time. I suppose that there really isn't much difference in the long run as long as tools exist that make these translations relatively easy but I can't quite shake the thought of trying to teach my brother, a biologist, how to enable localization in his code in an easy manner. Anyway, you have made good points and maybe all I need are some better integrated tools for localizing my applications. Since you brought it up, how does gettext handle multiple users? Does each user get a different gettext library (dll) instance? Brian From reply.in.the.newsgroup at my.address.is.invalid Tue Jan 13 13:45:18 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 13 Jan 2004 19:45:18 +0100 Subject: System calls over network References: Message-ID: Gabriel Leblanc: >I am wondering if there's an easy way to do a system call to a file >that resides on the network. Say for example I would like to call the >batch file which is located at > >\\ComputerName\file.bat > >I tried : > >>>> import os >>>> os.popen("\\ComputerName\file.bat") System calls, batch files, UNC paths and pipes are different things. What exactly are you trying to acomplish? And on what platform? Also, you should use raw strings to prevent the double backslash from being escaped to a single backslash: r"\\ComputerName\file.bat" -- Ren? Pijlman From skip at pobox.com Tue Jan 20 16:04:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 20 Jan 2004 15:04:20 -0600 Subject: Do (USA) Python conferences require a coast? In-Reply-To: <6b50e1-goo.ln1@jowls.lairds.org> References: <6b50e1-goo.ln1@jowls.lairds.org> Message-ID: <16397.38868.283539.483276@montanaro.dyndns.org> Kyler> Even the Plone conference (New Orleans) was on a coast. Do Kyler> Python users always have to be "on edge"? I'd vote for Chicago. Of course, technically speaking we're on a coast also. It should be just about the easiest city to get to from anywhere in the US though. Skip From adalke at mindspring.com Thu Jan 1 20:53:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 02 Jan 2004 01:53:23 GMT Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com><99dce321.0312311130.5b7c7c8a@posting.google.com><3ff49f0e.776954150@news.blueyonder.co.uk> Message-ID: Dave Harris: > How many of you will fess up to have written a script named > 'test' and were puzzled when it did not run?? > > UNIX and sh fail to be mature by the proposed measure. How much longer till > they 'come of age'? Or tried to save to a file named "prn" or "aux" under MS Windows ;) Andrew dalke at dalkescientific.com From richie at entrian.com Wed Jan 21 07:58:26 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 21 Jan 2004 12:58:26 +0000 Subject: Pyrex without Python (was Re: calling Pyrex results from C) In-Reply-To: References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> Message-ID: [Andrew] > I just use the compiler package to get an AST for a chunk of Python code > [...] > The nice thing is that the code generator knows the C-level types of > variables How does it know the types? Pyrex adds additional syntax to do this, but if you're using the plain vanilla compiler package then presumably you're doing something else? -- Richie Hindle richie at entrian.com From csgcsg39 at hotmail.com Fri Jan 30 10:47:54 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Fri, 30 Jan 2004 15:47:54 -0000 Subject: Simple list question Message-ID: Dear all, I have a list something like this: ['1','+','2'], I went to go through and change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing this? The way I done it seems wrong, e.g. nod=['1','+','2'] i=0 while i References: Message-ID: <3ff5dc88$0$318$e4fe514c@news.xs4all.nl> Randall Smith wrote: > How do I import a module when given the module name as input? > import modname exec "import "+your_module_name > from modname import * exec "from %s import %s" % (your_module_name, your_imported_symbol) HTH, Irmen. From davidb at mcs.st-and.ac.uk Sun Jan 18 16:16:11 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 18 Jan 2004 13:16:11 -0800 Subject: Fw: PDF library for reading PDF files References: Message-ID: <4de76ee2.0401181316.322922ab@posting.google.com> "Peter Galfi" wrote in message news:... > I am looking for a library in Python that would read PDF files and I > could extract information from the PDF with it. I have searched with > google, but only found libraries that can be used to write PDF files. > > Any ideas? I quickly searched back through Google, but I knew exactly what I was looking for: ;-) http://groups.google.com/groups?selm=4de76ee2.0311251258.2bcf8bea%40posting.google.com The page referred to is here: http://www.boddie.org.uk/david/Projects/Python/pdftools/ The module is very much a "work in progress". You can probably get some text and bitmap images out of a few documents, but that's probably all you can expect unless you want to improve it (and submit patches). Good luck! David From jcarlson at uci.edu Wed Jan 21 22:00:04 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Jan 2004 19:00:04 -0800 Subject: Assignment to slice References: <20040121130236.D8E3.JCARLSON@uci.edu> Message-ID: <20040121185145.C648.JCARLSON@uci.edu> All 'different' language features are 'unusual' until people get used to them. While you are currently saying, "I can't believe people don't think this is strange", the rest of us got over it, and may even be using the feature to get the job done. Hell, I think that Perl variables are f-ing weird. In the dozen languages I've learned over the years, Perl is the only one where you have to say hey, you this variable I'm accessing now, it is a scalar, not a string. What the hell is that? On the other hand, Perl users have gotten used to it, and don't think it is strange. The real difference is that I'm not hanging out on Perl newsgroups or mailing lists saying, "Dude, this variable thing is wack" (this actually has more to do with the fact that I don't much like Perl, and don't use it, than anything else). Get used to slices working the way they do, it is not likely to change anytime soon. - Josiah > I'm just surprised that nobody thinks it's unusual. > > >>> x = [] > >>> x[4] = 5 > Python says "Wrong! Can't do that! I'm quitting now!" > >>> x = [] > >>> x[4:5] = [1,2,3,4,5] > Python says "Ok. Cool. Those indices don't exist in x so I'll just stick > your list at the beginning, > and the indices you used in the slice have nothing to do with where the > elements end up, > since they don't exist in the list anyway." > > To me that doesn't look much different than if python were to do this: > (not real code obviously) > > >>> x = [] > >>> x[4] = 5 > >>> x > [5] > Python says "Well, x[4] doesn't exist so you must have meant x[0]." > > > That would make no sense. So why does it make sense to do that same > exact thing if you're > assigning to a slice, instead of an element? > > That's what I see as inconsistent; not that python does not behave just > like perl. I'm sure that > a little more time will reveal this 'inconsistency' as a shortcoming in > the wiring of my brain, and > not a weird python idiosyncrasy. It's cool to hear other people's take > on it. > Thanks alot. > Rich > > > > > > > > On Wed, 2004-01-21 at 16:09, Josiah Carlson wrote: > > > > Instead python will just tack stuff on to the front of > > > the array. Which, I still believe, is totally > > > inconsistent. But what do I know? I have about 5 > > > minutes of python experience. > > > > > Oh well. Maybe my problem is that I'm using perl as my > > > model of consistency. Plus, it's a minor issue anyway. > > > I just need to be aware of it, and not try to write > > > perl code in python. I need to learn to write python > > > code in python. > > > > There are a few choices that one can make when allowing slice reading > > and writing in sequences. Python made one: never cause an exception for > > integer arguments, and certain indices map to the same location. Perl > > made another: extend the sequence if necessary to fill it out. > > > > Both are consistent and predictable. Python does it one way, Perl does > > it another. Heck, Python has variable definitions that are done one way, > > Perl has variable definitions that are done another. They were choices > > made during the creation that fit a paradigm. > > > > Expecting Python to behave like Perl is like expecting your mother to > > pee standing up; without alteration, it's not gonna happen. > > > > - Josiah From eurleif at ecritters.biz Thu Jan 22 19:19:47 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 23 Jan 2004 00:19:47 GMT Subject: My Python cannot find wxPython In-Reply-To: <692feddd.0401221457.18d40480@posting.google.com> References: <692feddd.0401221457.18d40480@posting.google.com> Message-ID: Equis Uno wrote: > Does Python have a concept like PATH or CLASSPATH? Yes, the PYTHONPATH environment variable. From tim.golden at viacom-outdoor.co.uk Mon Jan 26 11:53:12 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 26 Jan 2004 16:53:12 -0000 Subject: Py2exe and WMI module Message-ID: >From: nekiv at start.no [mailto:nekiv at start.no] > >I'm having a problem when I try to make a standalone installation of a >Python program using Tim Goldens WMI-module. The py2exe produce the >exe-file as expected, but it fails to execute. Well, I've tried to play with wmi-py2exe myself for the first time, with mixed results. If I understand the idea, what you do is this: Use the makepy generator to generate gen_py support for the Microsoft WMI 1.1 Scripting Library. This will result in a proxy module in %TEMP%\gen_py\2.3 (for recent win32all releases) called something like: 565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1.py Note the x0x1x1 at the end. You then need a setup script such as this one: from distutils.core import setup import py2exe setup ( console=["wmi_test.py"], options = { "py2exe": { "typelibs": [('{565783C6-CB41-11D1-8B02-00600806D9B6}', 0, 1, 1)] } } ) That "typelibs" line is made up from the proxy string effectively split like this: "565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1".split ("x") It's not exactly that, but you can work it out for yourself. In fact, the first bit is the CLSID, and the others are the LCID, major and minor numbers from within 565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1.py <... snipped from Python proxy module ...> CLSID = IID('{565783C6-CB41-11D1-8B02-00600806D9B6}') MajorVersion = 1 MinorVersion = 1 LibraryFlags = 8 LCID = 0x0 Given a module, say, wmi_test.py, which imports the wmi module, you can now run c:\python23\python setup.py py2exe in the usual way to create an exe. After that, you're even more on your own than you were before. 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 jsteve17 at tampabay.rr.com Thu Jan 15 10:47:03 2004 From: jsteve17 at tampabay.rr.com (JeffS) Date: Thu, 15 Jan 2004 15:47:03 GMT Subject: QT usage confusion References: <40069912$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > > am I wrong? > please tell me I'm wrong. You're not wrong although there have been persistent rumors that Trolltech will (real soon now) provide a free version of Qt for Windoze. I wouldn't hold my breath. Regards, JeffS From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Tue Jan 20 15:58:21 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 20 Jan 2004 22:58:21 +0200 Subject: New to Python: my impression v. Perl/Ruby References: Message-ID: >>>>> "Phil" == Phil Tomson writes: Phil> Different strokes for different folks, I guess. I remember Phil> that one of the first things I saw about Ruby was that even Phil> interger literals were objects that can receive messages and Phil> thinking how wonderful that was. As you say, you're not Ints are objects in python too: >>> a=1 >>> a.__lshift__(1) 2 Though "sending messages" to int literals is a syntax error. Phil> 10.times do something end Phil> is somehow so clear. It's almost zenlike. It's cute and fun to write, but less cute for people who have to read lots of such code in short time. I have a soft spot for such style also; I kinda like Python's "\n".join(["foo","bar"]), even if most seem to consider it a wart for readability reasons. -- Ville Vainio http://tinyurl.com/2prnb From cookedm+news at physics.mcmaster.ca Thu Jan 15 12:17:26 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 15 Jan 2004 12:17:26 -0500 Subject: Can MayaVi visualize 3D functions in an unstructured grid ? References: <11d4728b.0401150613.1bfb4ca3@posting.google.com> Message-ID: At some point, arian.novruzi at mathstat.uottawa.ca (A. Novruzi) wrote: > Hi, > > I am looking for a free 3D visualization software, running in Linux, > and able to visualize 3D functions in nonstructured mesh (basically, > my mesh is a set of thetraheders used for some 3D FE computations). > > Can anyone confirm that indeed MayaVi can visualize 3D functions in > nonstructured mesh? I went through the manuals but I didn't find that > MayVi can do so. It should. You'll have to write your function to a file, in VTK data format, which supports unstructured grid data. http://mayavi.sourceforge.net/docs/guide/x404.html -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 00:11:40 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 21:11:40 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> <1AjNb.8936$1e.894@newsread2.news.pas.earthlink.net> Message-ID: "Andrew Dalke" wrote in message news:1AjNb.8936$1e.894 at newsread2.news.pas.earthlink.net... > Brandon J. Van Every: > > Is there something fundamentally *wrong* with recognizing how useless > people > > are to your purposes? > > Nope. But if you blabber it to everyone in the manner you have > then when you do need someone else's help you're less likely to > get it. Hello, *what* planet are you on? You think there's some crowd of people out there just waiting to be useful to me? There isn't. That's what I've just taken 6 months to determine. > It's made even worse when you make claims related to your > profession (like "Even 12 years ago, "Computer Graphics: Principles > and Practice" didn't teach texture mapping. It didn't. I have my copy still, and there is no discussion of texture mapping algorithms in it. It was considered "an advanced subject." > Along came DOOM.") which is proveably false for several reasons Whatever dude. I could care less about such chronologies. So, why are you here then? Why are you wasting our time, talking about the finer points of my personal history? I'm here because I just watched Return Of The King, just installed a modem, and just finished a few slices of pizza. > (http://groups.google.com/groups?selm=aemtb.1153%24sb4.720%40newsread2.news. > pas.earthlink.net&oe=UTF-8&output=gplain ) > because then people tend to remind others of your follies to show > that your knowledge is less than you think it is. You are here out of a need to remind myself and others of my knowledge or lack thereof? Wow, what an important job. Hats off to you. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 17:05:22 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 14:05:22 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Peter Ashford" wrote in message news:NlhNb.11982$9k7.221029 at news.xtra.co.nz... > >> > >>Why do you think OS developers owe you any kind of value at all? > > > > I don't. But that's not going to stop me from denigrating them for being > > incapable of fulfillng the kinds of projects I have in mind. > > That's like criticising a high class restraunt for not serving burgers. > If they don't propose to solve your particular needs, criticising them > for not doing so is stupid and redundant. Referring to Bent's astute post, it's more like criticizing an OSS restaurant that says it serves a lot of things, but in fact doesn't. "Cross-platform, so long as your platform is Linux." -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From news at scphillips.co.uk Wed Jan 14 08:58:01 2004 From: news at scphillips.co.uk (Stephen C Phillips) Date: Wed, 14 Jan 2004 13:58:01 +0000 Subject: removing data from the profiler Stats object Message-ID: Hi, I have just started using the Python profiler and cannot get the output I want. Once I have profiled a piece of code and saved the data to a file, I can load it in using the pstats module. I have found that 96% of my program's time is spent in three object methods (and their callees) but want to know what the other 4% is. I can do this: p = pstats.Stats('profile.data') p.print_callees('expensive_method1') p.print_callees('expensive_method2') p.print_callees('expensive_method3') Which makes me think that the data must be held in a tree of some sort, but what I want is to prune those branches from the tree and see the rest of the data: p.print_stats(without expensive_method[123]) I suppose I could roughly get this data by changing the three expensive methods to immediately return some dummy data, but thought it ought to be possible to interrogate the Stats object to get the answer. The other 4% may also include calls to the same functions as in the 96% so it is not just a matter of looking at the data for particular functions. I know it seems silly to be chasing after 4% of the profile but it is important in this case. Thanks. Stephen Phillips. From reply.in.the.newsgroup at my.address.is.invalid Wed Jan 7 06:12:26 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 07 Jan 2004 12:12:26 +0100 Subject: Windows service in Python References: Message-ID: <7bqnvv4bkeu8go66eo6qefib8fr6vinq94@4ax.com> Gandalf: >Can anybody tell me how to write a windows service in Python? http://www.python.org/windows/win32/#NTServices -- Ren? Pijlman From exarkun at intarweb.us Thu Jan 15 00:54:04 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 15 Jan 2004 00:54:04 -0500 Subject: I come not to bury C++, but to praise it... In-Reply-To: References: Message-ID: <20040115055404.GA20894@intarweb.us> On Thu, Jan 15, 2004 at 03:03:53AM +0000, python newbie wrote: > Are you against using C++ wrapped in a library such as wxWindows? This > library makes it pretty easy painless to write cross-platform stuff, but > even on Windows alone, it beats MFC or the going price of Delphi. > Except when it causes memory corruption and segmentation faults :( Jp From peter at engcorp.com Thu Jan 8 10:02:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Jan 2004 10:02:02 -0500 Subject: Why " ".some_string is often used ? References: Message-ID: <3FFD70EA.A6AF3CB8@engcorp.com> John Roth wrote: > > And I agree, it's not entirely obvious why it's a string > method rather than a list method, since it operates on > a list, not on a string. The only explanation that makes > sense is that, as a list method, it would fail if the list > contained something other than a string. That's still > not very friendly, though. One could about as easily argue (and I believe several have done this quite well in the past, better than I anyway) that you are actually operating on the *string*, not the list. You are in effect asking the string to act as a joiner for the elements in the list, not asking the list to join itself using the specified string. At least, if you look at it that way, it might be easier to swallow. -Peter From rays at blue-cove.com Thu Jan 29 19:03:59 2004 From: rays at blue-cove.com (Ray Schumacher) Date: Thu, 29 Jan 2004 16:03:59 -0800 Subject: win32com - .ocx won't Dispatch... Message-ID: <5.2.0.4.0.20040129160249.021eaff8@blue-cove.com> Thanks Markus, At 01:53 PM 1/29/2004, Markus Wankus wrote: >Well - I have never seen "Catastrophic failure" before - but I have fought with win32com and know how frustrating it can be. Also - I am NOT a COM guru - more of a trial and error guru ;o). I'm a Jack-of-all-master-of-none Guru... >Try the following: > >edr_mod = gencache.EnsureModule('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}',0,3,5) > >edr_obj = Dispatch("EDREUTLX.EDREUtlXCtrl.1") > >edr_obj.AboutBox() >>> from win32com.client import * >>> edr_mod = gencache.EnsureModule('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}',0,3,5) >>> edr_obj = Dispatch("EDREUTLX.EDREUtlXCtrl.1") >>> edr_obj.AboutBox > >>> edr_obj.AboutBox() Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\win32com\gen_py\8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py", line 34, in AboutBox return self._oleobj_.InvokeTypes(-552, LCID, 1, (24, 0), (),) pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None) Yep, the same. It sees the methods but fails when requesting them or properties. A capture of the Python com Browser is attached, as well as the .py... Thanks for your help, I did see one other post via Google about the issue, but it was not resolved. Ray >>From: Ray Schumacher >>To: Markus Wankus , python-list at python.org >>Subject: Re: win32com - .ocx won't Dispatch... >>Date: Thu, 29 Jan 2004 13:44:09 -0800 >> >>At 12:12 PM 1/29/2004, Markus Wankus wrote: >> >Open the gen_py'd file 8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py, and do some searching. You should be able to find an obvious main class related to what you are doing (I'm not sure what the .tlb is), and it will say in the comment or docstring that it is a ".", or whatever. >> >>Thanks Markus, >> >>The lines are from CoClassBaseClass: >>... >># This CoClass is known by the name 'EDREUTLX.EDREUtlXCtrl.1' >>class EDREUtlX(CoClassBaseClass): # A CoClass >>... >>That would be a helpful bit for the docs! >> >>So, the util class Dispatches, but all calls (properties and functions) give 'Catastrophic failure' >>Is this really some sort of types problem with this OCX? >>"pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None)" >> >>Thanks for the help, >>Ray >> >>Test run below, kitchen sink included: >> >>C:\projects\CV-Mini>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. >> >>> from win32com.client import * >> >>> util = gencache._GetModule('8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5') >> >>> gencache.GetGeneratedFileName('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA',0,3,5) >>'AA34F82-95C9-11D3-8EB6-00C0DF2247Cx0x3x5' >> >>> gencache.MakeModuleForTypelib('8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5',0 >>,3,5) >> >>> gencache.GetModuleForCLSID('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA') >> >>> gencache.GetClassForCLSID('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA') >> >>> gencache.GetModuleForProgID('EDREUTLX.EDREUtlXCtrl.1') >> >> >>> gencache.EnsureModule('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}',0,3,5) >> >> >>> gencache.EnsureModule('EDREUTLX.EDREUtlXCtrl.1',0,3,5) >> >>> util = Dispatch("EDREUTLX.EDREUtlXCtrl.1") >> >>> util >> >> >>> gencache.EnsureDispatch(util) >> >> >>> >> >>> util = Dispatch("EDREUTLX.EDREUtlXCtrl.1") >> >>> util >> >> >>> # pop-up, no args >>... util.AboutBox() >>Traceback (most recent call last): >> File "", line 2, in ? >> File "C:\Python23\lib\site-packages\win32com\gen_py\8AA34F82-95C9-11D3-8EB6-00 >>C0DF2247CAx0x3x5.py", line 34, in AboutBox >> return self._oleobj_.InvokeTypes(-552, LCID, 1, (24, 0), (),) >>pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None) >> >>> # a property >>... util.Version >>Traceback (most recent call last): >> File "", line 2, in ? >> File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 451, in >> __getattr__ >> return self._ApplyTypes_(*args) >> File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 445, in >> _ApplyTypes_ >> return self._get_good_object_(self._oleobj_.InvokeTypes(*((dispid, 0, wFlags >>, retType, argTypes) + args)), user, resultCLSID) >>pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None) >> >>> >> >> > > >---------- >The new MSN 8: smart spam protection and 2 months FREE* -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- # -*- coding: mbcs -*- # Created by makepy.py version 0.4.8 # By python version 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] # From type library 'EDREUtlX.ocx' # On Wed Jan 28 16:25:02 2004 """EDRE Utility Control""" makepy_version = '0.4.8' python_version = 0x20303f0 import win32com.client.CLSIDToClass, pythoncom import win32com.client.util from pywintypes import IID from win32com.client import Dispatch # The following 3 lines may need tweaking for the particular server # Candidates are pythoncom.Missing and pythoncom.Empty defaultNamedOptArg=pythoncom.Empty defaultNamedNotOptArg=pythoncom.Empty defaultUnnamedArg=pythoncom.Empty CLSID = IID('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}') MajorVersion = 3 MinorVersion = 5 LibraryFlags = 10 LCID = 0x0 from win32com.client import DispatchBaseClass class _DEDREUtlX(DispatchBaseClass): """Dispatch interface for EDREUtlX Control""" CLSID = IID('{8AA34F83-95C9-11D3-8EB6-00C0DF2247CA}') coclass_clsid = IID('{8AA34F85-95C9-11D3-8EB6-00C0DF2247CA}') def AboutBox(self): return self._oleobj_.InvokeTypes(-552, LCID, 1, (24, 0), (),) def GetErrorName(self, ErrorCode=defaultNamedNotOptArg): # Result is a Unicode object - return as-is for this version of Python return self._oleobj_.InvokeTypes(13, LCID, 1, (8, 0), ((3, 0),),ErrorCode) def Query(self, QueryCode=defaultNamedNotOptArg, Param=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(14, LCID, 1, (3, 0), ((3, 0), (3, 0)),QueryCode, Param) def SelectDialog(self): return self._oleobj_.InvokeTypes(12, LCID, 1, (3, 0), (),) _prop_map_get_ = { "ADChannels": (6, 2, (3, 0), (), "ADChannels", None), "BoardName": (5, 2, (8, 0), (), "BoardName", None), "BoardType": (4, 2, (3, 0), (), "BoardType", None), "Counters": (11, 2, (3, 0), (), "Counters", None), "DAChannels": (7, 2, (3, 0), (), "DAChannels", None), "DIOPorts": (8, 2, (3, 0), (), "DIOPorts", None), "DriverVersion": (3, 2, (8, 0), (), "DriverVersion", None), "ManDate": (10, 2, (8, 0), (), "ManDate", None), "Revision": (9, 2, (3, 0), (), "Revision", None), "SerialNumber": (1, 2, (3, 0), (), "SerialNumber", None), "Version": (2, 2, (8, 0), (), "Version", None), } _prop_map_put_ = { "ADChannels" : ((6, LCID, 4, 0),()), "BoardName" : ((5, LCID, 4, 0),()), "BoardType" : ((4, LCID, 4, 0),()), "Counters" : ((11, LCID, 4, 0),()), "DAChannels" : ((7, LCID, 4, 0),()), "DIOPorts" : ((8, LCID, 4, 0),()), "DriverVersion" : ((3, LCID, 4, 0),()), "ManDate" : ((10, LCID, 4, 0),()), "Revision" : ((9, LCID, 4, 0),()), "SerialNumber" : ((1, LCID, 4, 0),()), "Version" : ((2, LCID, 4, 0),()), } class _DEDREUtlXEvents: """Event interface for EDREUtlX Control""" CLSID = CLSID_Sink = IID('{8AA34F84-95C9-11D3-8EB6-00C0DF2247CA}') coclass_clsid = IID('{8AA34F85-95C9-11D3-8EB6-00C0DF2247CA}') _public_methods_ = [] # For COM Server support _dispid_to_func_ = { } def __init__(self, oobj = None): if oobj is None: self._olecp = None else: import win32com.server.util from win32com.server.policy import EventHandlerPolicy cpc=oobj._oleobj_.QueryInterface(pythoncom.IID_IConnectionPointContainer) cp=cpc.FindConnectionPoint(self.CLSID_Sink) cookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy)) self._olecp,self._olecp_cookie = cp,cookie def __del__(self): try: self.close() except pythoncom.com_error: pass def close(self): if self._olecp is not None: cp,cookie,self._olecp,self._olecp_cookie = self._olecp,self._olecp_cookie,None,None cp.Unadvise(cookie) def _query_interface_(self, iid): import win32com.server.util if iid==self.CLSID_Sink: return win32com.server.util.wrap(self) # Event Handlers # If you create handlers, they should have the following prototypes: from win32com.client import CoClassBaseClass # This CoClass is known by the name 'EDREUTLX.EDREUtlXCtrl.1' class EDREUtlX(CoClassBaseClass): # A CoClass # EDRE Utility Control CLSID = IID('{8AA34F85-95C9-11D3-8EB6-00C0DF2247CA}') coclass_sources = [ _DEDREUtlXEvents, ] default_source = _DEDREUtlXEvents coclass_interfaces = [ _DEDREUtlX, ] default_interface = _DEDREUtlX RecordMap = { } CLSIDToClassMap = { '{8AA34F83-95C9-11D3-8EB6-00C0DF2247CA}' : _DEDREUtlX, '{8AA34F84-95C9-11D3-8EB6-00C0DF2247CA}' : _DEDREUtlXEvents, '{8AA34F85-95C9-11D3-8EB6-00C0DF2247CA}' : EDREUtlX, } CLSIDToPackageMap = {} win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap ) VTablesToPackageMap = {} VTablesToClassMap = { } NamesToIIDMap = { '_DEDREUtlX' : '{8AA34F83-95C9-11D3-8EB6-00C0DF2247CA}', '_DEDREUtlXEvents' : '{8AA34F84-95C9-11D3-8EB6-00C0DF2247CA}', } From stephan.diehlNOSPAM at gmx.net Fri Jan 9 06:54:59 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Fri, 09 Jan 2004 12:54:59 +0100 Subject: Object-based inheritance in Python References: Message-ID: Tobias Windeln wrote: > Hi! > > I'm looking for suggestions on object-based inheritance > in Python. Automatic forwarding (often called delegation) > in Python is easy: > Have a look at Hans Nowaks 'selfish' implementation: http://zephyrfalcon.org/download/selfish-0.4.2.zip This is a pythonesque interpretation of the 'self' language by Sun. By the way, if you are googling, you want probably look for 'prototype based languages'. From aienthiwan at mountaincable.net Mon Jan 19 12:49:38 2004 From: aienthiwan at mountaincable.net (Aienthiwan) Date: 19 Jan 2004 09:49:38 -0800 Subject: CGI Python user/group permission weirdness References: Message-ID: Hi Sam, Thanks for your prompt reply, and for all your suggestions. The process is a cgi python script being called from apache, so it's the www-data user that apache generated by default. That idea of making a link is a good one - I'll remember that for next time. I tried pretty much all of what you suggested, to know avail. The last thing I tried shortly after writing this e-mail was going into apache and switching the Group directive from www-data to dbtest in httpd.conf to see if that made a difference; and it did. So it seems to be dropping groups somehow - I did some research on this and all the evidence in apache documentation let to the contrary. I didn't want to leave my www-data user by default as dbtest group, so I tinkered around with it some more, and eventually put it back the way that it was. And then everything started working properly. I wish I had an idea of what I did exactly - serves me right for attempting this stuff at 5 in the morning I guess. Well, problem's solved although I don't know exactly why - thx again for all your help and suggestions! Regards, Aienthiwan Samuel Walters wrote in message news:... > | Aienthiwan said | > > > Ok - this one's a baffling one. > > > I have confirmed that it's the www-data user by calling a > > os.system('whoami') in my script for debugging. > > > The only inconsistancy is in dbtest and cvs. > > Have you tried os.system('groups') to verify that the user is in groups > dbtest and cvs? Though I can't think of a reason why, maybe the script > or the calling process is dropping it's privileges to these groups. > Have you tried making all the directories leading up to the path of the > file executable by dbtest and cvs? Some oddball code may be walking to > the path, rather than jumping to the file. How about world executable? > > If you're just testing, you might also try making the files 777 for a > minute and testing to see if the problem persists. (Don't leave this in > production, only use it to isolate the error.) > > Try making a link from the file you want into another directory. Can you > access it with the same permissions as the original, or perhaps with > different permission? > > What www-daemon is this running on? Some www-daemons can be configured to > lock down certain directories and var is a likely candidate for that. Can > you access other files withing the var directory? If you fail this test, > and succeed with the previous two tests, consider that it might be the > daemon with an out-of-box configuration to keep web-processes out of > sensitive system areas. > > HTH > > I'll post if I think of anything else. > > Sam Walters. From poelzi at poelzi.org Tue Jan 6 12:26:47 2004 From: poelzi at poelzi.org (daniel.poelzleithner) Date: Tue, 06 Jan 2004 18:26:47 +0100 Subject: Problems with threads and embedding In-Reply-To: <20040106160036.GJ18443@unpythonic.net> References: <3FFAC395.9080900@poelzi.org> <20040106160036.GJ18443@unpythonic.net> Message-ID: <3FFAEFD7.8070705@poelzi.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jeff Epler wrote: | This suggests that the problem may be architecture-specific, | thread-library specific, or it may be due to some difference between | the normal python executable and the executable with embedded Python. Thanks for testing. i forgot: [poelzi at dirus]> python/ gcc --version gcc.real (GCC) 3.3.2 (Debian) Copyright (C) 2003 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [poelzi at dirus]> python/ python -V Python 2.3.3 [poelzi at dirus]> python/ uname -a Linux dirus.intra.poelzi.org 2.4.22 #5 Sa Okt 18 22:45:53 CEST 2003 i686 GNU/Linux glibc: Version: 2.3.2 regards ~ Daniel - -- nihil me cirumdat .. . .. ... . . .. . ... . .. . ... . . . pgp key @ http://files.poelzi.org/pgp.txt ED80 E53D 5269 4BB1 1E73 3A53 CBF9 A421 0A7B 003D -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Debian - http://enigmail.mozdev.org iD8DBQE/+u/Wy/mkIQp7AD0RAh3NAKDO8NiT/RGfU5b7hMArdVFRKY1mfwCg1T5J osWEFOghslxRgzXcFtAvzpI= =5dTV -----END PGP SIGNATURE----- From stefano.covino at libero.it Wed Jan 14 04:08:27 2004 From: stefano.covino at libero.it (Stefano Covino) Date: Wed, 14 Jan 2004 10:08:27 +0100 Subject: function minimization Message-ID: Hi! Does anyone of you know a python library to find minima of multivariable mathematical functions? I know that in SciPy there is what I need, however I wonder if there is something lighter without the need to install the whole package. Thank you a lot, Stefano From cliechti at gmx.net Fri Jan 30 14:28:10 2004 From: cliechti at gmx.net (Chris Liechti) Date: Fri, 30 Jan 2004 19:28:10 +0000 (UTC) Subject: Tcp/ip programs in python References: Message-ID: Jp Calderone wrote in news:mailman.1056.1075488164.12720.python-list at python.org: > On Fri, Jan 30, 2004 at 06:27:45PM -0000, M.Dikmen wrote: >> Do you now a source about socket programming in python? or some source >> codes, demo programs? i really need them >> > In order of increasing relevance: not to forget the python documentation that is also on your harddisk... http://www.python.org/doc/current/lib/socket-example.html and also http://www.amk.ca/python/howto/sockets/ (found on http://www.python.org/doc/) > http://www.google.com/ > > http://www.vex.net/parnassus/ > > http://www.twistedmatrix.com/ > > Jp -- Chris From guido at python.org Thu Jan 22 10:02:09 2004 From: guido at python.org (Guido van Rossum) Date: Thu, 22 Jan 2004 07:02:09 -0800 Subject: PyCon price schedule correction In-Reply-To: Your message of "Mon, 19 Jan 2004 09:50:31 PST." Message-ID: <200401221502.i0MF29812035@c-24-5-183-134.client.comcast.net> In my previous announcement, I wrote: > This is a reminder that the deadline for early bird registration for > PyCon DC 2004 is February 1, 2004. Early bird registration is $175; > after that, it will be $200 through March 17, then $250 at the door. Unfortunately this gave a too rose-colored view on the not-so-early registration fees. The correct price schedule is: - Early bird (through Feb 1) $175 - Normal reg (until March 17) $250 <-- correction! - Walk-ins $300 <-- correction! To register, visit: http://www.pycon.org/dc2004/register/ I urge everybody coming to the conference to register ASAP -- save yourself or your employer $75!!! You have until February 1st. --Guido van Rossum (home page: http://www.python.org/~guido/) From usenet_spam at janc.invalid Fri Jan 9 16:39:09 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 09 Jan 2004 21:39:09 GMT Subject: Python is far from a top performer according to benchmark test... References: Message-ID: "Krzysztof Stachlewski" schreef: > With "heavy use of Numeric module" you were calling functions > written in C. So how can you say that Python is fast, > when C code is doing all the work. I think all (or at least most) of the tested compilers, VMs, etc. were written in C/C++, and thus are using libraries written in C/C++... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From rajas_sambhare at lycos.com Tue Jan 6 15:12:15 2004 From: rajas_sambhare at lycos.com (Rajas Sambhare) Date: 6 Jan 2004 12:12:15 -0800 Subject: libmysqld.dll almost working in python... Message-ID: Hi, This is a followup on a previous thread by JZ http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=ki39sv8s7ui622uriis8mfsg1daca34qqu%404ax.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3Dki39sv8s7ui622uriis8mfsg1daca34qqu%25404ax.com The mysql-python page at sourceforge.net contains beta versions of mysqldb (specifically 0.9.3b2). This does have the necessary embedded server support. Some amount tweaking of setup.py is required (namely pointing the lib variable to the correct directory (usually c:/mysql/Embedded/DLL/Release). The library builds and installs, and typing import MySQLdb at the python prompt loads LIBMYSQLD.DLL. What happens then though, is that calling MySQLdb.server_init with the correct parameters causes the python IDE to crash, with an access violation in LIBMYSQLD.DLL. I checked a bit and it seems the flag USE_TLS has to be set for the mysys project in the mysql source. http://dbforums.com/arch/156/2002/11/554910 I did this, created a new libmysqld.dll etc, and recompiled mysqldb 0.9.3b2, but the problem continues. Does anybody know how to avoid this? Thanks Rajas Sambhare From tepihlaj at NOpaju.SPAMoulu.fi Mon Jan 5 17:39:19 2004 From: tepihlaj at NOpaju.SPAMoulu.fi (Tero Pihlajakoski) Date: 5 Jan 2004 22:39:19 GMT Subject: Python/C and PYTHONPATH References: Message-ID: Samuel Walters wrote: > Fair warning: At this point, I couldn't even get the example you quoted > to link properly. Of course, I didn't dig too deep, as I'm in a hurry. > ---code--- ... snip ... > Or, call setenv ("man 3 setenv") to manually set a python-path. > you can use that in combo with getenv ("man 3 getenv") to append to an > existing PYTHONPATH, if you so choose. > Give it a go, please let me know how it turns out. If this doesn't shed > some light on the matter I might have another idea once I'm not rushing > around. (Sorry for the delay, I was offline) I'll see if it's actually the C-part that's causing problems, but I worked it around by adding: PyRun_SimpleString("import sys\nsys.path.insert(0,'')"); right after the Py_Initialize(). Works ok. Guess I'm "allowed" to do that(?) Thanks, - Tero -- From jeremy at jdyallop.freeserve.co.uk Sat Jan 17 18:38:01 2004 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 17 Jan 2004 23:38:01 GMT Subject: Best way to do this? References: <100jg9er3qak890@corp.supernews.com> Message-ID: Wil Schultz wrote: > One of the exercises asks for a program to ask for a password three > times. Surprisingly this took me much longer that it probably should > have so I am curious if the following is the easiest way this is done. > Thanks much! > > ************************************************* > #!/usr/local/bin/python > > count = 0 > password = "null" > > while count < 3: > count = count + 1 > password = raw_input("what's the pass: ") > if password == "mypass": > print "Access Granted" > count = 3 > else: > if count < 3: > print "Try Again" > else: > print "Too Bad" > ************************************************* I'd write it something like this: from getpass import getpass attempts, password = 3, 'mypass' for i in range(attempts): if i != 0: print 'Try again' if getpass("What's the pass: ") == password: print 'Access Granted' break else: print 'Too bad' Jeremy. From google at axiomatize.com Fri Jan 16 19:04:07 2004 From: google at axiomatize.com (Laurent Therond) Date: 16 Jan 2004 16:04:07 -0800 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> <265368cb.0401151529.50c36679@posting.google.com> <4007F50F.E2AF33AD@engcorp.com> Message-ID: <265368cb.0401161604.58099d89@posting.google.com> Peter, thank you for taking the time to answer. I will need some time to digest this information. >From where I stand, a Python newbie who knows more about Java, this concept of binary string is puzzling. I wish Python dealt in Unicode natively, as Java does. It makes things a lot easier to comprehend. Having strings be byte arrays, on the other, seems to confuse me. From CousinStanley at hotmail.com Fri Jan 9 15:01:09 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 9 Jan 2004 13:01:09 -0700 Subject: Problem with OpenGL.GLUT References: <7447dd2a.0401071402.2c0737e6@posting.google.com> Message-ID: Steven .... I'm also having import problems with a Win98 installation of PyOpenGL for Python 2.3 from .... http://prdownloads.sourceforge.net/pyopengl /PyOpenGL-2.0.1.07.py2.3-numpy23.exe?download Any of the test programs in the Demo folder that attempt from OpenGL.GLUT fail as does a direct import attempt from the Python interpreter .... python Enthought Edition build 1028 Python 2.3 (#46, Aug 11 2003, 09:34:05) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from OpenGL.GLUT import * Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: One of the library files needed to run this applic ation cannot be found. Using < dependency walker > to examine .... /site-packages/OpenGL/GLUT.pyd shows .... glut32.dll * Not Found * I've done a few searches on Google, but as yet haven't turned up what seems to be a compatible version of this particular missing DLL file .... Hopefully, someone here might know how to resolve this .... -- Cousin Stanley Human Being Phoenix, Arizona From jolsen at mail2world.com Thu Jan 29 04:37:28 2004 From: jolsen at mail2world.com (Jesper Olsen) Date: 29 Jan 2004 01:37:28 -0800 Subject: newsgroup lib References: <6b17fa95.0401280501.4be454cb@posting.google.com> Message-ID: <6b17fa95.0401290137.74dbef58@posting.google.com> Gerrit Holl wrote in message news:... > Jesper Olsen wrote: > > Is there a python module for accessing newsgroup articles? > > You're looking for nntplib > > http://www.python.org/dev/doc/devel/lib/module-nntplib.html > Indeed so. Thanks Gerrit & deelan Jesper From jepler at unpythonic.net Sat Jan 24 11:26:14 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 24 Jan 2004 10:26:14 -0600 Subject: Changing endian format In-Reply-To: <20040124145616.34640.qmail@web41306.mail.yahoo.com> References: <20040124145616.34640.qmail@web41306.mail.yahoo.com> Message-ID: <20040124162614.GB32445@unpythonic.net> On Sat, Jan 24, 2004 at 06:56:16AM -0800, Amit Gaur wrote: > Hi newbie to python here, > I have a binary file and i need to change the endian format..little to big as well as vice versa..could anyone help me out. > thanks The struct module supports an endian flag. As an example, suppose my data format is AAAA BB CC a 4-byte int followed by two 2-byte ints, and my task is to take a big-endian version of the data and convert it to small-endian: import struct def convert(format, s, e1, e2): l = struct.unpack(e1 + format, s) return struct.pack(e2 + format, *l) >>> convert("LHH", "12345678", ">", "<") '43216587' See the struct module documentation for more information. Jeff From newsgroups at jhrothjr.com Thu Jan 22 13:26:07 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 22 Jan 2004 13:26:07 -0500 Subject: What is object() References: Message-ID: <10105gchtsl1a21@news.supernews.com> "Aahz" wrote in message news:bup01m$hjm$1 at panix1.panix.com... > In article , > Hameed Khan wrote: > > > > i was reading library refrence manual. there i found > >object() function. they says in library refrence that > > "Return a new featureless object. object() is > >a base for all new style classes. It has the methods > >that are common to all instances of new style > >classes." > > There's not much use for an instance of object. Don't worry about it. Unless, of course, you're using the __new__() method. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ From james at logicalprogression.net Wed Jan 21 11:15:09 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 16:15:09 +0000 Subject: newbie: prefix operator "**" In-Reply-To: <20040121155959.GB18498@unpythonic.net> References: <20040121155959.GB18498@unpythonic.net> Message-ID: <200401211615.09463.james@logicalprogression.net> On Wednesday 21 January 2004 3:59 pm, Jeff Epler wrote: > On Wed, Jan 21, 2004 at 10:33:49AM -0500, Christian Jauvin wrote: > > Hello, > > > > I am playing with some classes in the Tkinter module > > to learn some GUI basics. > > Take a look at the Tutorial, section 4.7.2. The ** prefix for an > argument means that it accepts arbitrary keyword arguments. > http://python.org/doc/tut/node6.html#SECTION006720000000000000000 > > Example: > > def f(**kw): > print kw > > >>> f(a=1, b=2) > > {'a': 1, 'b': 2} Since Jeff beat me to it with his reply and reference to the tutorial I'll just add that ** is also used in a sort of reverse sense when calling - as opposed to defining - a function, so that you can pass a dictionary to a function and have all the key-value pairs treated as keyword arguments. This is called the extended call syntax and might be useful, for example, if a function with keyword arguments dictionary wants to pass these values on to another function, e.g.: def f(**kw): print kw def g(**kw): f(**kw) # extended call sytax g(a=1, b=2) With the same result as above. Extended call sytax is most useful to avoid the use of the deprecated apply(). See: http://www.python.org/doc/current/lib/non-essential-built-in-funcs.html under apply() and: http://www.python.org/doc/current/ref/calls.html Finally, as two stars are used for arbitrary dictionaries single stars are used for arbitrary sequences. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From cphsu at zen.com.tw Wed Jan 7 03:33:17 2004 From: cphsu at zen.com.tw (Kent Hsu (Hsu, Chih-Peng)) Date: Wed, 7 Jan 2004 16:33:17 +0800 Subject: os.system always opens new window on Windows XP/2000 References: Message-ID: John wrote in message news:d0132d7d.0401061045.73c28639 at posting.google.com... > Can anyone tell me how to run a bunch of commands in the same command > line window? When I do this: > > system("command1") > system("command2") > ... If you just want to hide the console window, try "win32process.CreateProcess" If you want to set environment variables, I think batch file is OK. Best Regards, Kent Hsu > > it opens a new window for every system call. The alternative I can > think of is to write out the command to a batch file and run that, but > I'm wondering if there is a better way to do it. > > Partly it is annoying to have 20 cmd windows flash on the screen, but > also I don't think it works if I do something like this: > > system("set envvar=hi") > > since I think the envvar does not persist once the command window is > closed. > > thanks! From nemesis at nowhere.invalid Sat Jan 24 14:39:42 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Sat, 24 Jan 2004 19:39:42 GMT Subject: any news client in Python? References: <2b4c49e0.0401230915.3438810f@posting.google.com> Message-ID: Mentre io pensavo ad una intro simpatica "Daniel Han" scriveva: > hello everybody. > i've been looking around for a decent newsreader (not rss) > that's written in Python. Strange, but i found none so far, > i've been to sf.net, freshmeat.net, and even googled that, > still nothing interesting. I know two newsreader written in Python at least. 1) Pyne, it is a mailreader/newsreader. It is good but lacks some charset related features. I don't remember the url. 2) XPN, it is an on-line newsreader written in Python+GTK2. I wrote it :-) It is at an early stage but is quite usable (better with a local server). Home page is in my sign, it is in italian, you can also check http://sourceforge.net/projects/xpn -- This is not a beer belly. It's a fuel tank for a sex machine. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From __peter__ at web.de Sat Jan 3 07:14:53 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Jan 2004 13:14:53 +0100 Subject: Filename type (Was: Re: finding file size) References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: Gerrit Holl wrote: > I propose to add a "filename" type to Python. > A different solution to this problem would be to introduce "filename" > type to Python, a subclass of str. The "name" attribute of file would be > of this type. This type would inherit a lot of os.path stuff: getsize > becomes simpler, more readable, and more object oriented, as do other > os.path functions. I think the alternatives look a lot more prety: > OLD NEW > os.path.realpath(fn) fn.realpath() > os.path.getmtime(fp.name) fp.name.getmtime() > os.path.ismount(os.path.dirname(fp.name)) fp.name.dirname().ismount() > > It's more beatiful, simpler, flatter (#3), practical, obvious, easy. You might have a look at http://mail.python.org/pipermail/python-list/2002-June/108425.html http://members.rogers.com/mcfletch/programming/filepath.py has an implementation of your proposal by Mike C. Fletcher. I think both filename class and os.path functions can peacefully coexist. Peter From gerrit at nl.linux.org Fri Jan 30 04:36:39 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 30 Jan 2004 10:36:39 +0100 Subject: Sort by key, then by content In-Reply-To: <200401292348.57424.shaleh@speakeasy.net> References: <9A8139BC-52F3-11D8-9115-000A959CB2EC@netmail.to> <200401292348.57424.shaleh@speakeasy.net> Message-ID: <20040130093639.GA3385@nl.linux.org> Sean 'Shaleh' Perry wrote: > >>> contents = zip(d.keys(), d.values()) How does this differ from d.items()? Gerrit. -- 42. If any one take over a field to till it, and obtain no harvest therefrom, it must be proved that he did no work on the field, and he must deliver grain, just as his neighbor raised, to the owner of the field. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From linus.elman at NOZPAMuniworkstech.com Mon Jan 5 19:17:08 2004 From: linus.elman at NOZPAMuniworkstech.com (Linus Elman) Date: Tue, 06 Jan 2004 00:17:08 GMT Subject: Thumbnailing webpages References: Message-ID: <88nKb.45072$dP1.183571@newsc.telia.net> Harald! I saw a message you wrote here last spring but being unable to reply to that one I do that here instead. You were interested in a component that creates thumbnails from webpages. Check out http://www.uniworkstech.com/com.htm , this one does just that. Any page, any thumb size and emulates any screen resolution (even weird ones like 1024x10000). Good luck! /Linus From cmkleffner at gmx.de Wed Jan 14 12:09:16 2004 From: cmkleffner at gmx.de (cmkl) Date: 14 Jan 2004 09:09:16 -0800 Subject: function minimization References: Message-ID: <3b091a1c.0401140909.78f3d66d@posting.google.com> what about "Differential Evolution" for Continuous Function Optimization? (by Kenneth Price and Rainer Storn) http://www.icsi.berkeley.edu/~storn/code.html there is a link to a pure python example on the web page. Carl Stefano Covino wrote in message news:... > Hi! > > Does anyone of you know a python library to find minima of > multivariable mathematical functions? > > I know that in SciPy there is what I need, however I wonder if there is > something lighter without the need to install the whole package. > > Thank you a lot, > Stefano From newsgroups at jhrothjr.com Tue Jan 27 15:23:44 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 27 Jan 2004 15:23:44 -0500 Subject: descriptors and old-style classes References: Message-ID: <101dia2qordds0b@news.supernews.com> "Adrien Di Mascio" wrote in message news:slrnc1d88e.qr.adim at lacerta.logilab.fr... > Hi, > > I've recently discovered that descriptors can be used with old-style > classes if they don't define a __set__ method (and this would be why > class and static methods are usable with old-style classes). > I understand why the __set__ method is not called with old-style > classes, but I don't understand why __get__ *is* called. > I thought the transformation from : > a.x > into : > type(a).__dict__['x'].__get__(a, type(a)) > was done in object.__getattribute__ (or type.__getattribute__), but then > this does not explain why this also seems to work with old-style > classes. > > Could someboby help me here ?? At a rough guess, the search logic is in __getattribute__, but the actual invocation is probably in the bytecode somewhere. __getattribute__, after all, is supposed to return the attribute requested, not to invoke it. So on an old style class, the standard search will find the descriptor object just fine, then the bytecode will detect it has a __get__ method and invoke it. John Roth > > Cheers, > Adrien. > > -- > Adrien Di Mascio > LOGILAB, Paris (France). > http://www.logilab.com http://www.logilab.fr http://www.logilab.org > From admin2 at enabled.com Thu Jan 15 12:15:16 2004 From: admin2 at enabled.com (Noah) Date: Thu, 15 Jan 2004 09:15:16 -0800 Subject: cannot find input file: Modules/Setup.config.in Message-ID: <20040115171436.M94467@enabled.com> freeBSD 4-8 STABLE cant install Python-2.3.3 configure: creating ./config.status config.status: creating Makefile.pre config.status: creating Modules/Setup.config config.status: error: cannot find input file: Modules/Setup.config.in clues please? - Noah From destan at sdu.edu.tr Mon Jan 5 11:03:44 2004 From: destan at sdu.edu.tr (Destan YILANCI) Date: Mon, 05 Jan 2004 18:03:44 +0200 Subject: (no subject) Message-ID: <3FF98AE0.2070100@sdu.edu.tr> From wweston at att.net Thu Jan 29 16:11:02 2004 From: wweston at att.net (wes weston) Date: Thu, 29 Jan 2004 21:11:02 GMT Subject: ditto In-Reply-To: References: Message-ID: Preferably, a program that runs or a screen dump. Mark McEahern wrote: > Elaine Jackson wrote: > >> If bool(B_i)==True for 1<=i<=n and j is the smallest i with >> bool(A_j)==True, >> then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns >> B_j without >> evaluating any other B_i. This is such a useful mode of expression >> that I would >> like to be able to use something similar even when there is an i with >> bool(B_i)==False. The only thing I can think of by myself is ( (A_1 >> and [B_1]) >> or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for >> obvious >> reasons. Does anybody know a good way to express this? Any help will >> be mucho >> appreciado. >> > Why not write a unit test that demonstrates the behavior you want? > It'll then likely be obvious to someone both what your problem is and > what a likely solution is. > > Cheers, > > // m > From aahz at pythoncraft.com Wed Jan 28 12:00:46 2004 From: aahz at pythoncraft.com (Aahz) Date: 28 Jan 2004 12:00:46 -0500 Subject: PEP 326 is D-E-A-D (was Re: How does compare work?) References: <40158680$0$7044$ba620e4c@news.skynet.be> <20040126235704.GD13453@siliconimage.com> Message-ID: In article , Mel Wilson wrote: > >Even then, what about PEP 326, which presumes to define highest and >lowest objects that can be compared with anything? What about it? ;-) (Guido just posted a Pronouncement rejecting it.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From ebgym at tm.net.my Thu Jan 8 23:49:47 2004 From: ebgym at tm.net.my (Mei) Date: Fri, 09 Jan 2004 12:49:47 +0800 Subject: silent saveas ? Message-ID: <000001c3d66c$0238ba30$0100a8c0@mei> HI! Sir, I'm having difficulties to save the web browser in silent. when I try to use WebBrowser1.ExecWB OLECMDID_SAVEAS, OLECMDEXECOPT_DONTPROMPTUSER, "c:\blank.html", "c:\blank.html" The save window keep prompting up. How can I keep the save window in silent? Please help me, Thanks a lot Mei -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcarlson at uci.edu Tue Jan 20 03:13:52 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 00:13:52 -0800 Subject: PDF library for reading PDF files References: <400BFF7B.95F21050@netsurf.de> Message-ID: <20040120001121.E680.JCARLSON@uci.edu> > Thanks. I am studying the PDF spec, it just does not seem to be that easy > having to implement all the decompressions, etc. The "information" I am > trying to extract from the PDF file is the text, specifically in a way to > keep the original paragraphs of the text. I have seen so far one shareware > standalone tool that extracts the text (and a lot of other formatting > garbage) into an RTF document keeping the paragraphs as well. I would need > only the text. > > Any suggestions? Peter, Suggestion: extract the document to RTF using that other tool, then use any one of the few dozen RTF parsers to convert them into plaintext. - Josiah From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 16:45:06 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 15 Jan 2004 13:45:06 -0800 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: Gerry Quinn wrote: > In article , "Brandon J. > Van Every" wrote: >> Agreed, and more specifically, there is a huge *cultural divide* >> between >> most OSS developers and proprietary commercial developers who simply >> want to >> add some OSS "to get the boring bits over with." > > And guess what bits of a project OSS programmers often tend not to > bother finishing? > > As somebody once said, the purpose of paying wages is not to motivate > people to work. It's to motivate them to come in on Monday mornings. > > Think of the boring bits as commercial software's secret weapon ;-) Some boring bits are easily accomplished, and tractable through incremental, communal effort. Others take too much pain to bother with. I think in theory, commercial developers could alleviate themselves of certain boring problems through BSD open source projects. A good example would be http://nebuladevice.sourceforge.net . Of course, that project would never have gotten off the ground without the up front contribution of Radon Labs, but since they did decide to do that, it's a viable 3D engine for solving various people's problems. In practice, there's all kinds of "Not Invented Here" and "Make Myself Invaluable" out there. I see a lot of political reasons why human beings will never cooperate to save humanity much labor. Even when projects *are* BSD licensed, like Python for instance, you can get people refusing to *market* a product properly for predictable political reasons. Distaste for commercial developers, "suits," other people's problems, etc. Consequently, relevance is diminished. When relevance is diminished, the available solutions become fractured and things don't work well together. Redundant labor is performed because people gotta be different, they gotta try to make everyone else march to *their* drum instead of being more inclusive. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From fumanchu at amor.org Mon Jan 5 14:59:13 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 5 Jan 2004 11:59:13 -0800 Subject: Problem: 'Threads' in Python? Message-ID: If you use mod_python with Apache, or ASP/IIS, you can spawn a new thread (see the threading module in the Python Library), and the page request will complete. Since the python module is not reloaded between requests, the new thread will continue even after the original thread has terminated. Not sure if that's worth it to you to change, or if there's a way to do it with bare cgi. FuManChu at amor.org > -----Original Message----- > From: Ralph Sluiters [mailto:ralph at sluiters.de] > Sent: Monday, January 05, 2004 11:58 AM > To: python-list at python.org > Subject: Problem: 'Threads' in Python? > > > Hi, > i've got a small problem with my python-script. It is a > cgi-script, which is > called regulary (e.g. every 5 minutes) and returns a > xml-data-structure. > This script calls a very slow function, with a duration of > 10-40 seconds. To > avoid delays, i inserted a cache for the data. So, if the > script is called, > it returns the last caculated data-structure and then the > function is called > again and the new data is stored in the cache. (There is no > problem to use > older but faster data) > > My problem is, that the client (A Java program (or browser, > command line)) > waits, until the whole script has ended and so the cache is > worthless. How > can I tell the client/browser/... that after the last print > line there is no > more data and it can proceed? Or how can I tell the python > script, that > everything after the return of the data (the retieval of the > new data and > the storage in a file) can be done in an other thread or in > the background? > > Greetings > > Ralph > > > -- > http://mail.python.org/mailman/listinfo/python-list > From codeapocalypse at msn.com Wed Jan 21 03:21:37 2004 From: codeapocalypse at msn.com (Brian) Date: 21 Jan 2004 00:21:37 -0800 Subject: Do (USA) Python conferences require a coast? References: <6b50e1-goo.ln1@jowls.lairds.org> Message-ID: > I'd vote for Chicago. Of course, technically speaking we're on a coast > also. It should be just about the easiest city to get to from anywhere in > the US though. Given recent weather conditions, I'd think everyone would jump at the idea of coming out here, to sunny Southern California for a conference... (I missed the Long Beach conference, and D.C. is just so far away...and much colder, brrr. :) From vidiv at gmx.net Tue Jan 13 10:20:30 2004 From: vidiv at gmx.net (vidiv at gmx.net) Date: Tue, 13 Jan 2004 16:20:30 +0100 (MET) Subject: (no subject) Message-ID: <10125.1074007230@www23.gmx.net> Hi All, I am a student-newbie to Python-List (for that matter Python language) working on a project for Terminal Emulation. The dumb terminal interacts with an IBM mainframe through a 'multiplexer-MUX'. The s/w is currently running in 'C' on a Windows NT environment and the requirement is to introduce Object Oriented concepts and C++ was the obvious choice, but i came across 'Python' (and also Perl, Ruby, ..etc) after i installed RH8 on my PC last month. We are actively canvassing the advantages of GNU s/w and philosophy and would like to simultaneously port it to GNU/Linux platform. I have read some of the documentation in Python. Before using Python as our project language it would be useful to know whether Python has functions, libraries/headers (like C does) capable of handling the foll. : 1] open and close serial ports, 2] set baud rates, 3] check parity bit/byte, 4] stop bits, 5] Hardware handshaking, 6] selection of port,...... Our existing 'C' code is to be ported to the GNU/Linux platform so we are actively looking at an OOP concept. The part for serial port communication in C++ has classes so its easier to write customized programs to do most of the above. Most importantly compatibility issues with the existing Multiplexer and Cisco Routers have to be kept in mind as the company will *not* make any H/W changes. We saw that python has some routines for using existing C code, so we dont have to rewrite everything and can make modules containing functions and use it to operate on files. Does it provide any other serial port communication features ? It would be nice if anyone could throw some light on some of the above issues. Thankyou for your time. Ciao, Vidya. -- +++ GMX - die erste Adresse f?r Mail, Message, More +++ Neu: Preissenkung f?r MMS und FreeMMS! http://www.gmx.net From claird at lairds.com Fri Jan 23 22:02:31 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 24 Jan 2004 03:02:31 -0000 Subject: Perl vs. Python for text manipulation (was: [OPINION] - does language really matter if they all do the samething?) References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> Message-ID: <1013o27e3nb141@corp.supernews.com> In article , Paul Prescod wrote: >Dietrich Epp wrote: >> >>... >I would appreciate an example of something you would do by capturing a >message that cannot be done in Python. > >I rather wonder if you've illustrated the downside of flitting from >language to langauge. You may think you're using a language to capacity >without actually doing so. I could be wrong but perhaps even the tasks >you turn to Lisp or Perl for may have easy equivalents in Python. > > Paul Prescod > > The comparison with Perl in particular interests me. I often encounter characterizations of Perl (or Ruby--I regard them as equivalent in this dimension) as the par- agon of text manipulation. It's not, of course, as Icon conclusively demonstrates, at least for me; but I don't even see Perl as distinctly superior to Python in text mangling. I recognize that Python REs can feel a bit cumbersome, in comparison to Perl, because they essenti- ally demand the extra step of explicit compilation. Is that all that people mean, though, when they talk about Perl's superiority for text mangling? Is there more to it? -- Cameron Laird Business: http://www.Phaseit.net From anthony at interlink.com.au Tue Jan 27 23:10:23 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Wed, 28 Jan 2004 15:10:23 +1100 Subject: I support PEP 326 In-Reply-To: <698f09f8.0401272000.79704ef0@posting.google.com> References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> Message-ID: <20040128041023.2EB9225B353@bonanza.off.ekorp.com> >>> Jeremy Fincher wrote > I simply can't understand this aversion to sticking useful things in > the builtin namespace. Especially when marginally useful things like > reversed (a trivially written 3-line generator) have been put there. >>> len(dir(__builtins__)) 125 That's a _lot_ of stuff in one module. Even if you exclude the 40-odd exceptions that are there, that's still a lot of guff in one big flat namespace. Anthony From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 02:13:20 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 23:13:20 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Peter Ashford" wrote in message news:n22Nb.11299$9k7.210522 at news.xtra.co.nz... > Brandon J. Van Every wrote: > > "Peter Ashford" wrote in message > > news:K_YMb.10994$9k7.204413 at news.xtra.co.nz... > > > >>Brandon, don't be such an arsehole. OS developers do things their own > >>way and offer their labour for free. If you don't like it noone will > >>care - but don't denegrate people just because they don't do things your > >>way. > > > > > > I'll denigrate them all I want. With rare exceptions, they aren't a value > > add to what I want to get done. There's this huge cultural divide between > > hobbyists and commercialists. > > > > Why do you think OS developers owe you any kind of value at all? I don't. But that's not going to stop me from denigrating them for being incapable of fulfillng the kinds of projects I have in mind. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From miki.tebeka at zoran.com Thu Jan 8 08:40:09 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 8 Jan 2004 05:40:09 -0800 Subject: Read from, then write to a file without closing first??? References: Message-ID: <4f0a9fdb.0401080540.dd5ce58@posting.google.com> Hello Amy, > I am looking to make this code a little "nicer"... any suggestions??? > I want to do a "read+" where I would be able to first read the contents of > the file... then either close the file out or write to the file without > appending. I want to overwrite the content. def check(file, msg): if open(file).read() != msg: open(file, "w").write(msg) HTH. Miki From CousinStanley at hotmail.com Sat Jan 17 18:32:00 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 17 Jan 2004 16:32:00 -0700 Subject: py2exe 0.5.0 (finally) released References: Message-ID: | .... | python setup.py py2exe | .... | RuntimeError: this function requires unicows.dll in the Python directory | on Win95/98/Me | .... Thomas .... Google search found a MicroSoft download for unicows.dll .... http://www.microsoft.com/downloads/details.aspx?familyid=73ba7bd7-ed06-4f0d-80a4-2a7eeaee17e2&displaylang=en A copy of this dll in the Python23 folder has eliminated the problem and Windows executables generated for .... /py2exe/samples/simple work as expected .... Thanks for making py2exe available .... Now I'm looking forward to learning how to use it .... -- Cousin Stanley Human Being Phoenix, Arizona From aahz at pythoncraft.com Sat Jan 24 17:07:04 2004 From: aahz at pythoncraft.com (Aahz) Date: 24 Jan 2004 17:07:04 -0500 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> Message-ID: In article , Serge Orlov wrote: >"Aahz" wrote in message news:buu7pq$i67$1 at panix1.panix.com... >> >> At this point, >> Perl's speed advantage should come from two and only two sources: Perl >> optimizes the snot out of platform I/O (so these speed tests don't apply >> to a platform Perl hasn't been ported to), and Perl does not use the >> thread-safe forms of I/O. Python does a fair amount of internal caching >> to make up for that, and the file object is already written in C. > >I'm not sure I understand what does it mean "optimize the snot out >of platform I/O"? You just use the bare bones non-caching API and do >your own simple caching doing as little as possible. This will allow >programs that work with files as streams (read sequentially a lot from >one file, write sequentially to another) to run at top speed. Other >access patterns may suffer but not very much. My understanding is that Perl uses platform-specific low-level I/O calls when possible. Python sticks with ANSI functions. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From carroll at tjc.com Fri Jan 9 15:10:50 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri, 09 Jan 2004 20:10:50 GMT Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> <871xq9ky6v.fsf@pobox.com> Message-ID: <4k2uvvkiu7kd5rjsqhci29r9sg97fjdmd8@4ax.com> On 09 Jan 2004 14:12:56 +0000, jjl at pobox.com (John J. Lee) wrote: >Don't do it, then. Use the google API (mind you, not certain that >google groups is part of that). Can Google APIs be used to access Google Groups? ... No. The Google Web APIs service can only be used to search Google's main index of 3 billion web pages. http://www.google.com/apis/api_faq.html#ini2 From jjl at pobox.com Sat Jan 24 10:18:48 2004 From: jjl at pobox.com (John J. Lee) Date: 24 Jan 2004 15:18:48 +0000 Subject: Urllib2 upgrade is breaking urlopen() References: <1d17eeb7.0401221818.7d98672@posting.google.com> <87znce4yv5.fsf@pobox.com> Message-ID: <8765f11ijr.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > dj00302003 at yahoo.com (Jay Davis) writes: > > > We have a lot of simple code using 'urllib', that basically > > just goes out and opens and read()'s some http url. Very basic, > > ten line scripts, and they work fine with urllib. > > > > We want to use urllib2 for everything, though, but when we > > do we get: > [...] > > urllib2.HTTPError: HTTP Error 302: The HTTP server returned a redirect > > error that would lead to an infinite loop. > > The last 30x error message was: > > Found > > Which version of Python are you using? > > It might also help if you can give a publicly-accessible URL that > triggers the problem (mail it to me privately if you prefer). Jay sent me a URL, and it turns out both urllib and urllib2 are functioning as intended. There's a 302 loop caused by the server expecting cookies to get returned. urllib goes into a loop until it notices it's redirected 10 times, then just returns the 302 as a normal response (which doesn't seem very nice, but appears to be what was intended). urllib2 detects the loop and returns the 302 as an HTTPError exception (which can be caught and .read() if necessary). John From jwoehr at attglobal.net Fri Jan 16 12:39:01 2004 From: jwoehr at attglobal.net (Jack J. Woehr) Date: Fri, 16 Jan 2004 10:39:01 -0700 Subject: viewcvs install error on solaris References: <4007e92d$0$325$ba620e4c@news.skynet.be> Message-ID: <400821B5.F7B7AB1B@attglobal.net> bva wrote: > Hello, > > While trying to install viewcvs on a solaris 5.9 machine I get the > following error message: > > Traceback (most recent call last): > File "./viewcvs-install", line 35, in ? > import compat > File "./lib/compat.py", line 20, in ? > import urllib > File "/usr/local/lib/python2.2/urllib.py", line 26, in ? > import socket > File "/usr/local/lib/python2.2/socket.py", line 41, in ? > from _socket import * > ImportError: No module named _socket > > Python is installed on the machine. Can anybody tell me what I'm doing > wrong or what I've forgotten? > Apparently, there's a module named "socket" that you don't have installed. -- Jack J. Woehr # Ceterum censeo PO Box 51, Golden, CO 80402 # in herbas belli http://www.softwoehr.com # ab idem desistamus. From mesteve_b at hotmail.com Fri Jan 23 20:50:36 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 24 Jan 2004 01:50:36 GMT Subject: debugging References: <88bc63c6.0401230416.7acf904c@posting.google.com> <1012jf28chjio61@corp.supernews.com> Message-ID: I second the recommend. on Komodo. I'm definitely happy with it myself. I recently bought the personal edition. If you install the ActiveState version, as you heard by now, you get PythonWin which can debug. I notice the similarity in interfaces even, as they were both made by ActiveState of course. However Komodo has a lot of functionality beyond it, if you need that it is (if you even care about Komodo and what I'm typing here, bye). "Michael Geary" wrote in message news:1012jf28chjio61 at corp.supernews.com... > Doug Farrell wrote: > > Can someone help me out a little with Python? What do people > > use to debug Python code? I don't understand how to use the > > built in debugger and I haven't had any luck getting ddd to > > debug my Python programs. I end up falling back on > > inserting print statements in my code to figure out what's > > going on. This works but isn't always the fastest route to a > > solution. So, I'm just wondering what other people do. > > What OS are you running? > > On Windows, PythonWin has a nice interactive debugger. > > My favorite is Komodo, which is available for Windows, Linux, and Solaris: > > http://www.activestate.com/Products/Komodo/ > > Komodo is not free, but the personal edition is pretty cheap, and the > commercial edition is well worth the price for commercial development. > > -Mike > > From fBechmann at web.de Sat Jan 24 12:48:54 2004 From: fBechmann at web.de (Frank Bechmann) Date: 24 Jan 2004 09:48:54 -0800 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: but you will be able to read/expand/... your python program also 6 months after you wrote it and that won't happen w/ perl. and that should be worth some price. From fumanchu at amor.org Wed Jan 28 10:24:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 28 Jan 2004 07:24:49 -0800 Subject: fast deep-copying of instances Message-ID: Michal Vitecek wrote: > hello, > > i have a data cache which sits between a slow database and > my server and > it's used to cache data retrieved from the database. in > order for it to > work correctly (race-conditions) i need a fast deep-copying of > instances (the cache is used heavily). > > i tried to use copy module but it's *very* slow, then i tried cPickle > to pickle and depickle instances which was faster, but still slow. > > then i've come across cCopy which is 8x faster than copy, but > unfortunately it doesn't work with new style classes because type()'s > return is crappy for them. so the question is: does there > exist a fast > copy module which works with new style classes? If you don't find something pre-built, you can always build it yourself into the classes which you are caching, via __copy__ and __deepcopy__ methods.: def __copy__(self): newUnit = self.__class__() newUnit.ID = u'' newUnit._data.update(self._data) newUnit.dirty = False newUnit.concrete = False return newUnit >From the Library ref on the copy module: "In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument." HTH! Robert Brewer MIS Amor Ministries fumanchu at amor.org From tim.hochberg at ieee.org Wed Jan 21 18:22:43 2004 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 21 Jan 2004 16:22:43 -0700 Subject: [Numpy-discussion] Status of Numeric In-Reply-To: References: Message-ID: <400F09C3.9020708@ieee.org> Arthur wrote: [SNIP] > Which, to me, seems like a worthy goal. > > On the other hand, it would seem that the goal of something to move > into the core would be performance optimized at the range of array > size most commonly encountered. Rather than for the extraodrinary, > which seems to be the goal of numarray, responding to specific needs > of the numarray development team's applications. I'm not sure where you came up with this, but it's wrong on at least two counts. The first is that last I heard the crossover point where Numarray becomes faster than Numeric is about 2000 elements. It would be nice if that becomes smaller, but I certainly wouldn't call it extreme. In fact I'd venture that the majority of cases where numeric operations are a bottleneck would already be faster under Numarray. In my experience, while it's not uncommon to use short arrays, it is rare for them to be a bottleneck. The second point is the relative speediness of Numeric at low array sizes is the result that nearly all of it is implemented in C, whereas much of Numarray is implemented in Python. This results in a larger overhead for Numarray, which is why it's slower for small arrays. As I understand it, the decision to base most of Numarray in Python was driven by maintainability; it wasn't an attempt to optimize large arrays at the expense of small ones. > Has the core Python development team given out clues about their > feelings/requirements for a move of either Numeric or numarray into > the core? I believe that one major requirement was that the numeric community come to a consensus on an array package and be willing to support it in the core. There may be other stuff. > It concerns me that this thread isn't trafficked. I suspect that most of the exchange has taken place on numpy-discussion at lists.sourceforge.net. [SNIP] -tim From jepler at unpythonic.net Tue Jan 6 22:48:28 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 6 Jan 2004 21:48:28 -0600 Subject: KeyboardInterrupt and threading In-Reply-To: References: Message-ID: <20040107034828.GD17102@unpythonic.net> Running your attached program, it works just fine whereever I try it, except on a system so old it only has Python 1.5 installed. Even that worked after a few seconds of editing. Here's the behavior I saw on Fedora Core 1: $ python ivan.py CPU hog subthread spawned main thread caught KeyboardInterrupt CPU hog subthread joined at counter 76429 This is the behavior I saw on redhat 9: $ python /tmp/ivan.py CPU hog subthread spawned main thread caught KeyboardInterrupt CPU hog subthread joined at counter 89897 Here's the behavior I saw on Red Hat 7.2: CPU hog subthread spawned main thread caught KeyboardInterrupt CPU hog subthread joined at counter 31764 Here's the behavior I saw on Windows XP: C:\...> python ivan.py CPU hog subthread spawned main thread caught KeyboardInterrupt CPU hog subthread joined at counter 665928 Here's the behavior I saw on Red Hat 6.2: $ python1.5 ivan.py File "ivan.py", line 19 self.counter += 1 ^ SyntaxError: invalid syntax $ vi ivan.py $ python1.5 ivan.py CPU hog subthread spawned main thread caught KeyboardInterrupt CPU hog subthread joined at counter 238983 Jeff From mwh at python.net Tue Jan 13 12:37:16 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 17:37:16 GMT Subject: Design Question References: <73b00f0c.0401130928.595842c0@posting.google.com> Message-ID: ferrell at diablotech.com (Robert Ferrell) writes: > I have a question which is more about OO design than Python per se. > I've noticed that a number of posters to this list have very good > suggestions for SE issues, so I'm hoping that someone will be able to > give me some guidance. > > My question is about how to architect a class hierarchy where some > methods are nearly identical between a superclass and a subclass, but > differ slightly. For example: > > class Sup(object): > def __init__(self): > self.specialFlag = False > def aMeth(self): > > > > > class Sub(Sup): > def __init__(self): > self.specialFlag = True > > In this example, the method aMeth just checks for specialFlag, and if > it's True, does the special stuff required. > > This allows me to share aMeth, and not have to duplicate code. > However, this doesn't feel great to me because Sup has to know about > Sub in some fashion. I'm not an OO bigot, and in some circumstances I think that superclasses knowing about all their subclasses is just fine. > If later I add other subclasses with their own special needs, the > entanglement will just get worse. If you do this, then yes. Are you going to? (Yes, you can feel an XP flavour to my thoughts...). The idea that sometimes seems to appear of almost doing battle with your subclasses seems particularly misguided. [...] > I'm guessing that there is some well known pattern that addresses this > issue, but I don't know what it is. Does anyone have suggestions for > architecture that provides a good solution? well, class Sup(object): def __init__(self): self.specialFlag = False def aMeth(self): self.doSpecialThing() def doSpecialThing(self): pass class Sub(Sup): def doSpecialThing(self): kind of suggests itself, but it's hard to say out of context whether it applies. You might enjoy reading Alex Martelli's talk on the template design pattern that he gave at EuroPython 2003: http://www.strakt.com/docs/ep03_pydp.pdf Cheers, mwh -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From mir4uu at yahoo.com Wed Jan 7 11:08:55 2004 From: mir4uu at yahoo.com (mir nazim) Date: 7 Jan 2004 08:08:55 -0800 Subject: Twisted or Medusa or Zope Message-ID: <425cc8d1.0401070808.14690325@posting.google.com> hi, i m planning to start writing intranet applications and want ur real cool advices for choosing the correct platform. the choice is between the three: 1. Twisted 2. Medusa 3. Zope (i do not know any of the three). i want u people to help me choose the correct platform. my questions are: 1. which has the least learning curve. 2. which is best suited for the purpose for applications like workflow automation, groupware, and other business related apps. please also highlight the major diffrences between the three. also tell if there is a better alternative. thanks in advance. From google at axiomatize.com Thu Jan 15 17:19:33 2004 From: google at axiomatize.com (Laurent Therond) Date: 15 Jan 2004 14:19:33 -0800 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> Message-ID: <265368cb.0401151419.7663823e@posting.google.com> Peter Hansen wrote in message news:<4006F13C.7D432B98 at engcorp.com>... > The above is confusing. Why not just do > > def bencode_rec(x, b): > assert type(x) is str > b.write(.....) > > Why the if/else etc? That's a code extract. The real code was more complicated. > This is Python. Why not try it and see? I wrote a quick test at > the interactive prompt and concluded that StringIO converts to > strings, so if your input is Unicode it has to be encodeable or > you'll get the usual exception. Good point. Sorry, I don't have those good reflexes--I am new to Python. So, your test revealed that StringIO converts to byte strings. Does that mean: - If the input string contains characters that cannot be encoded in ASCII, bencode_rec will fail? Yet, if your locale specifies UTF-8 as the default encoding, it should not fail, right? Hence, I conclude your test was made on a system that uses ASCII/ISO 8859-1 as its default encoding. Is that right? > > a) A sequence of bytes where each byte represents an ASCII character > > Yes, provided your input is exclusively ASCII (7-bit) data. OK. > > b) A sequence of bytes where each byte represents the UTF-8 encoding of a > > Unicode character > > Yes, if UTF-8 is your default encoding and you're using Unicode input. OK. > > c) It depends on the system locale/it depends on what the site module > > specifies using setdefaultencoding(name) > > Yes, as it always does if you are using Unicode but converting to byte strings > as it appears StringIO does. Umm...not sure here...I think StringIO must behave differently depending on your locale and depending on how you assigned the string. Thanks for your help! L. From mi-mal at o2.pl Mon Jan 12 06:37:10 2004 From: mi-mal at o2.pl (Mimal) Date: Mon, 12 Jan 2004 12:37:10 +0100 Subject: CGI module problem: duplicated output In-Reply-To: <40027E9F.2010209@pollenation.net> References: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> <40027E9F.2010209@pollenation.net> Message-ID: > Check there is no cgi.pyc from when the script was still called cgi.py. Thanks a lot!!! That was it! I should think about the name of the script. I knew it must be something silly. :-) -- Mimal From edcjones at erols.com Thu Jan 22 09:48:46 2004 From: edcjones at erols.com (Edward C. Jones) Date: Thu, 22 Jan 2004 09:48:46 -0500 Subject: [Numpy-discussion] Status of Numeric In-Reply-To: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> Message-ID: <400fe3c5$0$3036$61fed72c@news.rcn.com> Arthur wrote: > On Wed, 21 Jan 2004 16:22:43 -0700, Tim Hochberg > wrote: > > >>Arthur wrote: > >>The first is that last I heard the crossover point where >>Numarray becomes faster than Numeric is about 2000 elements. It would be >>nice if that becomes smaller, but I certainly wouldn't call it extreme. >>In fact I'd venture that the majority of cases where numeric operations >>are a bottleneck would already be faster under Numarray. In my >>experience, while it's not uncommon to use short arrays, it is rare for >>them to be a bottleneck. > > > Couldn't one argue that - for example - in 3d graphic applications the > performance as to short arrays is crucial. In some numerical / graphing packages, there are specialized, fast, fixed-size arrays for sizes less than 4 by 4. From NOusenetSPAM at gdargaud.net Wed Jan 21 09:25:54 2004 From: NOusenetSPAM at gdargaud.net (Guillaume Dargaud) Date: Wed, 21 Jan 2004 15:25:54 +0100 Subject: Checking for duplicate instances of a script... References: <400e4638$0$19274$626a54ce@news.free.fr> <4ywu7l5v76.fsf@skjellgran.ii.uib.no> Message-ID: <400e8bfb$0$19294$626a54ce@news.free.fr> > This can probably be done in *many* different ways, maybe there is > even an agreed upon on best solution. This is a small suggestion > based on fcntl.flock() (Unix only I am afraid): Wrong prediction: it works fine in Cygwin under windows, but it doesn't on my linux server... Traceback (innermost last): File "./CounterTest.py", line 24, in ? fcntl.flock(lockH, fcntl.LOCK_EX | fcntl.LOCK_NB) TypeError: illegal argument type for built-in operation Cygwin: 2.3.3 (#1, Dec 30 2003, 08:29:25) [GCC 3.3.1 (cygming special)] Linux: 1.5.2 (#1, Jan 31 2003, 10:58:35) [GCC 2.96 20000731 (Red Hat Linux 7.3 2 Is this too old ? Maybe I'll try with os.open flags... -- Guillaume Dargaud http://www.gdargaud.net/ "My goal is to be a meteorologist. But since I possess no training in meteorology, I suppose I should try stock brokerage." - Found in a resume. From max at NcOviSsPiAoMntech.com Thu Jan 29 10:44:24 2004 From: max at NcOviSsPiAoMntech.com (max khesin) Date: Thu, 29 Jan 2004 15:44:24 GMT Subject: Pausing python programs In-Reply-To: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> References: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> Message-ID: Graham wrote: > How can I cause a python program to pause/suspend execution for a period of > time? I am checking status of an external system and only want to check > every second as opposed to my current which checks may times a secnod and > hogs my cpu in the process!!! > > Thank you to anyone who can help. > > Graham Smith > > PeopleSoft Technical Team Leader > OXFAM GB > +44 (1865) 313255 > gsmith at oxfam.org.uk > > > Sleep() (at least on windoze) will suspend your app from execution. From some experiments I think Python's time.sleep() uses it. max From EP at zomething.com Mon Jan 12 22:01:02 2004 From: EP at zomething.com (EP) Date: Mon, 12 Jan 2004 19:01:02 -0800 Subject: Problem with what raw_input() returns In-Reply-To: <56f42e53.0401121746.39b9e4db@posting.google.com> Message-ID: <5.2.0.9.0.20040112190013.0265a420@mail.zomething.com> What do you get if you >>> print one ? At 05:46 PM 1/12/2004 -0800, sebb wrote: >If I do the following script: > ># -*- coding: cp1252 -*- >one = "??" >two = one.replace("?","a") > >print two # it prints aa as I expected > > >But with the following script: > ># -*- coding: cp1252 -*- >one = raw_input() # When I run the script, I type ?? >two = one.replace("?","a") > >print two # it still prints ?? and I want it to print aa > > >Can someone help me with that problem? >Thanks >-- >http://mail.python.org/mailman/listinfo/python-list From emonk at slingshot.no.uce Sat Jan 17 15:07:33 2004 From: emonk at slingshot.no.uce (Corey Murtagh) Date: Sun, 18 Jan 2004 09:07:33 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: <1074370049.790131@radsrv1.tranzpeer.net> Nick Vargish wrote: > "Brandon J. Van Every" writes: >>Or requiring Cygwin or MinGW, which real Windows developers don't want to >>use. > > Where "real Windows developers" == "Brandon Van Every". I see plenty > of open source Windows projects with compilation instructions that > require the use of Cygwin or MinGW. Actually I kind of agree here. I've had plenty of problems with Cygwin - although less with MinGW. An OSS project that requires a Linux emulation shim to run on any other platform is not, IMHO, cross-platform at all. -- Corey Murtagh The Electric Monk "Quidquid latine dictum sit, altum viditur!" From fa_pinkse at msn.com Sat Jan 24 04:19:20 2004 From: fa_pinkse at msn.com (fa_pinkse at msn.com) Date: 24 Jan 2004 01:19:20 -0800 Subject: Boa: printing source in the Editor References: <4jwOb.40507$DF4.24648@amsnews02.chello.com> Message-ID: Uwe Grauer wrote in message news:... > > > Using boa 0.2.8 i see Print under the Edit menu of the Editor. > > Uwe Thanks Uwe, It took me awhile to get the latest version. Now I can print. with best regards, Frans. From sandysj at juno.com Tue Jan 20 12:41:36 2004 From: sandysj at juno.com (Jeff Sandys) Date: Tue, 20 Jan 2004 17:41:36 GMT Subject: Fw: PDF library for reading PDF files References: <400BFF7B.95F21050@netsurf.de> Message-ID: <400D6850.C7BB72D6@juno.com> Peter Galfi wrote: > ... > The "information" I am trying to extract from the PDF file is the text, > specifically in a way to keep the original paragraphs of the text. ... > > Any suggestions? Ghostscript has an Extract Text capability that I have used successfully on some pdf files (but not on some others): http://www.cs.wisc.edu/~ghost/ Thanks, Jeff Sandys From deets_noospaam at web.de Fri Jan 30 11:39:27 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Fri, 30 Jan 2004 17:39:27 +0100 Subject: easiest transition for a PHP website to move to Python? References: Message-ID: > I've got a database-driven website that's written entirely in PHP. > > It's all pretty MVC : NOT embedded little calls inside HTML, but > rather little controller apps in the webroot that merge data with > HTML templates on the fly. > > But for various reasons (mostly fun) I want to rewrite it in Python. > > There are so many different approaches, though! Zope, Twisted, > mod_python, clearsilver, and all the goodies in standard library. Regardless my answer to Lothar's posting (which is about zope not beeing python), I agree with him that webware appears to be close to what you are expecting from a web-framework. So the transition to webware might be the easiest, if you want to do it as straight-forward as possible. Mind you, I never worked with webware so far, but it looks promising. However, ZOPE has a different approach. Its outstanding feature is the built-in database ZODB. This is a hierarchical strucured object-orientied database with versioning. It stores everything - app-logic, templates and data. Together with CMF/Plone or ZMS, there exist nice and clean dublin-core aware data-from-layout-abstractions. Setting up a blog or even much more complicated, content driven website is only a matter of a few clicks. All editing of content is done via the webbrowser, and as zope comes with its own user-model, its easy for you as admin to create new accounts and grant fine-grained access to your sites for their respective authors/editors/whatever. So I would definitly advise you to take a look at zope - install it and play around with it, especially with plone or zms. But as said before - if you are actually seeking for the smoothest transition, you might be better off with webware. Regards, Diez From michael at foord.net Thu Jan 29 03:34:37 2004 From: michael at foord.net (Fuzzyman) Date: 29 Jan 2004 00:34:37 -0800 Subject: Simple Database Package References: Message-ID: <8089854e.0401290034.4d57a45d@posting.google.com> Pieter Claerhout wrote in message news:... > Take a look at: > MetaKit: http://www.equi4.com/metakit/ > SQLite: http://www.sqlite.org/ > > Cheers, > > > pieter Thanks.... I don't know what it is - but I asked a couple of questions here yesterday... and seem to have received a lot of help from peopel called Peter..... sounds suspiciously like a conspiracy to me :-) Anyway - I couldn't decide between SQLobject and metakit (I'd already seen sqlite but wanted some advuice before I chose one to dive into..). Anyway - the windows download for SQLobject is zero sized - so I've gone for metakit and will have a play. Fuzzy > -- > > 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.voidspace.org.uk/atlantibots/pythonutils.html > The home of Python dateutils - dateutils, ConfigObj, StandOut, > CGI-News etc From jacek.generowicz at cern.ch Thu Jan 8 07:46:27 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jan 2004 13:46:27 +0100 Subject: Descriptor puzzlement References: Message-ID: "John Roth" writes: > It doesn't look like the descriptor protocol is getting > invoked at all. > > What's happening here? Try changing the following > class AnotherObject(object): > def __init__(self): > self.prop = AnObject("snafu") to class AnotherObject(object): prop = AnObject("snafu") From staff-admin at cis.ohio-state.edu Wed Jan 28 12:34:02 2004 From: staff-admin at cis.ohio-state.edu (staff-admin at cis.ohio-state.edu) Date: Wed, 28 Jan 2004 12:34:02 -0500 Subject: Your message to Staff awaits moderator approval Message-ID: <20040128173402.4504.66121.Mailman@mail.cis.ohio-state.edu> Your mail to 'Staff' with the subject TEST Is being held until the list moderator can review it for approval. The reason it is being held: Message has a suspicious header Either the message will get posted to the list, or you will receive notification of the moderator's decision. From francisgavila at yahoo.com Sun Jan 11 14:03:26 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 11 Jan 2004 14:03:26 -0500 Subject: readling newlines References: Message-ID: <10037hsb7bqp1d4@corp.supernews.com> Samuel Walters wrote in message ... > >Not quite sure what "U" mode is, but try adding the "b" mode when opening FYI, 'U' is universal newline mode, which will quietly convert the newline convention of a file into '\n'. I think it has some rudamentary ability to handle mixed-convention newline ugliness. See the documentation on file() in the library reference, and there's a PEP on the feature, too. -- Francis Avila From mwh at python.net Thu Jan 15 06:15:51 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 15 Jan 2004 11:15:51 GMT Subject: Cyclic garbage collection and segfaults... References: Message-ID: "Thomas Mailund" writes: > Hi group. > > I have a problem with some C extensions I am working with and > hope that some of you can help. [snippety] > static void > Simple_dealloc(SimpleObject *self) > { > fprintf(stderr,"Simple_dealloc %p\n", self); > self->ob_type->tp_free((PyObject*)self); /* <= segfault here */ Well, you're calling tp_free from a tp_dealloc. That doesn't *sound* sensible to me. > Can anyone explain what I'm doing wrong? Or perhaps suggest a better > solution to my "real" problem, if I'm approaching the problem completely > wrong :-) There are docs on this sort of thing. Cheers, mwh -- "Sturgeon's Law (90% of everything is crap) applies to Usenet." "Nothing guarantees that the 10% isn't crap, too." -- Gene Spafford's Axiom #2 of Usenet, and a corollary From dripton at wizard.net Sat Jan 24 22:12:59 2004 From: dripton at wizard.net (David Ripton) Date: 24 Jan 2004 19:12:59 -0800 Subject: Compiling DCOracle2 on RH Linux 8.0 References: Message-ID: <8725c51c.0401241912.316a7cfc@posting.google.com> reidyre at yahoo.com (Ron Reidy) wrote in message news:... > I am trying to compile DCOracle2 on RedHat 8.0 and make is giving me > the following error: > > gcc -pthread -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes > -I/usr/local/include/python2.3 -I/usr/local/include/python2.3 @DEFS@ > -I/oracle/app/oracle/9i/rdbms/demo > -I/oracle/app/oracle/9i/network/public > -I/oracle/app/oracle/9i/plsql/public > -I/oracle/app/oracle/9i/rdbms/public -DORACLE9i -c ././dco2.c -o > ./dco2.o > gcc: cannot specify -o with -c or -S and multiple compilations > > > Did I do something wrong? No. The DCOracle2 build process isn't very robust. Look at src/Makefile. Find a line that says "DEFS=%DEFS" and change it to "DEFS=-fno-strict-aliasing" From peter at engcorp.com Wed Jan 21 14:30:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Jan 2004 14:30:30 -0500 Subject: Reading BLOB References: <400e3510.18785312@news.eunet.be> <400E8AB0.9D4DEB79@engcorp.com> <400ea2c0.46864796@news.eunet.be> Message-ID: <400ED356.A0621A6C@engcorp.com> Johan.Vervoort at utimaco.be wrote: > > This is the sample code: It should dump all the certificates to the > certs directory... > What I suspect is that python thinks that the certif field is a STRING > and it's truncated when the first '\0' occurs... > (The data is stored completely in the database as an equivalent > C-program works fine...) Python itself does not care about '\0' in a string, and will happily handle strings with any kind of binary data. At the least, then you need to look lower, perhaps at the ODBC wrapper code itself, perhaps at the database schema or something. Are there multiple types of string that can be stored in the database, and you've picked one that is effectively null-terminated? Or, wait a minute, your subject line is "reading BLOB", yet you are dealing with strings in some way, given this: >>> reload (Test) [('csernum', 'STRING', 80, 80, 0, 0, 0), ('certif', 'STRING', 0, 2147483647, 0, 0, 0)] Surely that is the cause of the problem, at least indirectly? Isn't there some kind of BLOB data type instead? -Peter From cookedm+news at physics.mcmaster.ca Mon Jan 26 17:38:22 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 26 Jan 2004 17:38:22 -0500 Subject: Newbie : innerproduct function from Numarray References: Message-ID: At some point, "Ohkyu Yoon" wrote: > I have two vectors that have about 2000 elements. > I need to calculate the innerproducts of those vectors 2000 times where > one of them cycles left(ie 1234, then 2341, then 3412, etc) > Basically, I want to calculate A*x, where A is a left-circulant cyclic > matrix, > and x is a vector. > > I tried it two ways. > vector1 & vector2 are lists. ^^^^^^ This is your problem: everytime you pass these to innerproduct, it turns them into arrays (which, with the current version of numarray, is a relatively expensive operation). Try something like import numarray as na output = [] vector1 = na.array(vector1) vector2 = na.array(vector2) temp = na.concatenate((vector1,vector1)) # temp is twice the length of vector1 for i in range(2000): output.append(na.innerproduct(temp[i:(i+2000)],vector2) This uses arrays always. You might be better off explicity constructing your left-circulant cyclic matrix A, and doing the full matrix multiply -- for this size of matrix, the multiply is going to be fast (because it's going to be done by code written in C, and, depending on how you set it up, using an optimized BLAS routine). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From peter at engcorp.com Thu Jan 29 09:44:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Jan 2004 09:44:25 -0500 Subject: Python & XML & DTD (warning: noob attack!) References: Message-ID: <40191C49.786AAF89@engcorp.com> Igor Fedorow wrote: > > I have an XML file with an internal DTD which looks roughly like this: > [snip] > I want to parse this file into my application, modify the data (this includes > maybe creating and/or deleting nodes), and write it back into the file -- > including the DTD. (It doesn't necessarily need validation, though.) > > I tried xml.dom.ext.PrettyPrint, but it produces only > [snip] > actually lacking the document type definition. > > Any help is appreciated! Unfortunately I don't know of any way you could generate the DTD again, and I've never seen a package which supports what you ask for (not that it isn't possible, mind you). On the other hand, are you sure you need the DTD? We use XML in dozens of ways and absolutely have never benefited from attempts to use DTDs, and don't appear to suffer from the lack thereof. Also, aren't DTDs sort of considered either obsolete or at least vastly inferior to the newer approaches such as XML Schema, or both? So my recommendation is to ditch the DTD and see if any problems arise as a result. -Peter From james at logicalprogression.net Fri Jan 16 17:41:07 2004 From: james at logicalprogression.net (James Henderson) Date: Fri, 16 Jan 2004 22:41:07 +0000 Subject: Bug or feature? In-Reply-To: <20040116191853.GA27129@intarweb.us> References: <200401161613.06481.james@logicalprogression.net> <20040116191853.GA27129@intarweb.us> Message-ID: <200401162241.07500.james@logicalprogression.net> On Friday 16 January 2004 7:18 pm, Jp Calderone wrote: > Of course, it should be noted that, in Python, "a += b" is only sometimes > synonymous with "a = a + b". The rest of the time, it's hard to say what > it is synonymous with :) What do you have in mind? J. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From spamtrap at bigfoot.com Fri Jan 30 03:51:45 2004 From: spamtrap at bigfoot.com (zde) Date: Fri, 30 Jan 2004 09:51:45 +0100 Subject: comparing booleans In-Reply-To: <4019BBDE.D4429EDF@alcyone.com> References: <40185112.264898A4@alcyone.com> <4019BBDE.D4429EDF@alcyone.com> Message-ID: Erik Max Francis wrote: > This is because of operator chaining, which only exists a special case > for the relational operators (==, !=, <, <=, >, >=). It's not actually > a difference in the truth table; it's because chaining operators behave > differently than other operators. Unfortunately, this mis-feature works for other operators as well: Since 'in' operator usually has higher precedence than '==', it's pretty annoying to see: Python 2.3.3 (#2, Jan 4 2004, 12:24:16) >>> 'a' in 'abc' True >>> 'a' in 'abc' == True False >>> From stephendotboulet at motorola_._com Mon Jan 26 10:51:02 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Mon, 26 Jan 2004 09:51:02 -0600 Subject: Single and double asterisks preceding variables in function arguments Message-ID: I've run across code like "myfunction(x, *someargs, **someotherargs)", but haven't seen documentation for this. Can someone fill me in on what the leading * and ** do? Thanks. Stephen From myles at geocities.com Tue Jan 13 19:57:41 2004 From: myles at geocities.com (Myles) Date: 13 Jan 2004 16:57:41 -0800 Subject: Calling dlls with Calldll/WinDll or Ctypes or... References: <9b849915.0312172302.7999d44a@posting.google.com> Message-ID: > Pardon my ignorance here. I would like to talk to someone that has > had success in calling ddls in Windows NT/2000/XP. caldll works, but the more recent ctypes is easier to use. The ctypes documentation has nice examples for calling functions exported by standard Windows DLLs (i.e. Microsoft ones that are supplied with Windows). Below are a couple of examples of calling third-party DLLs. Regards, Myles. # ------------------ snip ------------------------ from ctypes import * import time # ------------------------------------------------ anotherdll = windll.AutoItDLL # loads AutoItDLL.dll (in same directory) # AutoItDLL.dll exports a function AUTOIT_ClipPut anotherdll.AUTOIT_ClipPut(c_char_p("something")) # AutoItDLL.dll exports a function AUTOIT_ClipGet s = c_buffer(16384) # size of clipboard buffer time.sleep(2) # apparently it takes a while to create that buffer ? anotherdll.AUTOIT_ClipGet(s) print repr(s.value) # ------------------------------------------------ somedll = windll.FreeImage # loads FreeImage.dll (in same directory) # some DLLs export function names strangely # (open the .dll in a capable text editor to read the function names) GetVersion = getattr(somedll, "_FreeImage_GetVersion at 0") GetVersion.restype = c_char_p print GetVersion() GetFileType = getattr(somedll, "_FreeImage_GetFileType at 8") filename = "/temp/screen01.jpg" imgtype = GetFileType(filename, 0) Load = getattr(somedll, "_FreeImage_Load at 12") image_ptr = Load(imgtype, filename, 0) GetWidth = getattr(somedll, "_FreeImage_GetWidth at 4") print GetWidth(image_ptr) # --------------- snip --------------------------- From aahz at pythoncraft.com Thu Jan 29 21:01:05 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2004 21:01:05 -0500 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: In article <6714766d.0401291559.45413e0d at posting.google.com>, Robert Dodier wrote: > >In reading through old posts to this newsgroup, I see there is >an often-repeating warning against modifying the contents of locals(). >Fair enough. However, is there anything wrong with modifying globals() >? Not wrong, exactly, but there may well be in the future, and there are better ways currently. >By the way, is there another way to introduce a new variable into >a scope (local or global) other than assigning directly to the >dictionary returned by locals() or globals() ? For locals, it's a lot trickier, but you're less likely to want to do that. >Just some context -- I want to parse strings written in a >"little language" and then have new variables show up in the Python >environment so the user can manipulate them. E.g., > > >>> parse_funky_language("Hey, this is far out, man.") > >>> Hey.part_of_speech > Interjection import __main__ tmp = parse_funky_language("Hey, this is far out, man.") setattr(__main__, tmp.name, tmp.value) In the context of the interactive interpreter, it's a bit harder to do; I don't remember off-hand what the namespace of the interpreter is. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From bart_nessux at hotmail.com Tue Jan 27 19:47:39 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 27 Jan 2004 19:47:39 -0500 Subject: threads In-Reply-To: References: Message-ID: <401706AB.6020703@hotmail.com> Thank you both for the info on threads in Python it was very helpful to me, I've written something that I think can benefit from threading... here is the code, I copied this from a few books and a few Web examples and modified it to suit my test: class trivialthread(threading.Thread): def url_open(self): for x in xrange(999999): f = urllib.urlopen("http://xxx.xxx.xxx") f.read() f.close() print self, x if __name__ == '__main__': threads = [] for x in range(15): 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) However, when this runs, the output looks like this: 16 threads running incl. main 1 threads running incl. main 1 threads running incl. main 1 threads running incl. main 1 threads running incl. main 1 threads running incl. main 1 threads running incl. main ... ... Why does the 16 appear initially and then be replaced by 1? Are there no longer 16 threads running? If so, why not? TIA!!! From cpl.19.ghum at spamgourmet.com Sun Jan 18 13:54:40 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 18 Jan 2004 19:54:40 +0100 Subject: Fw: PDF library for reading PDF files References: Message-ID: > I am looking for a library in Python that would read PDF files and I > could extract information from the PDF with it. I have searched with > google, but only found libraries that can be used to write PDF files. reportlab has a lib called pagecatcher; it is fully supported with python, it is not free. Harald From mark at diversiform.com Fri Jan 2 15:49:08 2004 From: mark at diversiform.com (mark) Date: Fri, 2 Jan 2004 12:49:08 -0800 Subject: Can this be reversed (Tkinter)? Message-ID: <002d01c3d171$df2920b0$5501a8c0@markxp> I am looking at the format used by root.geometry(). The string returned from root.geometry() is "%dx%d+%d+%d". Is there a quick and painless way to extract the values from that string (i.e., "100x150+25+25" => (100,150,25,25))? - Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Fri Jan 2 16:13:29 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 2 Jan 2004 13:13:29 -0800 Subject: how to import a module dynamically Message-ID: Randall Smith wrote: > How do I import a module when given the module name as input? > > Between __import__, imp, and rexec, I'm very lost. What I want to do > seems so simple, but I don't know the best way to do it. I was very lost, too, once upon a time. I wrote my eventual solution for this into a Python Cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972 ...which is geared toward importing when you know the full package name, for example "myapp.tools.utilities". Feel free to hack it up for your own study and/or use. Robert Brewer MIS Amor Ministries fumanchu at amor.org From prof_888 at hotmail.com Fri Jan 9 16:41:53 2004 From: prof_888 at hotmail.com (ChrisD) Date: 9 Jan 2004 13:41:53 -0800 Subject: unable to register PythonService.exe References: Message-ID: > > Looks like a bug to me, it behaves the same for me. > > OTOH, it seems that it's not required to do this registration since the > sample PythonTestService.py works fine for me. > It works for me, too! I didn't even think of trying that. It does appear that the installation program registered PythonService.exe - which the book says it does... I obviously didn't pay enough attention to that! Thanks for helping me figure that out. Chris From oren-py-l at hishome.net Fri Jan 16 15:33:49 2004 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 16 Jan 2004 15:33:49 -0500 Subject: data structures module In-Reply-To: References: <92c59a2c.0401152306.1c6a17f5@posting.google.com> Message-ID: <20040116203349.GA36773@hishome.net> On Fri, Jan 16, 2004 at 01:08:51PM -0500, Aahz wrote: > In article <92c59a2c.0401152306.1c6a17f5 at posting.google.com>, > MetalOne wrote: > > > >Today, I wanted a priority queue. > >I notice that Python does not have any sorted lists. > >I know that I can call list.sort(), but that seems rather inefficient > >to call every time an element is added. > >I am wondering why there is not a module or modules containing many > >common data structures. Has such a thing been decided against? Is it > >that just nobody has done it? Has nobody else suggested the need for > >it? Maybe I should search, but I am too tired now, I need sleep. > > There's a current discussion on python-dev about a "collections" module > or package, and that's one of the structures under discussion. The major thread of the discussion there is about enhancing the built in list type to handle popping the first item more efficiently behavior) so the append/pop() idiom of implementing a queue will work in amortized O(1) time. I like the general direction this is going - no new basic data types. Lists and dicts are sufficient for 98% of all will we ever need. The remaining 2% can mostly be implemented in Python because it's rarely performance-critical. The remaining cases are probably better handled by specialized extension modules anyway (e.g. jkbuckets) Oren From peter at engcorp.com Tue Jan 6 08:56:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 08:56:28 -0500 Subject: Launching pdb from within a script References: Message-ID: <3FFABE8C.126E2E92@engcorp.com> "Mike C. Fletcher" wrote: > > Peter Otten wrote: > > >Graham Nicholls wrote: > > > > > ... > > >>But pdb complains that there are no such variables. It may be that I had > >>to add some incantation around the script startup - I just can't remember > >>(and its frustrating!). > >> > >> > ... > > >-> Pdb().set_trace() > >(Pdb) abc > >*** NameError: name 'abc' is not defined > >(Pdb) u > > > > > This is the key line, 'n' would work as well. The reason your variables > weren't being found is that you were still inside the call to > set_trace(). You need to return from that (either by going "u"p to the > calling context, or to the "n"ext instruction, which returns to the > calling context by finishing the set_trace() call). "r" (for "return") works as well.... Wow! Three obvious ways to do the same thing. ;-) -Peter From fuf at mageo.cz Wed Jan 28 10:48:00 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 16:48:00 +0100 Subject: fast deep-copying of instances In-Reply-To: References: Message-ID: <20040128154800.GB11485@foof.i3.cz> Robert Brewer wrote: >Michal Vitecek wrote: >> hello, >> >> i have a data cache which sits between a slow database and >> my server and >> it's used to cache data retrieved from the database. in >> order for it to >> work correctly (race-conditions) i need a fast deep-copying of >> instances (the cache is used heavily). >> >> i tried to use copy module but it's *very* slow, then i tried cPickle >> to pickle and depickle instances which was faster, but still slow. >> >> then i've come across cCopy which is 8x faster than copy, but >> unfortunately it doesn't work with new style classes because type()'s >> return is crappy for them. so the question is: does there >> exist a fast >> copy module which works with new style classes? > >If you don't find something pre-built, you can always build it yourself >into the classes which you are caching, via __copy__ and __deepcopy__ >methods.: i know of this mechanism but a) i fear it would be still slower than cPickle and be quite time consuming to implement (lots of classes) b) cCopy is the C implementation of the copy module so it's "lightning" fast the current cCopy is at http://www.jessikat.fsnet.co.uk/cCopy.html . if someone would be so kind to add support for new style classes to it (or tell me how to do it), i'd be very very grateful. thank you, -- fuf (fuf at mageo.cz) From cookedm+news at physics.mcmaster.ca Thu Jan 15 12:05:33 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 15 Jan 2004 12:05:33 -0500 Subject: More than one python in a linux References: Message-ID: At some point, Zunbeltz Izaola wrote: > Hi, > > I've build and installed python 2.2 and python2.3 in a linux box. > Now i want to install some packages (Numeric, wxPython and > scipy). I've install Numeric and wxPython for python2.3 without > problem (python2.3 setup.py install ... and so on). But when I try > > python2.2 setup.py install > > I get the following error (for wxpython) > > running build_py > copying wxPython/__version__.py -> build/lib.linux-i686-2.2/wxPython > running build_ext > error: invalid Python installation: unable to open > /usr/lib/python2.2/config/Makefile (No such file or directory) You probably don't have the development package for python2.2 installed (python2.2-dev or python2.2-devel or something). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From swalters_usenet at yahoo.com Sun Jan 18 10:48:38 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 15:48:38 GMT Subject: Using python for _large_ projects like IDE References: <930ba99a.0401180625.5863acd4@posting.google.com> Message-ID: | Sridhar R said | > 1. if python is used, then the memory required for running the IDE > will be high. > 2. if pure python is used, the IDE will be slower. > > I'm not sure whether they are true. Well, it depends on your definition of "high memory usage." I had no problems running GUI python apps on my old pentium 100mhz with 74 megs of ram. So, unless your program should be able to run on smaller systems, I wouldn't worry much. > Then I thought of using python for 90% of the code and using C for > other performance critical part. But the problem is in identifying > the performance critical code. People suggest to start with pure > python and then _recode_ the performance critical code after profiling > the original code. But I fear whether there will be a conflit in say > data structures. Not yet expert in extending/embedding python. > Are there any ways to forsee the performance critical parts? Data structures are easier to handle than you'd think when extending python. I recommend either boost or pyrex. I've used pyrex, but most people seem to use boost. There are great python profiling tools. It's not at all difficult to find the performance critical portions. As far as advice on forseeing performance critical parts, keep in mind that there are different standards for different portions of a program. An IDE would have many parts where interactivity is a concern. Noone likes to see their keystrokes appear two seconds after they have been typed. Things like syntax highlighting can form a bottleneck, but I've seen enough apps that manipulate data like this that I know it can be done. There are other parts, such as search-and-replace that people are a bit more patient about. Try to separate the two types of functionality so that they can be recoded independently. HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From knoppix at laptop.home.net Sun Jan 11 12:13:04 2004 From: knoppix at laptop.home.net (Knoppix User) Date: Sun, 11 Jan 2004 11:13:04 -0600 Subject: [Newb] Still not able to solve class attribution Message-ID: Hi folks I still have not been able to solve this one, which didn't manage to garner a response yesterday, so I'm rephrasing it here. If I define an attribute in the __init__ statement of a class, I should be able to access that attribute in a later method of that class, right? I have run into a situation where that does not SEEM to happen [newbie alert]. What should I be looking into to try to solve this bug, as I am SOL with new ideas?! Although I am using wx, I do not believe that this has anything to do with wx, but with syntax / semantics. Any thoughts are very much appreciated. I copy the original question below, for convenience. Steve class GIP(wx.Frame): def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, size = (600, 460)) .... self.Image = wx.StaticBitmap(self, -1, wx.EmptyBitmap(*self.thumbSize), pos = (160,10)) <<<<<<<<<<<<<<<<<<<", line 197, in ? File "/usr/lib/python2.3/site-packages/wxPython/wx.py", line 1951, in __init__ _wxStart(self.OnInit) File "", line 191, in OnInit File "", line 78, in __init__ File "", line 116, in DisplayImg AttributeError: GIP instance has no attribute 'Image' From tim.one at comcast.net Mon Jan 26 11:35:36 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 26 Jan 2004 11:35:36 -0500 Subject: Overriding compare in SequenceMatcher In-Reply-To: <001a01c3e3fb$4d409380$7800a8c0@mailer> Message-ID: [Peter Galfi] > I am trying to make a compare between two lists of numbers using the > SequenceMatcher, however I would need somehow to override the method > which is used by SequenceMatcher to determine if two elements of the > list are equal or not. > > In my specific case a number of the list might be equivalent with > another number of the list yet their values would be different. > > Any idea as to how what and how I can override or any workaround for > this problem? Elements of sequences are used internally as dict keys, so it's not enough just to override comparison -- you also need to define a hash function consistent with your idea of equality (objects that compare equal must deliver the same hash codes). So you need to wrap your numbers in a class, and define the class's __eq__ and __hash__ methods appropriately. There's no need to define any comparison method other than __eq__. From wilkSPAM at OUTflibuste.net Sat Jan 10 07:58:50 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sat, 10 Jan 2004 13:58:50 +0100 Subject: what is best for web development?? References: Message-ID: <87wu80559x.fsf@blakie.riol> ketulp_baroda at yahoo.com writes: > i am developing a web application and i am really confused on what should i use. > should i use just python and use the cgi module availabe. > Or should i use application like WebWare.Also there is PSP available. > I am really confused and need help It depends of the kind of application you want to do exactly, there are many possibilities from cgi to zope... Look into the archive of the list, you'll find a lot of answer to this question. Or describe more what you need. bye -- Wilk - http://flibuste.net From mark at mceahern.com Sun Jan 4 20:40:23 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 04 Jan 2004 19:40:23 -0600 Subject: Why does this fail? In-Reply-To: References: Message-ID: <1073266823.12941.24.camel@dev.internal> On Sun, 2004-01-04 at 18:58, Dave Murray wrote: > New to Python question, why does this fail? [...] > try: [...] > except: [...] Because you're treating all errors as if they're what you expect. You should be more specific in your except clause. Do this and you'll see what I mean: try: whatever except: raise # raise whatever exception occurred return 0 In other words, you should be explicit about the errors you silence. Also, it's not clear what Checkit() is actually supposed to do. Is it supposed to verify the URL actually exists? urllib doesn't raise an error for 404 not found--urllib2 does. Try that instead. Cheers, // m From aahz at pythoncraft.com Mon Jan 19 10:26:01 2004 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2004 10:26:01 -0500 Subject: Optimized quoting (was Re: Speed?) References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: In article , Martin Maney wrote: >Aahz wrote: >> In article , >> Michael Hudson wrote: >>>aahz at pythoncraft.com (Aahz) writes: >>>> >>>> "Premature optimization is the root of all evil in programming." >>>> --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) >>> >>>Cite? > >> http://www.haskell.org/pipermail/haskell-cafe/2001-January/001461.html >> Anybody have a copy of _Literate Programming_ to check? > >Surely someone else must have checked this before now. Perhaps the >reply went astray, or isn't threaded properly so that I don't see it. >Anyway. Yes, Knuth says, in a parenthetical aside on page 276, "But I >also knew, and forgot, Hoare's dictum that premature optimization is >the root of all evil in programming." > >Which fails to answer the quite reasonable wish for a cite attributing >the phrase, rather than the concept, to Hoare. (a distinction Cally >likes to troll in her .sig, as you know.) Well, I tried sending e-mail to Hoare; he hasn't responded. Knuth doesn't do e-mail, and I'm not sure whether I should bother sending him snail mail. If anyone else feels like doing it (and I suppose he's more likely to respond if multiple people do), here's his address: Prof. Donald E. Knuth Computer Science Department Gates Building 4B Stanford University Stanford, CA 94305-9045 USA -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From robhboyd at yahoo.com Thu Jan 22 11:15:07 2004 From: robhboyd at yahoo.com (Robert Boyd) Date: Thu, 22 Jan 2004 08:15:07 -0800 (PST) Subject: PyCon2004 - Where to stay, which airport? In-Reply-To: Message-ID: <20040122161507.88909.qmail@web14102.mail.yahoo.com> --- Brad Clements wrote: > Cheap flights from Ottawa (2 hour drive), $278 or so > to DCA. (but from > Massena, 30 minute drive) $1200 to DCA. Thanks FAA > Essential Air Service. > > Anyway, where should I stay that's cheap but not too > yucky? I don't mind > riding the subway. I might come early for sprints or > the Smithsonian. > > I couldn't find recommended lodgings on the PyCon > wiki. Is DCA the correct > airport? > Check the prices to BWI (Baltimore-Washington International) and IAD (Dulles). BWI often is the cheapest of the 3 DC metro area airports. I'm pretty certain BWI has a shuttle to downtown DC, I know Dulles has cheap shuttle to DC or to nearby Metrorail (subway). Washington Flyer shuttle to Metro: www.washfly.com. SuperShuttle van transport: www.supershuttle.com. "Raygun" National Airport is right on a subway line. As for hotels, how cheap is cheap? Arlington Virginia is probably cheaper than downtown DC, and there's subway. Rob __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From altis at semi-retired.com Thu Jan 29 16:11:42 2004 From: altis at semi-retired.com (Kevin Altis) Date: Thu, 29 Jan 2004 13:11:42 -0800 Subject: wxPython: images from URLs References: <84fc4588.0401280613.771ac07@posting.google.com> Message-ID: "Anand Pillai" wrote in message news:84fc4588.0401280613.771ac07 at posting.google.com... > I have written some code for this in my PyWiew application > which allows one to open image urls directly. > > Copying some relevant code from the application... > > self._imgstream = urllib2.urlopen(url).read() > stream=cStringIO.StringIO(self._imgstream) > > try: > img=wxImageFromStream(stream) > except: > pass > > In short you do the following. > > 1. Use urllib or urllib2 to open the image data stream > 2. Make a cStringIO string buffer from the data stream > 3. Pass it to "wxImageFromStream()" method to get the > wxImage object. > 4. Display the image directly or by converting to > a suitable format using PIL. > > In my experience I found that wxWindows tend to > display an error message window when the image is displayed > directly as a wxImage though the image data is quite ok. > (Something like a corrupt stream dialog). So what I have > done in the application is, use PIL to convert the wxImage > to Windows BMP format and then display it. This seems > to work for all images. > > HTH. > > -Anand > > > > Tim Roberts wrote in message news:... > > Jonathan Daugherty wrote: > > > > > >Does anyone here know if the wxImage class in wxPython supports dislaying > > >images from URLs? > > > > wxImage will read from a file or from a wxWindows stream. It won't > > download from a web site, but that's trivially easy using something like > > urllib. In general you don't display a wxImage object directly. In wxWindows, wxImage is the platform-independent image class and wxBitmap is the platform-specific image class. So, when you set an image to be used with a wxStaticBitmap or wxBitmapButton or draw to a wxDC you use a wxBitmap. Certain image operations not yet supported by wxWindows are easier to handle with PIL in which case your solution of keeping a working image in PIL format and then converting a wxBitmap prior to display is also a good solution. Conversion is covered in the wxPython wiki. http://wiki.wxpython.org/ Here are some of the conversion routines PythonCard uses to deal with PIL, wxImage, wxBitmap, and NumPy numeric arrays. def PILToImage(pilImage): if (pilImage.mode != 'RGB'): pilImage = pilImage.convert('RGB') imageData = pilImage.tostring('raw', 'RGB') img = wx.wxEmptyImage(pilImage.size[0], pilImage.size[1]) img.SetData(imageData) return img def PILToBitmap(image): return wx.wxBitmapFromImage(PILToImage(image)) def BitmapToPIL(bmp): imageData = wx.wxImageFromBitmap(bmp).GetData() imagePIL = fromstring('RGB', (bmp.GetWidth(), bmp.GetHeight()), imageData) imagePIL = imagePIL.convert('RGB') return imagePIL def numericArrayToImage(array): height, width = array.shape[:2] img = wx.wxEmptyImage(width, height) img.SetData(array.tostring()) return img ka From peterwu at hotmail.com Thu Jan 22 11:17:56 2004 From: peterwu at hotmail.com (Peter Wu) Date: Thu, 22 Jan 2004 11:17:56 -0500 Subject: Program Python in VIM Message-ID: <871xpsc5zf.fsf@tulip.whu.ca> I'm giving vim a try to program Python. The following are the steps I follow to code/test a python program. vi test.py [key in some python code] :wq :!python test.py Is there any other way? I don't want to type 'python test.py' every time I've made any modifications. In Emacs, I can simply fire C-c C-c to fire the python interpreter. Thanks! -- ,,, (o o) Peter Wu ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From heavens7s at hotmail.com Wed Jan 28 13:16:41 2004 From: heavens7s at hotmail.com (Joe) Date: 28 Jan 2004 10:16:41 -0800 Subject: directory/file copy over ftp Message-ID: <560d84ab.0401281016.30706c7d@posting.google.com> This is my first time working with the ftplib from Python. I am trying to copy files from the directory. Do you know how? From NAIGIMSESRIMAIL at gims.com Fri Jan 30 10:37:17 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 30 Jan 2004 17:37:17 +0200 Subject: ALERT - GroupShield ticket number OB70_1075477035_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: latex-bugs at latex-project.org Sent: -265200128,29615942 Subject: Re: hello 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: 1797 bytes Desc: not available URL: From stephan.diehlNOSPAM at gmx.net Tue Jan 20 11:58:29 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Tue, 20 Jan 2004 17:58:29 +0100 Subject: personal document mgmt system idea References: Message-ID: Sandy Norton wrote: Hi Sandy, looks like this will be the year of personal document management projects. Since I'm involved in a similar project (hope I can go Open Source with it), here are some of my thoughts. > Hi folks, > > I have been mulling over an idea for a very simple python-based > personal document management system. The source of this possible > solution is the following typical problem: > [...] > > The first problem I've run into is that mysql or the MySQL > connector crashes when the size of one BLOB reaches a certain point: > in this case an .avi file of 7.2 mb . > Just dump your files somewhere in the filesystem and keep a record of it in your database. In addition, a real (text) search engine might be of help. I'm using swish-e (www.swish-e.org) and are very pleased with it. Maybe, before you invest to much time into such a project, you should check out the following: Chandler (http://www.osafoundation.org) if it's finished, it will do excactly what you are aiming for (and it's written in Python) ReiseFS (see www.namesys.com -> Future Vision) Gnome Storage (http://www.gnome.org/~seth/storage) WinFS (http://msdn.microsoft.com/Longhorn/understanding/pillars/WinFS/default.aspx) Hope that helps Stephan From bkelley at wi.mit.edu Fri Jan 16 11:51:18 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 16 Jan 2004 11:51:18 -0500 Subject: MySQLDB multiple cursor question In-Reply-To: <4so1d1-a13.ln1@beastie.ix.netcom.com> References: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu> <3ffd7dbe$0$560$b45e6eb0@senator-bedfellow.mit.edu> <4so1d1-a13.ln1@beastie.ix.netcom.com> Message-ID: <40081686.9020006@wi.mit.edu> Dennis Lee Bieber wrote: > Brian Kelley fed this fish to the penguins on Thursday 08 January 2004 > 16:28 pm: > > >>There you have it. MySQLdb has a threadsafety level of 1 which means >>that connections can't be shared but the module can. >> > > I'd run into a reference to that attribute in the Nutshell, but the > section on DB-API only mentioned that 0 meant not-thread-safe; no > explanation of what different positive values might mean (and I didn't > have time this morning to try to find it via google). If you google for PEP 249 you'll find the description. Brian From sa at sfsu.edu Fri Jan 16 12:53:47 2004 From: sa at sfsu.edu (Sean Abrahams) Date: Fri, 16 Jan 2004 09:53:47 -0800 Subject: Web Form Error Handling Techniques Message-ID: The following is a reprint of a message I sent to the tutor list a long time ago, that I haven't gotten around to discussing with anyone else and failed to hear a reply on the tutor list. Hoping someone here may want to have some dialog. -- I'm learning to write unit tests and am trying to write them for a web application I'm working on. I'm currently writing a test that is to purposefully fail by passing invalid data to a function. However this brought me to thinking about how to handle errors. Let me set up a hypothetical scenario. I have a web form with name and age as its two fields. When a person enters his/her information and submits the form, I take the two fields and create a dict that contains {'name' : 'Foo', 'age' : '82'}. I pass this information to a function called, insertData which looks something like this: def insertData(data): # test data for validity if not data['name'].isalpha(): raise InvalidDataError(data['name'], "Name contains non-alpha characters") if not data['age'].isdigit(): raise InvalidDataError(data['age'], "Age contains non-digit characters") sql = """ INSERT INTO people (name, age) VALUES ('%s', '%s') """ % (data['name'], data['age']) executeSQL(sql) I should first check to see if the data is valid, meaning that the name contains only alpha characters and the age only containing numeric characters. If I raise an exception, how would one handle the reprinting of the web form with a red * next to the field that contains invalid data? If one field is in error, I can see that upon receiving an exception you can have your code just reprint the web form with the red star, but what about when both fields are in error, do you have the exception create a list which then your code checks to see if it exists and then loops through it to know what fields are in error? And then again, perhaps I'm completely wrong and am going about this in an amateur manner. I realize this is more of a style question, but that's what I'm interested in discussing. Thanks, --Sean From aahz at pythoncraft.com Sat Jan 3 19:05:13 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 Jan 2004 19:05:13 -0500 Subject: Creating a capabilities-based restricted execution system References: <9Jecnc6TZdy4lGqiXTWc-w@speakeasy.net> Message-ID: In article , John Roth wrote: >"Sean R. Lynch" wrote in message >news:9Jecnc6TZdy4lGqiXTWc-w at speakeasy.net... >> John Roth wrote: >>> >>> Yes, you're missing something really obvious. Multi-level security >>> is a real difficult problem if you want to solve it in a believable >>> (that is, bullet-proof) fashion. The only way I know of solving it >>> is to provide separate execution environments for the different >>> privilege domains. In the current Python structure, that means >>> different interpreters so that the object structures don't intermix. >> >> Hmmm, can you give me an example of a Python application that works >> this way? Zope seems to be doing fine using RestrictedPython. >> RestrictedPython is, in fact, an attempt to provide different >> execution environments within the same memory space, which is the >> whole point of my exercise. Now, I know that the lack of an example >> of insecurity is not proof of security, but can you think of a way to >> escape from RestrictedPython's environment? DoS is still possible, >> but as I'm not planning on using this for completely untrusted users, >> I'm not too concerned about that. > >Restricted Python was withdrawn because of a number of holes, of which >new style classes were the last straw. RestrictedPython was *not* withdrawn; rexec was withdrawn. This is a difficult enough issue to discuss without confusing different modules. See http://dev.zope.org/Wikis/DevSite/Projects/SupportPython21/RestrictedPython -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From simonb at NOTTHISBIT.webone.com.au Tue Jan 20 18:25:24 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Wed, 21 Jan 2004 10:25:24 +1100 Subject: Pyrex and numarray References: Message-ID: On Tue, 20 Jan 2004 13:48:42 +0100, Marco Bubke wrote: > thx > > but I need to extract the array to a float*. > > I do NA_OFFSETDATA(NA_InputArray(odata, tFloat64, C_ARRAY)) but this isn't > working because Pyrex says he can't storage it. There is a unknown size. I > only need the pointer tp a C array of floats. Thats all. > > ragards > > Marco Use a variable? cdef float* data array = NA_InputArray( array, natype, C_ARRAY ) data = NA_OFFSETDATA(array) Simon. From stefnin.nospam at yahoo.fr Wed Jan 7 07:44:19 2004 From: stefnin.nospam at yahoo.fr (Stéphane Ninin) Date: 07 Jan 2004 12:44:19 GMT Subject: Why ' '.some_string is often used ? Message-ID: Hi all, This is not the first time I see this way of coding in Python and I wonder why this is coded this way: Howto on PyXML (http://pyxml.sourceforge.net/topics/howto/node14.html) shows it on this function, but I saw that in many other pieces of code: def normalize_whitespace(text): "Remove redundant whitespace from a string" return ' '.join(text.split()) Is there a reason to do instead of just returning join(text.split()) ? what does this mean ? Thanks in advance for your explanations. Regards, -- Stephane Ninin From max at alcyone.com Thu Jan 29 21:05:18 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 29 Jan 2004 18:05:18 -0800 Subject: comparing booleans References: <40185112.264898A4@alcyone.com> Message-ID: <4019BBDE.D4429EDF@alcyone.com> Dang Griffith wrote: > Not that I've never used this (cool) Python syntax in practice, > but I thought it was worth mentioning that using != and ^ in > boolean expressions does not always give the same result. It does > give the same result when there are only two operands. This is because of operator chaining, which only exists a special case for the relational operators (==, !=, <, <=, >, >=). It's not actually a difference in the truth table; it's because chaining operators behave differently than other operators. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The work will teach you how to do it. -- (an Estonian proverb) From lutz_p at gmx.net Thu Jan 22 10:42:12 2004 From: lutz_p at gmx.net (Lutz Paelike) Date: Thu, 22 Jan 2004 16:42:12 +0100 Subject: Looking for advice: supporting multiple embedded interpreters Message-ID: <400FEF54.4040902@gmx.net> Paul is totally right. I am in the same situation here. He described very clearly the problem. Any insights anybody? Lutz Paelike Paul Miller wrote: > Some background first - we have some software that embeds a Python > interpreter into a host application. Scripts are loaded dynamically and > used. But we want to support the ability to edit scripts while the app > is running. This means we have to "unload" the script and cause a > reload. Normal module reloading tricks don't work because if you try to > reimport a script that imports another script, and if the nested script > is changed, it might not be reloaded itself. Also, we have 2 parts of > the software, each using Python for its own set of scripts. We don't > want scripts loaded into each parts to "see" scripts loaded into the > other part. Ideally, we would like multiple "instances" of a Python > interpreter to manage this. > > So, for Python 2.2, I came up with a system that works. When we need a > new self-contained Python interpreter, I use Py_NewInterpreter(), swap > it in using PyThreadState_Swap, load my built in modules, and swap it > back out. When I need to run some code in that interpreter, I swap it > back in, load the module I need, call methods in it, and swap it back > out. When I'm done with the interpreter, I swap it back in and call > Py_EndInterpreter. > > When I want to force a reload of all the script code in a given > interpreter, I just delete the interpreter, create a new one, and load > the scripts into that one. This has worked flawlessly. And each "part" > of my application can use a different interpreter without modules and > globals in each one interfering with the other. > > Now, with Python 2.3, this code doesn't seem to work anymore. Someone > told me it is likely because of the extensive rewrite of GUSI or > whatnot. It is important to note that I'm NOT really doing any > threading. I just was self-contained interpreters for the above reasons. > > What I am wondering is if there a reliable method in 2.3 that does what > I need? > > It has recently come to my attention that Lutz Paelike is in exactly the > same situation I am in, so I don't think this is a fringe concept. > > ------ From miki.tebeka at zoran.com Thu Jan 8 04:57:29 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 8 Jan 2004 01:57:29 -0800 Subject: Bits from Numbers. References: <3ffcb189$1@nntp0.pdx.net> Message-ID: <4f0a9fdb.0401080157.6686499e@posting.google.com> Hello Scott, > I am whacking away at some code to view numbers as bit sequences. > While this is not complete, I'd appreciate some feedback from anyone > who is interested in looking at it: > http://members.dsl-only.net/~daniels/bits.html Looks great. Several things: 1. I think a new object "bitarray" which will be a subclass of "list" will be more "natural". Then you'll get: bitcount(n) -> n.count(1) bit(n, x) -> n[x] extract(x, lo, hi) -> n[lo:high] ... 2. There is no function to set a range of bits n = setbits(n, start, end, value) 3. I'd prototype it first in Python and after the interface has matured move it to C. This way you'll be able to make changes faster. (This is the way the Python library works - see sets, itertools, heapq ...) HTH. Miki. From fumanchu at amor.org Sun Jan 18 21:46:13 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 18 Jan 2004 18:46:13 -0800 Subject: Determining a replacement dictionary from scratch Message-ID: Dan wrote: > I'd like to be able to take a formatted string and determine the > replacement dictionary necessary to do string interpolation with it. > For example: > > >>> str = 'his name was %(name)s and i saw him %(years)s ago.' > >>> createdict( str ) > {'name':'', 'years':''} > >>> > > Notice how it would automatically fill in default values based on > type. I figure since python does this automatically maybe there is a > clever way to solve the problem. Otherwise I will just have to parse > the string myself. Any clever solutions to this? If the only functionality you want is the ability to fill in default values, you could try a variation on subclassing dict: PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. >>> class DefaultDict(dict): ... def __init__(self, default): ... self.default = default ... def __getitem__(self, key): ... try: ... return dict.__getitem__(self, key) ... except KeyError: ... return self.default ... >>> str = 'his name was %(name)s and i saw him %(years)s ago.' >>> d = DefaultDict('???') >>> d['years'] = 3 >>> str % d 'his name was ??? and i saw him 3 ago.' Robert Brewer MIS Amor Ministries fumanchu at amor.org From graham at rockcons.co.uk Sun Jan 4 16:25:33 2004 From: graham at rockcons.co.uk (Graham Nicholls) Date: Sun, 04 Jan 2004 21:25:33 +0000 Subject: Launching pdb from within a script References: Message-ID: Peter Otten wrote: > Graham Nicholls wrote: > >> I'm sure I was able to print the value of variables like this: >> >> except : >> pdb.set_trace() > [...] >> But pdb complains that there are no such variables. It may be that I had >> to add some incantation around the script startup - I just can't remember >> (and its frustrating!). > > > import pdb > abc = 1 > try: > print "before" > 1/0 > except: > pdb.set_trace() > print "after" > > > Now run it: > > before > --Return-- >> /(suppressed)/python2.3/pdb.py(992)set_trace()->None > -> Pdb().set_trace() > (Pdb) abc > *** NameError: name 'abc' is not defined > (Pdb) u >> /(suppressed)/debugger.py(7)?() > -> pdb.set_trace() > (Pdb) abc > 1 > (Pdb) > > If the above sample session doesn't help, you could actually read the pdb I have had a look, but its rather a case of you don't know what you don't know, IYSWIM. > documentation - or do something new and dangerous: search google groups > for, say, Nicholls and set_trace :-) What a good idea! Thanks again PS 1 minute later and I've found the relevant posting, which indeed mentions using set_trace(). I have in ordinary google searches of course returned ng postings, but had never used their group searches, so thnkas on two counts. > > Peter Regards Graham -- #include From Scott.Daniels at Acm.Org Wed Jan 14 10:57:55 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 14 Jan 2004 07:57:55 -0800 Subject: Safe prime numbers in Python In-Reply-To: References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> Message-ID: <4005725d$1@nntp0.pdx.net> Skip Montanaro wrote: > Tim> Does any know of or have Python code (or C or Fortran code wrapped > Tim> as a Python module) for efficiently finding safe prime numbers - > Tim> that is a number p such that p and (p-1)/2 are both prime? > > Here's what I came up with using gmpy: > > import gmpy > > def safe_primes(last=1): > while True: > next = gmpy.next_prime(last) > if gmpy.is_prime((next-1)/2): > yield next > last = next > I suspect it might be faster if you looked for the lower prime: def safe_primes(last=1): while True: last = gmpy.next_prime(last) other = last * 2 + 1 if gmpy.is_prime(other): yield other -Scott David Daniels Scott.Daniels at Acm.Org From jepler at unpythonic.net Sun Jan 18 15:27:10 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Jan 2004 14:27:10 -0600 Subject: Determining a replacement dictionary from scratch In-Reply-To: References: <4b805376.0401181116.3b0adb41@posting.google.com> Message-ID: <20040118202710.GA20915@unpythonic.net> On Sun, Jan 18, 2004 at 07:34:07PM -0000, Dave Benjamin wrote: > Here's a solution that uses a regular expression. It only handles strings > and doesn't cache the regular expression; I'll leave this up to you. =) Of course, since it uses regular expressions it's also wrong... >>> createdict("%%(foo)s") {'foo': ''} This version might be more correct: pat = re.compile("%\([^)]*\)s|%%") def createdict(fmt): keys = [x[2:-2] for x in pat.findall(fmt) if x != '%%'] return dict(zip(keys, [''] * len(keys))) Here's another way, one I like better: class D: def __init__(self): self.l = [] def __getitem__(self, item): self.l.append(item) def createdict(fmt): d = D() fmt % d return dict(zip(d.l, [''] * len(d.l))) .. I like it better because it uses the exact same logic to determine the needed names as it will when the string is actually formatted. Jeff From paul at fxtech.com Tue Jan 27 11:14:22 2004 From: paul at fxtech.com (paul at fxtech.com) Date: Tue, 27 Jan 2004 11:14:22 -0500 (EST) Subject: print format for binary representation In-Reply-To: <20040127151009.GA16950@intarweb.us> References: <6f03c4a5.0401270700.713a73aa@posting.google.com> <20040127151009.GA16950@intarweb.us> Message-ID: <7990.195.173.15.12.1075220062.squirrel@webmail.pair.com> > Here's a version to toy with: > > binary = lambda i, c = (lambda i, c: i and (c(i >> 1, c) + str(i & 1)) > or ''): c(i, c) Is this example in perl or python? My brain hurts! :-) From seanl at chaosring.org Sat Jan 3 13:25:40 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 10:25:40 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: <9Jecnc6TZdy4lGqiXTWc-w@speakeasy.net> John Roth wrote: > Yes, you're missing something really obvious. Multi-level > security is a real difficult problem if you want to solve it > in a believable (that is, bullet-proof) fashion. The only way > I know of solving it is to provide separate execution > environments for the different privilege domains. > In the current Python structure, that means different > interpreters so that the object structures don't intermix. Hmmm, can you give me an example of a Python application that works this way? Zope seems to be doing fine using RestrictedPython. RestrictedPython is, in fact, an attempt to provide different execution environments within the same memory space, which is the whole point of my exercise. Now, I know that the lack of an example of insecurity is not proof of security, but can you think of a way to escape from RestrictedPython's environment? DoS is still possible, but as I'm not planning on using this for completely untrusted users, I'm not too concerned about that. From andrew-pythonlist at puzzling.org Wed Jan 28 01:21:35 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 28 Jan 2004 17:21:35 +1100 Subject: Tcl style traces In-Reply-To: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Message-ID: <20040128062135.GA22097@frobozz> On Wed, Jan 28, 2004 at 10:18:59AM +0800, Derek Fountain wrote: > Does Python have something similar to Tcl style tracing? That is, the > ability to call a subroutine when a variable is written to or read from? Not for variables in general, unless you feel like mucking about with sys.settrace. For attributes of objects, you can use __getattr__/__setattr__ methods, use __getattribute__/__setattribute__ methods, use properties, or even roll-your-own descriptor, depending on what you need. What do you need this for? If you can be more specific, we might be able to help you a little better. -Andrew. From python at g2swaroop.net Mon Jan 19 09:39:21 2004 From: python at g2swaroop.net (python at g2swaroop.net) Date: Mon, 19 Jan 2004 09:39:21 -0500 (EST) Subject: Looking for very simple general purpose tokenizer Message-ID: <.202.71.153.169.1074523161.squirrel@www.g2swaroop.net> Hi, Maybe the Spark module can help you. Here's a DeveloperWorks tutorial on that : http://www-106.ibm.com/developerworks/linux/library/l-spark.html Hope it helps, Swaroop --------------------------------------------------------------------------- Hi group, I need to parse various text files in python. I was wondering if there was a general purpose tokenizer available. I know about split(), but this (otherwise very handy method does not allow me to specify a list of splitting characters, only one at the time and it removes my splitting operators (OK for spaces and \n's but not for =, / etc. Furthermore I tried tokenize but this specifically for Python and is way too heavy for me. I am looking for something like this: splitchars = [' ', '\n', '=', '/', ....] tokenlist = tokenize(rawfile, splitchars) Is there something like this available inside Python or did anyone already make this? Thank you in advance Maarten -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From danb_83 at yahoo.com Wed Jan 28 01:56:15 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 Jan 2004 22:56:15 -0800 Subject: Best way to compare a list? References: <7b454334.0401271739.59267018@posting.google.com> Message-ID: faizan at jaredweb.com (Fazer) wrote in message news:<7b454334.0401271739.59267018 at posting.google.com>... > Hello, > > I was wondering which would be the best way to compare a list? To compare a list to _what_? From sambo at void.com Thu Jan 22 19:39:20 2004 From: sambo at void.com (sambo) Date: Thu, 22 Jan 2004 16:39:20 -0800 Subject: Best way to do this? References: <100jg9er3qak890@corp.supernews.com> Message-ID: <40106D38.3010302@void.com> > >The "obscure" for/else can help: > > >def get_password (prompt): > for i in (1, 2, 3): > password = raw_input (prompt) > if password == 'mypass': > return True > else: > print "Try Again" > else: > print "Too Bad" > return False > > > > Regards. Mel. > Obscure? at least it does something. What is the advantage of the following assignment ( a few messages up) attempts, password = 3, 'mypass' Reading difficulty - at least 3 (no relation, hehe) Ciao From HAALrvanderhWEG at xs4all.nl Thu Jan 22 12:56:27 2004 From: HAALrvanderhWEG at xs4all.nl (Rik van der Helm) Date: Thu, 22 Jan 2004 18:56:27 +0100 Subject: newbie,cgi,os.system,cdrecord References: <400fe08c$0$326$e4fe514c@news.xs4all.nl> <20040122085927.026A.JCARLSON@uci.edu> Message-ID: <40100ea3$0$316$e4fe514c@news.xs4all.nl> Josiah Carlson wrote: > > On Thu, 22 Jan 2004 15:39:47 +0100 > Rik van der Helm wrote: > >> Hello, >> >> I am trying to make a backupscript in python, which I want to manage via >> a webform (cgi). In my script I use os.system to execute the following >> shellscript: >> "cdrecord -s -dev=0,1,0 -blank=fast -speed=2 fs=8m file.tgz" >> >> When I execute the pythonscript in the shell, it gets executed well and I >> get some output from cdrecord. Which I don't understand because I put >> cdrecord at silent (-s !) I thought. >> >> When I execute the pythonscript in a webbrowser via cgi, cdrecord also >> gets executed well but I get an 'Internal Server Error' of Python and in >> '/var/log/httpd/error_log' it says: >> "malformed header from script. Bad header=Cdrecord 1.11a19 etc....." >> >> I think I understand what is going wrong. Apache tries to print the >> output of cdrecord and finds something wrong and stops executing the >> script. Is this correct ? If this is correct how do I get cdrecord stop >> making output texts ? >> >> All suggestions are welcome >> >> Thanks, Rik >> > > Try: > "cdrecord -s -dev=0,1,0 -blank=fast -speed=2 fs=8m file.tgz > /dev/null" Thanks very much, Josiah From martin at v.loewis.de Fri Jan 16 02:44:31 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 16 Jan 2004 08:44:31 +0100 Subject: Suggested generator to add to threading module. In-Reply-To: <7934d084.0401152058.164a240c@posting.google.com> References: <7934d084.0401152058.164a240c@posting.google.com> Message-ID: <4007965F.6030106@v.loewis.de> Andrae Muys wrote: > I considered suggesting it for itertools, but really it's thread > specific so I am suggesting it for the threading module. If you are willing to contribute this function, please submit a patch to sf.net/projects/python, including documentation changes, and test cases. Regards, Martin From netquest at sympatico.ca Tue Jan 27 22:46:18 2004 From: netquest at sympatico.ca (KNS) Date: Tue, 27 Jan 2004 19:46:18 -0800 Subject: winapi: mouseclick In-Reply-To: References: Message-ID: It's looking like I must use pyHooks...Thanks. From andrearo at stud.ntnu.no Sun Jan 18 16:03:34 2004 From: andrearo at stud.ntnu.no (=?ISO-8859-1?Q?Andreas_R=F8sdal?=) Date: Sun, 18 Jan 2004 22:03:34 +0100 Subject: parse binary file in python? Message-ID: Hello, I want to parse a binary file in python. Does python have some built in methods for doing this easily? Any links to example code would be nice.. Thanks Andreas R. From jcarlson at nospam.uci.edu Sun Jan 25 20:06:35 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 17:06:35 -0800 Subject: Mod_python on Windows Troubles In-Reply-To: References: Message-ID: > modules/mod_python.so" to httpd.conf, the Apache service refuses to > start with the following error: "Cannot load C:/Program Files/Apache > Group/Apache2/modules/mod_python.so into server: The specified module While I'm not using Apache or mod_python, I would be willing to bet that your error is the result of using 'mod_python.so' in Windows. Try 'mod_python.dll' instead. - Josiah From paul.moore at atosorigin.com Mon Jan 5 17:53:47 2004 From: paul.moore at atosorigin.com (Paul Moore) Date: Mon, 05 Jan 2004 22:53:47 +0000 Subject: PEP 324: popen5 - New POSIX process module Message-ID: <1xqedn2c.fsf@yahoo.co.uk> I've read the PEP, and I'd like to help with an implementation for Windows, if no-one else is doing it. Initially, I'll probably use win32all (or maybe ctypes) but the intention is that longer term the necessary functions be migrated into a supporting C extension. I do have some comments, which may be of interest. The whole interface feels very Unix-specific. In particular, 1. The preexec_* arguments have no meaning on Windows, where the low-level functionality is CreateProcess (spawn) rather than fork/exec. This isn't too crucial, as use of the argument can either be ignored, or probably better, treated as an error on Windows. 2. The method name poll() doesn't seem appropriate in a Windows context (I don't know how it fits with Unix). Better might be is_complete() returning True/False, and use returncode to get the status separately. 3. The whole thing about the return code encoding both the exit status and the signal number is very Unix-specific. Why not split them - status and signal attributes, and maybe have is_complete() return 3 possible values - +1 = completed OK, 0 = still running, -1 = died due to a signal. 4. wait() should be defined as "wait for the subprocess to finish, and then return is_complete()". That's basically what you have now, it's just a bit clearer if you're explicit about the intent. 5. I don't like the names fromchild, tochild, and childerr. What's wrong with stdin, stdout, and stderr? OK, stdin is open for write, and the other two for read, but that's fairly obvious as soon as you think about it a bit. The biggest issue, though, is that args as a sequence of program arguments is very Unix-specific. This is a big incompatibility between Unix and Windows - in Windows, the low-level operation (CreateProcess) takes a *command line* which is passed unchanged to the child process. The child then parses that command line for itself (often, but not always, in the C runtime). In Unix, exec() takes an *argument list*. If you have a command line, you have to split it yourself, a task which is usually delegated to /bin/sh in the absence of anything else. This is hard to handle portably. I'd suggest that the Windows implementation allow two possibilities for the "args" argument. If args is a string, it is passed intact to CreateProcess. That is the recommended, and safe, approach. The shell is still not invoked, so there's no security issue. If a (non-string) sequence is passed, the Windows implementation should (for Unix compatibility) build a command line, using its best attempt to quote things appropriately (this can never be safe, as different programs can implement different command line parsing). This is not safe (wrong answers are the main problem, not security holes), but will improve portability. I agree with Guido's comments on python-dev - this module (popen5 is a *horrible* name - I'd prefer "process", but am happy if someone comes up with a better suggestion) should aim to be the clear "best of breed" process control module for all platforms. Some other points may well come up as I try to implement a Windows version. I hope this is of some use, Paul. -- This signature intentionally left blank From edcjones at erols.com Thu Jan 22 09:56:04 2004 From: edcjones at erols.com (Edward C. Jones) Date: Thu, 22 Jan 2004 09:56:04 -0500 Subject: python said : "1, 2, 3, 6, 7, manbo !" In-Reply-To: <400F3D90.2176087B@alcyone.com> References: <400F3D90.2176087B@alcyone.com> Message-ID: <400fe57a$0$3043$61fed72c@news.rcn.com> Erik Max Francis wrote: > - wrote: > > >>Why 5 does not appear ? (this was the source of a deep bug in a 4000+ >>lines networked program...) > > > You are iterating over a mutable sequence while you are mutating it. > That is a big no-no. This can sometimes be done safely by iterating backwards: n = len(seq) for i in range(n-1, -1, -1): ... From jacek.generowicz at cern.ch Wed Jan 14 07:04:56 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 14 Jan 2004 13:04:56 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Michael Hudson writes: > > Careful. If you were to make such a suggestion on comp.lang.lisp, then > > you'd be likely to be told that learning Scheme first will cause you > > irreversible brain damage. Of course, now that He Whose Name Must Not > > Be Mentioned is no longer posting there, > > Heeeeeeeeee's back! Yes, kinda ironic that I happened to post this on the eve of his return. From james at logicalprogression.net Wed Jan 21 15:33:34 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 20:33:34 +0000 Subject: python mode question In-Reply-To: <87y8s1oxuj.fsf@tulip.whu.ca> References: <87y8s1oxuj.fsf@tulip.whu.ca> Message-ID: <200401212033.34507.james@logicalprogression.net> On Wednesday 21 January 2004 8:23 pm, Peter Wu wrote: > After firing C-c C-c to execute a python program in Python mode, an > output buffer will be displayed at the bottom of the window. Also, the > focus remains in the output buffer. How can I switch the focus from the > output buffer to the editing buffer? Thanks! C-x o I take it you're talking about Emacs. :) -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From jzgoda at gazeta.usun.pl Wed Jan 14 15:57:47 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 14 Jan 2004 20:57:47 +0000 (UTC) Subject: id3v2 module References: Message-ID: Guido Schimmels pisze: >>>> I'd like to know if there is a third-party module for reading/writing >>>> id3v2 informations. >>> http://id3-py.sourceforge.net/ >> >> This one is able to read and write only ID3v1.1 tags. > > O, sorry. Maybe this is what you are looking for then: > http://tunetagger.sourceforge.net/snapshots/ No, I'm not looking for any ID3 library -- I just had something to do with mp3s lately... ;) -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From tim.one at comcast.net Sun Jan 11 21:01:57 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 11 Jan 2004 21:01:57 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401111712.22a74be7@posting.google.com> Message-ID: [Aaron Watters] > Some SQL isolation levels are hacks to allow long running > transactions, etcetera. If you keep to the strictest isolation level > you get the classical behaviour which has been studied and elaborated > by many very smart people over the last several decades and which is > very well understood. > > Does ZODB support the strictest isolation levels? I'm almost certain it doesn't, but I'm not a DB expert. Please take this to a ZODB list, as previously suggested. > If so how? If not what does it support exactly? I pointed you to Jeremy's relevant blog entry last time, which discusses these issues -- and nobody knows more about ZODB than Jeremy. If you want someone to read it for you and reword it, I'm sure someone on a ZODB list will be happy to do so . From skip at pobox.com Wed Jan 28 09:52:55 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 08:52:55 -0600 Subject: I support PEP 326 In-Reply-To: <20040128090205.GA3086@nl.linux.org> References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> <20040128041023.2EB9225B353@bonanza.off.ekorp.com> <20040128090205.GA3086@nl.linux.org> Message-ID: <16407.52423.664582.438055@montanaro.dyndns.org> >> That's a _lot_ of stuff in one module. Even if you exclude the 40-odd >> exceptions that are there, that's still a lot of guff in one big flat >> namespace. Gerrit> Any plans to clean it up in Python 3.0? Yes, there has been some discussion about this on python-dev. It doesn't appear a PEP's been written yet. Skip From jjl at pobox.com Mon Jan 12 18:53:53 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Jan 2004 23:53:53 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <877jzwg1v2.fsf@pobox.com> "Bicho Verde" writes: [...] > I have some basic skills in programming (C, Pascal, Macromedia > Actionscript) but don't know exactly what to do in the world of programming. If you just want to motivate yourself for some semi-arbitrary project, my advice is to start using some open-source software. All software sucks, so you'll eventually find something that pisses you off enough to make you want to fix it or do it from scratch, properly :-) > And also I don't know exactly why would I learn Python rather than C#, > C++ or Perl. They are all very different languages. Trawl through google groups -- comp.lang.python is a great place to look for comments on all three (but I would say that). Try some of Alex Martelli's posts. I used to default to the widely-held position that "language wars" are mostly content-free "religious" arguments, but experience has taught me otherwise. There are big, important, differences in programmer efficiency, in computer-resource efficiency, and in community support. And, to some extent, in the ways they make you think about problems. The issues are subtle and complicated, and understanding them requires writing programs in a set of languages diverse enough to come somewhere vaguely close to spanning the big space of language-design possibilities. I'm feeling particularly self-indulgent, so here are a bunch that seem notable current players to me: Python: All-round pragmatic winner, and elegant to boot. One disadvantage: you'll struggle to motivate yourself to learn any other language once you've used it ;-) Perl: CPAN is great; the language is merely an insane version of Python (yes, Perl does predate Python). C++: No compromises on execution speed; plays well with C (and with Python: check out Boost Python); horrendously complicated; no garbage collector (unless you add one yourself, but then you'd be better off mixing C++ with a saner language). Notable for "templates". C: Needs no introduction! Java: Solid security model; piles of code; shockingly mediocre language, to the extent that there would be precious few sane uses of the thing were it not for Jython and all those libraries (but watch out for over- engineering). C#: Java for MS .NET users (to first order, anyway). .NET has broader goals than Java for language interoperation, so even though Jim Hugunin and others have done some initial work on a .NET implementation of Python, dynamic languages like Python will likely never be full .NET citizens (thanks to the design of the .NET CLR). If that full citizenship is important to you, C# has that advantage, but I'm reliably informed it's fairly well-described as "a Java clone" (implying programmer-inefficiency), so I'd be inclined to look for a better language with a good .NET implementation. Lisp? Smalltalk? (there was talk of an excellent .NET smalltalk implementation, but I'm not sure whether that was vapourware or not...) O'Caml: Excellent execution speed without C/C++'s unpleasant bugs. Functional (in the technical sense), with elegant static type inference, but multi-paradigm: you can write procedural code too. Requires a different way of thinking to procedural languages for best use. Nasty syntax. O'Reilly book in English and French. Haskell: Another functional language (like O'Caml); good for forcing you to think functionally; lazy evaluation. Lots of good books. Fortran: Still rules for some numerical analysis work. Lisp: Powerful, elegant and well-established, but it has been argued (see recent threads here) that Lisp macros are not best described as a language feature, but rather as a harmful, Babel-inducing, tool for making new languages. Scheme: Cleaned-up version of Lisp. Beautifully simple. Suffers from a splintering of the user community thanks to a multitude of subtly different implementations. Worth learning just to read Abelsson & Sussman's (sp?) freely-downloadable book "Structure and Interpretation of Computer Programs". Eiffel: Design by contract. The book to read is Meyer's "Object- Oriented Software Construction". Full of interesting stuff, if you can stand his self-importance ;-). Lua: Pint-sized Python. Erlang: Concurrent programming. Ruby: Python with a smaller user community (unless you're Japanese), some minor wins and losses, and a very questionable design decision or two thrown in (see numerous threads on this group). Smalltalk: Never tried it, but sounds interesting, and similar to Python in some ways. Oz: Prolog for the 21st century (OK, I admit I haven't a clue what it's like really, but I have to try it some day...). Mathematica and Maple: Heaven, if you're into maths. Alex Martelli has pointed out the brain-stretching value of learning languages of a different nature (some of which aren't Turing complete): including query languages (eg. SQL) and markup languages (eg. XML). Everybody here will tell you this, but I'm going to say it yet again: don't be so foolish as to think you have to write *all* your code in a language like C++ (or C, or Fortran, depending on the use) just because you want the program as a whole to run fast. And take the current myopic view of static typing (in the eyes of the great unwashed programming public) with a bucket of salt. > Basicaly I don't know where to start, if there is much to do or > if it is has it seems and there is software to everything nowadays and so > doesn't make sense to spend time in learning a programming language. > > I just have this idea that I would like to contribute to the curve of > accelarated exponential progress (technological singularity), artificial > intelligence and so on. From that point of view there is much to do... But You should be able to get that lot done in a weekend, no? Really, if you buy the notion of a technological singularity, you've got me well-and-truly puzzled as to how you fit that into your brain at the same time as believing that "there is software to everything [sic] nowadays"! > can I stand for it and where to start? Small?... and, of course, keep your eyes peeled for something you think really matters. John From sdeibel at wingide.com Thu Jan 15 11:02:16 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Thu, 15 Jan 2004 11:02:16 -0500 (EST) Subject: Best Python IDE Code Completion! In-Reply-To: Message-ID: On Thu, 15 Jan 2004, Mirko Zeibig wrote: > Python is dynamically typed, so no editor in the world can guess the > type of any function parameters correctly. If you know about the true > nature of one, you may assist Wing IDE by using isinstance. > > class Klass(object): > > def hello(self): > print "Hello" > > def foo(bar): > assert isinstance(bar, Klass) > bar.hello() > > Without the assert line, it's impossible to detect which type bar has. > Only during runtime the type of bar is known. Note that you can also use the following form to cover cases where you run into circular imports: if 0: import mymod isinstance(bar, mymod.Klass) The source analyser still picks up on the hint but nothing is done at runtime. > John said the following on 01/15/2004 12:52 PM: > > Wing IDE seems converse. The editor auto list members is great but > > has no calltips. The interactive window has no completion at all. > I second this, though the editor sometimes need a bit of help ... > and I do not like the MDI approach they have. We're changing that and adding calltips too... If you want announcement of upcoming releases sign up here: http://wingide.com/announcelist Sorry, I can't currently reveal anything about expected release dates. > > Python has great introspective capabilities and we have a great open > > contributing community. What technical difficulties keep us from > > having REAL code completion like MS, Borland and several Java IDEs > > (All of which have been funded at one time or the other if not > > entirely - perhaps this is the reason?) Wing does static analysis of code (which can't use Python's introspection) because it can't rely on all code being executed (all classes instantiated, etc). Also, during editing code often is incorrect and won't run but we still want to update analysis information. It's not a trivial problem, esp. considering the need for speed, but it basically is doable for most Python code. Something like runtime introspection is a lot easier when appropriate, and ahem yes, we really should add that to our shell and debug probe tools! Stephan Deibel -- Wing IDE for Python Archaeopteryx Software, Inc Take Flight! www.wingide.com From jepler at unpythonic.net Mon Jan 5 22:54:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Jan 2004 21:54:30 -0600 Subject: Repost: Can't sys.exit() from SIGTERM handler? In-Reply-To: References: <20040106013708.GD5514@unpythonic.net> Message-ID: <20040106035430.GF5514@unpythonic.net> Python's signal handling is "strange at best". As I understand it, when you register a Python function via signal.signal, Python installs a C signal handler that sets a flag, and then the interpreter checks for that flag to be set. If it is set, the Python signal handler is invoked. This was an expedient way to do this, because the alternative (running the Python code in the signal handler) would mean making sure signal arrival at any moment was safe for the state of Python objects---a virtually impossible task. #1. The idiom for "exit" is either sys.exit() or raise SystemExit, arg Everywhere you are writing a "blanket except statement" like except: or except Exception: you will have to write something like except (SystemExit, KeyboardInterrupt): raise as an earlier except clause to get the proper behavior. This will, ahem, encourage you to avoid overly broad exception handlers. Most Python programs I write don't have any such clause, and Python programs that need to run in a "server" kind of role probably have exactly one of them, in the right place to kill a particular connection but leave the server running. #2. You're getting into territory where I've never been. Thinking that the problem might be with multiple SIGTERMs delivered to the Python process, I changed my earlier program and got results I don't understand. :r term2.py import os, signal, time, sys, traceback x = 0 def sig(a, b): print "Entering exception handler" global x x = x + 1 print "sigterm", x print "sleeping in exception handler" time.sleep(2) print "Exiting exception handler" x = x - 1 sys.exit() signal.signal(signal.SIGTERM, sig) os.system("(while true; do sleep 1; kill %s || exit; done) &" % os.getpid()) print "Sleeping (should be killed)" try: time.sleep(2) except SystemExit: traceback.print_exc() raise print "sleep finished (!?)" $ term2.py Sleeping (should be killed) Entering exception handler sigterm 1 sleeping in exception handler Entering exception handler sigterm 2 sleeping in exception handler Entering exception handler sigterm 3 sleeping in exception handler Entering exception handler sigterm 4 sleeping in exception handler # hit ctrl-c here Traceback (most recent call last): File "term2.py", line 22, in ? time.sleep(2) File "term2.py", line 12, in sig print "Exiting exception handler" File "term2.py", line 12, in sig print "Exiting exception handler" File "term2.py", line 12, in sig print "Exiting exception handler" File "term2.py", line 12, in sig print "Exiting exception handler" KeyboardInterrupt By commenting out the line "print "Exiting exception handler"" (which never seemed to be reached !?) gives this behavior: $ python term2.py Sleeping (should be killed) Entering exception handler sigterm 1 sleeping in exception handler Entering exception handler sigterm 1 sleeping in exception handler $ sh: line 1: kill: (13961) - No such process If I had to guess, I'd say that in the first example something about the 'print' statement causes pending Python signal handlers to be invoked, and in the second example that the Python signal handler is invoked after the 'except' statement's body is executed but before anything is printed. Back to your question, remember that Python exceptions raised in a signal handler can be handled in the main program (that's how sys.exit works, after all). So what if the flow of code looks like this: sigterm delivered waitpid sigterm delivered waitpid when the "inner" waitpid finishes, the outer will wait for the same process and get the ECHILD exception. If that's the case, then you could either wait for your processes in a way that is safe in the presence of a recursive invocation, such as: while list: pid = kids.pop() os.kill(pid, signal.SIGTERM) waitpid(pid, 0) ... another way to make this safe would be a targeted try: except: block around the waitpid line, if that's the site where you've seen the exception raised: try: waitpid(pid, 0) except OSError, detail: if detail.errno != errno.ECHILD: raise else: react to the fact that the child is already dead Handling child processes is hopelessly subtle (especially when signals are in the mix), and I'm sure I've gotten some things here terribly wrong too. I wish there was somebody else offering you better advice. Jeff From mail at malgadey.de Thu Jan 29 08:34:26 2004 From: mail at malgadey.de (Wolfgang Malgadey) Date: Thu, 29 Jan 2004 14:34:26 +0100 Subject: Compiled Python binaries Message-ID: Hello! i am searching for a resource of compiled python binaries. I am working on a spezial linux version (no compiler onboard). It must be linked to glibc5. Maybe you can help? greets from cologne, germany Wolfgang Malgadey From sombDELETE at pobox.ru Sun Jan 4 17:05:22 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 5 Jan 2004 01:05:22 +0300 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "John Roth" wrote in message news:vvg0h93ue63c0b at news.supernews.com... > > Much of this thread has focused on "capabilities" and the use of > proxies to implement capabilities. AFIAC, that's not only putting > attention on mechanism before policy, but it's putting attention on > mechanism in the wrong place. I'm not sure why it should be discussed here since Sean refered to E in the first post (http://www.erights.org/), so I think he's comfortable with the policy defined by E? I think he has missed the part that implementation should help as much as it can prevent leaking capabilities from one security domain to another. I pointed to that already. > > What I *haven't* seen in this thread is very much consideration of > what people want from a security implementation. I think Sean is talking about his own implementation. I didn't see anywhere he said he's going to write general implementation for other people. He said what he wants from his implementation. > One problem I've been playing around with is: how would you > implement something functionally equivalent to the Unix/Linux > chroot() facility? The boundaries are that it should not require > coding changes to the application that is being restricted, and it > should allow any and all Python extension (not C language > extension) to operate as coded (at least as long as they don't > try to escape the jail!) Oh, yes. It has to work on Windows, > so it's not a legitimate response to say: "use chroot()." I don't see any unsolvable problems. Could you be more specific what is the problem? (besides time, money, need to support alternative python implementation, etc...) -- Serge. From pythonguy at Hotpop.com Wed Jan 28 09:13:13 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 28 Jan 2004 06:13:13 -0800 Subject: wxPython: images from URLs References: Message-ID: <84fc4588.0401280613.771ac07@posting.google.com> I have written some code for this in my PyWiew application which allows one to open image urls directly. Copying some relevant code from the application... self._imgstream = urllib2.urlopen(url).read() stream=cStringIO.StringIO(self._imgstream) try: img=wxImageFromStream(stream) except: pass In short you do the following. 1. Use urllib or urllib2 to open the image data stream 2. Make a cStringIO string buffer from the data stream 3. Pass it to "wxImageFromStream()" method to get the wxImage object. 4. Display the image directly or by converting to a suitable format using PIL. In my experience I found that wxWindows tend to display an error message window when the image is displayed directly as a wxImage though the image data is quite ok. (Something like a corrupt stream dialog). So what I have done in the application is, use PIL to convert the wxImage to Windows BMP format and then display it. This seems to work for all images. HTH. -Anand Tim Roberts wrote in message news:... > Jonathan Daugherty wrote: > > > >Does anyone here know if the wxImage class in wxPython supports dislaying > >images from URLs? > > wxImage will read from a file or from a wxWindows stream. It won't > download from a web site, but that's trivially easy using something like > urllib. From gagenellina at softlab.com.ar Fri Jan 2 19:49:03 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 02 Jan 2004 21:49:03 -0300 Subject: NEWBIE: Sub-classes revisited In-Reply-To: Message-ID: <5.2.1.1.0.20040102204815.023f1340@192.168.0.115> At 31/12/2003 15:47, you wrote: ># IN MOD_1.PY > >class B: > def __init__ (self): > self.B_init_var = 1 > def B_meth(self): > self.B_meth_var = 2 > ># IN MOD_2.PY > >import mod_1 > >class A(mod_1.B): # B needs to be qualified > def __init__(self): > mod_1.B.__init__(self) # Needs to be qualified > self.B_meth() # But B's method doesn't > print self.B_init_var # Just to be sure > print self.B_meth_var # Ditto Apart from trial-and-error and self-discoving things, which is really good, you should read the Python Tutorial which is very good too. If you did already, do it again, specially section 9 (Classes). >Is the following true? > >1. When A is instantiated, B's name space is exposed > to A. No. Python uses dynamic binding. If you come from a statically-binded language like Java or C++ this may be confusing. In Python, the attributes and methods are searched *looking*inside*the*instance*, not by knowledge of some prior declarations of type. At the beginning of A.__init__ the 'self' parameter has been constructed, and you can use its attributes and methods (as far as nothing depends of __init__). By example, you can use: self.B_meth() >2. B is not instantiated when A is, > therefore B's init is not run. No. The object is already constructed; __init__ is an initializer, not a constructor. See above. >3. If A can't find B_meth in it's own namespace, > it looks in B's namespace. Yes. And if not found there, in its parent and so on. See section 9.5.1 in the Python tutorial. >4. If one attempts to run B's init in A's init, > using self.__init__(), one is in for a long wait...:) Yes... >5. B's init in A's init must be qualified to prevent #4 Yes, and to specify *which* init you want to call, in case of multiple inheritance. >6. The proper terminology is: > 'A inherits B's methods and attributes' Yes. Maybe a purist would object something but it's ok... >7. An init in B is of limited usefulness. Why? B.__init__ should do whatever is needed to properly initialize class B. Usually you inherit to specialize behaviour. In BaseHTTPServer.py you have class HTTPServer which inherits from TCPServer which inherits from BaseServer; each one has its own responsabilities; altough you could have written all that stuff in just one class, that would be difficult to reuse or modify. >8. If all one needs is to 'declare and inialize' > variables common to a number of classes, one > really doesn't need a base class, > just a module containing the 'constants'. > But if there are methods which are semi-common > to all sub-classes, and can be overidden or > extended to do the job, then it makes sense to > use inheritance. Mmm, no. In an OO environment, classes are used to build a *model* of something, you *design* using classes and inheritance and hierarchies and composition and delegation... Look for any OO design introduction. >9. Inheriting variables (only), then (always) > over riding their values in the sub-classes > doesn't save memory. I don't understand this. You can save some memory if you declare default values for attributes inside the class (*not* assigning them to self), As far as they are never changed, they are shared by all instances. Is this what you mean? class Example: x = 1 class Example2(Example): x = 2 a = Example2() print a.x # prints 2 b = Example2() print b.x # prints 2; both refer to the same shared attribute a.x = 3 # now 'a' contains its own instance attribute print a.x # prints 3 Gabriel Genellina Softlab SRL From michele.simionato at poste.it Tue Jan 13 09:28:16 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 Jan 2004 06:28:16 -0800 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <877jzwg1v2.fsf@pobox.com> Message-ID: <95aa1afa.0401130628.7992e9e1@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<877jzwg1v2.fsf at pobox.com>.. > Eiffel: Design by contract. The book to read is Meyer's "Object- > Oriented Software Construction". Full of interesting stuff, if you can > stand his self-importance ;-) I couldn't! From alf at calvin.fayauffre.org Tue Jan 6 02:27:47 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Tue, 6 Jan 2004 07:27:47 +0000 (UTC) Subject: UML tools for python References: <13dc97b8.0312301543.39192aa2@posting.google.com> <13dc97b8.0401051848.11205ed4@posting.google.com> Message-ID: Le 06-01-2004, Andy Bulka a ?crit?: > I *have* reported numerous problems with pyreverse to your mailing > list. Why do you say I haven't? Specifically: > > Jun 2003 DOCTYPE XMI directive and MSXML3 parser > Feb 2003 Running the latest version locks up when no -d option > Feb 2003 Pyreverse 0.4.2 requires logilab.common and > optik.OptionParser ? > Dec 2002 Fwd: [Gentleware #12069] Poseidon - version 1.5 XMI import > prob. > > and many more before that. And I appreciate you guys responding - > great. Whoops. I realize I had not checked the mailing lists archives correctly. I apologize. > Anyway - ideally I was hoping for a robust discussion by senior Python > people on what they may be using with regards to UML and what their > feelings are about the situation. UML is very important yet there is > no GUI driven two-way tool for python programmers. Surely serious, > larger scale, software development in Python would want to be using > UML as part of the process? Well, not necessarily. Of course I can only speek for myself (and a bit for my company), but my prefered UML modelling tool is a whiteboard, used in conjunction with Agile Modelling practices (http://www.agilemodeling.com). And even then I tend to model lightly, because the projects on which I work are generally fast moving targets, which means that heavy up front modelling often results in waisted effort. We found that on demand modelling sessions on the whiteboard to answer specific questions provided the best results. The code we produce ends up being refactored very often as requirements change anyway, and maintaining up to date models costs us too much time. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From jarausch at skynet.be Tue Jan 27 12:44:09 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 27 Jan 2004 18:44:09 +0100 Subject: How does compare work? In-Reply-To: References: <40158680$0$7044$ba620e4c@news.skynet.be> Message-ID: <4016A368.9050806@skynet.be> Terry Reedy wrote: > "Helmut Jarausch" wrote in message > news:40158680$0$7044$ba620e4c at news.skynet.be... > >>what does Python do if two objects aren't comparable (to my opinion) > > > Sorry, Python does what it does, which is generally to compare any two > objects unless explicitly disabled as with complex numbers or in > user-written method of user class. > > >>If I've understood "Python in a Nutschell" correctly it should raise an >>exception but it doesn't do for me. > > > Perhaps you could quote the line that mislead you, and someone could > explain, or suggest a change to the author. > First let me say that IMHO this is a big misdesign of Python. I've come to Python from Perl since many posts convinced me that Python is safer - and mostly it is. But silently(!) comparing apples with pears is evil. E.g. the example I came across this was thresh=raw_input('enter threshold') ... level=2 ... if level > thresh : which failed miserably. By the way, Perl does convert the string to an integer silenty and, as most of the time, these Perl conversions are just what one wants, so here. Nevertheless, I'd prefer an exception in this case since automatic conversions can never be right in all circumstances. So this is a case where Python is a very dangerous language! For the quotation In my 'Python in a Nutshell' by Alex Martelli (a tremendously good book), 1st edition on page 91 (Special Methods) it reads __cmp__ ...... ............... When __cmp__ is also absent, order comparisons (<,<=,>,>=) raise exceptions. Equality comparisons (==,!=), in this case, become identity checks: x==y evaluates id(x)==id(y) (i.e., x is y) end of quotation. I wish this were true for the current Python implementation. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From amk at amk.ca Fri Jan 30 21:12:17 2004 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 30 Jan 2004 20:12:17 -0600 Subject: RESTful Python References: Message-ID: On Fri, 30 Jan 2004 13:39:02 +0800, SimonW wrote: > I want to be able to address sections of an XML document using an URI, > but I am not sure how to implement this. I've seen this done in Python > before, however I cannot find the site again, and cannot recall the > correct google incantations to re-discover it. The usual way would be to use a fragment identifier, so that the client can find the right element, e.g. http://example.com/foo.xml#id45 means downloading foo.xml and looking for the element with an id="id45" attribute. But the fragment identifier isn't sent to the HTTP server, so you couldn't do a DEL or PUT to replace just that fragment; I don't know if that's what you want. > Can anyone point me to some REST style implementations in Python? Someone's already pointed you to Dave Kuhlman's article on REST and Quixote, which is a good start. --amk From llothar at web.de Fri Jan 30 21:58:46 2004 From: llothar at web.de (Lothar Scholz) Date: 30 Jan 2004 18:58:46 -0800 Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> <87k739xcaq.fsf@andreasen.org> Message-ID: <6ee58e07.0401301858.2d3cc1b5@posting.google.com> "Erwin S. Andreasen" wrote in message news:<87k739xcaq.fsf at andreasen.org>... > llothar at web.de (Lothar Scholz) writes: > > > is there something like "JpGraph" for python ? > > For those who don't know this PHP library: It is a high level > > drawing library that generates gif files with all kind of charts. > > I've used gdchart previously but these days I use ChartDirector which, > although being a commercial program ($99), was well-worth the money > for me. > > It produces high-quality charts, is very flexible (e.g. you can > overlay different chart types, add custom symbols, produce HTML image > maps) and has excellent bindings for Python and many languages. > > Also, I've found the support to be unusually friendly, accurate and > fast. The documentation is good enough so you won't need it much (and > customised to each language too, with something like 100 examples). > > Some samples: > http://www.advsofteng.com/gallery.html Thanks. I would buy it but there are two problems: First it is US$ 499 when i use it in a program and then there is only a precompiled library for LINUX. It's okay to get a precompiled library for windows. But my experiences with binary Linux API changes are really bad, on for this i can only accept source code, at least when i pay US$ 499. And the footprint of the library seems also to be a little bit high with 3 MB. From brian at bluecoat93.org Fri Jan 16 12:31:25 2004 From: brian at bluecoat93.org (Brian Landers) Date: 16 Jan 2004 09:31:25 -0800 Subject: [ANNOUNCE] PyGoogle has a new maintainer and home Message-ID: I have recently taken over the maintenance and development of PyGoogle, a native Python module for accessing the Google Web APIs. Currently, it allows you to search Google, retrieve a page from the cache, and ask Google for spelling corrections. This module was originally developed by Mark Pilgrim (http://www.diveintomark.org) and now lives at SourceForge. Please take a look if you are interested in developing Google Web API applications in Python. http://pygoogle.sourceforge.net Thanks, Brian From sax at csmisc72.cs.chalmers.se Fri Jan 30 11:36:15 2004 From: sax at csmisc72.cs.chalmers.se (Stefan Axelsson) Date: 30 Jan 2004 16:36:15 GMT Subject: Simple list question References: Message-ID: In article , Dave Brueck wrote: > How about: > >>>> nod = ['1','+','2'] >>>> for i in range(len(nod)): > ... try: > ... nod[i] = float(nod[i]) > ... except ValueError: pass > ... >>>> nod > [1.0, '+', 2.0] Perhaps minor style issue; I'd use 'map' (even though Guido isn't crazy about it), or perhaps a list comprehension. Like so: >>> def tofloat(x): ... try: ... return float(x) ... except ValueError: return x ... >>> map(tofloat, nod) [1.0, '+', 2.0] Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From newsgroups at jhrothjr.com Thu Jan 8 06:42:11 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Jan 2004 06:42:11 -0500 Subject: Why " ".some_string is often used ? References: Message-ID: "St?phane Ninin" wrote in message news:Xns94698A5566736stefninnospamyahoofr at 213.228.0.4... > > Hi all, > > This is not the first time I see this way of coding in Python and > I wonder why this is coded this way: > > Howto on PyXML > (http://pyxml.sourceforge.net/topics/howto/node14.html) > shows it on this function, but I saw that in many other pieces of code: > > def normalize_whitespace(text): > "Remove redundant whitespace from a string" > return ' '.join(text.split()) > > Is there a reason to do instead of just returning join(text.split()) ? > why concatenate " " to the string and not just returning the string instead ? This particular idiom replaces sequences of multiple whitespace charaters with a single blank. And I agree, it's not entirely obvious why it's a string method rather than a list method, since it operates on a list, not on a string. The only explanation that makes sense is that, as a list method, it would fail if the list contained something other than a string. That's still not very friendly, though. John Roth > > Thanks in advance for your explanations. > > Regards, > > -- > Stephane Ninin > > > From pierren at mac.com Wed Jan 28 07:02:17 2004 From: pierren at mac.com (Pierre N) Date: Wed, 28 Jan 2004 12:02:17 +0000 Subject: package similar to XML::Simple In-Reply-To: References: Message-ID: <1075291336.4813.42.camel@Pismo> I'm using pyRXP, and it's great. It's using one tuple, not dictionnaries. Very very fast. By the way I'm just starting using this package, anybody met any problems with pyRXP? -- Pierre On Wed, 2004-01-28 at 09:53, Paulo Pinto wrote: > Hi, > > > does anyone know of a Python package that > is able to load XML like the XML::Simple > Perl package does? > > For those that don't know it, this package > maps the XML file to a dictionary. > > Of course I can build such a package myself > but it would be better if it already exists :) > > -- > Paulo Pinto From usenet at mail-2-me.com Sat Jan 31 17:56:25 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: Sat, 31 Jan 2004 23:56:25 +0100 Subject: Running External Programs from Within Python In-Reply-To: References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: RayS wrote: > Hi Dirk, > >> That is very easy: popen() >> Check the FAQ and documentation again for popen. > > > That reminds me, I was asked if you can open a bi-directional pipe to > control an external console program on Windows. A guy has compiled > FORTRAN (~4,000 lines of 1980's spaghetti) and wants to add a modern GUI > and a front end method to check data. > Can you both send commands to, and read STDOUT from, a remote console app? > > Ray > > I'm not sure if I got the point, but, for example, with popen I can ping from the console a computer and read the result. But sending commands to a remote console is a problem which troubles myself in another context (I asked here yesterday). Dirk From newsgroups at jhrothjr.com Wed Jan 7 11:24:50 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 7 Jan 2004 11:24:50 -0500 Subject: Pre-PEP: Dynamically evaluating default function arguments References: <338366A6D2E2CA4C9DAEAE652E12A1DE010633FF@au3010avexu1.global.avaya.com> Message-ID: "Gerrit Holl" wrote in message news:mailman.179.1073485918.12720.python-list at python.org... > Delaney, Timothy C (Timothy) wrote: > > IMO it's not a waste of time for this PEP to be written. Unfortunately, not many people are willing to formally document something that they would like to see when the guaranteed result is that it will be rejected. > > PEP 313? It hasn't been rejected yet. Pep CCCIXXX is needed to set the state of the Abacus objects correctly. The Comp Center needs this in case of a casastrophic systems failure. Pep 666, on the other hand, was submitted explicitly for rejection. Maybe this one should be 668 (the neighbor of the beast?) John Roth > > :) > > Gerrit. From whiteywidow at yahoo.com Wed Jan 21 12:24:06 2004 From: whiteywidow at yahoo.com (rt lange) Date: Wed, 21 Jan 2004 17:24:06 GMT Subject: Jython and SciTE Message-ID: I'm trying to get SciTE to run and compile my jython scripts. This is what I have in my python.properties file: command.name.1.*.py=Go Jython command.1.*.py=jython $(FileNameExt) command.1.subsystem.*.py=1 command.name.2.*.py=Jython -> jar command.2.*.py=jythonc --core --jar $(FileName).jar $(FileNameExt) command.2.subsystem.*.py=1 I keep getting as output: >jython DiceRoll.py >The system cannot find the file specified. >jythonc --core --jar DiceRoll.jar DiceRoll.py >The system cannot find the file specified. It works fine from the command line (PATH is set correctly.) From yan at NsOeSiPnAeMr.com Tue Jan 27 11:27:27 2004 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Tue, 27 Jan 2004 11:27:27 -0500 Subject: phpwiki and mySQL Message-ID: I've got a mySQL error that I hope someone can decipher for me. (LOCK TABLES page WRITE,version WRITE,link WRITE,recent WRITE,nonempty WRITE [nativecode=1044 ** Access denied for user: 'yan at localhost' to database 'phpwiki']) The app is phpwiki (phpwiki.sf.net) and AFAICT my userid, login, etc. are correct. I know very little about mySQL. Does the above mean I don't have write permission to the database? Or is this something best taken to the mySQL list? TIA, --Kamus From aldo123 at onet.pl Thu Jan 8 04:15:59 2004 From: aldo123 at onet.pl (mic) Date: Thu, 8 Jan 2004 10:15:59 +0100 Subject: win32: internet explorer automation problem Message-ID: I'm currently trying to write an MSIE automation software and have run into such problem - have no idea how to take control of external popup windows - I use WebBrowser COM object and am able to catch the NewWindow2 event, but don't know how to change 'focus' to other than main explorer window. I tried to use winguiauto package and am able to get the HWND of the 'Internet Explorer Server' control located in that new window, but I don't know whether it is possible to force it to be my new COM object. Regards, Michal Zylinski From forsale2tor at yahoo.com Tue Jan 13 12:36:57 2004 From: forsale2tor at yahoo.com (Victor) Date: 13 Jan 2004 09:36:57 -0800 Subject: Visual Jython idea brainstorming welcome Message-ID: <1db780c8.0401130936.88d1da4@posting.google.com> Hi all, I had this idea two minutes ago. I am proprosing an idea to build an IDE called "Visual Jython" with Eclipse technology. This IDE is targeted towards building enterprise client applications running any Java platform mostly non-web based clients. My background is diversed in UNIX variants, Java and Python. Here are something off the top of my head. 1. Basically from UI perspective, it will be like as name implied "Visual Studio" like. 2. plug in architecture This IDE should define or use a componenent architecture to plug & play component written in Java confining to a Jython Plug in API. For instance, we can develop plug in for ODBC, Oracle, DB2, Informix, MQ, SAP etc for enterprise uses. 3. gluing languag--Jython maybe we need funding to support Jython for this matter to make it commerical quality. 4. .NET integration? Should this IDE generate code that can run on top of .NET to attract more VB/.Net programmers into this field? Welcome comments on features this IDE should have. cheers, Victor From fumanchu at amor.org Tue Jan 13 13:02:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Jan 2004 10:02:51 -0800 Subject: Design Question Message-ID: > I have a question which is more about OO design than Python per se. > I've noticed that a number of posters to this list have very good > suggestions for SE issues, so I'm hoping that someone will be able to > give me some guidance. > > My question is about how to architect a class hierarchy where some > methods are nearly identical between a superclass and a subclass, but > differ slightly. For example: > > class Sup(object): > def __init__(self): > self.specialFlag = False > def aMeth(self): > > > > > class Sub(Sup): > def __init__(self): > self.specialFlag = True > > In this example, the method aMeth just checks for specialFlag, and if > it's True, does the special stuff required. Since classes in Python are "first class objects" just like instances, I often modify arrangements like your example to: class Sup(object): specialFlag = False def aMeth(self): doStuff() if self.specialFlag: doSpecialThing() doMoreStuff() class Sub(Sup): specialFlag = True If you never assign self.specialFlag, it remains a "class attribute" (that is, since specialFlag is never bound to the instance, it continues to be looked up in the class dict). Once you've done *that*, you then see further options. In my designs, I tend to eliminate such flags, replacing them with the actual behavior which the flag references: class Sup(object): specialThing = [] def aMeth(self): doStuff() for eachItem in self.specialThing: doMoreStuff(eachItem) class Sub(Sup): specialThing = [1, 2, 3] ---or--- class Sup(object): specialThing = lambda x: None def __init__(self): self.x = 0 self.y = 0 def aMeth(self): doStuff() self.y = self.specialThing(self.x) doMoreStuff() class Sub(Sup): specialThing = lambda x: x[4] + 3 Which one you choose will be dependent upon your design. Robert Brewer MIS Amor Ministries fumanchu at amor.org From csgcsg39 at hotmail.com Thu Jan 15 06:06:45 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Thu, 15 Jan 2004 11:06:45 -0000 Subject: urllib problem Message-ID: Dear All, I'm having problems using the urllib module and was wondering if anyone could suggest a solution. The only thing I can thing of is that I'm using at university and my uni uses a compulsory proxy. I'm using the python 2.3.3 and have tried both windows and Linux environments. I've tried different urls as well. Here's the code and error message I get Thanks Colin import urllib usock=urllib.urlopen('http://slashdot.org/slashdot.rdf') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/urllib.py", line 76, in urlopen return opener.open(url) File "/usr/lib/python2.3/urllib.py", line 181, in open return getattr(self, name)(url) File "/usr/lib/python2.3/urllib.py", line 297, in open_http h.endheaders() File "/usr/lib/python2.3/httplib.py", line 712, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 597, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 564, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 548, in connect raise socket.error, msg IOError: [Errno socket error] (113, 'No route to host') From mk at net.mail.penguinista Wed Jan 14 18:13:07 2004 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Thu, 15 Jan 2004 00:13:07 +0100 Subject: [OT] AS/400 References: Message-ID: <4005cd03@news.mt.net.mk> > (will not mention that it works on AS/400, the best > minicomputer(!) ever made). Why is it the best minicomputer ever made? I really want to know! -- ?????? (jabberID:damjan at bagra.net.mk) To boldly go where I surely don't belong. From cookedm+news at physics.mcmaster.ca Thu Jan 22 21:59:45 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 22 Jan 2004 21:59:45 -0500 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: At some point, Erik Max Francis wrote: > Gary Robinson wrote: >> If there anywhere else I should be expressing my opinion on this, let >> me >> know. > > Seems quite reasonable to me. The only issue I'd take with it is the > choice of Min and Max for the names of the singletons; they're a little > too close to the functions min and max, which obviously they're both > likely to be used with. I would suggest something a little more verbose > such as Minimum and Maximum, or if you want to get silly, Infimum and > Supremum. Or, expressing the idea that they're the ends of a number line: PosInf, NegInf PosInfinity, NegInfinity PositiveInfinity, NegativeInfinity If IEEE floating point was done correctly everywhere, I'd say make them the corresponding floating-point constants (Inf+ and Inf-). Or, FreakingHuge, FreakingHugeTheOtherWay -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From alessandro at sephiroth.it Wed Jan 14 20:17:11 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Thu, 15 Jan 2004 01:17:11 GMT Subject: dde References: <8EFMb.102403$_P.3808599@news4.tin.it> Message-ID: "Tim Roberts" ha scritto nel messaggio news:f3s900dhej5v8pd7dnurrpo0gl7i7v4d2k at 4ax.com... > "Alessandro Crugnola *sephiroth*" wrote: > > > >Hi all > >I would like to send dde messages to an application, but i don't know which messages it supports. > >Is possible to do in some way or I absolutely need the api specifications? > > You need specs and/or examples. One of the biggest shortcomings of DDE is > that it is there is no way to ask an application what operations it > supports. Worse, there is no particular standard for the format of DDE > messages, so even if you know the function you want to perform, you can't > guess what the message and its parameters should be. I imagine.. thanks > > What DDE app are you trying to control? macromedia Flash > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From reply.in.the.newsgroup at my.address.is.invalid Thu Jan 8 15:51:56 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 08 Jan 2004 21:51:56 +0100 Subject: books References: <3FFDC029.AB0A4097@unet.univie.ac.at> Message-ID: Thomas Mang: >Which books would you recommend to buy? > >I am both looking for an introduction into the language, as well as >complete guides. http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks I've used the online Python tutorial (http://www.python.org/doc/current/tut/tut.html), Programming Python (http://www.amazon.com/exec/obidos/tg/detail/-/0596000855/ref=pd_bxgy_text_1/002-2113420-5243224?v=glance&s=books&st=*) and Python in a Nutshell (http://safari.oreilly.com/0596001886) to get started myself. -- Ren? Pijlman From tim.one at comcast.net Sun Jan 4 16:13:29 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 4 Jan 2004 16:13:29 -0500 Subject: Is Python Mac Centric??? In-Reply-To: Message-ID: [Tim] >> Mark likes having a release schedule independent of Python's, and >> Guido hates Mark's coding style. Both act against folding the >> Windows extensions into the core. [Peter ?strand] > So, theoretically, if another person stepped forward that re-indented > the source code and was happy about following the Python release > schedule, then the extensions could be added? Not really. It would have to be someone who could make a credible case that they're going to continue supporting this spinoff of Mark's work, year after year. Guido has grown (with good reason) wary of accepting code into the core unless it comes with a credible plan for supporting it after the initial contributor loses interest (gets a real job , dies, etc). > I think it's a shame that such minor issues as coding style and > release schedules should block an important thing like this. To the contrary, it's ongoing maintenance that consumes the most time in any project, and those "minor issues" are major from that perspective. Python-style docs and test suites would also need to be created. From premshree_python at yahoo.co.in Sun Jan 25 07:53:23 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sun, 25 Jan 2004 12:53:23 +0000 (GMT) Subject: makeExe.py Message-ID: <20040125125323.65486.qmail@web8307.mail.in.yahoo.com> Wrote a simple Python script that makes life a wee bit easier when using py2exe: Also available at http://premshree.resource-locator.com/python/makeExe.py """ makeExe.py - Simple Python script to automate the creation of Python executables using py2exe. (c) 2004 Premshree Pillai (24/01/04) http://www.qiksearch.com/ """ ## Run this file from Python root dir import sys import re fileName = raw_input("Enter file name (rel or abs path, eg., python/file.py): ") package = re.split(":",fileName) package = re.split("/",package[len(package) - 1]) package = re.split(".py",package[len(package) - 1]) package = package[0] fp = open("setup.py","w") temp = """from distutils.core import setup import py2exe setup(name = "%s", scripts = ["%s"], )""" % (package,fileName) fp.write(temp) fp.close() sys.argv.append("py2exe") execfile("setup.py") fp = open("setup.py","w") temp = "" fp.write(temp) fp.close() print "\n", "Executable created!" print "Press to exit..." if(raw_input()): exit ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From clifford.wells at comcast.net Sat Jan 24 17:40:04 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Sat, 24 Jan 2004 14:40:04 -0800 Subject: [OPINION] - does language really matter if they all do the same thing? In-Reply-To: <20040123183127.GA35281@mail.hitmedia.com> References: <20040123183127.GA35281@mail.hitmedia.com> Message-ID: <1074984003.13581.1036.camel@devilbox.homelinux.net> On Fri, 2004-01-23 at 10:31, Python Baby wrote: > Are programming languages like spoken languages, in the sense > that they all say the same things, just using different words? As others have said, languages all constrain how you think in one way or another, even "natural" languages. Programming languages are even worse, since even "general purpose" programming languages are designed to fit a certain criteria that makes them more expressive in one way and less in another. > Can Ruby do something (important) that Python can't? > Can Python do something (important) that PHP can't? > Can PHP do something (important) that Ruby or Python can't? It's interesting that you mention this as I'm a long-time Python programmer who just got his first taste of PHP (required for a job). If it's a simple matter of choosing between Python and PHP, the things that have struck me so far are as follows: 1. PHP is a much "noisier" language than Python. Braces, semicolons, variable declarations, $ notation on variables, arrays declared as if they are a function (array()) rather than direct language syntax, etc. This is mostly cosmetic and doesn't detract from the usefulness of the language, and for a language targeted at the web, there is a definite advantage to using braces as block-delimiters, if not the other "noise". 2. PHP and Python are both very dynamic, although they do it in somewhat different ways. As an example, in Python, to get a reference (pointer) to a function, you'd just refer to the function without parentheses. In PHP you'd probably use a string with the function name and call it. I prefer Python's method of string interpolation over PHP's. This sounds like a minor nit, but if you're dynamically generating text, then you get this minor nit a lot. PHP's method isn't bad if the strings are inline, but if you are reading text from one file and substituting values into it from another, Python's method is much simpler. 3. PHP's object-model appears remarkably similar to Python's on the surface. This similarity is only skin-deep, however. It is openly acknowledged that OO won't fully be supported until PHP5 is released, but it's possible to use it in 4 (as I have been). As such, I'm reluctant to criticize it too much as it really isn't bad, but it appears incomplete (and some features are outright broken at the moment). Not to mention it's pretty damn slow. Hopefully this will be taken care of in PHP5. Most of the problems I've had with PHP have not been with the language itself (which really doesn't seem that bad), but rather with the implementation (i.e. the interpreter). Poor error reporting, bugs, general slowness, immature libraries, etc. Obviously PHP has some strengths in the web arena (ability to arbitrarily intermix PHP and HTML being the most noticable, although getting carried away with this seems like a bad idea). > Are they all just the same, and it's just a matter of taste? It depends. If you're comparing PHP and Python, then the answer is "yes, to a great extent". If you're comparing Python and a language like C, then the answer is a definite no. You might be able to get similar results, but how you get there will be completely different. > Should I stick with PHP for the same reason that pop singers > worldwide sing in English for maximum compatibility with the medium? Only you can decide that. Try Python and see if it "fits your brain" as many here like to describe it. Just be sure to give it a fair shake as any new tool is bound to be occasionally frustrating (as has been the case for me with PHP). > Though PHP wasn't design for OOP should I use it that way anyway? If you aren't familiar with OOP, then no. There are far too many bugs and problems with the current OO implementation in PHP. You'll pull your hair out trying to get things that *should* work to do as you expect. If you're familiar with OOP and think you can work around PHP's shortcomings in this area, then sure. I'm fairly happy with the results I've gotten, although it took twice as long as it would have taken were I to have done it in Python (at least some of this is due to my being new to PHP, but more of it was due to the lack of adequate error reporting and obscure bugs and misfeatures). Regards, Cliff -- I have seen too much, wipe away my eyes -Bauhaus From sross at connectmail.carleton.ca Mon Jan 5 20:04:25 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 5 Jan 2004 20:04:25 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> <5sFJb.20923$Vl6.3818930@news20.bellglobal.com> Message-ID: "Samuel Walters" wrote in message news:pan.2004.01.05.17.54.22.894833 at yahoo.com... > "If a and b are integers such that b != 0, then there exist unique > integers r and q such that a = q*b + r and 0 <= r < abs(b)" > > For non-mathematical spectators, the divmod() function is defined so that > q, r = divmod(a, b) by the definition above. Right. The only thing that was still mildly interesting to me was why does divmod() return a negative remainder? >>> a = 5 >>> b = -10 >>> q,r = divmod(a,b) >>> q -1 >>> r -5 If divmod() where defined based on the definition above, then divmod(5, -10) should return (0, 5). Well ... that's too strong. The above is a theorem - it doesn't say remainders have to be nonnegative, it only says that there exist yada yada yada ... whatever, I'm not that interested. From none at none.com Tue Jan 20 11:19:24 2004 From: none at none.com (Derek) Date: Tue, 20 Jan 2004 11:19:24 -0500 Subject: I come not to bury C++, but to praise it... References: <20040114153516.GA16224@intarweb.us> Message-ID: "Oren Tirosh" wrote: > A traceback is also much less nasty than deciphering a > 1000-character long compiler error message reported in > code that uses a heavily templated library. Absolutely correct. But remember that ugly template-related compiler error messages are a reflection of current compiler technology, not a fundamental limitation of C++. I suspect future compilers will make debugging templates much easier. From rainerd at eldwood.com Thu Jan 29 00:04:09 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 29 Jan 2004 05:04:09 GMT Subject: Rookie question about data types (hashtables) References: Message-ID: Steve D. Perkins wrote: > What I would LIKE to have is a hashtable-like structure that lets > me retrieve multiple values based on a partial key. Sounds like a sorted list would work best. A binary search (see the bisect module) lets find all matches in O(log n) time. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From M at a.k Fri Jan 2 15:17:41 2004 From: M at a.k (Midas) Date: Fri, 02 Jan 2004 20:17:41 GMT Subject: Passing to a function -- object and method names (or references) References: <3ff595e2.67831682@news.iprimus.ca> Message-ID: <3ff5d14c.83044196@news.iprimus.ca> Peter Otten wrote: >You can access attributes with the getattr() builtin. > >carGas = getattr(car, "gas") > >You can refer to a method either directly > >fun = car.drive >fun(123) > >or via getattr(): > >fun = getattr(car, "drive") >fun(321) > >I've modified your example to demonstrate this. Thank you very much, Peter! It works nicely! Midas From no at spam.invalid Thu Jan 8 17:00:07 2004 From: no at spam.invalid (Russell E. Owen) Date: Thu, 08 Jan 2004 14:00:07 -0800 Subject: Tkinter button command curiousity References: Message-ID: In article , mksql at yahoo.com wrote: >New to Tkinter. Initially, I had some code that was executing button commands >at >creation, rather than waiting for user action. Some research here gave me a >solution, but I am not sure why the extra step is necessary. > >This causes the "graph" function to execute when the button is created: > Button(root, text='OK', command=graph(canvas))) > >However, this waits until the button is pressed (the desired behavior): > def doit(): > graph(canvas) > Button(root, text='OK', command=doit)) > > >Functionally, what is the difference? Why do I need to create a function, to >call a function, simply to make a button command wait until pressed? Is there >a >better method? This is a standard issue with callback functions. Suppose you have a trivial function foo: def foo(arg1, arg2): print "foo(%r, %r)" % (arg1, arg2) To use foo as a callback function you need to pass it *AS* a function: anobj(callback=foo) and that callback had better include the necessary args. If you try to specify args when specifying the callback, you end up passing the RESULT of the function (the mistake): anobj(callback=foo("bar", "baz")) foo gets called just once, when creating an obj, and callback gets set to None (the result of calling foo with args "bar" and "baz"). Later when anobj wants to call the callback, it has nothing to call! There are various solutions. The one you chose is excellent. Others include: -Use lambda to avoid creating a named function, but I find this much less readable. - Use a "currying" class; this takes an existing function and pre-defined arguments and returns a new function that you use as your callback. A good example of such a class is: . It's a nice thing to have around if you do a lot of callbacks, but otherwise I find your solution the most readable. - If your widget is a class, you may be able to pass your data as class instances. This works if there is only one obvious canvas to graph. For example: class mywdg(Tkinter.Frame): def __init__(self, master, etc.) Tkinter.Frame.__init__(self, master) self.canvas = Tkinter.Canvas(self,...) self.button = Tkinter.Button(self, command=self.graph) ... def graph(self): # do stuff to self.canvas - As a more sophisticated variant, if you several canvases to graph, and want one button for each, you could make the canvases into objects (similar to the example above) and pass the right one to the button, e.g.: for cnvsobj in listofobj: abutton = Tkinter.Button(self, command= cnvsobj.graph) - Also note that a very few Tkinter functions (such as after) allow you to specify a function and additional arguments. -- Russell From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jan 9 16:08:31 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 09 Jan 2004 22:08:31 +0100 Subject: Python is far from a top performer according to benchmark test... In-Reply-To: References: Message-ID: <3fff184f$0$327$e4fe514c@news.xs4all.nl> Carl wrote: > "Nine Language Performance Round-up: Benchmarking Math & File I/O" > http://www.osnews.com/story.php?news_id=5602 This benchmark is beaten to pulp in the discussion about it on slashdot. It's a real stupid benchmark (as most benchmarks are) IMNSHO. I mean, using python's arbitrary precision long object for 'math' and comparing it to the other languages' long /machine types/... come on. And thats just one of the flaws. --Irmen From Kyler at Lairds.com Wed Jan 21 12:16:54 2004 From: Kyler at Lairds.com (Kyler Laird) Date: Wed, 21 Jan 2004 12:16:54 -0500 Subject: calling Pyrex results from C In-Reply-To: <400EA799.7080706@prescod.net> References: <20040120172733.GA7666@titan.progiciels-bpi.ca> <20040120234855.GV22782@jowls> <400EA799.7080706@prescod.net> Message-ID: <20040121171654.GC22782@jowls> On Wed, Jan 21, 2004 at 08:23:53AM -0800, Paul Prescod wrote: > First, I'd suggest that "integer" is a perfectly good type in both C and > Pyrex so you shouldn't pass around Python objects representing integers. That would be my inclination too if I just had an integer to pass. Are you suggesting that I should pass tuples of integers as pointers to (an array of) integers? > Second, you aren't checking the return codes of your functions and C has > no exception handling, tracebacks, etc. image_size is probably returning > 0 because it is probably throwing an exception because you are asking > for the size attribute of the Image class rather than the image_PIL object. I'm trying to keep my examples simple so that it's easy to pick out the mistakes. > Once I fix the Image/Image_PIL error your code runs okay on my computer. Grrr...yup, that does it. Dumb mistake - the result of pulling code out of various places and gluing it together without checks. > But you are walking on thin ice and may just be lucky. It is simply > not possible to work with strings generated at runtime in C without > worrying about memory allocation sometime. In this case I have the > strong suspicion that the string() function is either creating and > destroying a string object and then returning you a pointer to the dead > object's internal memory buffer (bad news!) or simply losing a reference > to the (still living) string object: still not a good thing. Eyeballing > the code I believe the former is the issue. You could check for sure by > adding some printf's to the generated code to look at __pyx_v_s->ob_refcnt. I feared this was a problem. I'll play with it. > Why not let Python do the "print" rather than using "printf". Printing is not always my final goal. Thank you. --kyler From eurleif at ecritters.biz Thu Jan 22 19:02:15 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 23 Jan 2004 00:02:15 GMT Subject: strtotime? In-Reply-To: <40105afb$0$319$e4fe514c@news.xs4all.nl> References: <40105afb$0$319$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: >> PHP has a very nice strtotime function (http://php.net/strtotime) >> which converts a date/time in virtually any format into a timestamp. >> Does Python have a similar function? > > I guess you're looking for: time.strptime Thanks, but no. PHP's strtotime() function magically guesses the format on its own, time.strptime() just uses a fixed format. From mwilson at the-wire.com Thu Jan 22 13:05:40 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 22 Jan 2004 13:05:40 -0500 Subject: Need help with Python class idioms References: <200401212101.33605.james@logicalprogression.net> <20040121210142.GA27469@mail.theserver.ath.cx> Message-ID: <0DBEAls/KrhZ089yn@the-wire.com> In article , James Henderson wrote: >On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote: >> # P.S. Since you're asking about idiom, it would be more Pythonic to write: >> # >> # if self.mandatoryVar1 is None: >> # >> # using the identity test "is" rather than equality test "==", since there >> is # only one None. >> >> I'd write >> >> if not self.mandatoryVar1: >> >> but the first method works, too. > >Are you sure an empty sequence or zero aren't valid values? J. It can get weird if you have to allow your caller to optionally specify the value None: class _MissingParam: "An object that no-one else will have a valid use for." ... def a_func (opt1=_MissingParam): if opt1 is _MissingParam: opt1 = default_calculation () # for instance ... Regards. Mel. From goodger at python.org Mon Jan 5 09:40:36 2004 From: goodger at python.org (David Goodger) Date: Mon, 05 Jan 2004 09:40:36 -0500 Subject: prePEP "Decimal data type" v0.2 In-Reply-To: References: Message-ID: <3FF97764.9060702@python.org> Batista, Facundo wrote: > By the way, which is the extension for a reST document? (I used .txt). .txt is fine. Full details in question 2.4 of the FAQ: http://docutils.sourceforge.net/FAQ.html -- David Goodger From skip at pobox.com Sun Jan 25 13:13:15 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 25 Jan 2004 12:13:15 -0600 Subject: Text Animation In-Reply-To: <7b454334.0401242038.11404dac@posting.google.com> References: <7b454334.0401242038.11404dac@posting.google.com> Message-ID: <16404.1851.997662.600203@montanaro.dyndns.org> faizan> Any ideas how these effects can be achieved? You can start here: http://www.musi-cal.com/~skip/python/progress.py That module provides a couple simple progress counters. Skip From guido at python.org Mon Jan 19 12:50:31 2004 From: guido at python.org (Guido van Rossum) Date: Mon, 19 Jan 2004 09:50:31 -0800 Subject: PyCon Reminder: Early bird reg deadline 2/1 Message-ID: <200401191750.i0JHoVm23314@c-24-5-183-134.client.comcast.net> Info ---- This is a reminder that the deadline for early bird registration for PyCon DC 2004 is February 1, 2004. Early bird registration is $175; after that, it will be $200 through March 17, then $250 at the door. To register, visit: http://www.pycon.org/dc2004/register/ Plug ---- PyCon is the most important conference in the year for me. It brings together the largest group of Python users and developers imaginable. I come to PyCon for many reasons: to meet with other core Python developers face to face; to hear about the exciting things that users from all over the world are doing with Python; to interact in person with Python users of all types, from newbies to veterans of many years; to hear everybody's feedback on where Python is and where they'd like it to go; and perhaps most of all to continue to encourage this wonderful community by my presence, words and actions to grow, reach out to new users of all kinds, and keep listening to each other. I hope everyone who comes to the conference will return from it with a new or renewed feeling of excitement about Python, whether they are developers, sophisticated users, beginners, or even skeptical passers-by. The Python community includes everyone, from grade schoolers just learning about computer science to renowned scientists interested in using the best tools and business people looking for a secret weapon. I'm looking forward to seeing you all at PyCon! Background ---------- PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. We're looking for volunteers to help run PyCon. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ --Guido van Rossum (home page: http://www.python.org/~guido/) From shoot at the.moon Mon Jan 26 14:54:52 2004 From: shoot at the.moon (Steve Horsley) Date: Mon, 26 Jan 2004 19:54:52 +0000 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <64cff82f.0401251143.328388bd@posting.google.com> References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: malcolm wrote: > Why you can't get something for nothing > Jack Schofield Jan 22 2004 > > > "Indeed, the whole progress of commercial computing has been from > expensive hand-written, bug-ridden, company-specific programs to > cheaper but more powerful off-the-shelf packages. From that point of > view, open source is a throwback." That doesn't ring true to me. This sounds more realistic... "Indeed, the whole progress of commercial computing has been from expensive hand-written, bug-ridden, company-specific programs to cheaper but more powerful off-the-shelf packages. From that point of view, open source is the next logical advancement. Steve From mepython at yahoo.com Fri Jan 2 16:34:06 2004 From: mepython at yahoo.com (Samir Patel) Date: Fri, 2 Jan 2004 13:34:06 -0800 (PST) Subject: Simulation library in Python Message-ID: <20040102213406.63152.qmail@web41510.mail.yahoo.com> For last couple of weeks, I was doing lot of research on various simulation libraries. Only one I find in python is http://simpy.sourceforge.net. It is very powerful, but it seems that it does not have any active development. I am sure there are more than that. Where are they? If one wants to create a new simulation program, what are different packages to use: simulation event list - priority queue? simulation model creation (preferable data flow) - dia, Pyut, OGL reports - http://reportlab.com http://docutils.sourceforge.net/ graph - http://navi.picogui.org/svn/misc/trunk/rtgraph/ http://matplotlib.sourceforge.net/ animation - Blender?, VTK, VPython cad - http://pythoncad.sf.net GIS - ? Storage - ZODB Import/Export - ? I am interested in creating a professional level simulation model in Python, so any help regarding this will be very much appriciated. __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From mtk at qm.com Tue Jan 13 21:05:20 2004 From: mtk at qm.com (Totte Karlsson) Date: Tue, 13 Jan 2004 18:05:20 -0800 Subject: Printing to console, no scroll Message-ID: Hi, How can I print to the console without having it scrolling to a new line for each print statement? I want to print a count down in the console, but for each count it scrolls the screen (of course). Is there another way? Here is the simple script for now print "Closing window in :" for second in range(10): time.sleep(1) print `10-second` +" seconds" thanks /totte From ashleylloyd at hotmail.com Wed Jan 7 09:58:41 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Wed, 07 Jan 2004 14:58:41 +0000 Subject: Newbie: Getting Image From Disk into Buffer Message-ID: I have been trying to get an image into an interbase database (see earlier post), and came across a post made on a list some time ago (I ignored it earlier as we use kinterbasDB not gvib, but I thought I'd try using it in kinterbasDB anyway): ________________________________________________________________ I think I can provide some information. I have added a jpg to an interbase table and have successfuly displayed it in ZOPE. First off you may know that Interbase does not store BLOB data directly in a table's blob column. It stores the data elsewhere and then stores a "pointer" to it in the table column. This means that BLOB data MUST be inserted via program code and thus you cannot do the following in a Zope SQL Method: insert into the_table (blob_column) values (blob_data) If you are using the gvibDA you can code an external method to do this: import gvib cn = gvib.connect(...) cr = cn.cursor() cr.execute('insert into the_table (blob_column values (?)', (blob_data,)) cn.commit() cr.close() cn.close() ________________________________________________________________ I apologise for my ignorance (newbie, sorry), but can anyone tell me how it is that you get the image from disk into blob_data? I have tried several ways of opening up the image into a buffer, but it always seems to place into the database a string of either the name of the image on disk ('c:/image.bmp', say), or text such as the following: Once again I apologise for my stupidity (and for making 3 requests today - I am trying to figure them out myself, honest!), but if someone could tell me how I get the image into blob_data (which I assume is a buffer), I'd be very grateful. TIA Ashley _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From mnations at airmail.net Tue Jan 20 13:55:18 2004 From: mnations at airmail.net (Marc) Date: 20 Jan 2004 10:55:18 -0800 Subject: Error with Shelve from a frozen application Message-ID: <4378fa6f.0401201055.384a057d@posting.google.com> Hello all, I have searched and experimented but can't find a way to make this work. I have an application that I froze using py2exe which uses Shelve to store data for me. This is the error I am getting: Traceback (most recent call last): File "", line 14, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "anydbm.pyc", line 62, in ? ImportError: no dbm clone found; tried ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] A couple of places mentioned forcing the compiler to import the anydbm module. I've tried this both from within the main program and from the compiler options. Neither of them worked. Can someone please tell me how to fix this? Thanks ahead of time, Marc From aahz at pythoncraft.com Sat Jan 24 11:51:06 2004 From: aahz at pythoncraft.com (Aahz) Date: 24 Jan 2004 11:51:06 -0500 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <871xpp1i8r.fsf@pobox.com> Message-ID: In article , Serge Orlov wrote: >"Ganesan R" wrote in message news:ou4qulnwy0.fsf at andlx-anamika.cisco.com... >> >> fileinput is not optimized yet, at least I don't remember any mails >> about fileinput in python-devel since python 2.3 was released. I >> know that it is slow. for line in file: does seem to be optimized >> though. The last time I ran the tests python was definitely twice as >> slow (which was before python 2.3 was officially released); now it >> appears to be only about 40% slower. I need to revisit these crude >> benchmarks. > >Since this problem is not IO bound but rather python internals bound, >it makes sense to try psyco. Pysco won't help and might actually make things worse. At this point, Perl's speed advantage should come from two and only two sources: Perl optimizes the snot out of platform I/O (so these speed tests don't apply to a platform Perl hasn't been ported to), and Perl does not use the thread-safe forms of I/O. Python does a fair amount of internal caching to make up for that, and the file object is already written in C. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From ebolonev at punkass.com Tue Jan 6 03:00:34 2004 From: ebolonev at punkass.com (Egor Bolonev) Date: Tue, 6 Jan 2004 18:00:34 +1000 Subject: Downloading files off Interet References: Message-ID: Hello, Blaktyger! You wrote on 5 Jan 2004 23:32:53 -0800: B> I would like to download some mp3 files from a web site. There is to B> much of them and I had the idea of writing a script to do it for me. B> Code: B> import string B> import urllib B> f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") B> fic=open('mp3file.mp3','w') B> fic.write(f.read()) B> fic.close() B> f.close() B> I ran the program and the file is not playing. B> Can someone help me? B> Thanks may be devas esti wb fic=open('mp3file.mp3','wb') With best regards, Egor Bolonev. E-mail: ebolonev at rin.ru From PeterAbel at gmx.net Thu Jan 1 15:48:56 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 1 Jan 2004 12:48:56 -0800 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: <21064255.0401011248.6d309292@posting.google.com> Irmen de Jong wrote in message news:<3ff1b688$0$319$e4fe514c at news.xs4all.nl>... > Hi > I have this dict that maps a name to a sequence of other names. > I want to have it reversed, i.e., map the other names each to > the key they belong to (yes, the other names are unique and > they only occur once). Like this: > > { "key1": ("value1", "value2"), "key2": ("value3,) } > > --> > > { "value1": "key1", "value2": "key1", "value3": "key2" } > > What I'm doing is using a nested loop: > > dict2={} > for (key,value) in dict1.items(): > for name in value: > dict2[name] = key > > which is simple enough, but I'm hearing this little voice in > the back of my head saying "there's a simpler solution". > Is there? What is it? ;-) > > Thanks > --Irmen. ... and after all there is always a hacky one-liner: >>> org = {"key1": ("value1", "value2"), "key2": ("value3",)} >>> dict(reduce(lambda l,(k,v):l.extend(zip(v,(k,)*len(v))) or l,org.items(),[])) {'value3': 'key2', 'value2': 'key1', 'value1': 'key1'} >>> Happy new year Peter From enrique.palomo at xgs-spain.com Wed Jan 21 04:49:31 2004 From: enrique.palomo at xgs-spain.com (Enrique) Date: Wed, 21 Jan 2004 10:49:31 +0100 Subject: python As400 In-Reply-To: Message-ID: <001801c3e003$df20ac50$6c010a0a@epalomo> i checked before this website, http://www.iseriespython.com/, but found no much information in it (docs) worse? how much worse? more worse that can be assumed? and connect python on windows with db2 in as400?? -----Mensaje original----- De: python-list-bounces+enrique.palomo=xgs-spain.com at python.org [mailto:python-list-bounces+enrique.palomo=xgs-spain.com at python.org]En nombre de Jarek Zgoda Enviado el: martes, 20 de enero de 2004 20:30 Para: python-list at python.org Asunto: Re: python As400 Enrique pisze: > I'm very interested in python for AS/400. I must migrate an application that > is running under windows to AS/400. > Has anyone worked with python in that platform?? Yes, with real pleasure. ;) > what about performace?? Worse than CL/RPG, similar to Java, better than REXX -- in case of batch jobs. Didn't try running Python scripts interactively. > The scripts are basicly of string manipulation and i/o. Check http://www.iseriespython.com/ -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ -- http://mail.python.org/mailman/listinfo/python-list **AVISO DE CONFIDENCIALIDAD** La informaci?n contenida en este mensaje y archivos es privada y confidencial estando dirigida solamente al destinatario. Si Ud. ha recibido esta informaci?n por error, por favor, proceda a su inmediata destrucci?n. Cualquier opini?n o punto de vista contenido en este mensaje corresponde al remitente y necesariamente no representa la opini?n del GRUPO XEROX. From netquest at sympatico.ca Tue Jan 27 11:52:50 2004 From: netquest at sympatico.ca (KNS) Date: Tue, 27 Jan 2004 08:52:50 -0800 Subject: winapi: mouseclick In-Reply-To: References: Message-ID: Thank you for the response. I am actually using win32all to launch an application and am waiting for user actions or changes in state. Once the application is launched (e.g., IE) the program just records changes in URLs. Now I would like the various states (e.g., time, mouse position) saved whenever the mouse is clicked on the application (or even the desktop). So, can I just use an 'if' (within a while-loop) to test whether WM_LBUTTONDOWN == 0 and if so what is the appropriate syntax with win32all? Thanks. Tim Golden wrote: >>-----Original Message----- >>From: KNS [mailto:netquest at sympatico.ca] >>Sent: 27 January 2004 08:19 >>To: python-list at python.org >>Subject: Re: winapi: mouseclick >> >> >> >>Just to add some clarification, this is in fact a Python question. >>I'm just working within the Windows environment. And, now that >>I'm here, I'm certain this is child's play for many of you, so >>a bit of help would be most welcomed. >> >>Thanks. >> >>KNS wrote: >> >>>Hello, >>> >>>Can someone please suggest how to test for a mouse click using >>>the WinAPI? I have dispatched a windows application and would >>>like to detect any mouseclicks (and keyboard entry for that >> >>matter)... >> >>>Thanks. >>> >> > > > Your question is not the most precise one I've ever seen. If > you have written a Windows app then you presumably understand > how the Windows messaging setup works. In which case, what > you need to do is to handle WM_LBUTTONDOWN and related messages. > > If you're not sure which messages to go for, look at this: > > http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/use > rinput.asp > > which gives an overview. > > There's an example of doing this kind of thing in Python > using the ctypes modules: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/208699 > > You can also do it with the win32all extensions from Mark > Hammonds pages: > > http://starship.python.net/crew/mhammond/win32/Downloads.html > > If this isn't really what you were asking, could you post a > segment of code showing what you're about and where you're > stuck? > > 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 CousinStanley at hotmail.com Thu Jan 15 12:38:36 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Thu, 15 Jan 2004 10:38:36 -0700 Subject: [ANNOUNCE] gtkmvc-0.9.0 References: Message-ID: | MVC Framework for Pygtk2 version 0.9.0 has been released | .... Roberto .... Thanks for providing a very nice MVC example .... http://sra.itc.it/people/cavada/mvc/index.html Python MVC gtkmvc I've had your original version for a few months with the intent to try and adapt a graphics application that I've written to the MVC pattern and hopefully the new version you've provided will inspire me to go ahead and do it .... My application currently is written using the Tkinter GUI, but conversion using PyGTK and your examples should be straightforward .... Following are a few links I've collected, not all Python based, that may be useful to anyone else interested in MVC .... http://www.faqts.com/knowledge_base/view.phtml/aid/3171/fid/245 Python MVC GladeBase.py http://twistedmatrix.com/documents/TwistedDocs/TwistedDocs-1.0.0/howto/woven.html Python MVC Twisted http://webware.colorstudy.com/twiki/bin/view/Webware/ModelViewController Python MVC WebWare http://st-www.cs.uiuc.edu/users/smarch/st-docs/mvc.html SmallTalk MVC http://www.owlnet.rice.edu/~comp212/01-spring/labs/05/ Java MVC Rice University http://www.chinajavaworld.net/examples/application/mvc.html Java MVC ChinaJavaWorld http://www.cs.indiana.edu/~rawlins/symphony/mvc2/mvc2-proposal.html Java MVC Refactoring -- Cousin Stanley Human Being Phoenix, Arizona From paul at boddie.net Wed Jan 14 05:23:53 2004 From: paul at boddie.net (Paul Boddie) Date: 14 Jan 2004 02:23:53 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: <23891c90.0401140223.344b22af@posting.google.com> Erik Max Francis wrote in message news:<4004EC9E.1E2E2893 at alcyone.com>... > > There are plenty of things you can get out of starting, getting involved > with, and approaching open source projects. A legion of personal > servants is not going to be one of them, and only a crass idiot would > think otherwise. As far as I've been able to discover, life is just one long cocktail party in Brandon's honour. So it isn't exactly surprising that everyone appears to him as just another waiter with a tray of drinks. Paul From anand at easi.soft.net Wed Jan 21 07:32:49 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Wed, 21 Jan 2004 18:02:49 +0530 Subject: invoking interpeter in another interpeter Message-ID: <400E7171.6060702@easi.soft.net> Hi I have extended/embedded python into my application, it is working great, The documentation is too good, I could replace existing scripting tool to python in no time. I have one problem with invoking python interpreter from another python interpreter. This is how it is. I have one C API which executes python interpreter passing the file name, So there are chances that in that file one command it self is the API to execute python. It is hanging in the second invocation, could some one help. Thanks in advance Anand ------------------------------------------------------------------- Python code: First python file from Vdb import * # This is the invocation of another python interpeter from one ExecutePythonInterpeter("another.py" ) The application first calls the ExecutePythonInterpter C API, which in turn calls same API for different file, from python, Following is the C implementation of ExecutePythonInterpeter. void ExecutePythonInterpeter( char *file ) { FILE *fp; char *msg ; PyObject *exc, *val, *trb, *obj ; PyThreadState *gtstate = NULL; if( Py_IsInitialized() == FALSE) { Py_Initialize(); PyEval_InitThreads(); gtstate = PyEval_SaveThread(); } ExecutePythonInterpeterThread(file); if(gtstate) { PyEval_AcquireThread(gtstate); Py_Finalize(); gtstate=NULL; } return ; } void ExecutePythonInterpeterThread( char *file ) { FILE *fp; char file_name[256] ; PyThreadState *tstate ; PyEval_AcquireLock(); tstate = Py_NewInterpreter(); initVdb(); initVdbPythonVgPoint2() ; initVdbPythonVgPoint3(); if(tstate == NULL) { fprintf(stderr, "Can't create an interpreter\n"); return ; } sprintf(file_name,"%s",file); fp=fopen(file_name,"r"); if(!fp) { fprintf(stderr,"FATAL:File open for %s failed\n",file); return ; } PyRun_SimpleFile(fp,file_name) ; Py_EndInterpreter(tstate); PyEval_ReleaseLock(); fclose(fp); return ; } From LittleDanEhren at yahoo.com Tue Jan 6 21:05:10 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 6 Jan 2004 18:05:10 -0800 Subject: Pre-PEP: Dynamically evaluating default function arguments References: <711c7390.0401061452.3ee3789f@posting.google.com> Message-ID: <711c7390.0401061805.70d0944f@posting.google.com> I'm sorry I wasted your time, everyone. From cartermark46 at ukmail.com Tue Jan 20 12:03:07 2004 From: cartermark46 at ukmail.com (Mark Carter) Date: 20 Jan 2004 09:03:07 -0800 Subject: Python-based file synchronizer (like Unison)? References: Message-ID: > Anyone know of anything like this? It doesn't seem like it > should take a lot to sit on top of rsync and resolve conflicts. You might also consider dfp (but it has no GUI): http://www.homepages.lu/pu/dfp.html From gagenellina at softlab.com.ar Mon Jan 19 22:51:23 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Tue, 20 Jan 2004 00:51:23 -0300 Subject: Launching Wordpad on Windows In-Reply-To: Message-ID: <5.2.1.1.0.20040120004513.024a7910@192.168.0.115> At 20/1/2004 00:50, you wrote: >item = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WORDPAD.EXE" >key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, item, 0, > win32con.KEY_QUERY_VALUE) >info = win32api.RegQueryValueEx(key, None) >win32api.RegCloseKey(key) >editor = win32api.ExpandEnvironmentStrings(info[0]) > >I would like to solicit learned opinions about this. Which >version will work in more versions of Windows? Is there a >better approach? I think this is the best way. Untested, but that should work even on Windows95. Anyway, you could provide a default (simply WORDPAD.EXE), just in case the application exists and is in the path but is not registered. Gabriel Genellina Softlab SRL From mesteve_b at hotmail.com Sat Jan 3 17:20:59 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 03 Jan 2004 22:20:59 GMT Subject: Lists are weird when they are instance members Message-ID: hey, okay, I'm trying to figure out why my books: Quick Python, Python in a Nutshell, Python Cookbook and Learning Python don't say anything about the weird behavior of a list when you have one as an object instance member. for instance (my first pun of 2004), if I have, test.py ---------------- global_filegroup_array = [] # array of filegroup objects class FileGroup: a = 0 mylist = [] # here it is def put_stuff_in_my_list(self, anyfile): self.mylist.append( get just a single string from file) # pls excuse the psuedo def __init__(self): put_stuff_in_my_list(anyfile) def main(): # do ten times: instantiate the above object, and add to the global array for i in xrange(10): filegroup = FileGroup() global_filegroup_array.append(filegroup) # print the list contents print global_filegroup_array[0].mylist ------------ end of file Output is: [u'.string1', u'.string2', u'.string3' ] # only u'string1' should show up No matter which index I use into the global array, I always get ALL of the strings showing up. I should only get u'string1' showing up, and u'string2' if I used "[1].mylist" How I resolved it, is by slipping in self.mylist = [] before put_stuff_in_my_list(anyfile) in __init__(self) Why should I have to empty out the list when it's a member of a newly instantiated object? thanks p.s. ( I'm actually not doing exactly the thing with the files, but instead iterating through a xml file with dom, debugging it showed the behavior ) From serve at detongiser.com Thu Jan 15 14:38:56 2004 From: serve at detongiser.com (Servé Lau) Date: Thu, 15 Jan 2004 20:38:56 +0100 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: <100dr2bonj4t2ed@corp.supernews.com> "Brandon J. Van Every" wrote in message news:bu4cdk$cv09p$1 at ID-207230.news.uni-berlin.de... > Except that I didn't say that, so it wouldn't be within your legal rights to > quote me as having said such. If you want to quote me, you're going to have > to *quote* me, not paraphrase me in your own idiom. aha, > Why do you think OS developers owe you any kind of value at all? "I don't. But that's not going to stop me from denigrating them for being incapable of fulfillng the kinds of projects I have in mind." From gsmith at oxfam.org.uk Thu Jan 29 11:43:11 2004 From: gsmith at oxfam.org.uk (Graham) Date: Thu, 29 Jan 2004 16:43:11 -0000 Subject: Pythonwin - breaking out of infinite loop Message-ID: <40193737$0$13350$ed9e5944@reading.news.pipex.net> How do I stop a Python program running in PythinWin? I would expect to be able to use CTR-C or CTRL-break etc. many thanks Graham Smith PeopleSoft Technical Team Leader OXFAM GB +44 (1865) 313255 gsmith at oxfam.org.uk From francisgavila at yahoo.com Mon Jan 12 21:23:20 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 12 Jan 2004 21:23:20 -0500 Subject: how can I execute a function string References: Message-ID: <1006qgl89mmsnf4@corp.supernews.com> Rajarshi Guha wrote in message ... >Hi , > I have some code that generates a function on the fly in a string. >At a later point in time I want to execute this function (which also >requires a parameters to be passed to it). So the code is something like >this: > >def generate_func(): > s = """ def function(x): > print x > return 2 >""" > return s > >funcstring = generate_func() >retval = .... > >That is, retval should have the value returned from the evaluation of the >function in the string funcstring. > >Is this possible by means of simple function calls or does this involve >some sort of black magic? > >Thanks, What is it with code-generation this week? Anyway, the exec statement (not function) will execute the contents of a string or code object as though it were inline code: E.g.: >>> x Traceback (most recent call last): ... NameError: name 'x' is not defined >>> exec 'x = 1' >>> x 1 >>> Use like so: exec generate_func() # 'function' is now in your namespace. function('hello') # should print 'hello' and return 2. A *slightly* better approach is to make a code object, using compile(). def gen_func(): s = ''' def f(x): return x ''' return compile(s, '', 'single') exec gen_func() # f gets dumped into your namespace. If you're very ambitious, you can generate an AST tree and compile that: see the compile module. In this simple case there's no advantage, however. I'll have to think about how to turn the raw source of a function definition into a callable. I'm not sure it's possible in a 100% reliable manner. Here's a first attempt (untested): def makecallable(source): """Return a function from string source. 'def ' must be the first tokens in source! """ co = compile(source, '', 'single') funcname = co.co_varnames[0] #This is VERY brittle!! fakelocals = {} exec co in globals(), fakelocals return fakelocals[funcname] Now that I've told you about exec, I'll tell you that you almost certainly shouldn't be using it. There is most likely a better way to do what you're doing than building code strings and executing them. Python has a lot of reflection, introspection, and dynamic object generation capabilities, which generally remove the need for using exec, which is slow, hackish, and error-prone. Please tell us more about what you're doing. -- Francis Avila From cookedm+news at physics.mcmaster.ca Tue Jan 27 18:44:20 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 27 Jan 2004 18:44:20 -0500 Subject: map float string '0.0' puzzle References: Message-ID: At some point, "j vickroy" wrote: > Howdy, > > I do not understand the following behavior for: > PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > win32. > >>>> >>>> float('0.0') > 0.0 >>>> row = ('0.0', '1.0', None) >>>> map(lambda setting: setting and float(setting) or None, row) > [None, 1.0, None] >>>> map(lambda setting: setting and (setting,float(setting)) or > (setting,None), row) > [('0.0', 0.0), ('1.0', 1.0), (None, None)] >>>> > > Specifically, why is the return value of the first map operation: > [None, 1.0, None] > > I was expecting: > [0.0, 1.0, None] Because float('0.0') is a false value -- 0.0 is taken as false. So the lambda becomes '0.0' and 0.0 or None which evaluates to None. It looks like you're trying to use the 'conditional expression' trick, which fails in these situations. It'd be clearer to be more expressive, and define a function: >>> def float_to_str(s): ... if s: ... return float(s) ... else: ... return None ... >>> [ float_to_str(s) for s in row ] [0.0, 1.0, None] where I've used a list comprehension instead of map. In fact, I'd probably define float_to_str like this: def float_to_str(s): try: return float(s) except: return None which now works for anything: if it's convertible to float, it returns the float, otherwise None. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From nico-NoSp at m-tekNico.net Mon Jan 5 04:01:10 2004 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Mon, 05 Jan 2004 10:01:10 +0100 Subject: Python for Embedded Devices? In-Reply-To: <4f0a9fdb.0401042307.1f6bd4e8@posting.google.com> References: <221e7b06.0401041537.2896b22d@posting.google.com> <4f0a9fdb.0401042307.1f6bd4e8@posting.google.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >> I have been tinkering around with some ideas to make a new language to >> fit the environment I deal with. This is slow work, as I haven't a lot >> of time to spend on it, and I am not a language design expert, but I'm >> having fun with it! > Maybe you can work with Fredrik Lundh on Pytte (http://effbot.org/zone/pytte.htm) Thanks for this link. There's nothing to download there, unfortunately. :^( Something else that's interesting for embedded devices is an environment for working in Python and generating the RTOS: "WhatOS is a free open source embedded system development solution. It provides a complete set of tools for creating high-quality, reliable embedded systems. These include: a real-time operating system (RTOS) generator, a simulator for testing and debugging generated systems, and tools for interacting with systems remotely after they have been embedded." http://www.sticlete.com/whatos/index.html - -- Nicola Larosa - nico-NoSp at m-tekNico.net "I am afraid that if the United States had to live by the [monetary] rules that are imposed on, say, Brazil, the USA would become a developing country in one generation. It's the system that is currently unstable, unfair and not working." -- Bernard Lietaer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/+SfUXv0hgDImBm4RAkkxAKCgi/prJnHbYv4BtiJwK/0g/KB3SQCfeyFR y5tG2razumSaRYG5cyVe7Y4= =a8cP -----END PGP SIGNATURE----- From ny_r_marquez at yahoo.com Tue Jan 20 16:04:11 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 20 Jan 2004 13:04:11 -0800 Subject: py2exe 0.5.0 (finally) released References: Message-ID: <8a27e309.0401201304.7ee860b0@posting.google.com> Maybe I'm missing it, but I don't see how to specify an icon to use for the exe. Is that funtionality no longer available? -Ruben From majordomo-owner at csl.sri.com Sat Jan 31 14:31:57 2004 From: majordomo-owner at csl.sri.com (majordomo-owner at csl.sri.com) Date: Sat, 31 Jan 2004 11:31:57 -0800 Subject: Majordomo results: Hi Message-ID: <200401311931.i0VJVvaV000964@quarter.csl.sri.com> An embedded and charset-unspecified text was scrubbed... Name: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: not available URL: From carroll at tjc.com Tue Jan 6 05:13:26 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue, 06 Jan 2004 10:13:26 GMT Subject: Downloading files off Interet References: Message-ID: On 5 Jan 2004 23:32:53 -0800, blaktyger at hotmail.com (Blaktyger) wrote: >I would like to download some mp3 files from a web site. There is to >much of them and I had the idea of writing a script to do it for me. > >Code: >import string >import urllib > >f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") > >fic=open('mp3file.mp3','w') >fic.write(f.read()) >fic.close() >f.close() > >I ran the program and the file is not playing. >Can someone help me? A couple possibilities: First, are you running on Windows? If so, you want your output file opened binary: fic=open('mp3file.mp3','wb') Second, what does your output file look like? See if it's a text error message. Some sites will check to see whether there is a referring page from their own web site, and disallow transfer otherwise (or divert to a different site). If your somemp3site.com site does that, your download will fail. The only way I know around this is to give up using urllib, and use urllib2 instead, opening a Request rather than the url directly, and specifying the referring page from which you picked up the URL to the MP3 page. I can give more detail on this, but check the binary open first. Also, if the referring page is not the issue, you will probably find it much simpler to use urlretrieve instead. See http://www.python.org/doc/current/lib/module-urllib.html . Instead of: import string import urllib f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") fic=open('mp3file.mp3','w') fic.write(f.read()) fic.close() f.close() You just do: import urllib urllib.urlretrieve(""" http://www.somemp3site.com/somemp3.com""") That's it. It's almost cheating. Unfortunately, there's no urllib2.urlretrieve, so if that referring page thing is your issue, you can't use urlretrieve. Hope this helps. From oliver.schoenborn at utoronto.ca Mon Jan 26 10:39:13 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Mon, 26 Jan 2004 09:39:13 CST Subject: collaborate on open source project Message-ID: Hello, I'm looking for someone interested in participating in a small open-source project that requires processing cgi using python. If you know (or are learning) python and cgi and would like to know more, send me an email. The project is at http://www.sf.net/projects/bbmg. Thanks, Oliver -- PLEASE NOTE: comp.infosystems.www.authoring.cgi is a SELF-MODERATED newsgroup. aa.net and boutell.com are NOT the originators of the articles and are NOT responsible for their content. HOW TO POST to comp.infosystems.www.authoring.cgi: http://www.thinkspot.net/ciwac/howtopost.html From miki.tebeka at zoran.com Sun Jan 18 16:56:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 18 Jan 2004 13:56:53 -0800 Subject: Where to post an article? Message-ID: <4f0a9fdb.0401181356.79a1ec87@posting.google.com> Hello All, I have a little article I'd like to publish. It's about how to use Python to repidly develop an assembler (2.5 days in my case). Can you recommend a site/paper to publish it? And yes, I have a web page... Thanks. Miki From danb_83 at yahoo.com Fri Jan 23 14:42:28 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Jan 2004 11:42:28 -0800 Subject: What is object() References: <10105gchtsl1a21@news.supernews.com> Message-ID: Gerrit Holl wrote in message news:... > Aahz wrote: > > >Unless, of course, you're using the __new__() method. > > > > "Not much" != "none" ;-) > > "Not much" >= "none" ;-) > Because none is not much ;-) No, "Not much" < "none", because the comparison is case-sensitive. However, it is True that "not much" >= "none" and "Not much" >= None ;-) From newsgroups at jhrothjr.com Thu Jan 29 16:32:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 29 Jan 2004 16:32:10 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <101iv0ri062ag22@news.supernews.com> "Daniel Ehrenberg" wrote in message news:711c7390.0401291301.3f95794 at posting.google.com... > Can anyone show me how to so much as alias "for" to "each" in Python Without getting into the language wars, I think what you're looking for is called the Visitor Pattern (Design Patterns: GOF). It's actually trivial to implement as long as you're not looking for built-in support. Something like this works quite well in any object where you want to implement a visitor over a collection: class aCollection: def visit(self, instance): for x in self._collection: instance.visitor(x) return instance.result() The final call is a little more than the bare visitor pattern, but it allows the visitor instance to pass back a result so you can use it in expressions. A visitor then looks like this: class fubar: def __init__(self): self.whatever = 0 def visitor(self, value): self.whatever += value def result(self): return self.whatever and you use it like this: ohWow = aCollection.visit(fubar()) Unlike a block in, for example, Ruby, a visitor instance can be pre-initialized, it can have multiple methods and it can persist after being passed against the collection. Of course, you can use more complex data structures as well, see the compiler stuff for examples of the visitor pattern used over the Python Abstract Syntax Tree. The visitor pattern is also very useful for file system navigation; I use it consistently. John Roth > > Daniel Ehrenberg From benjamin at araisoft.com Fri Jan 2 19:35:49 2004 From: benjamin at araisoft.com (benjamin at araisoft.com) Date: Fri, 2 Jan 2004 16:35:49 -0800 (PST) Subject: Python 2.3.3 compilation problem In-Reply-To: References: Message-ID: <21307.66.47.55.3.1073090149.squirrel@email.araisoft.com> There may be a conflict with the lib's directory with a previous installation of Python 2.3 already installed. For the configure try running: ./configure --prefix=/usr/local instead of ./configure > Zdenda wrote: > >> Hi, i have RH9 and i need python 2.3. I executed tgz file and typed >> ./configue. Then i type make. It is without problem. When I type make >> install ... ... >> ... >> Compiling /usr/local/lib/python2.3/xml/sax/handler.py ... >> Compiling /usr/local/lib/python2.3/xml/sax/saxutils.py ... >> Compiling /usr/local/lib/python2.3/xml/sax/xmlreader.py ... >> Compiling /usr/local/lib/python2.3/xmllib.py ... >> Compiling /usr/local/lib/python2.3/xmlrpclib.py ... >> Compiling /usr/local/lib/python2.3/zipfile.py ... >> make: *** [libinstall] Error 1 >> >> Have somebody any idea where is error? >> Thanks > I had the same problem on Mandrake. There seem to be some minor syntax > incompatibilities in zipfile.py, and others. Try make -i install, and all > should be fine. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From jepler at unpythonic.net Tue Jan 6 18:33:31 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 6 Jan 2004 17:33:31 -0600 Subject: Pre-PEP: Dynamically evaluating default function arguments In-Reply-To: <711c7390.0401061452.3ee3789f@posting.google.com> References: <711c7390.0401061452.3ee3789f@posting.google.com> Message-ID: <20040106233331.GA15852@unpythonic.net> That proposal gets "-All" from me. (or, at least, I think that's what I mean. Maybe I just mean "None", I couldn't stand that other thread) Reams of code depend on default arguments working as they do today. For instance: l = [] for i in range(10): l.append(lambda x, y=i: x+y) or def fib(x, y={0: 1, 1: 1}): assert x >= 0 if not y.has_key(x): y[x] = fib(x-1) + fib(x-2) return y[x] or def stack(): def push(x, l=[]): l.append(x) def pop(l=push.func_defaults[0]): return l.pop() return push, pop It's not clear exactly how this feature would work. What additional state will you store with function objects to make it work? Right now, it works like this: def f(l=x): pass is equivalent to _magic = x def f(*args): assert len(args) < 2 if args: l = args[0] else: l = _magic you're proposing something more like _magic = lambda: x def f(*args): assert len(args) < 2 if args: l = args[0] else: l = _magic() you've just added one additional function call overhead for each defaulted argument, plus the time to evaluate the expression 'x', even in cases where it makes no difference. Here's a case where the programmer has performed a micro-optimization that will probably be slower after your change (even though the program's meaning is not changed): def log10(x, l=math.log, l10=math.log(10)): return l(x)/l10 That leaves the case where you actually want the default argument value to depend on the current program's state, as below: def log(s, when=time.time()): print >>stderr, time.asctime(when), s I think it's better to write def log(s, when=None): if when is None: when = time.time() print >>stderr, time.asctime(when), s because it makes calling code easier, too: def log_with_prefix(p, s, when=None): log("%s: %s" % (p, s), when) instead of repeating the default argument everwhere you may call it both ways def log_with_prefix(p, s, when=time.time()): log("%s: %s" % (p, s), when) or having to test at each place you call: def log_with_prefix(p, s, when=None): if when is None: log("%s: %s" % (p, s)) else: log("%s: %s" % (p, s), when) Jeff From danieljng at yahoo.com Wed Jan 7 00:32:40 2004 From: danieljng at yahoo.com (Daniel) Date: 6 Jan 2004 21:32:40 -0800 Subject: compileall binaries don't run!? Message-ID: <798d4337.0401062132.1e82ee65@posting.google.com> Hi, I'm trying to use compileall to make pyc files from py files (without having to execute them at the same time). This is the first time I've used compileall, so maybe I've done something silly. I run it like this: python /usr/lib/python2.2/compileall.py /home/me/mySourceDir And the output looks fine, resulting in a bunch of pyc files. Then I try running the pyc file eg.: /home/me/mySourceDir/doodad.pyc But get the following error: bash: ./doodad.pyc: cannot execute binary file I notice that when I execute doodad.py, no pyc file is generated. Does this mean that Python can only make pyc files from some BUT NOT ALL py files? Is this my problem? I've ensured file access permissions are correct. Thanks, Dan. From ramen at lackingtalent.com Fri Jan 9 18:11:36 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 09 Jan 2004 23:11:36 -0000 Subject: Python and Jython are kinda different References: <87wu81jjg2.fsf@pobox.com> <8765fkrig3.fsf@pobox.com> Message-ID: In article <8765fkrig3.fsf at pobox.com>, John J. Lee wrote: > Yes, but it has been specifically noted by GvR (as well as the > Jythonistas) that Jython is lacking developers ATM. I see. >> represented in books and tutorials--just two implementations of the Python >> language, we all ought to be more concerned with unifying them. I never see >> Jython advertised as a limited subset of Python. > > Well, it's *not* a limited subset of CPython 2.1 (apart from tiny > differences). True. I suppose this brings up the following question: What *is* "Python"? Does the concept of Python *today* fit within Jython's feature set? I'd say much of it does, but a few things stick out, in order of decreasing importance (IMHO): - generators - properties - getattr/getitem behavior (which is even different from CPython 2.1) - type factories being classes - dictionary support for "in" keyword When I think of the Python language, as it stands today, I am tempted to include all of the above. I recently ported Python 2.3's "sets" module. I posted a patch here recently, although I've improved it somewhat and fixed a few bugs since then. The lack of an "itertools" module was perhaps my biggest obstacle (the "for key in adict" feature was another common one). Now, I suppose I could have tried to port "itertools", but there's no "yield", so how do I do that? I ended up just using the old map and filter functions, which means all of that code is back to the old Python memory efficiency. >> > PyPy is a research effort, so not immediately useful. It may have big >> > payoffs if successful, of course. >> >> Well, my thinking is that, since it's an implementation of Python written in >> Python, many of the new features of CPython that don't require syntactical >> or fundamental object-model changes could be ported from PyPy to Jython as a >> temporary fix, to be eventually recoded in Java. > > Library changes don't require PyPy, they already work (most of the > time) direct from CPython. It's the fundamentals that take the work. > I'm not sure whether there's a third category, as you suggest. Sometimes they do, sometimes they don't. But the list of things that you can't do in library code if you want to be compatible with Jython 2.1 is growing. For instance, the "str.join" trick that has been discussed recently won't work in Jython 2.1 since "str" is not a class. It's a minor thing, but I bet a lot of people aren't aware of that. Little things like that can add up. I've never looked at the code to PyPy, so this is purely speculative, but it seems like at least a plausible idea to provide an extension mechanism for Jython such that PyPy code can be incorporated. Imagine if you could add the "yield" keyword by just importing a pure-Python module. I suppose we'd be entering macro-like territory, so it'd be controversial... > I believe GvR said that PyPy might (might!) become a sort of > executable standard for Python in the future, though. I think that's an impressive idea, but it almost seems like the resources spent in keeping PyPy and CPython in parallel could be better spent keeping Jython and CPython in parallel, seeing as nobody is calling PyPy "Python" currently. I will check out the Jython list. Peace, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From timr at probo.com Thu Jan 29 23:24:04 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 29 Jan 2004 20:24:04 -0800 Subject: wxPython: images from URLs References: <84fc4588.0401280613.771ac07@posting.google.com> Message-ID: Jonathan Daugherty wrote: ># self._imgstream = urllib2.urlopen(url).read() ># stream=cStringIO.StringIO(self._imgstream) ># ># try: ># img=wxImageFromStream(stream) ># except: ># pass > >I have tried this and it appears to work, but once I have >the image (from wxImageFromStream), I use it as follows: > >try: > bm = wxBitmap(img) > self.bitmap.setBitmap(bm) >except Exception, e: > print e Why wouldn't you use wxBitmapFromImage? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sidharthk at hotmail.com Thu Jan 29 00:17:31 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Thu, 29 Jan 2004 10:47:31 +0530 Subject: Rookie question about data types (hashtables) References: Message-ID: the bsddb module has a binary tree database but that might be overkill. Other than that I doubt there's anything in standard python that would help. If you don't plan to add any words to your dictionary you could order the list and use a binary search to find the entries. you could use python list for that :-) From claird at lairds.com Mon Jan 19 08:04:34 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 19 Jan 2004 13:04:34 -0000 Subject: Fw: PDF library for reading PDF files References: <100luvhbh3vr75d@corp.supernews.com> Message-ID: <100nlf2b1qjdae2@corp.supernews.com> In article , Robert Kern wrote: >Cameron Laird wrote: >> In article , >> Harald Massa wrote: >> >>>>I am looking for a library in Python that would read PDF files and I >>>>could extract information from the PDF with it. I have searched with >>>>google, but only found libraries that can be used to write PDF files. >>> >>>reportlab has a lib called pagecatcher; it is fully supported with python, >>>it is not free. >>> >>>Harald >> >> >> ReportLab's libraries are great things--but they do not "extract >> information from the PDF" in the sense I believe the original >> questioner intended. > >No, but ReportLab (the company) has a product separate from reportlab >(the package) called PageCatcher that does exactly what the OP asked >for. It is not open source, however, and costs a chunk of change. Let's take this one step farther. Two posts now have quite clearly recommended ReportLab's PageCatcher . I completely understand and agree that ReportLab supports a mix of open-source, no-fee, and for-fee products, and that PageCatcher carries a significant license fee. I entirely agree that PageCatcher "read[s] PDF files ... and ... extract[s] information from the PDF with it." HOWEVER, I suspect that what the original questioner meant by his words was some sort of PDF-to-text "extrac- tion" (true?) and, unless PageCatcher has changed a lot since I got my last copy, PDF-to-text is NOT one of its functions. -- Cameron Laird Business: http://www.Phaseit.net From __peter__ at web.de Fri Jan 30 04:02:58 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Jan 2004 10:02:58 +0100 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: Aahz wrote: > import __main__ > tmp = parse_funky_language("Hey, this is far out, man.") > setattr(__main__, tmp.name, tmp.value) > > In the context of the interactive interpreter, it's a bit harder to do; > I don't remember off-hand what the namespace of the interpreter is. You don't need to :-) Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> __name__ '__main__' Peter From and-google at doxdesk.com Fri Jan 30 09:53:17 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 30 Jan 2004 06:53:17 -0800 Subject: Python & XML & DTD (warning: noob attack!) References: <40191C49.786AAF89@engcorp.com> Message-ID: <2c60a528.0401300653.670674e7@posting.google.com> Peter Hansen wrote: > Unfortunately I don't know of any way you could generate the DTD again It is possible to preserve the internal subset in DOM Level 3. You can read it from the property DocumentType.internalSubset, and it will be included in documents serialised by an LSSerializer. It is not, however, possible to write to the internalSubset, and you can't create a new DocumentType object with a non-empty internalSubset, for some reason. So the only standard way to copy an internalSubset would be to make the new document by parsing something with the same value, eg.: dtd= oldDocument.doctype.internalSubset parser= oldDocument.implementation.createLSParser(1, None) input= oldDocument.implementation.createLSInput() input.stringData= '' % dtd newDocument= parser.parse(input) > I've never seen a package which supports what you ask for Plug time: the only package I know of to support DOM Level 3 is my own: http://www.doxdesk.com/software/py/pxdom.html Currently this is based on the November 2003 CR spec; there have been a number of fixes and changes to L3 functionality since, but I'm waiting for W3C to publish the next draft (presumably Proposed Recommendation) before releasing 1.0. > Also, aren't DTDs sort of considered either obsolete or at least > vastly inferior to the newer approaches such as XML Schema, or both? Certainly they have their drawbacks: they're namespace-ignorant, not flexible enough for some purposes, and they're a legacy bag on the side of XML rather than something built on top of it in XML syntax. Still, they're well-understood and widely supported, and simpler to learn than Schema at least. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From Z_kline at hotmail.com Tue Jan 27 19:15:17 2004 From: Z_kline at hotmail.com (Zachary) Date: Tue, 27 Jan 2004 16:15:17 -0800 Subject: Upgrading to Python 3.0 Questions Message-ID: Hello, I've heard some rumors about Python 3.0. I am wondering what sort of upgrading I'll have to do, as I have also heard people on this group asking us to use certain modules or operators or whatever. Is it a major sort of upgrade? What would I need to do to prepare for it? Thanks, Zack From not at existing.ru Fri Jan 23 10:47:38 2004 From: not at existing.ru (bva) Date: Fri, 23 Jan 2004 16:47:38 +0100 Subject: viewcvs install error on solaris In-Reply-To: References: <4007e92d$0$325$ba620e4c@news.skynet.be> Message-ID: <40114222$0$285$ba620e4c@news.skynet.be> Michael Hudson wrote: > bva writes: > > >>Hello, >> >>While trying to install viewcvs on a solaris 5.9 machine I get the >>following error message: >> >>Traceback (most recent call last): >> File "./viewcvs-install", line 35, in ? >> import compat >> File "./lib/compat.py", line 20, in ? >> import urllib >> File "/usr/local/lib/python2.2/urllib.py", line 26, in ? >> import socket >> File "/usr/local/lib/python2.2/socket.py", line 41, in ? >> from _socket import * >>ImportError: No module named _socket >> >>Python is installed on the machine. Can anybody tell me what I'm >>doing wrong or what I've forgotten? > > > Your python install lacks the socket module. On Solaris this usually > means something exciting to do with your SSL install. Who installed > Python? Complain at them. OK I will :-) Thx > > Cheers, > mwh > From peterwu at hotmail.com Wed Jan 28 18:00:18 2004 From: peterwu at hotmail.com (Peter Wu) Date: Wed, 28 Jan 2004 18:00:18 -0500 Subject: Web Service in Python Message-ID: <87hdyffzlp.fsf@tulip.whu.ca> I'd like to write a Web Service in Python just for my personal interest now. Is there any reference or document on this? -- ,,, (o o) Peter Wu ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From kim at lignus.dk Fri Jan 23 11:39:31 2004 From: kim at lignus.dk (Kim Petersen) Date: Fri, 23 Jan 2004 17:39:31 +0100 Subject: Help and optimization hints, anyone? References: <87d69a6e2j.fsf@pobox.com> <87vfn2bpre.fsf@pobox.com> Message-ID: Den Fri, 23 Jan 2004 16:20:37 +0000. skrev John J. Lee: > Kim Petersen writes: >> Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee: > [...] >> > dict is also a bad name -- this is the name of the builtin dictionary >> > type, which you've just clobbered (in the local scope). >> >> Hmmm - isn't it called __dict__ ? > > No, __dict__ is an attribute of Python objects. It's the dictionary > in which most Python objects keep their data: ah - the class dict() - yeah i can see that (i didn't notice since i hardly ever call dict() directly but do it indirectly via {}. Sure i've clobbered that internally in this class and derived (will change) >> > Haven't read much further, but it looks like you might be better off >> > using attribute access rather than indexing. In 2.2, use properties. >> > Earlier, use __setattr__ / __getattr__ (make sure you read the docs). >> >> this migrated from a regular dict which i had to drop because its >> not hashable as mentioned earlier - next step __(get|set)attr__. > > dicts are deliberately not hashable, because they're mutable. Are you > sure you want a dict as a dictionary key (assuming that's what you're > doing)? I had the columns,rows and cells as simply dicts in the beginning, but that made self.cells[(row,column)] impossible - so i converted to classes instead (which works just as well). And migrated func- tionality to the classes. [this is also the reason for the attributes being access as dict]. > > > John -- Privat ========================== Kim Petersen ==================== Arbejde Email kim at vindinggaard.dk ===== Jens Gr?ns Vej 11 ===== Email kim at lignus.dk Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51 Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62 From peter at engcorp.com Tue Jan 20 11:48:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jan 2004 11:48:40 -0500 Subject: Please Help Me (Re: needed PyXPCOM tutorial.) References: <425cc8d1.0401150908.287de0d8@posting.google.com> <425cc8d1.0401170903.3c331ab9@posting.google.com> <425cc8d1.0401200844.f6dcf9c@posting.google.com> Message-ID: <400D5BE8.369E598E@engcorp.com> mir nazim wrote: > > Please help me find some tutorials on pyxpcom. my project is at hold due to it. I'm sort of guessing that if http://www.google.com/search?q=tutorial+pyxpcom doesn't help you with that, then nothing will. From newspost at lolmc.com Sat Jan 3 08:50:07 2004 From: newspost at lolmc.com (Lol McBride) Date: Sat, 03 Jan 2004 13:50:07 +0000 Subject: mysql python Newbie Question References: Message-ID: On Sat, 03 Jan 2004 17:50:03 -0800, Andrew wrote: > Hi I would like to create a program that accesses mysql from a gui on my > local computer "mysql is on a server" > > but I am fairly new to python and programming GUI's in general > > What I would like this program to do is be able to access my server and > change update add and delete records from my databases without having to > write sql. > > I can create the GUI fairly easily but I do not know how I or what functions > and modules would be needed to do this or how to write them "Forgive me if I > sound to Newb" > > If someone out there could help me out maybe offer advice or even better > some code to build on that would be cool > > Thanks in advance > > Cheers > > Andrew Hi Andrew, I think you'll find that you still have to master SQL and it's nonclementure as Python only provides a DB-API and you need to know the SQL in order to use the API to send your queries etc. I've recently started using it and although at first SQL seems daunting you do get the hang of it after time - like most languages really.If you need specific help get in touch and I'll help were I can. Lol McBride From flemming at bjerke.dk Thu Jan 29 05:41:54 2004 From: flemming at bjerke.dk (flemming at bjerke.dk) Date: 29 Jan 2004 10:41:54 -0000 Subject: I have changed my e-mail address Message-ID: <20040129104154.94258.qmail@dmerhverv.org> Send mail til: flem[SLET DETTE]@bjerke.dk Send mail to: flem[DELETE THIS]@bjerke.dk I close flemming at bjerke.dk. Flemming From tim.golden at viacom-outdoor.co.uk Wed Jan 21 10:00:39 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Jan 2004 15:00:39 -0000 Subject: Dailing modem. Message-ID: >Is the win32ras realy what I want? Basically what I am trying >to do, is to >convert my phone/voice-modem/computer into a "computer-phone". >I need to >dail a number and disconnect via an interface on the computer >using python. >So, I am dailing normal numbers and not RAS servers. Or am I missing >something? Ah. Sorry. Misunderstood. No, you're quite right: RAS is not what you want. (Backs away, humbled and blushing...) What you probably want is one of the Python-to-serial interfaces (assuming that your modem is of the conventional variety which pretends to be a serial port, even if it's not). Try: http://pyserial.sourceforge.net/ or possibly: http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html and then talk "AT" language to it, or whatever dialect it speaks: http://www.modems.com/general/extendat.html (2nd time lucky?) 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 usenet at -OBFUSCATION-joefrancia.com Wed Jan 28 13:41:34 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Wed, 28 Jan 2004 18:41:34 GMT Subject: Nested lists or conditional logic? In-Reply-To: References: Message-ID: mike beck wrote: > this is not all complex, but as a noob i'm having a hard time getting > my head around it. > > i have a list of items. i need to print the items in batches of x, > with a summary line after each complete or partial batch, and a total > line at the end of the job. > > if the list looks like ['line1','line2','line3'], and my ITEMSINBATCH > = 1, the output should look like this: > > line1 > ---summary line--- > line2 > ---summary line--- > line3 > ---summary line--- > ---total line--- > > if ITEMSINBATCH = 2, the output should look like this: > > line1 > line2 > ---summary line--- > line3 > ---summary line--- > ---total line--- > > i've done the following, which works, but it seems like there must be > a better/simpler/faster way to do this with nested loops. ideas? > > > # ---------------------Begin code--------------------- > ITEMSINBATCH = 1; > ARBITRARYNUM = 51; > > # create a list to work with > myList = ['1']*ARBITRARYNUM; > > for i in range( len(myList) ): > # avoid starting at 0 > count = i + 1; > > print "The item is:",myList[i],'\t',count; > > # ensure that the batch summary line is printed every ITEMSINBATCH > # times but not if the number of items is evenly divisible by > # ITEMSINBATCH, in which case both the inner print and the outer > # print would execute and we'd get consecutive batch summary lines > if ( (count) % ITEMSINBATCH ) is 0 and count != len(myList):: > print "-----Add batch summary line-----"; > > # add a final batch line for those trailing items > print "------Add batch summary line------And BTW, i is", count; > > # and add the final summary line > print "------Add file summary------"; > > # ---------------------End code--------------------- I'm not sure this is faster, but it sure is simpler: mylist = range(23) batchsize = 4 for i in range(0,len(mylist),batchsize): for l in mylist[i:i+batchsize]: print l print "---summary line---" print "---file summary---" -- Soraia: http://www.soraia.com From swalters_usenet at yahoo.com Fri Jan 9 16:17:24 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 21:17:24 GMT Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> <871xq8ri6h.fsf@pobox.com> Message-ID: |Thus Spake John J. Lee On the now historical date of Fri, 09 Jan 2004 20:16:54 +0000| > or again, you can set .addheaders on OpenerDirector (which will cause > those headers to be added to all requests). This, however, does not stop the original User-agent header to be sent, and google still filters out the request. Instead, it just causes a second user-agent to be sent. Here is the very bad code I used to solve this problem. There are better ways, I assure you, but it should point you in the right direction. You should probably do this with inheritance, but for my quick script, this is what I did. ---- #Override the default OpenerDirector Class Init. #OpenerDirector *insists* on adding a User-Agent #That some websites don't like. foo = OpenerDirector.__init__ def bar(self, Agent='None'): foo(self) self.addheaders = [('User-Agent',Agent)] OpenerDirector.__init__ = bar ----- HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From grreeder at ix.netcom.com Fri Jan 23 12:47:50 2004 From: grreeder at ix.netcom.com (jr) Date: Fri, 23 Jan 2004 17:47:50 GMT Subject: Sending Through ^] Through telnetlib References: Message-ID: Try sending: '\x1d' HTH -jr "John Abel" wrote in message news:mailman.687.1074866920.12720.python-list at python.org... > I have written a script that makes a telnet connection, runs various > commands, and returns the output. That was the easy bit :) However, to > close the session, I need to send ^] followed by quit. I've tried > sending chr(29), which is the ascii equivalent, but that doesn't seem to > work. Is there something I'm missing? > > Any pointers would be much appreciated. > > Thanks > > J > From exarkun at intarweb.us Fri Jan 30 09:42:54 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 30 Jan 2004 09:42:54 -0500 Subject: NEWLINE character problem In-Reply-To: <011101c3e73b$9da26c20$2f01a8c0@dchirila> References: <011101c3e73b$9da26c20$2f01a8c0@dchirila> Message-ID: <20040130144254.GA29356@intarweb.us> On Fri, Jan 30, 2004 at 04:16:12PM +0200, Dragos Chirila wrote: > Hi > > I have a string and I want to split it by NEWLINE character. > > It is knowned that "Microsoft Windows, Apple's Macintosh OS and various > UNIX, all use different characters to mark the ends of lines in text files. > Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return > (ASCII character 13), and Windows uses a two-character sequence of a > carriage return plus a newline". So, PLEASE don't tell me to use 'split' by > '\n' because it won't work. s.splitlines() Jp From marco at bubke.de Mon Jan 19 13:33:28 2004 From: marco at bubke.de (Marco Bubke) Date: Mon, 19 Jan 2004 19:33:28 +0100 Subject: Pyrex and numarray Message-ID: Hi I have tried to include numarray in Pyrex but I get allways this error: Traceback (most recent call last): File "gears.py", line 9, in ? import gl File "/home/marco/projects/test_pyrex/gl.pyx", line 40, in gl ctypedef class numarray.NumArray [object PyArrayObject]: ValueError: numarray.NumArray does not appear to be the correct type object The code is: cdef extern from "numarray/numarray.h": struct PyArray_Descr: int type_num, elsize char type ctypedef class numarray.NumArray [object PyArrayObject]: cdef char *data cdef int nd cdef int *dimensions, *strides cdef object base cdef PyArray_Descr *descr cdef int flags cdef object _data cdef object _shadows cdef long int nstrides cdef long byteoffset cdef long bytestride cdef long itemsize cdef char byteorder cdef char _aligned cdef char _contiguous cdef char *wptr def materialfv(GLenum face, GLenum pname, NumArray params): """ Set the material. materialfv(enum face, enum pname, params) params - should be a tuple """ assert (len(params) == 4 and pname in \ (AMBIENT, DIFFUSE, SPECULAR, EMISSION, AMBIENT_AND_DIFFUSE))\ or (len(params) == 1 and pname == SHININESS) \ or (len(param) == 1 and pname == COLOR_INDEXES),\ "arguments are not right" str_params = params.tostring() print str_params cdef float* flat_params flat_params = str_params glMaterialfv(face, pname, flat_params) I write a little OpenGL wrapper of my own(I know PyOpenGL but it doesn't fit to me). Now I try to get the numarray to this function and cast it to a float pointer(ugly hack, will be cleaned later). regards Marco From bhan at andrew.cmu.edu Fri Jan 23 16:00:36 2004 From: bhan at andrew.cmu.edu (Han Benjamin) Date: Fri, 23 Jan 2004 16:00:36 -0500 Subject: Psyco on PowerPC? Message-ID: <30E0BEC9-4DE7-11D8-B663-000393DB5438@andrew.cmu.edu> Is anyone aware of any effort in bringing Psyco onto other platforms, esp. PowerPC (Mac OS X)? I checked the website but it's still stated as X86 only. Thanks, Ben From reply.in.the.newsgroup at my.address.is.invalid Tue Jan 20 15:50:33 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 20 Jan 2004 21:50:33 +0100 Subject: an example of a singleton design pattern in python? References: Message-ID: <645r00hicslg2qn55sncentdk8alnbevab@4ax.com> Daniel Ortmann: >Does anyone have an example of a singleton design pattern in python? http://aspn.activestate.com/ASPN/search?query=singleton§ion=PYTHONCKBK&type=Subsection -- Ren? Pijlman From ccang at iprimus.com.au Thu Jan 15 22:05:40 2004 From: ccang at iprimus.com.au (cc) Date: Fri, 16 Jan 2004 14:05:40 +1100 Subject: id3v2 module In-Reply-To: References: Message-ID: <4007533f_1@news.iprimus.com.au> Dusausoy Bruno wrote: > Hi, > > I'd like to know if there is a third-party module for reading/writing > id3v2 informations. > Thanks Yet another id3 v2 but it does read only.... http://home.iprimus.com.au/ccang/scripts.html (I lost interest and didnt do the 'write' part). -- | The words GULLIBLE read the same when held in | front of a mirror. From sidharthk at hotmail.com Mon Jan 26 04:01:15 2004 From: sidharthk at hotmail.com (Sidharthk) Date: 26 Jan 2004 01:01:15 -0800 Subject: efficient updating of nested dictionaries References: Message-ID: <8d02ff63.0401260005.20b52b9f@posting.google.com> omission9 wrote in message news:... > I have a dictionary that looks like this > MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO > > I am having a problem updating this with a simple > MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting > into the inner dicts. > Getting the keys of each and iterating through and updating each one is > terribly slow as the number of keys gets bigger and bigger. > What is the bst way to update my nested dicts? Use Tuples MY_DICT[(KEY_X,KEY_Y,KEY_Z)]=FOO Unless for some you need to use nested dicts :) From tim.golden at viacom-outdoor.co.uk Fri Jan 30 11:42:53 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 30 Jan 2004 16:42:53 -0000 Subject: How to start a DTS Package on MS-SQL-Server? Message-ID: >-----Original Message----- >From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com] >Sent: 30 January 2004 12:48 >To: python-list at python.org >Subject: How to start a DTS Package on MS-SQL-Server? > > >Hi! > >Does anybody know how to start a DTS-Package on a MS-SQL-Server out of >a Python-Script? > >Thanks for your help! > >Dirk Haven't tried it, but there is a dtsrun executable (C:\Program Files\Microsoft SQL Server\80\Tools\BINN\dtsrun.EXE) in my setup, which seems hopeful. There is also a DTS COM library which might do something. 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 dkuhlman at rexx.com Sun Jan 4 15:48:07 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 04 Jan 2004 12:48:07 -0800 Subject: Let users execute but not view References: Message-ID: Florian Lindner wrote: > Hi! > I have a python script which should be executed my normal users > but they should not be able to view the sourcecode. Setting > permissions to x only does not help, the python interpreter can > not read the file. How can I do that? Compile it to a .pyc file and give that to your users instead of the .py file. You can use py_compile or compileall in the Python standard libraries for this. Note, however, that this does not protect you from the really inquisitive or from malicious users and so on. They could use dis, for example, from the Python standard library to learn about your code. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From llothar at web.de Sun Jan 25 08:21:26 2004 From: llothar at web.de (Lothar Scholz) Date: 25 Jan 2004 05:21:26 -0800 Subject: [OPINION] - does language really matter if they all do the same thing? References: <20040123183127.GA35281@mail.hitmedia.com> Message-ID: <6ee58e07.0401250521.2e26e370@posting.google.com> Jonathan Daugherty wrote in message news:... > that english and arabic are, in the same sense, just two sides > of the same coin, which is a gross oversimplification of the > matter and a disrespect to the qualities of the languages english and arabic are quite equal. compare it with tonal asian languages then you find some real difference. For example in the thai language there is no word that means "No", you can only politely deny "yes". This is mental difference. From blaktyger at hotmail.com Tue Jan 6 02:32:53 2004 From: blaktyger at hotmail.com (Blaktyger) Date: 5 Jan 2004 23:32:53 -0800 Subject: Downloading files off Interet Message-ID: I would like to download some mp3 files from a web site. There is to much of them and I had the idea of writing a script to do it for me. Code: import string import urllib f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") fic=open('mp3file.mp3','w') fic.write(f.read()) fic.close() f.close() I ran the program and the file is not playing. Can someone help me? Thanks From martin at v.loewis.de Fri Jan 16 18:10:47 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jan 2004 00:10:47 +0100 Subject: Retrive unicode keys from the registry In-Reply-To: <1xpzaa8i.fsf@python.net> References: <1xpzaa8i.fsf@python.net> Message-ID: Thomas Heller wrote: > My understanding is that it's possible to convert any (for a certain > definition of 'any) unicode string in a byte string (because the > encoding for the byte string can be specified), but that it's impossible > to convert a byte string into unicode unless the byte string's encoding > is known. > > Maybe this only shows my un-understanding of unicode... It certainly is. It is possible to create a registry key which the "ANSI" API (RegQueryValueExA) cannot find - i.e. where you truly need the "wide" API (RegQueryValueExW). An example would be a registry key with Cyrillic, Greek, or Japanese characters on your system. Encoding them as "mbcs" will convert those characters into question marks (which is a bug in itself - Python should rasise an exception instead). Regards, Martin From john at thegreys.co.uk Thu Jan 22 09:26:13 2004 From: john at thegreys.co.uk (John) Date: 22 Jan 2004 06:26:13 -0800 Subject: pass parameter to select tinytable to update Message-ID: <33dff922.0401220626.6e5e970c@posting.google.com> Hi I'm new to zope/python and hope this is fairly easy - I want to update a TinyTablePlus table from a script. So the following will do what I want on the table 'igrid'. context.igrid.setRow(number=number,score=newscore) But how can I do this on different tables where the table is passed to the script as a parameter - instead if igrid I want to include the value of the parameter. thanks, John From exarkun at intarweb.us Sat Jan 24 12:03:48 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 24 Jan 2004 12:03:48 -0500 Subject: there is no exitfunc in sys module In-Reply-To: <20040124080753.97159.qmail@web61109.mail.yahoo.com> References: <20040124080753.97159.qmail@web61109.mail.yahoo.com> Message-ID: <20040124170348.GA7002@intarweb.us> On Sat, Jan 24, 2004 at 12:07:53AM -0800, Hameed Khan wrote: > hi, > i was reading the manual for sys module. i found a > description for a function known as exitfunc. and it > says the function installed by > sys.exitfunc(cleanUpFunc) call will be called when the > interpreter exits. but when i try to call this > function on Python interactive prompt it says there is > no attribute named exitfunc in sys module. Use of sys.exitfunc is deprecated. Use the atexit module instead. The sys module does not have the exitfunc attribute unless you give it one. The proper (old, deprecated) way to do this was: sys.exitfunc = cleanUpFunc The new, non-deprecated, proper way to this is: atexit.register(cleanUpFuncC) Jp From exarkun at intarweb.us Fri Jan 16 14:29:59 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 16 Jan 2004 14:29:59 -0500 Subject: Web Form Error Handling Techniques In-Reply-To: References: Message-ID: <20040116192959.GB27129@intarweb.us> On Fri, Jan 16, 2004 at 09:53:47AM -0800, Sean Abrahams wrote: > The following is a reprint of a message I sent to the tutor list a long > time ago, that I haven't gotten around to discussing with anyone else > and failed to hear a reply on the tutor list. Hoping someone here may > want to have some dialog. > > -- > > I'm learning to write unit tests and am trying to write them for a web > application I'm working on. > > I'm currently writing a test that is to purposefully fail by passing > invalid data to a function. However this brought me to thinking about > how to handle errors. > > Let me set up a hypothetical scenario. > > I have a web form with name and age as its two fields. When a person > enters his/her information and submits the form, I take the two fields > and create a dict that contains {'name' : 'Foo', 'age' : '82'}. > > I pass this information to a function called, insertData which > looks something like this: > > def insertData(data): > > # test data for validity > if not data['name'].isalpha(): > raise InvalidDataError(data['name'], "Name contains non-alpha > characters") > if not data['age'].isdigit(): > raise InvalidDataError(data['age'], "Age contains non-digit > characters") > > sql = """ > INSERT INTO people (name, age) VALUES ('%s', '%s') > """ % (data['name'], data['age']) > > executeSQL(sql) The last two statements are not ideal. You probably want: sql = """ INSERT INTO people (name, age) VALUES(%s, %s) """ args = (data['name'], data['age']) executeSQL(sql, args) instead. But that's not what you asked about.. > > I should first check to see if the data is valid, meaning that the > name contains only alpha characters and the age only containing > numeric characters. > > If I raise an exception, how would one handle the reprinting of the > web form with a red * next to the field that contains invalid data? If > one field is in error, I can see that upon receiving an exception you > can have your code just reprint the web form with the red star, but > what about when both fields are in error, do you have the exception > create a list which then your code checks to see if it exists and then > loops through it to know what fields are in error? > > And then again, perhaps I'm completely wrong and am going about this > in an amateur manner. Consider this version of insertData: def insertData(data): errors = {} if not data['name'].isalpha(): errors['name'] = InvalidDataError(data['name'], "...") if not data['age'].isdigit(): errors['age'] = InvalidDataError(data['age'], "...") if errors: raise InvalidFormPostError(data, errors) # Your version, to minimize changes sql = """ INSERT INTO people (name, age) VALUES ('%s', '%s') """ % (data['name'], data['age']) executeSQL(sql) Now full form validation can be attempted, and full information about which fields are erroneous is available. Those fields can be marked, and the rest can be filled out with the values previously entered. Nevow might also be of interest to you. It offloads much of the work of form validation: http://stewstuff.com/doc/nevow.xhtml http://soundfarmer.com/content/logs/NevowLecture11-25-03.txt http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web Jp From bhoel at web.de Sat Jan 3 17:31:35 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sat, 03 Jan 2004 23:31:35 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: Andrew MacIntyre writes: > On Mon, 29 Dec 2003, Berthold H?llmann wrote: > >> so it seems that the other modules loaded in the "make test" run >> decrease the avaliable stack so that the test does not succeed but >> calling the test alone finds enough stack space avaliable? ... > Note that there are some subtleties here - even though your ulimit says > unlimited stackspace, in the presence of threads this may not hold. > It certainly doesn't on FreeBSD 4.x where there the pthreads support has a > hardcoded 1MB stack for the primary thread (which is what is running the I found a document stating it is 2MB for each thread on Linux using Google > regression test and is distinct from the stack created for each > instantiated thread). The LinuxThreads port on FreeBSD seems not to have > the same restriction. Exactly what is happening on your Linux system I > don't know; you would have to do some research to find out. > > Depending on how you wish to proceed, you have a couple of options: > - build normally, then blow away Modules/_sre.o and recompile > Modules/_sre.c with -Os (just temporarily doctor the Makefile). > From what I've seen -Os cuts the stack consumption enough to get > you through the full test suite, and doesn't seriously impact sre's > performance. This does work for me > - modify the USE_RECURSION_LIMIT macro in Modules/_sre.c to a lower value > and rebuild. Linux would be using the default definition of 10000 at > line 98 (for 2.3.3). #define USE_RECURSION_LIMIT 6835 does succeed, #define USE_RECURSION_LIMIT 6840 gives segfault for me. Will submit bugreport. > - find a way to change the default stack size for the primary thread. To be honest: I don't have an idea where to look at for this. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From PeterAbel at gmx.net Fri Jan 16 07:42:47 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 16 Jan 2004 04:42:47 -0800 Subject: Quick question..... References: <379178f1.0401151634.556bb405@posting.google.com> Message-ID: <21064255.0401160442.64a99937@posting.google.com> featherstone80 at hotmail.com (Narsil) wrote in message news:<379178f1.0401151634.556bb405 at posting.google.com>... > I tried that. I get the following error message > > Traceback (most recent call last): > File "E:\python\fun4b.py", line 80, in ? > menu() > File "E:\University\python\assign4b.py", line 49, in menu > print sum(weektotlist) > NameError: global name 'sum' is not defined > > What did I do wrong? > > TomN > > "Batista, Facundo" wrote in message news:... > > featherstone80 wrote: > > > > #- numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] > > #- > > #- How would I get the total, and how would I get the average? > > > > > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > > ... > > >>> numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] > > >>> sum(numberlist) > 174 > > >>> len(numberlist) > 10 > > >>> sum(numberlist)/len(numberlist) > 17 > > >>> from __future__ import division > > >>> sum(numberlist)/len(numberlist) > > 17.399999999999999 > > > > . Facundo As David told you it depends on your Pyhton version, but a sum-function is one-liner in Python: >>> sum=lambda numberlist:reduce(lambda x,y:x+y,numberlist,0.0) >>> # Remark, I use 0.0 as startvalue to force float >>> numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] >>> sum(numberlist)/len(numberlist) 17.399999999999999 >>> Regards Peter From scott.micciche at sbcglobal.net Wed Jan 28 23:11:32 2004 From: scott.micciche at sbcglobal.net (Scott (The Kurgan) Micciche) Date: Thu, 29 Jan 2004 04:11:32 GMT Subject: Web Service in Python References: <87hdyffzlp.fsf@tulip.whu.ca> Message-ID: Try this link: http://pywebsvcs.sourceforge.net/ "Peter Wu" wrote in message news:87hdyffzlp.fsf at tulip.whu.ca... > I'd like to write a Web Service in Python just for my personal interest > now. Is there any reference or document on this? > > -- > ,,, > (o o) Peter Wu > ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From fuf at mageo.cz Thu Jan 29 03:37:46 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Thu, 29 Jan 2004 09:37:46 +0100 Subject: isinstance() bug In-Reply-To: References: Message-ID: <20040129083746.GA27504@foof.i3.cz> Rainer Deyke wrote: >Michal Vitecek wrote: >> it's my belief that if i'm instantiating a class from the same >> location no matter how i imported its definition, its instances are >> always of the same class. > >Your belief is incorrect. 'package.module.A' and 'module.A' are distinct >classes. Modifications to one do not show up in the other. If 'isinstance' >reported that an instance of 'package.module.A' is an instance of >'module.A', 'isinstance' would be broken and unusable. could you elaborate further why do you consider the current behaviour to be correct? you've only described how it works currently. i'd be interested what's the reasoning behind that. i'm inclined to think that the current behaviour is a side-effect of the implementation (perhaps to which some got used to?). -- fuf (fuf at mageo.cz) From jtdubs at eos.ncsu.edu Sat Jan 24 01:02:55 2004 From: jtdubs at eos.ncsu.edu (Justin Dubs) Date: 23 Jan 2004 22:02:55 -0800 Subject: pty difficulties Message-ID: <2e262238.0401232202.5b21eba8@posting.google.com> I'm writing a utility that runs a program inside of a pseudo-tty and then multiplexes both stdin and a fifo to the child's pty via a select loop. In other words, you run my program, tell it the name of the program to run and the name of the fifo to use and then you can interact with the program as per usual. However, you can also send data into the fifo and the program will see it as input just as if you'd typed it on the keyboard. As a test I'm running sbcl (a lisp interpreter) through my python program. It works like a charm in normal usage. However, if I dump more than 2K or so of code into the FIFO, sbcl gets the first K fine, but then seems to miss a chunk, get another character or two and then freeze. After that I am unable to interact with it via either stdin or the fifo even though the select loop is still running. The pty just seems to be dead, eating input and giving nothing back. So, I tried running a different Lisp interpreter (openmcl) instead, but the problem persisted. So, I just ran vim through it and it handled the 2K of text just fine. However, vim is just sending the text into a buffer where-as sbcl is parsing and compiling it. If I add a sleep(1.0) after data is sent from the fifo to the pty then the problem goes away. So, it seems like if the child process can't pull things out of it's stdin as fast as I'm putting it in, something goes awry. Has anyone seen similar behavior? Does anyone have any idea why this would be happening? Any help would be greatly appreciated. Thanks everyone. The code is below. Justin Dubs Here's the code: from time import sleep from pty import spawn, fork from sys import stdin, stdout, stderr, exit, argv from os import fdopen, open, read, write, O_RDONLY, O_NONBLOCK from select import select from termios import tcgetattr, tcsetattr, tcdrain, ECHO, TCSADRAIN from tty import setraw if (len(argv) != 3): print "usage: vee.py program pipe" exit(0) pid, childID = fork() if pid == 0: spawn(argv[1]) else: fifo = fdopen(open(argv[2], O_RDONLY | O_NONBLOCK), 'r') child = fdopen(childID, 'r+') attribs = tcgetattr(stdin) attribs[3] = attribs[3] & ~ECHO tcsetattr(stdin, TCSADRAIN, attribs) setraw(stdin) connections = { child : stdout, stdin : child, fifo : child } try: while True: readable = select(connections.keys(), [], [])[0] for f in readable: data = read(f.fileno(), 1024) connections[f].write(data) connections[f].flush() except (OSError, IOError): exit(0) From gerrit at nl.linux.org Fri Jan 23 11:54:15 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 23 Jan 2004 17:54:15 +0100 Subject: get "yesterday's" date in iso format In-Reply-To: <877jzjb7o4.fsf@mrbun.watterson> References: <877jzjb7o4.fsf@mrbun.watterson> Message-ID: <20040123165415.GB4137@nl.linux.org> Tim Heaney wrote: > necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com writes: > > > > I am trying to find a simple way to get "yesterday's" date. > > Since time.time() gives the time in seconds since the epoch, you could > just subtract a day from that to get yesterday. Even better: >>> from datetime import date, timedelta >>> (date.today() - timedelta(1)).day 22 yours, Gerrit. -- 179. If a "sister of a god," or a prostitute, receive a gift from her father, and a deed in which it has been explicitly stated that she may dispose of it as she pleases, and give her complete disposition thereof: if then her father die, then she may leave her property to whomsoever she pleases. Her brothers can raise no claim thereto. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jepler at unpythonic.net Sat Jan 3 23:01:28 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 3 Jan 2004 22:01:28 -0600 Subject: Advanced (?) compiling, freezing, translating Python In-Reply-To: <312735AC.3841CC26.0331AA34@netscape.net> References: <312735AC.3841CC26.0331AA34@netscape.net> Message-ID: <20040104040128.GA18000@unpythonic.net> Here's one more link to add to the list of things that aren't what you're looking for: http://www.strout.net/python/ai/ (at the "python2c" heading) Jeff From bkelley at wi.mit.edu Mon Jan 26 19:27:55 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 27 Jan 2004 00:27:55 GMT Subject: wxpython and wxlocale In-Reply-To: References: Message-ID: Jarek Zgoda wrote: > Ya pisze: > > >>Is there any way of telling python that the text of the dialogues is in a >>specific language? >>And in affirmative case. How is it made? since all the attempts have been >>useless. >>I think that wxLocale has to be used, but I do not become clear. > > > loc = wx.Locale() > loc.Init(wx.LANGUAGE_POLISH) > > Et voila, your program uses Polish dialogs. > And if you want to internationalize your OWN dialogs: http://wiki.wxpython.org/index.cgi/Internationalization Brian From jsbenson at bensonsystems.com Wed Jan 14 16:04:53 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 14 Jan 2004 13:04:53 -0800 Subject: Lua versus C++ for embedded processor Message-ID: <024101c3dae2$0e68d040$8d09500a@jsbwxp3> Regarding the message appended below: I was in a similar situation, only I had 4 "small" (RAM-wise) legacy processors in a fault-tolerant Tandem K100 system. The system came with an old Borland C++ compiler but I didn't want to become an expert in anachronistic C++ trivia, so I ported Lua (www.lua.org) using the perfectly serviceable C compiler. Although I still need to put in library extensions to access the Tandem's Guardian OS API, Lua came up quick and easy, gave me object-oriented scripting and provided access to the applicable portion of the C Standard Library. I've programmed Z-World Z-180-based embedded microcontrollers in their Dynamic C language, and will be using their products again but I'm seriously considering porting Lua in via Dynamic C so I can have object-oriented scripting to facilitate prototyping and systems integration work. Whether it will work out in this case is not clear yet, but the Tandem port worked fine. Maybe Lua has a place in your embedded application, if there isn't enough infrastructure for Python. As for C++ on microcontrollers, I have absolutely no idea what the pros and cons are. Any ideas out there on whether C++ is a good fit there? Message: 5 Date: Wed, 14 Jan 2004 11:16:48 -0500 From: Peter Hansen Subject: Re: I come not to bury C++, but to praise it... To: python-list at python.org Message-ID: <40056B70.3E04217B at engcorp.com> Content-Type: text/plain; charset=us-ascii Cameron Laird wrote: > > I was still fussing with cfront in the early '90s. > Its era *had* passed by then, though. And I actually went looking for it again as recently as two years ago, considering the possibility of using it to allow the use of C++ code for a small embedded processor which did not have an available C++ compiler. I actually don't remember precisely why we didn't try it out, and I assume we simply got distracted by having to make things work and forgot to continue the search. Can it be used as a front-end for such chips, where at best there are two or three C compilers on the market? -Peter From lvrk at yahoo.com Sun Jan 4 19:00:03 2004 From: lvrk at yahoo.com (Raghav Lagisetty) Date: 4 Jan 2004 16:00:03 -0800 Subject: Let users execute but not view References: Message-ID: Hi Florian, Check this link from Python's programming FAQ to create compiled code from .py files: http://www.python.org/doc/faq/programming.html#how-do-i-create-a-pyc-file The "dis" module can be used to disassemble and examine this byte code. But creating a .pyc file should suffice your requirements. -Raghav. Florian Lindner wrote in message news:... > Hi! > I have a python script which should be executed my normal users but they > should not be able to view the sourcecode. Setting permissions to x only > does not help, the python interpreter can not read the file. > How can I do that? > Thanks, > Florian From paulpaterson at users.sourceforge.net Wed Jan 28 02:05:13 2004 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Wed, 28 Jan 2004 07:05:13 GMT Subject: Python on portable storage References: Message-ID: "Jeff Epler" wrote in message news:mailman.832.1075174501.12720.python-list at python.org... > One idea would be a directory structure that looks like the source tree: > > python23/python # linux executable > python23/python.exe # windows executable > python23/Lib # shared version of /usr/lib/python2.3 > python23/Lib/site.py # modify this to add any extra tweaks needed for > # things to work properly (it's loaded very early) > python23/Lib/plat-linux # linux shared-object modules > python23/Lib/plat-win32 # win32 shared-object modules > > In this setup, you are assuming some set of Linux shared objects, use > ldd to find out which. (A script setting LD_LIBRARY_PATH to point at > necessary libraries before calling python could help here) > > If you want to support multiple Unix architectures, make python a > shell script, and include multiple python.ARCH binaries. Have the shell > script determine the architecture, and then exec python.ARCH with > arguments intact. This should not affect the way Python determines the > default sys.path. > > I don't know much about windows .dll requirements or how to resolve > problems there. I can't add to the Linux part but I have Python23 installed on a USB keychain drive to run on Windows alone. I just installed using the standard Windows installer into a Python23 directory on the USB drive. You also need to make sure Python23.dll ends up in the Python23 directory, probably by manually copying it. Then to get it all to work properly I have a little batch file in the root of the USB drive with the following, ---- setup.bat ---- echo Setting Path path = %1:\python23;%1\python23\lib;%1:\python23\lib\site-packages;%1:\python23\dll s set pythonpath = %1:\python23 ---- end ---- When you mount the USB drive you open a command prompt and CD to the root of the USB and type "setup X" where X is the drive letter assigned to the USB drive. You can now run Python by just typing "python" at the command prompt. This works for me. You have to be a bit careful if you already have Python installed on the machine as sometimes sys.path includes parts of the existing installation even after you run the batch file. I think this might be something to do with stuff in the registry. Hope this helps. It is cool to keep a Python in your pocket. Paul From daniels at dsl-only.net Fri Jan 2 01:01:12 2004 From: daniels at dsl-only.net (sdd) Date: Thu, 01 Jan 2004 22:01:12 -0800 Subject: NEWBIE: map | zip | list comp In-Reply-To: References: Message-ID: <3ff514db$1@nntp0.pdx.net> engsolnom at ipns.com wrote: > ... > > for char_1 in base_seq: # Loop thru the set char_1 at a time > for char_2 in base_seq: # Loop thru the seq again for each char_1 > if char_2 == char_1: continue # Don't march 'A' thru a field of 'A's > for ix in range(length): # Now march char_2 thru a field of char_1's > print (char_1 * length)[:ix] + char_2 + (char_1 * length)[ix:-1] > which, as you can see, has three nested FOR loops. I played with map, zip and list comps a bit, but > couldn't figure out how to compress the above code. Am I barking up the wrong Python tree? I'd think so. The 3-level nest looks fine (clear) to me. The things I might change about the above code: for char_1 in base_seq: copies = char_1 * (length-1) for char_2 in base_seq: if char_2 != char_1: # For every pair of non-matching characters for ix in range(length): # March char_2 thru a field of char_1's print copies[:ix] + char_2 + copies[ix:] or: for char_1 in base_seq: for char_2 in base_seq: if char_2 != char_1: # For every pair of non-matching characters for ix in range(length): # March char_2 thru a field of char_1's print char_1 * ix + char_2 + char_1 * (length-1-ix) The point is to go for clarity, not brevity. I'd think about better names than char_1 and char_2, however. -Scott David Daniels Scott.Daniels at Acm.Org From max at alcyone.com Wed Jan 14 15:03:23 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 14 Jan 2004 12:03:23 -0800 Subject: pulling set of unique values from a list References: <400551c0$1@baen1673807.greenlnk.net> Message-ID: <4005A08B.56B4EE9C@alcyone.com> Ben Davies wrote: > personally I prefer the dictionary one-liner, but with the second > iterative > way it is probably more obvious what the code is doing (and perhaps > more > efficient?). No, the dictionary method is more efficient. The list-using algorithm has O(n^2) behavior, whereas the dictionary-using algorithm is only O(n). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ You can't expect to win unless you know why you lose. -- Benjamin Lipson From kkto at csis.hku.hk Sun Jan 25 21:14:48 2004 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 26 Jan 2004 10:14:48 +0800 Subject: xrange not hashable - why not? References: <20040125144724.GA13741@nl.linux.org> Message-ID: <7ifze3sbfr.fsf@enark.csis.hku.hk> >>>>> "Andrew" == Andrew MacIntyre writes: >> why is an xrange object not hashable? Andrew> xrange() returns an iterator. iterators seem universally Andrew> unhashable, probably because they can't be deemed "concrete", Andrew> though I can't find anything in the 2.3.3 docs about this - Andrew> perhaps the relevant PEPs might. xrange's are hashable in Python 2.3. >> I was trying to do something like: >> >> comments = { xrange(0, 4): "Few", xrange(4, 10): "Several", >> xrange(10, 100): "A lot", xrange(100, sys.maxint): "Can't count >> them"} for (k, v) in comments.items(): if n in k: commentaar = v >> break Andrew> Even if it worked, there's a nasty performance trap in the Andrew> sys.maxint case: if the sys.maxint case is the first returned by Andrew> the items() method call and n < 100, the "in" will evaluate the Andrew> sys.maxint xrange iterator. I used to think that the code won't work at all. I think xrange works like generators. If that is the case, the state stored within the xrange in the dict will cause the whole thing to fail if the same range is used the second time. E.g., >>> def yrange(x,y): ... ret = x ... while ret < y: ... yield ret ... ret += 1 ... >>> for a in yrange(1,5): ... print a ... 1 2 3 4 >>> comments = { ... yrange(0, 4): "Few", ... yrange(4,10): "Several", ... yrange(10,100): "A lot", ... yrange(100, sys.maxint): "Can't count them"} >>> for (k,v) in comments.items(): ... if 1 in k: ... print v ... break ... Few >>> for (k,v) in comments.items(): ... if 1 in k: ... print v ... break ... (type interrupt here after waiting for some time) Traceback (most recent call last): File "", line 2, in ? File "", line 5, in yrange KeyboardInterrupt But for xrange this is not the case: >>> comments = { ... xrange(0, 4): "Few", ... xrange(4, 10): "Several", ... xrange(10, 100): "A lot", ... xrange(100, sys.maxint): "Can't count them"} >>> for (k,v) in comments.items(): ... if 1 in k: ... print v ... break ... Few >>> for (k,v) in comments.items(): ... if 1 in k: ... print v ... break ... Few So xrange is not just an iterator. On the other hand, things like 1000000 in xrange(1,sys.maxint) really needs a long time to compute. That makes me wonder how xrange's are actually implemented. Regards, Isaac. From ryan.scott at sympatico.ca Tue Jan 20 21:54:02 2004 From: ryan.scott at sympatico.ca (Ryan Scott) Date: Tue, 20 Jan 2004 21:54:02 -0500 Subject: PyTime Object and Application Crashing Message-ID: <9RlPb.13768$U77.890295@news20.bellglobal.com> Hi, When I run a query against an access database and the default date for my date/time field is 12/30/1899 the application crashes. Changing this to a different date like 03/03/2003 works. The output of the query when returned as a list is as follows: [571, u'DE8', , , 0. 079999998211860657, u'1 - Litter in sample', u'', False, 10.0, 0.0] When I try to print item 4 (list[3]) of the list, the application stops and I get a "Send Error Report" in Windows XP. I am using python 2.3.3 and the win32all-163 extension. Thanks Ryan From robin at jessikat.fsnet.co.uk Sat Jan 10 06:17:11 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 10 Jan 2004 11:17:11 +0000 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> <6AlLb.134$hd.7718@news2.e.nsc.no> <3FFEB6D6.BF92551E@engcorp.com> <+vXesJAXsr$$EwJL@jessikat.fsnet.co.uk> <3FFEBE42.80962511@engcorp.com> Message-ID: In article , Jane Doe writes >On Fri, 09 Jan 2004 09:44:18 -0500, Peter Hansen >wrote: >>I get at least a temporary "server not found" error when I try that name. > >http://snakelets.sourceforge.org/ > >("We're Sorry. The SourceForge.net Website is currently down for >maintenance. We will be back shortly) :-) > >JD. whoops, my bad :( -- Robin Becker From tim.one at comcast.net Tue Jan 13 22:35:31 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 13 Jan 2004 22:35:31 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401131633.31ee5a60@posting.google.com> Message-ID: [Aaron Watters] > Alright, just for yucks. > Total blood supply must be kept above 50 except during emergencies. > Two transactions notice that there are 40 in bin 1 and 40 in bin two, > so one takes 30 units from bin 1 and the other takes 30 units from > bin 2. If you want to do this with ZODB, the first thing I'd recommend is that you simply refrain from writing your app to perform concurrent transactions. The "I" in ACID you're on about here works the way you want it to then. BTW, unless you're also using ZEO, you can't open a ZODB database in more than one process at a time, so it takes some work on your part for concurrent transactions to be possible. If this is the only blood supply in the country, thousands of hospitals hook up to it over the net, and you need the performance true concurrency can provide, then you've got more work to do. Easiest would probably be to treat it like your checking-account example, adding a member to the "blood supply" class recording total units of blood on hand. Then it's exactly like your checking-account example, and the same strategies apply (meaning you'll get a ConflictError on all but the first to commit of a batch of concurrent transactions trying to withdraw blood, and, if it's not good enough for your performance needs to retry failing transactions, you can go on to supply a conflict resolution method that suppresses the ConflictError whenever the total remaining exceeds 50 units; then the only transactions that fail would be those that truly require dropping the total to <= 50 units). I'll note here that ZODB holds Python objects of arbitrary user-defined classes, so the idea of adding class invariants is quite natural. > Or even return to the original problem assuming that the balance > doesn't change but the debits are entered as separate journal > entries, where the current balance is computed on the fly as the old > balance less withdrawals... You can figure this out on your own, if you want to use ZODB to solve it. > Sorry, I just don't know when to shut up, I know. But when I see > ACID I assume these things are not a problem. No matter how often the world disappoints you <0.9 wink>? > ps: Tim anticipated this reply in his post somewhat, but wasn't > concrete enough for my taste. I'm not a DB expert -- I don't even talk the talk. If you want to accomplish something with ZODB, though, I can usually help (if only by reminding you of the zodb-dev list, where you're conspicuous by absence ). From spam_no_thx_ei0stjo at chl.chalmers.se Mon Jan 5 10:49:56 2004 From: spam_no_thx_ei0stjo at chl.chalmers.se (Jonas) Date: Mon, 05 Jan 2004 16:49:56 +0100 Subject: problem with async chat client in windows In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Mon, Jan 05, 2004 at 03:02:29AM +0100, Jonas wrote: > >>Hi, >>I'm writing a small chat client to learn some python and networking. No >>problem with the network stuff tho, the problem is when the user should be >>able to interact and type messages to send. Since I work with windows I >>can't use the select function > > > Why not? select works perfectly well on Windows. > > See http://www.twistedmatrix.com/ > > Jp > Well the standard library select doesn't work for file descriptors like stdin on windows and I didn't know about Twisted. Anyway there must be some way to solve this without the need for extra depencencies?? From engsolnorm at ipns.com Mon Jan 26 01:08:05 2004 From: engsolnorm at ipns.com (engsol) Date: Sun, 25 Jan 2004 22:08:05 -0800 Subject: delta time = time stop - time start Message-ID: I'm using Python to parse a bunch of s/w test files and make csv files for later report generation by MS ACCESS....(my boss loves the quick turn-around compared to C). Each log file may contain one or more 'sessions', and each session may contain one or more 'nodes'. Each session in the log has an ASCII start and stop time, as does each node. I have the basic parse part done for parameters, errors, etc., but noticed my routine for determining how long each session/node took (delta time) was a bit repetitive, so decided to make a 'stand-alone' routine to handle this. The time format from the log is in the format of: hh:mm:ss and is a string with leading zeros where appropiate. Date is never a factor. The longest "delta" is maybe 5 hours. The routine I came up with is below, but seems a bit clunky. Is there a better way of doing this? I think it relies too much on integers rounding off in the proper direction, a la d_time_hr = d_time / 3600 below. Also, this will have to transition to Linux, if that makes a difference. START CODE: import string def deltatime(start, stop): t_start = (string.atoi(start[0:2]) * 3600) + (string.atoi(start[3:5]) * 60) + string.atoi(start[6:8]) t_stop = (string.atoi(stop [0:2]) * 3600) + (string.atoi(stop [3:5]) * 60) + string.atoi(stop [6:8]) if t_start < t_stop: d_time = t_stop - t_start else: d_time = (86400 - t_start) + t_stop d_time_hr = d_time / 3600 d_time_min = (d_time - d_time_hr * 3600) / 60 d_time_sec = (d_time - d_time_hr * 3600) - (d_time_min * 60) return str(d_time_hr) + 'hr ' + str(d_time_min) + 'min ' + str(d_time_sec) + 'sec' END CODE TRY IT print deltatime('23:45:00', '02:55:03') RETURNS 3hr 10min 3sec Thanks.....Norm PS Please reply via email (engsolnorm at hotmail.com) until my ISP gets fixed. From seanl at chaosring.org Tue Jan 6 02:04:47 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Mon, 05 Jan 2004 23:04:47 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: Ok, so how do I handle overriding methods? Allowing code that inherits from a class to override any method it can access could result in security problems if the parent doesn't expect a given method to be overridden. Shadowing the overridden method could result in unexpected behavior. And, of course, in some cases, we *want* to allow the programmer to override methods, because this is what code reuse is all about. I already have a solution in mind for __init__: provide another method that is always called on every superclass for any object that is created from a class that inherits from that superclass. The method takes no arguments and is called after __init__. Another option is to simply not provide any protection from inheriting classes. The more I think about it, the better this sounds. Classes don't contain any data other than perhaps class data, and a programmer shouldn't be allowing another programmer to subclass classes that contain data they want to protect. I could put all attributes back to being protected (rather than private) by default, and only have a single extra declaration required in a class statement to declare what attributes you want to make public. Can anyone (Serge?) think of an example of a case where this might cause leaks or privilege escalation? Remember that classes are opaque, so code can't get at unbound methods. Subclassing a class doesn't give you any special access to members of that class. From gnari at simnet.is Sun Jan 25 07:20:54 2004 From: gnari at simnet.is (gnari) Date: Sun, 25 Jan 2004 12:20:54 -0000 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: "Xah Lee" wrote in message news:7fe97cc4.0401242131.22acf485 at posting.google.com... > Just bumped into another irresponsibility in perl. > [snipped rand about File::Basename docs] > ... > Why the fuck do i need to know what is version, or examination what?? > Not every morons in this world is using unix with its morinic > convention of appending things to file names as a versioning system, > and not every moron in this world need to "exam" things. you are right. the docs do not seem to address the needs of morons. there sould be a shorter version of the docs, specially for morons, with each example if larger font, repeated 10 times. > To the rookie programers out there, i advice against learning Perl. > (i suggest Python instead) Please see > http://xahlee.org/UnixResource_dir/perlr.html thank you gnari From tim at lesher.ws Mon Jan 19 11:45:45 2004 From: tim at lesher.ws (Tim Lesher) Date: 19 Jan 2004 08:45:45 -0800 Subject: A lazy-committing database object with curry? Message-ID: I'm writing a database helper class that represents records in a SQL database as objects. I want to be able to instantiate the objects (from the database), play with their values locally, then lazily commit the changes all at once (via an explicit commit call). Other than the call to Commit(), I don't want clients of this class to have to think about the fact that there's a database behind it all--there are some interesting and non-obvious dependencies on the particular values that are committed together, and I want to hide that in the Commit() call. I'm going to have a number of these, so I wanted to come up with a solution that's short on glue code and can easily be aggregated into all the classes that represent record types. This is what I've come up with: # Simple currying class, no kwargs class curry: def __init__(self, fun, *args): self.fun = fun self.pending = args[:] def __call__(self, *args): return self.fun(*(self.pending + args)) # Simple table: two columns, "title" and "description" class SomeRecordType(object): def __init__(self, title, description): self.__modifications = {} # Avoid triggering propset on init self.__dict__['title'] = title self.__dict__['description'] = description def __getValue(name, self): try: return self.__modifications[name] except KeyError: return self.__dict__[name] def __setValue(name, self, newValue): self.modifications[name] = newValue name = property(curry(__getValue, 'title'), curry(__setValue, 'title')) description = property(curry(__getValue, 'description'), curry(__setValue, 'description')) def Commit(self): if self.modifications != {}: # - snip - Do database commit and clear modifications self.__dict__.update(self.modifications) self.modifications = {} So I can do this: foo = myDb.LookupTitleRecord('some title') print foo.description # 'foo' foo.description = 'bar' # not updated in the DB yet print foo.description # 'bar' foo.Commit() # now updated in the DB Are there any pitfalls to doing this? Am I being dazzled by the shiny new toy that is currying? Is there another simple solution, or a refinement of this one, that I'm not seeing? Thanks. -- Tim Lesher From martin at v.loewis.de Sun Jan 4 15:30:49 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 04 Jan 2004 21:30:49 +0100 Subject: codecs packages? In-Reply-To: References: Message-ID: Fortepianissimo wrote: > I'd like to decode some email headers into unicode, including some > Asian DBCS. I've searched several places and they pointed to the > Python Codecs project @ SF > (http://sourceforge.net/projects/python-codecs/), but I couldn't find > anything there. Could someone give me a pointer to any related > library? I recommend to use the cjkcodecs package, at http://cjkpython.i18n.org/#CJKCodecs (atleast, it ought to be there - cjkcodecs appears to change its home page with each release). Regards, Martin From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Mon Jan 12 11:21:05 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 12 Jan 2004 18:21:05 +0200 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: >>>>> "Bicho" == Bicho Verde writes: Bicho> I have now free time and money to do what I want :-) I have Bicho> some basic skills in programming (C, Pascal, Macromedia Bicho> Actionscript) but don't know exactly what to do in the Bicho> world of programming. And also I don't know exactly why Bicho> would I learn Python rather than C#, C++ or Perl. Basicaly Well, I assume you want to have fun programming, and that kinda rules out C# and (especially) C++. They don't really have the favourable effort/gratification ratio of Python. If you want to get something done, choose Python. If covering your ass if/when your project fails is more important than actually succeeding, choose more conservatively, which means Java/C++/C#. Since you are on your own in this, Python is an excellent choice. If you choose Perl, you will at some regret your choice and consider porting the app to Python. You save a lot of time/frustration by not going there in the first place. Bicho> I don't know where to start, if there is much to do or if Bicho> it is has it seems and there is software to everything Bicho> nowadays and so doesn't make sense to spend time in Bicho> learning a programming language. I just have this idea There really isn't software to do all those little script-level tasks you need to do every now and then, so learning Python is still not a lost cause even if you never get anything bigger done. Also, writing a Python script is often faster than searching for a program to do the thing and then learning how to use that program. It's also more fun. Bicho> that I would like to contribute to the curve of accelarated Bicho> exponential progress (technological singularity), Bicho> artificial intelligence and so on. From that point of view Bicho> there is much to do... But can I stand for it and where to Bicho> start? Anyone would help me and give me some hints? Learn Python first, the ease of programming can quite possibly inspire you to create something interesting. -- Ville Vainio http://www.students.tut.fi/~vainio24 From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jan 5 18:27:06 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 06 Jan 2004 00:27:06 +0100 Subject: local interpreter remote machines In-Reply-To: <3FF9EF41.8040804@hotmail.com> References: <3ff9e4b8$0$318$e4fe514c@news.xs4all.nl> <3FF9EF41.8040804@hotmail.com> Message-ID: <3ff9f2cb$0$324$e4fe514c@news.xs4all.nl> hokiegal99 wrote: > Irmen de Jong wrote: > [...about Pyro...] > Thank you, this is exactly what I was looking for! While Pyro may be of help (I'm sure it will be ;-) you should not forget that there are many other ways to do what you want. For instance, you could also create a simple web server application on the remote machine that has a page on which those data about the remote machine are written. You can then get the data from the web page using the urllib module. For really good advice you will have to tell a lot more about what you want exactly (and how it should work)... Good luck! --Irmen From rainerd at eldwood.com Tue Jan 6 14:47:26 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 06 Jan 2004 19:47:26 GMT Subject: looping to define a sequence of functions? References: Message-ID: r.e.s. wrote: > Suppose we want to define ten functions such that the > nth function of x simply returns x**n. Is there a way > to avoid explicitly writing ten function def's? (They > have to be ten distinct functions, not just a single > one like def f(n,x): return x**n.) functions = [lambda x, n=n: x**n for n in range(10)] -or- class X(object): def __init__(self, n): self.n = n def __call__(self, x): return x ** self.n functions = [X(n) for n in range(10)] -or- functions = [] for n in range(10): def f(x, n=n): return x**n functions.append(f) -or- def create_function(n): def f(x): return x**n return f functions = [create_function(n) for n in range(10)] -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From shalabh at gameboard.org Fri Jan 30 20:26:17 2004 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: 30 Jan 2004 17:26:17 -0800 Subject: TCP server as a Windows service using Python? References: Message-ID: David Mitchell wrote in message news:... > Hello group, > > I'm trying to create a TCP server using Python, and I want it to run under > Windows as a service. ... > I can't see how to let the service accept *either* an incoming TCP client > connection *or* an e.g. "stop service" message. If someone could point me > to some sample code, I'd greatly appreciate it - Google hasn't been > helpful. An alternative solution might be to split the functionality into two processes. The Windows service launches a second (TCP server) process, which it later kills upon being asked to stop. -- Shalabh From sprouts at xpress.se Fri Jan 16 11:05:44 2004 From: sprouts at xpress.se (Mikke Mattsson) Date: 16 Jan 2004 08:05:44 -0800 Subject: Numeric host name error (socket, win32) Message-ID: <867a19af.0401160805.74df8a78@posting.google.com> Does anoyne know how to get the socket-module to resolve numerical hostnames? The host address is not resolved correctly. >>> import socket >>> socket.getaddrinfo("3100",21) [(2, 2, 17, '', ('0.0.12.28', 21))] If I ping the computer from a dos-prompt, I get the correct address (192.168.65.3) From python at hitmedia.com Fri Jan 30 15:06:42 2004 From: python at hitmedia.com (Python Baby) Date: Fri, 30 Jan 2004 12:06:42 -0800 Subject: easiest transition for a PHP website to move to Python? In-Reply-To: <20040130055251.GA9734@mail.hitmedia.com> References: <20040130055251.GA9734@mail.hitmedia.com> Message-ID: <20040130200642.GA60408@mail.hitmedia.com> Thanks for your replies, everyone. You're right that WebWare looks cool, but more importantly I'm VERY VERY impressed with Cheetah! http://www.cheetahtemplate.org/ That has the nicest syntax of any template system I've ever seen! On Thu, Jan 29, 2004 at 09:52:51PM -0800, I wrote: > I've got a database-driven website that's written entirely in PHP. > It's all pretty MVC : NOT embedded little calls inside HTML, but > rather little controller apps in the webroot that merge data with > HTML templates on the fly. > But for various reasons (mostly fun) I want to rewrite it in Python. > There are so many different approaches, though! Zope, Twisted, > mod_python, clearsilver, and all the goodies in standard library. > What would be the SMOOTHEST TRANSITION for a newbie like me to > rewrite my PHP+MySQL website to Python? From paradisejourney at hotmail.com Tue Jan 20 09:41:54 2004 From: paradisejourney at hotmail.com (aj) Date: 20 Jan 2004 06:41:54 -0800 Subject: dependent pull downs Message-ID: <14ba0c0.0401200641.22650fa7@posting.google.com> hi everyone i am writing my first web application i wanna have dependent (nested) pull-downs that allow the set of values displayed in one pull-down to be determined by the values selected in another pull-downs. how can this be done?? can application framework simplify this.if so which ones?? From premshree_python at yahoo.co.in Tue Jan 27 08:48:02 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 27 Jan 2004 13:48:02 +0000 (GMT) Subject: makeExe.py In-Reply-To: <40156EC7.27EFC3F6@engcorp.com> Message-ID: <20040127134802.27165.qmail@web8302.mail.in.yahoo.com> > if you're interested > in integrating the > changes, and maintaining it, I'll forward our own > script which you can > pull apart and reuse as required... I'd be interested in that. --- Peter Hansen wrote: > Premshree Pillai wrote: > > > > Wrote a simple Python script that makes life a wee > bit > > easier when using py2exe: > > > > """ > > makeExe.py > > - Simple Python script to automate the creation > > of Python executables using py2exe. > > > [snip] > > fp = open("setup.py","w") > > temp = """from distutils.core import setup > > import py2exe > > setup(name = "%s", > > scripts = ["%s"], > > )""" % (package,fileName) > > fp.write(temp) > > fp.close() > > You could save yourself a fair bit of trouble, and > avoid writing a > "setup.py" file to the filesystem (possibly > overwriting an existing > one which might be important) by just calling the > setup() method > directly yourself. The only trick is that it checks > sys.argv[] for > the "py2exe" argument, so you have to fake that > first: > > sys.argv[1:] = ['py2exe'] > > from distutils.core import setup > setup(name=package, > scripts=[fileName]) > > That should do the trick.... if you're interested > in integrating the > changes, and maintaining it, I'll forward our own > script which you can > pull apart and reuse as required... > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From pinard at iro.umontreal.ca Thu Jan 1 11:02:18 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 1 Jan 2004 11:02:18 -0500 Subject: RELEASED: allout-vim 031229 In-Reply-To: References: Message-ID: <20040101160218.GA4090@titan.progiciels-bpi.ca> [Alexander Schmolck] > Fran?ois Pinard writes: > > In French, we easily use "formidable" to describe a girl who is > > wonderfully sympathetic and/or attractive. > I think sympathetic is another of those false friends :) Indeed, thanks!! I just looked it up in a dictionary... I meant "friendly" or "nice" (yet "nice" is a bit ambiguous). One may likely translate French "formidable" with English "fantastic": Python is fantastic. Python, c'est formidable! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From bkelley at wi.mit.edu Tue Jan 13 09:51:49 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 13 Jan 2004 09:51:49 -0500 Subject: py2exe, Inno Setup, and tkinter In-Reply-To: References: Message-ID: <400405a0$0$563$b45e6eb0@senator-bedfellow.mit.edu> Thomas Heller wrote: > Are you sure your installer reproduces the same directory structure as > the dist directory has? > The short script I sent reproduces the same directory structures with innosetup. > I would expect the init.tcl in this directory: > > c:/Program Files/shtoom/tcl/tcl8.4/init.tcl > > Thomas Brian From newsgroups at jhrothjr.com Mon Jan 5 18:35:05 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 5 Jan 2004 18:35:05 -0500 Subject: PRE-PEP: new Path class References: Message-ID: "Mike C. Fletcher" wrote in message news:mailman.118.1073338659.12720.python-list at python.org... > John Roth wrote: > ... > > >1) Should path be a subclass of str? > > > >No. Outside of the difficulty of deciding whether it's a > >subclass of single byte or unicode strings, it's a pure > >and simple case of Feature Envy. Granted, there will > >be times a developer wants to use string methods, but > >the most common operations should be supported directly. > > > > > It's not the methods that make me want to use str/unicode as the base, > it's the ability to pass the resulting instances to built-in methods > that explicitly expect/require str/unicode types. Not sure how many of > the core functions/libraries still have such requirements, but I'd guess > it's a few. > > That said, I don't mind making path it's own base-class, I just *really* > want to be able to pass them to path-unaware code without extra coercian > (otherwise switching a module to *producing* paths instead of raw > strings will cause the *clients* of that module to break, which is a > serious problem for rapid adoption). That's an excellent point, but it begs the question of which string class it should subclass. Unless it's got some way of changing its base class depending on the system it's running on. That, in turn, probably violates the Principle of Least Astonishment. > >5) Should == operator be the same as os.path.samefile()? > > > >Why not... > > > > > __eq__ sounds about right. I gather this call goes out to the > filesystem first, though. Might be good to first check for absolute > equality (i.e. the same actual path) before doing that. I think this has to do with "conceptual integrity." Are we talking about a path object that happens to have the ability to do file system operations in appropriate circumstances, or are we talking about a file system object that includes all of the usual path manipulations? You seem to be thinking of the first approach, and I'm thinking of the second. You're beginning to convince me, though. > >7) Should the various gettime methods return Datetime > >objects. > > > >Of course. > > > > > What are we doing for Python 2.2 then? I agree with the principle, but > we should likely have a fallback when datetime isn't available. Do we care? If this is going into Python, it will be in 2.4 at the earliest, with a possible addon to a late 2.3 release. I don't see it going into 2.2 at all, although a backwards version would be nice. > >10) Commonprefix, walk and sameopenfile? > > > >Commonprefix should be a string or list method, > >it doesn't fit here. > > > > > Path commonprefix are different operations from str commonprefix. Paths > should only accept entire path-segments (names) as being equal, while > strings should accept any set of characters: > > '/this/that/those/them' > '/this/thatly/those/them' > > should see '/this/' as the commonprefix for the paths, not '/this/that'. Good point if you're thinking of heterogenous collections. If you're thinking (as I am) that an object can represent a directory, then it seems like a singularly useless method. > >walk is a nice function, but it should be redone to > >use the visitor pattern directly, with different method > >names for files, directories and whatever else a > >particular file system has in it's warped little mind. > Reworking walk is probably a good idea. I'll let others worry about it, > as I've re-implemented the functionality so many times for my own code > that I'm just sick of it :) . I can understand that. [grin] > >13) chdir, chmod, etc? > > > >No. This has nothing to do with pathname. > > > > > chmod has to do with altering the access mode of a file/directory by > specifying it's path, no? Seems like it could readily be a method of > the path. Right. I forgot that these are two totally different issues. > chdir should accept a path, otherwise doesn't seem like it > should be a method. If the path object describes a directory, then I'd see a .chdir() method as useful. Otherwise, it belongs somewhere else, although I don't have a clue where at the moment. > > Enjoy all, > Mike John Roth From kim at lignus.dk Fri Jan 23 09:48:49 2004 From: kim at lignus.dk (Kim Petersen) Date: Fri, 23 Jan 2004 15:48:49 +0100 Subject: Help and optimization hints, anyone? References: <87d69a6e2j.fsf@pobox.com> Message-ID: Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee: > Kim Petersen writes: > >> I've worked on this table object a bit too long - and seem to have >> stared too long at the code. Can someone see where it goes wrong in >> the insertrow function? > > I made a few comments before I realised it was a Tkinter question, so > no answer, sorry! Just some style hints. thx. no problem tho - i should've remembered. >> >> class UserDict: > > Bad name -- UserDict is a standard library module. In 2.2 or newer, > you can subclass dict. In 2.3, you also have the option of > subclassing UserDict.DictMixin. If you just want to implement part of > the maping interface, just call your class something other than > UserDict -- say SimpleDefaultDictBase. > Actually i was planning to use the standard UserDict (basically because a class is hashable and dict isn't) - i got carried away and put some default handling in it as well - but didn't rename ;-) > > dict is also a bad name -- this is the name of the builtin dictionary > type, which you've just clobbered (in the local scope). Hmmm - isn't it called __dict__ ? >> >> def haskey(self,name): return self.dict.has_key(name) > > Did you really mean to call it that? The dict interface has a method > .has_key(), not .haskey(). yup - oversight > > >> class Cell(UserDict): >> defaults={"width": 0,"height": 0,"text": '',"color": "black","background": "white", >> "widgets": None} > [...] > > Haven't read much further, but it looks like you might be better off > using attribute access rather than indexing. In 2.2, use properties. > Earlier, use __setattr__ / __getattr__ (make sure you read the docs). this migrated from a regular dict which i had to drop because its not hashable as mentioned earlier - next step __(get|set)attr__. > > > John -- Privat ========================== Kim Petersen ==================== Arbejde Email kim at vindinggaard.dk ===== Jens Gr?ns Vej 11 ===== Email kim at lignus.dk Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51 Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62 From __peter__ at web.de Sun Jan 11 14:05:12 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Jan 2004 20:05:12 +0100 Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: Jens Thiede wrote: > OK, thanks for sorting that out, but what do I replace in the > following to avoid referancing: > > x = [[0]*5]*5 > x is [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] > > and after > > x[0][0] = 1; > x is [[1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0]] > > is there a shorthand way to avoid referance or do I have to use a loop > or: > > x = [[0]*5]+[[0]*5]+[[0]*5]+[[0]*5]+[[0]*5] > > which is obviously stupid to try and do when the second cofficiant is > large or a variable. >>> x = [[0]*5 for i in range(5)] >>> x[0][0] = 1 >>> x [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] or >>> y = map(list, [[0]*5]*5) >>> y[0][0] = 1 >>> y [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> Peter From jeremy at jdyallop.freeserve.co.uk Thu Jan 15 18:05:01 2004 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 15 Jan 2004 23:05:01 GMT Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> <4006f74a$0$567$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Brian Kelley wrote: > Skip Montanaro wrote: >> Bdb's license is not GPL: >> >> http://www.sleepycat.com/download/oslicense.html > > I stand corrected, it makes perfect sense that the Berkeley DB should be > released using the Berkeley license :) I don't know why I thought > otherwise. It's not the Berkeley licence, but it's not the GPL either, although it's similar: * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: [...] * 3. Redistributions in any form must be accompanied by information on * how to obtain complete source code for the DB software and any * accompanying software that uses the DB software. Note in particular "and any accompanying software". Previous versions of BDB were under the Berkeley licence, which is still included below the Sleepycat licence. Jeremy. From webmaster at beyond-thoughts.com Fri Jan 16 07:05:18 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 16 Jan 2004 13:05:18 +0100 Subject: PEP for new modules (I read PEP 2) In-Reply-To: References: Message-ID: <4007D37E.4050800@beyond-thoughts.com> Martin v. L?wis wrote: > Christoph Becker-Freyseng wrote: > >> So basically I want to relocate the real Specification, because the >> more specific it gets the more it looks like a documentation and the >> prePEP grows and grows ... >> >> >> Is this a valid option for a PEP? > > > If you are asking: "Can we have an implementation before we write the > PEP?", the answer is "Certainly, yes". > > The PEP procedure is designed to avoid wasting efforts in implementing > ideas that have no chance to ever get accepted to the Python core. > If this is no concern for you (i.e. you are willing to accept the risk > of wasting efforts), you can certainly implement the thing, wait for > user feedback, and then write the PEP. So if I do it this way, the PEP will not have to contain all the features of such a module but just a link to the documentation, which will describe all the classes, functions etc.? Thank You, Christoph Becker-Freyseng From apardon at forel.vub.ac.be Fri Jan 23 04:16:10 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Jan 2004 09:16:10 GMT Subject: Ordered dictionary? References: Message-ID: Op 2004-01-22, Paul McGuire schreef : > "Leif K-Brooks" wrote in message > news:leWPb.231$af7.162835 at newshog.newsread.com... >> I need to associate a string (key) with an integer (value). A dictionary >> would do the job, except for the fact that it must be ordered. I also >> need to look up the value for a specific key easily, so a list of tuples >> wouldn't work. >> > If you really need to access the dictionary in sorted key order, is this so > difficult? > > dKeys = d.keys() > dKeys.sort() > for k in dKeys: > # do stuff with k and d[k], such as: > print k, "=", d[k] > > Or if you are worried about updates to d between the time of key retrieval > and time of traversal (for instance, if a separate thread were to delete one > of the keyed entries), take a snapshot as a list: > > dItems = d.items() # from here on, you are insulated from changes to > dictionary 'd' > dItems.sort() # implicitly sorts by key > dItems.sort( lambda a,b: a[1]-b[1] ) # sorts by value, if you so prefer > for k,v in dItems: > # do stuff with k and v, such as: > print k, "=", v # <-- added benefit here of not re-accessing > the list by key Well I too sometimes need the keys in a dictionary to be sorted and your solutions wouldn't help. The problem is the following. I have a number of key value pairs, like names and telephone numbers. Just more subject to change. Now I want the telephone numbers of everyone whose name starts with "jan". Or I just inserted a name and want to know who is alphabetically next. Or I want to know who is first or last. -- Antoon Pardon From carroll at tjc.com Sat Jan 24 13:55:54 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat, 24 Jan 2004 18:55:54 GMT Subject: time.time() References: Message-ID: <7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com> On Sat, 24 Jan 2004 13:01:40 -0500, Bart Nessux wrote: >am I doing this wrong: > >print (time.time() / 60) / 60 #time.time has been running for many hours > >if time.time() was (21600/60) then that would equal 360/60 which would >be 6, but I'm not getting 6 so I'm not doing the division right, any tips? time.time() returns the number of seconds since the epoch. The epoch is generally Jan 1, 1970; you can check by trying time.gmtime(0). You're expecting time.time() to be 21600/60, or, in other words, for time() to be 1548; but 1548 seconds is only about 25 minutes. It's been a little more than 34 years since Jan 1, 1970, so the number you should expect from time.time() should be in the neighborhood of 34 years * 365.25 days/year * 24 hours/day * 60 min/hour * 60 sec/min = 1072958400. Trying time.time() directly confirms this: >>> time.time() 1074969863.888 Yeah, it's not on the nose, but close enough for a sanity check. By the way, this is usually a good thing to try when you're lost at sea like this -- go back to the original input data, in this case, time.time() output, and see if it's giving you what you expect. It sounds like you're thinking time.time() does something else, which you're trying to do. What is that? There might be another function for you. From barry at barrys-emacs.org Sun Jan 4 10:16:18 2004 From: barry at barrys-emacs.org (Barry Scott) Date: Sun, 04 Jan 2004 15:16:18 +0000 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: <3FF75AFC.3020204@v.loewis.de> References: <3FF75AFC.3020204@v.loewis.de> Message-ID: <6.0.1.1.2.20040104151236.02209ea0@torment.chelsea.private> At 04-01-2004 00:14, Martin v. Loewis wrote: >>With popen5, you can do it *without* using the shell. > >Why is that a good thing? Because using the shell on windows is causing a DOS box window to appear for every popen2/3/4 use in a windowed python program on Windows. Barry From jzgoda at gazeta.usun.pl Fri Jan 16 14:25:18 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 16 Jan 2004 19:25:18 +0000 (UTC) Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> <100dtle1tldg730@corp.supernews.com> Message-ID: Cameron Laird pisze: >>> Why is it the best minicomputer ever made? >>> I really want to know! >> >>Since nobody ever produced any other. Only IBM produced machines that >>can be called "midrange" (something between microcomputer and "real >>computer", the famous S/390 mainframe). They still use this terminology. > . > . > . > Sneaky, Jarek; but there were a LOT of "minicomputer" > manufacturers, including DEC, Data General, HP, Prime, > ... Oops! It seems I'm too young to make such authoritative statements, my adventure with computers started in mid-80's. So, please, take my apologies for inconvenience. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From roy at panix.com Mon Jan 19 20:02:44 2004 From: roy at panix.com (Roy Smith) Date: Mon, 19 Jan 2004 20:02:44 -0500 Subject: speedy Python strings? References: Message-ID: In article , Uwe Mayer wrote: > since strings are > immutable the string operations are so slow. More to the point, and I suspect what you're running into, string addition is linear with respect to string length because it has to create a new string each time and destroy the old one. Since each addition is linear with string length, a loop which adds strings will run in quadratic time. Possibly you want to look at the cStringIO class. Another possibility is to buffer things in a list, using append to add to the end and pop(0) to pop off the front (a roll-your-own queue). Lists do not suffer from the quadratic behavor that string addition does. From rajarshi at presidency.com Wed Jan 14 09:25:28 2004 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 14 Jan 2004 09:25:28 -0500 Subject: how can I execute a function string References: <1006qgl89mmsnf4@corp.supernews.com> Message-ID: On Mon, 12 Jan 2004 21:23:20 -0500, Francis Avila wrote: > Rajarshi Guha wrote in message ... >>Hi , >> I have some code that generates a function on the fly in a string. >>At a later point in time I want to execute this function (which also >>requires a parameters to be passed to it). So the code is something like >>this: [ > If you're very ambitious, you can generate an AST tree and compile that: > see the compile module. In this simple case there's no advantage, > however. > > I'll have to think about how to turn the raw source of a function > definition into a callable. I'm not sure it's possible in a 100% > reliable manner. Here's a first attempt (untested): > > def makecallable(source): > """Return a function from string source. > > 'def ' must be the first tokens in source! > > """ > co = compile(source, '', 'single') funcname = > co.co_varnames[0] #This is VERY brittle!! fakelocals = {} exec co in > globals(), fakelocals > return fakelocals[funcname] > Well I was playing with Andrews curves which allows one to visualize a vector of numbers in terms of a Fourier series. So basically I was creating a string that ontained the Fourier representation of the vector and then evaluating the resultant function. I know this can be done simpler using loops - I jst wanted to see how I could do this using a bit of code generation From jl at windsmith.net Wed Jan 21 09:10:12 2004 From: jl at windsmith.net (John Lull) Date: 21 Jan 2004 08:10:12 -0600 Subject: Multithreaded COM server problem... References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com> Message-ID: <9uvs00568u2tb2qp0lndh649d0ajdginkl@4ax.com> Mark Hammond wrote (with possible deletions): > Is there any way you can do it asynchronously? The main thread spawns a > second thread to do the work. The main thread then spins around a > MsgWaitForMultipleObjects, with an object set by the second thread. The > main thread will then be able to run a message pump, but also detect > when the second thread is done. Yes, except there doesn't seem to be any way to return a value from the first call until after the second call completes. > Apart from that, I am afraid I am out of ideas. I believe however that > you are hitting pure COM issues, and nothing related to Python. Looking > for the answer beyond the Python world may be fruitful. The three reasonable possibilities I see at the moment are: 1. Dig into exactly how apartment-threaded servers are supposed to be written in C or C++ & see how much of that is transferrable to Python. I'm not confident this would give me a solution, though. 2. Activate the server in 2 steps -- have the main thread create (on client request) "interlock" object that, when created, fires up a new thread for the client who created it. The new thread then calls factory.RegisterClassFactories() for the real worker object, then starts a message pump. The client then requests COM to create the worker object. The worker object creation method then calls factory.RevokeClassFactories() to revoke that thread's registration. The interlock and worker classes have to coordinate so that only one worker thread is registered as class factory at any time, and only one client is able to create the worker object at any time. The main thread also has to register as class factory only for the interlock object, not for the worker object. This requires changes to one py2exe module and to all applications that use my server, and will complicate shutdown, since I have to shut down the new thread only when all object's it's pumping messages for are gone. There's also the substantial possibility that the same bug I ran into when setting sys.coinit_flags=0 in localserver.py will rear its head here. 3. Dig into why setting sys.coinit_flags=0 in localserver.py doesn't work. This is probably the right thing to do, both because I know it will yield a solution, and because it would solve the same issue for anyone else with similar needs. Unfortunately it means I have to dig into Python threading internals, pythoncom internals, and the whole COM mechanism rather more heavily than I'd hoped to. Regards, John From dietrich at zdome.net Mon Jan 19 17:04:52 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Mon, 19 Jan 2004 14:04:52 -0800 Subject: Getting a process's output Message-ID: <82104858-4ACB-11D8-A692-0003934ACDEC@zdome.net> Is there any easy way to get all the output of a process? Ideally, the function takes parameters like exec(), calls fork(), wait()s for the process to complete, and returns the process's stdout, stderr, and exit status. By stdout and stderr I don't mean file objects or descriptors... I mean strings containing the entire output. I would try to do it myself, but I'm not sure how to interleave the operations. From skip at pobox.com Sat Jan 31 11:00:54 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 31 Jan 2004 10:00:54 -0600 Subject: timeit In-Reply-To: <16411.52801.42668.236157@montanaro.dyndns.org> References: <16411.52801.42668.236157@montanaro.dyndns.org> Message-ID: <16411.53558.416804.414405@montanaro.dyndns.org> >>>>> "Skip" == Skip Montanaro writes: Skip> tim = timeit.Timer(setup-'import subtract', stmt=s) Whoops! '-' should of course be '='... S From elainejackson7355 at home.com Sun Jan 4 01:45:46 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 04 Jan 2004 06:45:46 GMT Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: C rounds toward the nearest integer and Python rounds down. The behavior is consistent in each case. "Frank" wrote in message news:3987e01c.0401030832.114c6f2a at posting.google.com... | Hi, | | can anybody help with the following problem? | | In C++ | | i = 5 / 10 and | i = -5 / 10 both have the same result 0. | | In python | | i = 5 / 10 gives me 0 as expected, but | i = -5 / 10 gives -1 as result. | | Is this a feature or a bug? I remember Delphi gave me the same result as | C++. | | TIA, | Frank From jepler at unpythonic.net Mon Jan 5 08:47:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Jan 2004 07:47:54 -0600 Subject: Python/C and PYTHONPATH In-Reply-To: References: Message-ID: <20040105134753.GA5514@unpythonic.net> You'd need to tell us how you're invoking Python. When the Python executable is invoked without arguments, the current directory is on the sys.path: $ 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 sys >>> sys.path[0] '' When you run a script, the directory of that script is in sys.path[0]: $ echo "import sys; print sys.path[0]" > /tmp/script.py $ python /tmp/script.py /tmp Some Python editors may put the directory where they reside on sys.path, but not the current directory. They might do other startup that is different from normal. The newest Python I have on this machine is 2.3b1, and its idle puts these elements at the start of Pythonpath: Python 2.3b1 (#16, May 19 2003, 10:22:28) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import sys >>> sys.path[:2] ['/home/jepler', '/usr/local/bin'] ... so instead of "the current directory" ('' or '.'), sys.path[0] is "the directory idle was invoked from", and that's followed by "the directory where the idle script lives". Jeff From jblazi at hotmail.com Sat Jan 10 16:08:16 2004 From: jblazi at hotmail.com (jblazi) Date: Sat, 10 Jan 2004 22:08:16 +0100 Subject: Emacs python mode question Message-ID: If I should like to go to line 345: how can I do that? Typing M-x goto-line and then 345 is a bit cumbersome. I defines the key Alt-g to be goto-line, but it does not work. TIA, jb ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From miallen at miallen.com Sat Jan 17 18:15:20 2004 From: miallen at miallen.com (Michael B Allen) Date: Sat, 17 Jan 2004 18:15:20 -0500 (EST) Subject: rfc822.py date parsing problem Message-ID: <41886.207.172.179.21.1074381320.squirrel@li4-142.members.linode.com> How can I zoom in on what's going on below? $ archivemail -n ~/Maildir/.Lists.* /home/miallen/Maildir/.Lists.CIFS: I would have archived 11 of 29 message(s) in 0.1 seconds /home/miallen/Maildir/.Lists.Expat: I would have archived 113 of 116 message(s) in 0.3 seconds /home/miallen/Maildir/.Lists.JCIFS: I would have archived 628 of 1796 message(s) in 4.2 seconds /home/miallen/Maildir/.Lists.Jarapac: I would have archived 0 of 6 message(s) in 0.0 seconds /home/miallen/Maildir/.Lists.Libmba: I would have archived 21 of 39 message(s) in 0.1 seconds /home/miallen/Maildir/.Lists.Linux-UTF8: I would have archived 0 of 190 message(s) in 0.4 seconds Traceback (most recent call last): File "/usr/bin/archivemail", line 968, in ? main() File "/usr/bin/archivemail", line 550, in main archive(mailbox_path) File "/usr/bin/archivemail", line 761, in archive _archive_dir(mailbox_name, final_archive_name, "maildir") File "/usr/bin/archivemail", line 877, in _archive_dir if should_archive(msg): File "/usr/bin/archivemail", line 674, in should_archive time_message = guess_delivery_time(message) File "/usr/bin/archivemail", line 613, in guess_delivery_time date = message.getdate(header) File "/usr/lib/python2.1/rfc822.py", line 362, in getdate return parsedate(data) File "/usr/lib/python2.1/rfc822.py", line 901, in parsedate t = parsedate_tz(data) File "/usr/lib/python2.1/rfc822.py", line 826, in parsedate_tz if data[0][-1] in (',', '.') or data[0].lower() in _daynames: IndexError: list index out of range From hans at zephyrfalcon.org Tue Jan 27 11:53:13 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 27 Jan 2004 11:53:13 -0500 Subject: os.path.split: processing paths from one OS on another In-Reply-To: <401691D7.8050607@holmes.nl> References: <401691D7.8050607@holmes.nl> Message-ID: <40169779.6080106@zephyrfalcon.org> Martijn Ras wrote: > Heya folks, > > I ran into the following problem: > > When i run this on Windows everything is as expected: > C:\>python > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> file='/TEST/FILE.EXT' > >>> print os.path.split(file) > ('/TEST', 'FILE.EXT') > >>> file='C:\\TEST\\FILE.EXT' > >>> print os.path.split(file) > ('C:\\TEST', 'FILE.EXT') > > However, when i run this on Linux the results are unexpected: > $ python > Python 2.2.3 (#1, Nov 12 2003, 15:53:11) > [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> file='/TEST/FILE.EXT' > >>> print os.path.split(file) > ('/TEST', 'FILE.EXT') > >>> file='C:\\TEST\\FILE.EXT' > >>> print os.path.split(file) > ('', 'C:\\TEST\\FILE') > > All i can find is some comments on POSIX-ness (or not) of the OS, in > regard to os.path.split(), but i fail to see why that explains the > different outcome of the last command in the two examples above. os.path is really a portable layer over platform-specific modules. Try this little experiment: >>> import os >>> os.path >>> On Windows, os.path is really the ntpath module, but on Linux, you'll see 'posixpath'. ntpath and posixpath implement platform-specific rules, for example, they deal with the path separator used on a given system. Windows can deal with both slashes and backslashes as separators, but posix (apparently) only accepts slashes: >>> import ntpath, posixpath >>> ntpath.split("c:/foo/bar.txt") ('c:/foo', 'bar.txt') >>> ntpath.split("c:\\foo\\bar.txt") ('c:\\foo', 'bar.txt') >>> posixpath.split("c:/foo/bar.txt") ('c:/foo', 'bar.txt') >>> posixpath.split("c:\\foo\\bar.txt") ('', 'c:\\foo\\bar.txt') > My server needs to be run on either Linux or Windows, it receives > requests from clients that may run either OS. To process those requests > i need to split the path and filename. I hoped to solves this using > os.path.split (), any suggestions as to how to fix this? One possible solution is to always use forward slashes for literal paths. These should work on both Linux and Windows. If necessary, you can convert backslashes to forward slashes before processing. It's easy enough: >>> string.replace("c:\\foo\\bar.txt", "\\", "/") 'c:/foo/bar.txt' >>> HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From __peter__ at web.de Sun Jan 18 19:41:50 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jan 2004 01:41:50 +0100 Subject: Printing variable names References: Message-ID: Mike wrote: > This is what I'm trying to accomplish: > > Basically I have a list of pointers to functions (or whaterver it's called > in > Python). Something like this: > > commands = [func1, func2, ...funcN] > > This is in a script that I use to test an embedded system through the > comport. I call the script with the command number (func1 etc...), which > calls the corresponding function, which sends a command to the embedded > system. > > I'd like to be able to call the script with --help and have it spit out > the list of commands (the names func1, func2 etc...). You're lucky, functions "know" their name: >>> def func1(): pass ... >>> def func2(): pass ... >>> for f in [func1, func2]: ... print f.__name__ ... func1 func2 Peter From bmgx_no_sp at mgleesonprop.co.za Thu Jan 8 11:42:35 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Thu, 08 Jan 2004 18:42:35 +0200 Subject: creating a daemon? In-Reply-To: References: <3ffd355c.0@news1.mweb.co.za> Message-ID: <3ffd886d.0@news1.mweb.co.za> Yeah ok, "FORK" being the golden word I failed to see at first, got some answers @ google groups but the most helpful was this link: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 now to stick those DAEMONS with my fork()! anyone have an os.knife()? Harry George wrote: > bmgx writes: > > >>This is what I am trying to find out, instruction on how to create a >>simple daemon on unix systems(Linux), can't find any info on usual >>sources.. >> > > > 1. The idea is to fork, clean up all the inheritable stuff like files > and environment vars, and then fork again. The resulting process > can then be left running to do the daemon work. I recall there is > a daemon.py module somewhere which does this all for you. Here are > the basics: > > def main(args): > #---first fork--- > try: > pid = os.fork() > if pid > 0: > #---first parent--- > sys.exit(0) > except OSError,e: > print >>sys.stderr, "fork #1 failed %d (%s)" % (e.errno,e.strerror) > sys.exit(1) > > > #---make a clean process--- > os.chdir('/') > os.setsid() > os.umask(000) > child_in =open('/dev/null','r') > child_out=open('/dev/null','w') > os.dup2(child_in.fileno(), sys.stdin.fileno()) > os.dup2(child_out.fileno(), sys.stdout.fileno()) > os.dup2(child_out.fileno(), sys.stderr.fileno()) > > #---second fork--- > try: > pid = os.fork() > if pid > 0: > #---second parent--- > sys.exit(0) > except OSError,e: > print >>sys.stderr, "fork #2 failed %d (%s)" % (e.errno,e.strerror) > sys.exit(1) > > > #---in clean child--- > x=MyApp() > x.run() > > > 2. To talk to that daemon, you can use a) files at known locations, b) > pipes (see popen), c) sockets with ad hoc protocols (see asyncchat > and SocketServer), d) predefined protocols (see Internet Protocols > and Services). The various "server" modules have the setup code > from "1" above builtin, so you can ignore that level of detail. > ["see" references can be found in the normal python documentation's > Library Reference"]. > > 3. Once you have a working daemon, you need a way to start and stop > it. You could manually start it each time you need it and then > "kill" it when done. More commonly you would do it (in Linux and > UNIX) via a boot-time initialization script (typically found in > /etc/init.d). Each *NIX has its own flavor of setting these up, so > you need to look at existing services and maybe copy-and-edit a > working script. > > 4. If security is an issue (it probably is), you may also want to hide > the service behind xinetd. That is a whole setup story in its own > right. And if security is really troublesome, you may need to > assure the python interpreter itself is safe. That kind of > consideration is way out of my league. > From ramen at lackingtalent.com Fri Jan 9 13:06:10 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 09 Jan 2004 18:06:10 -0000 Subject: Why " ".some_string is often used ? References: Message-ID: In article , Terry Reedy wrote: > > "John Roth" wrote in message > news:vvqghojub1dl07 at news.supernews.com... >> And I agree, it's not entirely obvious why it's a string >> method rather than a list method, > > Because, as I and others have posted several times in previous threads, and > explicated with several examples, .join is NOT, NOT, NOT a > list method, anymore than it is a tuple, dict, array, generator-iterator, > or any other iteratable method. Taking 'string' genericly (as either type > str or unicode), .join joins a sequence (iterable) of strings with a > string. It's not a list method because it's not a list method or any other kind of iterable method? That seems like circular reasoning. Consider the following two pieces of data: 1. 'the,quick,brown,fox' 2. ['the', 'quick', 'brown', 'fox'] They are both lists of words. Perhaps the first is not a Python-list of words, but it's a list of words nonetheless. #1 can be converted into #2 by calling ".split(',')" on it. Doesn't it seem natural that #2 be converted to #1 by calling ".join(',')"? It works this way in JavaScript and Ruby, at least. The argument is more of a technical issue. There are only two kinds of strings. There are many kinds of "iterables". So, it's easier to define "join" on the string, and force implementers of custom string types to implement "join" as well (since this is more rare) than to define "join" on an iterable and force implementers of the many kinds of iterables to define "join" as well. Conceptually, I'm not sure that the case is so strong that "join" is a string method. In reality, "join" isn't really a string method any more than it's an iterable method. It's a string-iterable method; it operates on the relationship between a string and an iterable of strings. If we had a class that could represent that relationship, "join" would be a method of that class, ie.: seq = ['the', 'quick', 'brown', 'fox'] sep = ',' ssi = StringStringIterable(sep, seq) result = ssi.join() But this would be somewhat pointless because: 1. This would be a pain to type. 2. The class probably wouldn't pull its weight. 3. The elegance Python has with text processing is lost. Another solution might be to use a mixin class that provides StringIterable methods, and have the built-in list include this mixin. Then, you could always mix it into your own iterable classes if you wanted "join" to be available. But then, you've still got issues trying to integrate it with tuples and generators. Sometimes, object-orientedness gets in the way, and I think this is one of those cases. "str.join" is probably the winner here, but since it's really just a string method being used "out of context", the delimeter is the first argument, and this doesn't read well to me. I think that "string.join" makes more sense; it says "join this sequence using this delimeter" instead of str.join's "join using this delimeter this sequence". >>since it operates on a list, not on a string. > > Huh? It operates on a sequence of strings. It has nothing to do with > lists in particular. The builtinness and mutability of lists is irrelevant > to this generic read-only operation. Only because it is defined as such. Ruby and JavaScript define the "join" method on built-in arrays. Newcomers to Python who have programmed in those languages will naturally associate "join" with lists, even though technically, in the Python world, it's really something associated with the relationship between a string and an iterable of strings. Which is an awful lot of semantics to digest when you just want to stick some commas between words in a list. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From gerrit at nl.linux.org Tue Jan 6 14:39:51 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 6 Jan 2004 20:39:51 +0100 Subject: PRE-PEP: new Path class In-Reply-To: <3FFA7E82.4020609@beyond-thoughts.com> References: <3FFA7E82.4020609@beyond-thoughts.com> Message-ID: <20040106193951.GD4581@nl.linux.org> Christoph Becker-Freyseng wrote: > [1] I think Path being a subclass of str is odd. There are a lot of > string-operations that don't fit to path (some of them should be > implemented in a different way e.g. __mul__ if at all). > However the point with the old os function etc. is very sound. So it > might be a good idea to have Path being a subclass of str *for > transition*. But finally all those functions should call str(argument) > instead of of demanding a str-object as argument (if they don't already > today). Another possibility, which I have put in the Pre-PEP, is; We can add a method .openwith(), which takes a callable as it's first argument: p.openwith(f, *args) would result in f(str(p), *args). This would make p.open(*args) a shorthand for p.openwith(file, args). What do you think? > This takes me to my last point: > What about invalid paths? > Should Path-Class take care of always being a valid path (this doesn't > necessarily mean a path of an existing file/directory) It may be a good idea to do so. At first, I didn't understand what it meant, an 'invalid path', but let's define it as anything that triggers a TypeError when passed to open or listdir. On POSIX, I know only one case: \0 in path. It may be a lot more difficult on Windows or the Mac. I'm not sure about this idea yet. > Especially if someone uses string-methods on a Path-object there could > arise invalid paths, even if finaly the path is valid again. Yes. But I can't really think of a use case for doing operations on a path which make it invalid. Does it occur in practice? yours, Gerrit. -- 123. If he turn it over for safe keeping without witness or contract, and if he to whom it was given deny it, then he has no legitimate claim. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From tim.golden at viacom-outdoor.co.uk Tue Jan 20 07:22:32 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 20 Jan 2004 12:22:32 -0000 Subject: ANN: WMI 0.5 Message-ID: *************************** Python WMI Module - CHANGES *************************** What is it? =========== The Python WMI module is a lightweight wrapper on top of the win32all extensions, and hides some of the messy plumbing needed to get Python to talk to the WMI API. It's pure Python and should work with any version of Python from 2.1 onwards (list comprehensions) and any recent version of win32all. Where do I get it? ================== http://tgolden.sc.sabren.com/python/wmi.html What's Changed? =============== 17th Jan 2004 v0.5 + Added support for the WMI Registry interface. The new module-level Registry method returns a WMI registry object whose methods include EnumKeys, CreateValue &c. There are a couple of examples in the cookbook. 15th Dec 2003 v0.4 + Added machines_in_domain (from a post to python-win32 by "Sean") + Factored out moniker construction to make it easier to support use of StdRegProv to update registry. (Coming soon). + Added support for a timeout on the event watcher; timeout is specified in milliseconds and raises x_wmi_timed_out on a call to the watcher object. This allows for the possibility of pumping for waiting messages to prevent eg, the PythonWin IDE locking up. See the docstring for the watch_for method. + Added connect_server function, making it slightly easier to construct a WMI object, eg with username and password. 10th Jul 2003 v0.3 + Changes by Paul Moore to allow a ready-made WMI Services object to be passed in (WMI.__init__). + This header and the __VERSION__ number added by Tim G. 9th Jul 2003 v0.2 + Sundry changes by Tim G, including but not limited to: - support for moniker parts (WMI.__init__) - creating new instances of WMI classes (WMI.new) - passing return value back from wmi methods (_wmi_method.__call__) - better COM error-handling (handle_com_error) 5th Jun 2003 v0.1 + Initial release by Tim Golden ________________________________________________________________________ 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 2002 at weholt.org Thu Jan 8 18:21:46 2004 From: 2002 at weholt.org (Thomas Weholt) Date: Fri, 9 Jan 2004 00:21:46 +0100 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> Message-ID: <6AlLb.134$hd.7718@news2.e.nsc.no> "Peter Hansen" wrote in message news:3FFD7159.55630AE0 at engcorp.com... > Thomas Weholt wrote: > > > > My advice ( I got some experience in all of them ) : > > > > Medusa is old and you have to do alot yourself. You have to know abit about > > HTTP, how async works etc. Get ready to get your hands dirty. > > > > Twisted is similar to Medusa, but comes with a bunch of very cool > > ready-to-use/more-or-less-stable modules which can be combined into complex > > Heh. :-) > > Twisted is similar to Medusa in about the same way that Linux is similar to, > say, CPM... > > -Peter Ok, my point was that they are similar type of frameworks, if we compare medusa and the webserver-part of Twisted. They don't do much without a bit of work/coding. Unlike Zope which comes with a UI, user-management etc running the minute you finish the installation procedure. I might not know the entire technical aspect of medusa and twisted, not really enough to compare them in detail. I was referring to the way a programmer will have to use them, based on my experience using the two. In that regard they're somewhat similar and different from zope. If I'm completly off track here feel free to enlighten me. Thomas From mal at lemburg.com Fri Jan 23 10:54:37 2004 From: mal at lemburg.com (mal) Date: Fri, 23 Jan 2004 16:54:37 +0100 Subject: ANN: eGenix mxODBC Zope Database Adapter 1.0.8 Message-ID: <401143BD.5070706@lemburg.com> ________________________________________________________________________ ANNOUNCEMENT EGENIX.COM mxODBC Zope Database Adapter Version 1.0.8 Available for Zope 2.3 through 2.7 on Windows, Linux, Solaris and FreeBSD ________________________________________________________________________ INTRODUCTION The eGenix mxODBC Zope Database Adapter (Zope DA) allows you to easily connect your Zope installation to just about any database backend on the market today, giving you the reliability of the commercially supported eGenix.com product mxODBC and the flexibility of the ODBC standard as middle-tier architecture. Unlike Zope's ZODBC Zope DA, the mxODBC Zope DA works on Windows XP/NT/2000/98, Linux, Solaris and FreeBSD using the same interface on all platforms. The mxODBC Zope DA implements high performance thread-safe connection pooling and multiple physical connects per logical Zope connection. You can safely run Z SQL Methods in parallel, achieving a much better throughput than ZODBC Zope DA or similar Zope database adapters under heavy load. This makes it ideal for deployment in ZEO Clusters and Zope hosting environments where stability and high performance are a top priority. ________________________________________________________________________ FEATURES * Zope Level 3 Database Adapter: the mxODBC Zope DA is fully multi-threaded and can handle multiple connections to multiple databases. * Fully compatible to Z SQL Methods. * Drop-in compatible to the ZODBC DA: the mxODBC Zope DA provides the same interfaces as Zope's ZODBC DA to allow a smooth upgrade path from this simplistic adapater to the high performance mxODBC Zope DA. * Fully compatible to the Znolk SQL Wizard Product and other similar products relying on the common database schema access methods .tables() and .columns(). * Connection Pooling: physical database connections are pooled and kept open, to reduce the connection overhead to a minimum. This is especially important for high latency database connections and ones like Oracle which take a considerable amount of time to setup * Parallel Execution of Queries on a single logical connection: the mxODBC Zope DA can manage any number of physical connections on a single logical connection. This enables running truly parallel Z SQL Method queries -- a feature not available in other Zope DAs. * Robust Mode of Operation: connections which have timed out or go away due to network problems are automatically reconnected. * Cross-platform Connection Objects: The Zope DA will automatically choose the right platform specific ODBC manager for you. * Per Connection Adjustable ODBC Interface: mxODBC comes with many different subpackages to choose from on Unix. The Zope DA allows you to select these subpackages on a per-connection basis. * Per Connection Error Handling: you can tell each connection whether it should report ODBC warnings or not; furthermore all warnings and errors are made available as list .messages on the DatabaseConnection object. * Transaction safe automatic reconnect: when the DA finds that a connection has timed out, it automatically tries a reconnect and replays the transaction on the connection (unlike other DAs which break the transaction scheme by doing a reconnect without replay). * Built-in Schema Cache: this results in improved performance under heavy load. * Database Schema Access: all ODBC catalog methods are made available for much better database schema inquiry. The catalog methods allow building generic database interrogation or manipulation tools and facilitates writing database independent Zope products. * Lazy Connect: the mxODBC Zope DA only connects to the database backends when a connection is actually requested. This results in a better use of resources compared to other Zope DAs. ________________________________________________________________________ NEWS Version 1.0.8 includes the following changes and enhancements: * Zope 2.7.0 and Python 2.3 are fully supported on all platforms: Windows, Linux, Solaris and FreeBSD. * You can let the mxODBC Zope DA return empty strings instead of None for SQL NULL values. This should simplify porting existing applications to the mxODBC Zope DA. * The included mxODBC 2.1 provides full Unicode support if accessed directly. Using e.g. the EasySoft ODBC-ODBC bridge this allows you to connect to any remote Unicode aware ODBC backend from any of the supported platforms. In short: mxODBC Zope DA is continuing to become the number one solution for integrating relational databases with Zope applications. ________________________________________________________________________ UPGRADING If you have already bought mxODBC Zope DA licenses, you can use these license for the updated version as well. There is no need to buy new licenses. The same is true for evaluation license users. ________________________________________________________________________ MORE INFORMATION For more information on the mxODBC Zope DA, licensing and download instructions, please visit our web-site: http://zope.egenix.com/ You can buy mxODBC Zope DA licenses online from the eGenix.com shop at: http://shop.egenix.com/ ________________________________________________________________________ Thank you, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 23 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 davecook at nowhere.net Sat Jan 3 15:42:14 2004 From: davecook at nowhere.net (David M. Cook) Date: Sat, 03 Jan 2004 20:42:14 GMT Subject: mysql python Newbie Question References: Message-ID: In article , Andrew wrote: > Hi I would like to create a program that accesses mysql from a gui on my > local computer "mysql is on a server" > > but I am fairly new to python and programming GUI's in general > > What I would like this program to do is be able to access my server and > change update add and delete records from my databases without having to > write sql. You might give an object-relation mapper like SQLObject or MiddleKit a try. http://www.thinkware.se/cgi-bin/thinki.cgi/ObjectRelationalMappersForPython However, SQL is easy to learn and is very useful since you still may need to tweek the schemas that these ORMs produce for you. Also, SQLObject seems quite slow, though maybe I'm just using it wrong. It should also be said that SQL is simply one of those things that programmers are expected to know. Another option is MetaKit, which is procedural as opposed to descriptive, e.g. SQL: select * from person p, address a where p.person_id=a.person_id; MK: vw = person.join(address, person_id) Dave Cook From bignose-hates-spam at and-benfinney-does-too.id.au Tue Jan 20 19:30:50 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 21 Jan 2004 11:20:50 +1050 Subject: regular expression question References: Message-ID: On Wed, 21 Jan 2004 00:38:12 -0000, Steve Lamb wrote: > import re > line = 'match this' > foo = re.search(r'.*(this)', line) > foo.groups()[0] >>> import re >>> line = 'match this' >>> foo = re.search( r'.*(this)', line ) >>> foo.groups() ('this',) >>> foo.group(0) 'match this' >>> foo.group(1) 'this' Read more on the methods available from a MatchObject: -- \ "The man who is denied the opportunity of taking decisions of | `\ importance begins to regard as important the decisions he is | _o__) allowed to take." -- C. Northcote Parkinson | Ben Finney From eric.brunel at N0SP4M.com Fri Jan 16 04:21:48 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Fri, 16 Jan 2004 10:21:48 +0100 Subject: wxPython worries References: <92c59a2c.0401152257.5b93167b@posting.google.com> Message-ID: MetalOne wrote: [snip] > Tkinter has issues here > also. There is no means for a worker thread to put an event in the > GUI thread. We've successively used the event_generate method on Tkinter widgets from worker threads to communicate with the main thread. You can also have less straightforward solutions involving the main thread regularly checking for a Queue or Event (using the after method) to get events from the worker threads. So you definitely can't say there's "no means" to do it. But it's clearly not as easy as it should. [snip] > Tkinter is also giving me problems. I have been trying to add > controls to a canvas and to have a scrollbar that will scroll the > controls on the canvas. I think I have it figured out now, but it is > damn near impossible to figure out from the documentation. I had to > scour the internet looking for solutions. The documentation is clearly the main problem with Tkinter. It's not really that there's not enough, but useful information must be gathered from too many places... The best places are: - For beginners, "Thinking in Tkinter" from Stephen Ferg: http://www.ferg.org/thinking_in_tkinter/index.html - Tkinter demos in the Python distribution: unfortunately one of Tkinter's best kept secrets. Just go to /Demo/tkinter and look at the scripts. I've learnt a lot from them, even if they're far from perfect (where on earth did they get the idea to make all their application inherit from Frame?!) - "An introduction to Tkinter" from Fredrik Lundh: http://www.pythonware.com/library/tkinter/introduction/index.htm - very useful, but unfortunately incomplete... - And finally the man pages for tcl/tk: http://www.tcl.tk/man/ - only useful once you've practiced a bit, since you must know how to translate tcl/tk to Python/Tkinter to be able to use it. The book "Python and Tkinter programming" from John Grayson seems interesting, but I never used it myself. You can get an idea of its contents and download the example scripts here: http://www.manning.com/grayson/ HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jepler at unpythonic.net Sat Jan 24 14:01:19 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 24 Jan 2004 13:01:19 -0600 Subject: time.time() In-Reply-To: References: Message-ID: <20040124190119.GF32445@unpythonic.net> time.time() returns seconds since a particular time in the past ("the Epoch"), not seconds since program start or anything like that. >>> import time >>> help(time.time) Help on built-in function time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. From rainerd at eldwood.com Sun Jan 11 01:46:50 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Sun, 11 Jan 2004 06:46:50 GMT Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: Samuel Walters wrote: > So, I guess that my point is that C might not be the right language > for doing numerical processing, but it seems the right language for > implementing the primitives of numerical processing. The issue with C is that it is too slow for implementing those primitives (in part due to pointer aliasing issues). Fortran is considerably faster. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From usenet at -OBFUSCATED-joefrancia.com Sat Jan 31 19:10:44 2004 From: usenet at -OBFUSCATED-joefrancia.com (Joe Francia) Date: Sun, 01 Feb 2004 00:10:44 GMT Subject: Problems embedding Python In-Reply-To: References: Message-ID: <8uXSb.6209695$be.1021111@news.easynews.com> Psymaster wrote: > I've tried running scripts from the embedded interpreter but it doesn't > work. If I try the same scripts as strings to interpret it works. Here > is my program: > > #include > #include "Python.h" > > int main(int argc, char *argv[]) > { > FILE *script = fopen("c:/c.py", "r"); > > Py_Initialize(); > PyRun_SimpleFile(script, "c.py"); > Py_Finalize(); > > return 0; > } > > > c.py contains just a simple print statement. > > This compiles and links under MSVC 6 but when run crashes. Any help? Maybe escape your backslash? : FILE *script = fopen("c:/c.py", "r"); ------------------------^ From aahz at pythoncraft.com Thu Jan 22 12:08:06 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Jan 2004 12:08:06 -0500 Subject: What is object() References: Message-ID: In article , Hameed Khan wrote: > > i was reading library refrence manual. there i found >object() function. they says in library refrence that > "Return a new featureless object. object() is >a base for all new style classes. It has the methods >that are common to all instances of new style >classes." There's not much use for an instance of object. Don't worry about it. >My questions are whats the use of this function and >the object returned by it? and what are new style >classes?. http://www.python.org/2.2.3/descrintro.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From max at alcyone.com Wed Jan 28 19:17:22 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 28 Jan 2004 16:17:22 -0800 Subject: comparing booleans References: Message-ID: <40185112.264898A4@alcyone.com> Gerrit Holl wrote: > is it proper to compare booleans? It is possible, of course, because > they're compatible with numbers, but booleans aren't truly numbers. > I'm > tempted to write: > > return cmp(self.extends, other.extends) Even if you're seriously worried about the correctness of comparing Booleans, you can always explicitly turn them into integers: return cmp(int(self.extends), int(other.extends)) > (Hmm, makes me wonder, for booleans, are != and ^ equal?) Easily checked: >>> for x in (True, False): ... for y in (True, False): ... print x, y, x != y, x ^ y ... True True False False True False True True False True True True False False False False -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Weakness of attitude becomes weakness of character. -- Albert Einstein From peter at engcorp.com Mon Jan 5 17:38:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Jan 2004 17:38:51 -0500 Subject: Socket Programming References: <56LGb.5852$UB3.4119@nwrddc03.gnilink.net> Message-ID: <3FF9E77B.EE769F8F@engcorp.com> trainee wrote: > > Thanks, everyone. > Michael: I am really just fooling around for the moment. Are you telling me > that there are modules for specific things like IRC? In addition to the other responses to this: the Twisted package does include IRC support, along with dozens of other protocols and both higher and lower level things galore, generally or at least often done in a way that vastly simplifies the whole issue well beyond what other approaches have managed. Go to www.twistedmatrix.com to learn more. -Peter From Pieter.Claerhout at Creo.com Wed Jan 21 09:43:18 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 21 Jan 2004 15:43:18 +0100 Subject: py2exe error Message-ID: <490316A24CC5D411ACD700B0D078F7F003915DD0@cseexch01.cse.creoscitex.com> Change the setup script to: from distutils.core import setup import py2exe setup( options = { 'py2exe': { 'packages': 'encodings' } }, name = 'default', version = '0.1.0', console = ["CLI_Backup.py"], windows = ["Configurator.py"] ) This will force py2exe to include the encodings package which should solve your problem. Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Haim Ashkenazi [mailto:haim at babysnakes.org] Sent: 21 January 2004 15:40 To: python-list at python.org Subject: py2exe error Hi (complete newbie warning...:) ) I've written a script that uses pickle to store data to a file. here's the code that stored the data: ------------- def put(self, conf): """ dump the preferences to a file""" # TODO: make a backup copy of the prefs !!!! try: f = open(self.bacFile, "w") except: raise 'BadFileError', "couldn't write file" pickle.dump(conf, f) f.close() --------------------------------- when running from regular python interperter, it works fine. I need this script to run without python installed, so I've created a stand-alone binary with py2exe. I used the following simple setup.py: from distutils.core import setup import py2exe setup(name = 'default', version = '0.1.0', console = ["CLI_Backup.py"], windows = ["Configurator.py"] ) ------------------------- when running from this binary I get this error: Traceback (most recent call last): File "MainFrame.pyc", line 140, in OnSaveMenuEvent File "MainFrame.pyc", line 174, in dumpPrefs File "NS_Backup.pyc", line 64, in put File "pickle.pyc", line 1382, in dump File "pickle.pyc", line 231, in dump File "pickle.pyc", line 293, in save File "pickle.pyc", line 663, in save_dict File "pickle.pyc", line 677, in _batch_setitems File "pickle.pyc", line 293, in save File "pickle.pyc", line 514, in save_unicode LookupError: no codec search functions registered: can't find encoding ----------------------------- I guess I should add some custom module to the setup.py but I don't know which (or am I completely off track here...). can someone help? thanx -- Haim -- http://mail.python.org/mailman/listinfo/python-list From eric.brunel at N0SP4M.com Mon Jan 19 09:54:01 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 15:54:01 +0100 Subject: Tk Icon - request to Fredrik Lundh References: <8089854e.0401190436.10f99713@posting.google.com> Message-ID: Fuzzyman wrote: > There is a very interesting (and potentially useful) program on the > effbot website - called Tkicon. > > http://www.effbot.org/downloads/ > > Unfortuantely the last supported version of python is 2.1 > I've seen a few people asking, but never an answer, on Python 2.3 > support. This utility should not be needed anymore if you're using a recent version of tcl/tk: the method wm_iconbitmap on toplevel's, that didn't work on earlier versions of tk on Windows, now works without problem. You should specifiy a .ico or .icr file name as its argument. See the documentation for the corresponding tk command at: http://www.tcl.tk/man/tcl8.3/TkCmd/wm.htm#M15 HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From premshree_python at yahoo.co.in Mon Jan 12 08:39:30 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 12 Jan 2004 13:39:30 +0000 (GMT) Subject: Using switches with exec? Message-ID: <20040112133930.90763.qmail@web8309.mail.in.yahoo.com> Hello, I need to run a Python program dynamically within another program. I am using exec for the purpose. Is there a way to pass parameter switches to exec? -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From claird at lairds.com Sat Jan 24 07:25:21 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 24 Jan 2004 12:25:21 -0000 Subject: Tkinter Base Window References: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Message-ID: <1014p1hore6k694@corp.supernews.com> In article <401257c4$0$26116$afc38c87 at news.optusnet.com.au>, Peter Moscatt wrote: >Ok.... I am pretty new to Python (as you may have gathered from previous >posts). So now it time for another one of my ridiculous questions.... :-) > >When using 'Tkinter', what is used as the base window to work from, meaning >what widget do I use to place all other widgets onto to create a custom >dialog ? . . . When I use Tkinter, I don't talk that way. I think in terms of the '.' root toplevel, into which I might pack several frames: import Tkinter root = Tkinter.Tk() frame1 = Tkinter.Frame(root, ...) frame2 = Tkinter.Frame(root, ...) important_button = Tkinter.Button(root, ...) one_label = Tkinter.Label(frame1, ...) ... [and so on] Is that what you're getting at? -- Cameron Laird Business: http://www.Phaseit.net From cwilcox at etcconnect.com Fri Jan 9 12:04:27 2004 From: cwilcox at etcconnect.com (Christian Wilcox) Date: Fri, 9 Jan 2004 11:04:27 -0600 Subject: displaying extended ASCII from a telnet session Message-ID: <69A0D4AB81C51447AD6BA387782B8D64093D62@midl-mail4.etcconnect.com> I'm trying to programmatically access information from a telnet session which is normally accessed with a telnet program capable of terminal emulation (currently set at VT320). The initial login text displays fine, of course, but when I get to the section which displays extended ASCII characters, Telnet from telnetlib displays the following garbled mess: ?[?40h?[?3l?[0;1m?>?[?1l?[?25l?[?3l?[0;0H?[2J?[?25l?(B??[0;7m?[23B ba6.0 version 03-1993/R1 ?[0m?[0; 7m?[1;2Hmtccom00000000?[1C ?[1C ?[1C ?[1C ?[ 0m?[10;5H?(0?lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk?[11;5Hx?[68Cx?[1 2;5Hx?(B? License Code : 178241/105?[39C?(0?x?[13;5Hx?(B? Developed for:?[52C?(0?x?[14;5Hx?(B? Electronic Theatre Controls?[39C?(0?x?[15;5Hx?[68Cx?[16;5Hmqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq x?(B??[60CChoice:s?[56C?(0?x?[1D?[1B(0?x?[1D?[1B ?[5C?(0?x?[1D?[1B Any ideas of a way to decode this information? Christian From dw-google.com at botanicus.net Sat Jan 24 15:58:50 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 24 Jan 2004 12:58:50 -0800 Subject: Changing endian format References: Message-ID: <99dce321.0401241258.1f74915f@posting.google.com> Amit Gaur wrote... > Hi newbie to python here, > I have a binary file and i need to change the endian format..little to big as well as vice versa..could anyone help me out. If you use the struct module to read the file, this appears to be handled for you. http://python.org/doc/current/lib/module-struct.html Example (pack the value 1234 into an unsigned long in little endian, then big endian format): py> import struct py> struct.pack(' struct.pack('>L', 1234) '\x00\x00\x04\xd2' See also 'struct.unpack', 'socket.htons', and 'socket.htonl'. From kevin at sb.org Wed Jan 28 11:51:37 2004 From: kevin at sb.org (Kevin Ballard) Date: Wed, 28 Jan 2004 11:51:37 -0500 Subject: Webhosting with Python References: <8089854e.0401280834.6fd4f972@posting.google.com> Message-ID: On 2004-01-28 11:34:43 -0500, michael at foord.net (Fuzzyman) said: > I've recently starting using a very cheap web hoster who has python > 2.2 installed.... almost free hosting (but not quite)..... > > Thought some of you guys might be interested.......... > > http://www.xennos.com > > Fuzzyman How do you plan to make money off of this? From dave at pythonapocrypha.com Fri Jan 23 09:17:08 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 23 Jan 2004 07:17:08 -0700 Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <015501c3e1bb$963670b0$6401fea9@YODA> Moosebumps wrote: > So, after reading some messages about os.system, and looking at the popen > stuff and trying it a bit, I still have not found a way to keep a command > window open for several commands (on Windows 2000/XP), while seeing the > normal output in a command window. All I want to do is do what a batch file > does, but I want to actually have functions and associative arrays and all > the other niceties of python. Can you give an example of what you mean, in Perl as well as what you hoped would work in Python? I couldn't quite understand what it is that you're trying to do. > What's the deal with that? I thought Python started out as a scripting > language. And that seems like the most basic thing that a scripting > language should do. Dunno, although MS-DOS shell scripting is certainly a small subset of scripting in general. Maybe with a concrete example somebody will be able to give you a hand. -Dave From fumanchu at amor.org Sat Jan 17 15:01:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 17 Jan 2004 12:01:48 -0800 Subject: yield Message-ID: Gerrit Holl wrote: Gerrit Holl wrote: > If a generator reaches a 'yield' statement, it returns > the result of the expression behind the 'yield' statement. > ...When you call the 'next' method of the generator, the > body is executed, until it reaches a 'yield' statement. > When you call the body again, it is executed again, until > it reaches a 'yield' statement again, A bit more explicitly (so as not to mislead the original poster): When you call the body again, the function "picks up where it left off" rather than "it is executed again". Example: >>> def gen(): ... x = 0 ... while x < 5: ... yield x ... x += 1 ... >>> [a for a in gen()] [0, 1, 2, 3, 4] If it were "executed again", you'd be rebinding x to 0 each time, and would never exit the while loop, nor would x be incremented. However, since it "picks up where it left off" (i.e. the yield statement), x is incremented and the while loop continues until x == 5. Robert Brewer MIS Amor Ministries fumanchu at amor.org From graham at rockcons.co.uk Fri Jan 2 15:23:49 2004 From: graham at rockcons.co.uk (Graham Nicholls) Date: Fri, 02 Jan 2004 20:23:49 +0000 Subject: Debugging a script Message-ID: I've got a (python) program which crashes. WHat I'd like to do is something loke this: try: lots of stuff, or more pertinintly, the code which is failing except: drop in to the debugger So that I can print various things. Also, is there a way to display the line number - eg: except something: print ("DEBUG: exception %s at line number %s" % (sys.exc_type, sys.linenumber)) Thanks Python 2.3 (#1, Sep 11 2003, 14:36:40) -- #include From rjack at elegancetech.com Sat Jan 3 18:01:25 2004 From: rjack at elegancetech.com (Roger Jack) Date: Sat, 3 Jan 2004 18:01:25 -0500 Subject: Cheetah best for templating? Message-ID: I have just finished reading Code Generation In Action which uses Ruby for code generation. I would like to use Python instead. Is Cheetah the best tool to use for templating source code files and then generating code? Is there something more mature or better? Thanks! -- Roger Jack Elegance Technologies, Inc. 484.431.1775 rjack at elegancetech.com www.elegancetech.com From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Tue Jan 20 16:07:09 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 20 Jan 2004 23:07:09 +0200 Subject: I come not to bury C++, but to praise it... References: <20040114153516.GA16224@intarweb.us> <400D5B8F.8C597B9E@engcorp.com> Message-ID: >>>>> "Peter" == Peter Hansen writes: Peter> Derek wrote: >> Absolutely correct. But remember that ugly template-related >> compiler error messages are a reflection of current compiler >> technology, not a fundamental limitation of C++. I suspect >> future compilers will make debugging templates much easier. Peter> I believe I heard that claim, almost verbatim, sometime Peter> around the last time I was actively using C++, which was Peter> about a decade ago... Yes, C++ doesn't suck, it's the implementations. C++ will rock any day now. Honest. The same is true for Python - Python isn't slower than C, it's just an artifact of the current implementation. Python-in-the-sky actually runs 10-20% faster than C++ code. -- Ville Vainio http://tinyurl.com/2prnb From candiazoo at comcast.net Fri Jan 2 13:50:56 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 18:50:56 GMT Subject: Problem building on BeOS... References: Message-ID: Hmm. I got the sources directly from sourceforge. I am thinking maybe the lines are terminated with \r. I think there may be a line termination changing program somewhere on BeBits... I'll go check! Thanks! Mike In message , "Martin_v._L?wis" wrote: > Zoo Keeper wrote: > > > For some reason, the Python preprocessing balks on the "\" line > continuation > > character. Any ideas/thoughts? Is it just that my version of gcc is not > > supported? > > Yes, in combination with the way your source files are structured. > > It appears that the line ending convention differs in your source files > from the line endings that gcc expects. E.g. the source files may have > \r\n at the end of a line, whereas your gcc may expect only \n. As > a result, \\\r\n is treated as an escaped \r, which gives a stray \. > > I don't know what line ending convention your system uses, or where > you got the sources from, but it appears you need to convert them. > > Later versions of gcc support "universal text mode". > > Regards, > Martin > From FBatista at uniFON.com.ar Thu Jan 29 13:46:20 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 29 Jan 2004 15:46:20 -0300 Subject: read() on tempfile Message-ID: cherico at bonbon.net wrote: #- f = NamedTemporaryFile () #- f = write ( 'test' ) #- print f.read () #here print nothing Never used it, but are you sure it's not: f.write('test') Regards, . Facundo From martin at v.loewis.de Fri Jan 16 02:42:51 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 16 Jan 2004 08:42:51 +0100 Subject: PEP for new modules (I read PEP 2) In-Reply-To: References: Message-ID: Christoph Becker-Freyseng wrote: > So basically I want to relocate the real Specification, because the more > specific it gets the more it looks like a documentation and the prePEP > grows and grows ... > > > Is this a valid option for a PEP? If you are asking: "Can we have an implementation before we write the PEP?", the answer is "Certainly, yes". The PEP procedure is designed to avoid wasting efforts in implementing ideas that have no chance to ever get accepted to the Python core. If this is no concern for you (i.e. you are willing to accept the risk of wasting efforts), you can certainly implement the thing, wait for user feedback, and then write the PEP. Regards, Martin From tjreedy at udel.edu Wed Jan 14 23:39:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Jan 2004 23:39:47 -0500 Subject: Deleting objects References: Message-ID: wrote in message news:c542f8acd755de732c9da8fc39fbb50a at news.teranews.com... > Say I have an object (foo), that contains an > array (bar) of references to other objects. > > Now I want to puff some of the objects from the > array so that I remove the array element, and > destroy the oject. > > but when I do: > > del foo.bar[0] > > Python says: > object doesn't support item deletion What is the actual type of foo.bar? >>>type(foo.bar) # prints what? tjr From gerrit at nl.linux.org Sat Jan 17 11:59:21 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 17 Jan 2004 17:59:21 +0100 Subject: yield In-Reply-To: <20040117170808.GA21486@mrna.tn.nic.in> References: <20040117170808.GA21486@mrna.tn.nic.in> Message-ID: <20040117165920.GA31881@nl.linux.org> > i didnt understand the purpose of 'yield' keyword and the concept of 'generators' in python. can someone explain me with a small example how generators differ from normal function calls? > kindly enlighten You can see 'yield' as a continuable function: def f(): yield time.time() yield time.time() yield time.time() now f() will return a generator, with a .next() method. Try: g = f() g.next() g.next() g.next() on the interactive prompt, and see what happens... yours, Gerrit. -- Mozilla _is_ the web: it grows faster than you can download it. 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 From google at axiomatize.com Thu Jan 15 18:29:21 2004 From: google at axiomatize.com (Laurent Therond) Date: 15 Jan 2004 15:29:21 -0800 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> Message-ID: <265368cb.0401151529.50c36679@posting.google.com> I used the interpreter on my system: >>> import sys >>> sys.getdefaultencoding() 'ascii' OK >>> from cStringIO import StringIO >>> b = StringIO() >>> b.write('%d:%s' % (len('string'), 'string')) >>> print b.getvalue() 6:string OK >>> c = StringIO() >>> c.write('%d:%s' % (len('string?'), 'string?')) >>> print c.getvalue() 7:string? OK Did StringIO just recognize Extended ASCII? Did StringIO just recognize ISO 8859-1? ? belongs to Extended ASCII AND ISO 8859-1. >>> print c.getvalue().decode('US-ASCII') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 8: ordinal not in range(128) >>> print c.getvalue().decode('ISO-8859-1') Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\encodings\cp437.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\x82' in position 8 : character maps to >>> OK It must have been Extended ASCII, then. I must do other tests. From cy.fbp.eryvtvne at ncbybtrglxn.pbz Mon Jan 12 09:28:58 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Mon, 12 Jan 2004 15:28:58 +0100 Subject: [Webware] FormKit - dynamic fields problem Message-ID: <5lb5001v1j64v6kdbteaas235d5sj6lan2@4ax.com> I use Webware and FormKit. I have a problem with dynamic added field to the form. The following code creates one input field and two submit buttons. I would like to add more (up to 4) input fields after pressing "more" button. It does not work and I have no idea how to solve it. import re from WebKit.Page import Page from FormKit import Form, Fields, Validators from FormKit.FormKitMixIn import FormKitMixIn class DynamicProblem(FormKitMixIn, Page): def __init__(self): Page.__init__(self) notEmpty = Validators.NotEmpty() f = self.form = Form.Form() self.addForm(f) f.addField(Fields.TextField('msg', validators=[notEmpty])) f.addField(Fields.WebKitSubmitButton('more')) f.addField(Fields.WebKitSubmitButton('send')) def sleep(self, trans): self.resetForms() Page.sleep(self, trans) def writeHTML(self): self.write(self.form.dump()) def extendForm(self): notEmpty = Validators.NotEmpty() f = self.form nr = len(filter(lambda x:re.match(r'^msg',x), self.form.values().keys())) if nr < 4: f.addField(Fields.TextField('msg%d' % nr, validators=[notEmpty])) def actions(self): return ['more', 'send'] def more(self): if self.form.isSuccessful(): self.extendForm() def send(self): if self.form.isSuccessful(): pass -- JZ From bart_nessux at hotmail.com Fri Jan 16 08:38:04 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 16 Jan 2004 08:38:04 -0500 Subject: python & mathematical methods of picking numbers at random In-Reply-To: <59idnYa3_eQMtJrd4p2dnA@comcast.com> References: <59idnYa3_eQMtJrd4p2dnA@comcast.com> Message-ID: Terry Reedy wrote: > "Bart Nessux" wrote in message > news:bu6rvn$njg$1 at solaris.cc.vt.edu... > >>Jeff Epler wrote: >> >>>But why are *you* using >>> random.sample(range(len(x)), 25) >>>instead of >>> random.sample(x, 25) >>>? > > >>Because it works and it's fast and len(count) changes every drawing. > > > I think you missed Jeff's point, which is that you are repeating part of > the work that sample tries to do for you. From the Lib Ref: > " > sample(sequence, k): Return a k length list of unique elements chosen from > the population sequence. Used for random sampling without replacement. New > in version 2.3. > > Returns a new list containing elements from the population while leaving > the original population unchanged. The resulting list is in selection order > so that all sub-slices will also be valid random samples. This allows > raffle winners (the sample) to be partitioned into grand prize and second > place winners (the subslices). > " > When you get the sample from range(n), you have to use them as indexes into > x to get the actual list of names. But the indexing and extraction is what > sample would do if you gave it x instead of range(x)! > > Terry J. Reedy > > Also, the below statement should be removed from random's documentation... it's where I got the idea to do: random.sample(range(len(x)), 25) instead of random.sample(x, 25) "To choose a sample from a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60)." http://www.python.org/doc/current/lib/module-random.html From ferrell at diablotech.com Thu Jan 15 18:29:29 2004 From: ferrell at diablotech.com (Robert Ferrell) Date: 15 Jan 2004 15:29:29 -0800 Subject: Redefining __call__ in an instance Message-ID: <73b00f0c.0401151529.676347b6@posting.google.com> I have a question about assigning __call__ to an instance to make that instance callable. I know there has been quite a bit of discussion about this, and I've read all I can find, but I'm still confused. I'd like to have a factory class that takes a string argument and returns the appropriate factory method based on that string. I'd like the instances to be callable. Like this: fact = Factory('SomeThing') aSomeThing = fact(some args) anotherFact = Factory('SomeThingElse') anotherThing = anotherFact(some other args) The way I thought to do this was to assign the __call__ attribute of the fact instance to the appropriate factory method in __init__. That does not work, as many others have pointed out. I know there are workarounds. The appended code shows the variants I know of. I can use one of them, but they are not quite what I am looking for. Have I missed the key message that explains how to make new-style classes callable, with the called method unique to each instance? thanks, -robert """Test use of __call__ in a (new style) class. The classes below show various ways of making instances of a class callable. The goal is to make an instance callable, with the called method defined distincly for each instance. """ def firstFunc(word = 'up'): """This is the method to call, when an instance is invoked.""" print "This is firstFunc, word %s." % word return class callWorks(object): """This works, since the called method is defined in the class.""" def __init__(self): pass def __call__(self, word = 'up'): print 'This is inside callWorks, word %s.' % word return class callNoWork(object): """This doesn't work, since __call__ is defined for the method, not the class.""" def __init__(self): # This does not make an instance of callNoWork callable self.__call__ = firstFunc class callWorksNoFun(object): """This works, but since the class's method is being called, the default arguments are defined by the class, and do not properly reflect the default arguments of the method that wants to be called.""" def __init__(self): self._callFunc = firstFunc def __call__(self, word = None): # Although an instance of callWorksNoFun is callable, # the default arguments are wrong self._callFunc(word) return class addCallAttribute(object): """Add the attribute 'callMe', which is the callable function. This works fine, but requires the user to invoke this as instance.callMe(), rather than just instance().""" def __init__(self): self.callMe = firstFunc # Simplest thing cw = callWorks() cw() # Natural thing to try, but doesn't work cnw = callNoWork() # The instance, cnw, is not callable. try: cnw() except Exception, exception: print 'Call did not work, gave exception: %s.' % exception # Works, but actually invoking class method, not instance's method cwNF = callWorksNoFun() # The instance cwNF is callable, but the default value for the callable is wrong. # This works fine cwNF('No up') # This should default to print 'Up', but instead it defaults to None. cwNF() # Fine, but requires user to invoke instance.callMe(), rather than just instance(). aCA = addCallAttribute() # To call the instance, use the callMe attribute. That respects defaults fine. aCA.callMe() From pgmoscatt at optushome.com.au Sat Jan 24 06:32:19 2004 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Sat, 24 Jan 2004 21:32:19 +1000 Subject: Tkinter Base Window Message-ID: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Ok.... I am pretty new to Python (as you may have gathered from previous posts). So now it time for another one of my ridiculous questions.... :-) When using 'Tkinter', what is used as the base window to work from, meaning what widget do I use to place all other widgets onto to create a custom dialog ? Pete From max at alcyone.com Fri Jan 23 02:16:44 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Jan 2004 23:16:44 -0800 Subject: Mixing protocols in pickles? References: Message-ID: <4010CA5C.2B09D009@alcyone.com> Tim Peters wrote: > Try getting gzip out of your test program; pickles are exercised more > heavily than gzip. Try it with both pickle and cPickle; it might > matter. Actually in this test case gzip was not being used at all. > That's especially puzzling to me because that error message isn't one > Python > produces: all messages of this form produced by the core spell it > "module" > instead of "Module". Yes, that was from a client typing in the results; I verified that the error was genuine. A typo here, a typo there. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Freedom is never voluntarily given by the oppressor. -- Dr. Martin Luther King, Jr. From davidb at mcs.st-and.ac.uk Fri Jan 9 14:15:58 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 9 Jan 2004 11:15:58 -0800 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> <4de76ee2.0401081318.bab6f62@posting.google.com> Message-ID: <4de76ee2.0401091115.1a242974@posting.google.com> Jacek Generowicz wrote in message news:... > Thank you for your refreshingly constructive followup. No problem. > davidb at mcs.st-and.ac.uk (David Boddie) writes: > > > Jacek Generowicz wrote in message news:... > > > [...] > > > > revealed that the basic information about the PYTHONDOCS environment > > variable can be found at the foot of the following page: > > > > http://www.python.org/dev/doc/devel/lib/module-pydoc.html > > This strikes me as not very helpful to someone looking to solve the > problem of _keyword_ documentation not working. Remember, we're > talking about poor lost newbies. Well, it addresses part of the problem, but I mentioned it because it reveals the inadequacy of the available information. Not that it's the fault of the pydoc documentation author(s) for this shortcoming, of course. The page does link to a page which deals with the issue of feedback: http://www.python.org/dev/doc/devel/lib/about.html ;-) [Draft document - Setting it up] > > If the documentation is required then go to:: > > > > http://www.python.org/download/ > > > > and find the appropriate documentation. Download it and install it > > in a place where it can be read by those who will be using it. > > How about > > If the documentation is required then go to: > > http://www.python.org/doc//download.html > > and download the HTML documention and install it in a place where it > can be read by those who will be using it. > > ? Perhaps. I'd hesitate to use "" in the URL because it may actually be displayed as a link in whichever browser is used to display the documentation. Note that I'd used the "::" at the end of the initial sentence because I'd subversively used reStructuredText markup (http://docutils.sf.net/). How about the following text? If the documentation is required then go to:: http://www.python.org/doc/download.html and download the HTML documention which is suitable for the version of Python you wish to use and install it in a place where it can be read by those who need it. > > Enabling this by default > > ------------------------ > > Any ideas? > > I guess this would require the HTML documentation to be bundled in > with the Python distribution tarball, and I can imagine that being an > unpopular suggestion. I meant, "How can one set up the interpreter so that PYTHONDOCS is already set to the correct value?" For example, on a Linux system, one could ensure that each user's environment has this variable set up by modifying a relevant file in their home directory. I don't know how you would do this on the Mac or on Windows. Another approach would be to modify the sitecustomize.py file; see the site.py for information about this. > Now, currently one gets the following from Python's built-in help: > > >>> help('if') > > Sorry, topic and keyword documentation is not available because the Python > HTML documentation files could not be found. If you have installed them, > please set the environment variable PYTHONDOCS to indicate their location. > > How about augemnting this with something like: > > The HTML documentation files can be obtained from > > http://www.python.org/doc//download.html > > ? Maybe you should forward this suggestion to one of the Python developers; unless they're reading this thread already. > And then there's the wart surrounding the following: > > lambda, and, not, or > > I always get > > could not read docs from $PYTHONDOCS//ref/lambda.html > > Note, I even get 'lambda.html' in the message when asking for help on > the other three. Any ideas what's going on there ? This works for me, although I am using the docs from Python 2.2 with the Python 2.3 interpreter. Which versions of each are you using? Maybe something changed at some point - some files were reorganised, or something? > Furthermore, is there anyway of getting help of keywords via pydoc ? It's the same approach: PYTHONDOCS= pydoc David From galfip at freestart.hu Sun Jan 18 08:01:14 2004 From: galfip at freestart.hu (Peter Galfi) Date: Sun, 18 Jan 2004 14:01:14 +0100 Subject: Fw: PDF library for reading PDF files Message-ID: <000c01c3ddc3$27312800$7800a8c0@mailer> Hi! I am looking for a library in Python that would read PDF files and I could extract information from the PDF with it. I have searched with google, but only found libraries that can be used to write PDF files. Any ideas? Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ravenar at cox.net Sat Jan 31 22:28:04 2004 From: ravenar at cox.net (Corwan) Date: 31 Jan 2004 19:28:04 -0800 Subject: What's the difference between win32ui and win32gui? Message-ID: <543bb43c.0401311928.3be1fe36@posting.google.com> What's the difference between win32ui and win32gui? From skip at pobox.com Sat Jan 10 13:36:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 12:36:21 -0600 Subject: Setting up test for XML-RPC In-Reply-To: References: Message-ID: <16384.17957.721185.451449@montanaro.dyndns.org> MB> OK, I tried the obvious and it worked. : ) I just changed the call MB> to server.pow(3,5) and it returns the correct result. I wonder why MB> they aren't set up that way in the first place. The xmlrpclib module predates SimpleXMLRPCServer by a fair amount. The getStateName() test was meant to connect to UserLand's original test server. As I recall, that was the sole function it exported. I don't see any reason why SimpleXMLRPCServer needs to implement getStateName(), but I imagine it would be reasonable for xmlrpclib's test to call pow(). MB> But the second question still stands. I am running both the client MB> and server on my own machine now (Windows 2000). Would I just need MB> Python and web server if they were different machines? I would like MB> to avoid installing a bunch of software on the 20 machines if MB> possible. You should be able to build a server and a client with just the standard Python distribution. If performance is an issue (it will be if you are passing large chunks of data back and forth), there are some things you can do to speed it up: * Install Fredrik Lundh's sgmlop module. * Marshal or pickle your data first, then base64 encode them before passing them to or fro. This greatly reduces the number of XML tags on-the-wire, and thus the encode/decode time and data size. Obviously, this only works if you are talking Python-to-Python. * Tweak things to gzip-encode the traffic between server and client. * Use the xmlrpclib.MultiCall class to bundle logical multiple calls into a single physical XML-RPC call. Skip From eric.brunel at N0SP4M.com Mon Jan 19 09:34:59 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 15:34:59 +0100 Subject: Analysing Word documents (slow) What's wrong with this code please! References: <3d06fae9.0401161351.75e7f5a@posting.google.com> Message-ID: jmdeschamps wrote: > Anyone has a hint how else to get faster results? > (This is to find out what was bold in the document, in order to grab > documents ptoduced in word and generate html (web pages) and xml > (straight data) versions) > > # START ======================== > import win32com.client > import tkFileDialog, time > > # Launch Word > MSWord = win32com.client.Dispatch("Word.Application") > > myWordDoc = tkFileDialog.askopenfilename() > > MSWord.Documents.Open(myWordDoc) > > boldRanges=[] #list of bold ranges > boldStart = -1 > boldEnd = -1 > t1= time.clock() > for i in range(len(MSWord.Documents[0].Content.Text)): > if MSWord.Documents[0].Range(i,i+1).Bold : # testing for bold > property Vaguely knowing how pythoncom works, you'd really better avoid asking for MSWord.Documents[0] at each loop step: pythoncom will fetch the COM objects corresponding to all attributes and methods you ask for dynamically and it may cost a lot of time. So doing: doc = MSWord.Documents[0] for i in range(len(doc.Content.text)): if doc.Range(i,i+1).Bold: ... may greatly improve performances. > if boldStart == -1: > boldStart=i > else: > boldEnd= i > else: > if boldEnd != -1: > boldRanges.append((boldStart,boldEnd)) > boldStart= -1 > boldEnd = -1 > t2 = time.clock() > MSWord.Quit() > > print boldRanges #see what we got > print "Analysed in ",t2-t1 > # END ===================================== > > Thanks in advance -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nopa90 at msn.com Sat Jan 17 01:22:09 2004 From: nopa90 at msn.com (maxwell hammer) Date: Sat, 17 Jan 2004 06:22:09 +0000 Subject: Python wrapper to ffmpeg and speex Message-ID: Wrapper to ffmpeg or the libavcodec part atleast and another wrapper to the speex library _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail http://join.msn.com/?page=dept/bcomm&pgmarket=en-ca&RU=http%3a%2f%2fjoin.msn.com%2f%3fpage%3dmisc%2fspecialoffers%26pgmarket%3den-ca From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 17:01:40 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 14:01:40 -0800 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: "Bent C Dalager" wrote in message news:bu3iv2$n2u$4 at tyfon.itea.ntnu.no... > In article <4004EC9E.1E2E2893 at alcyone.com>, > Erik Max Francis wrote: > > > >If you're saying that you've come to the realization that volunteer > >programers on a project with which you only have a passing interest > >won't follow your orders and do whatever you say, I'd say pointing that > >out is less like "denigration" and more like "common goddamn sense." > > It is, never the less, worth pointing out. It would seem that Brandon > entered the scene with an idea that OSS developers might be incredibly > useful to him for some reason or other. Other game developers might > very well have the same idea. When Brandon finds out that this is not > the case and describes in some detail why OSS won't do the job for > him, than this can certainly be useful for other game developers to > learn so that don't have to spend 6 months figuring out the exact same > thing themselves. > > The conclusion may seem obvious to _you_ but this is no guarantee that > everyone else also possesses this knowledge. OSS is being hailed as > the second coming, and it comes as no surprise therefore that some > people might be deluded into thinking they could harness this power to > cure cancer overnight or land a man on Mars by 2005. Agreed, and more specifically, there is a huge *cultural divide* between most OSS developers and proprietary commercial developers who simply want to add some OSS "to get the boring bits over with." There are also huge cultural divides between Linux and Windows developers, and again between commercial game developers and hobbyist game developers. These cultural divides are what make the vast majority of people useless to my purposes, not some table waiter fetish as some other poster indicated. The problem is, the OSS people are inevitably going to pursue *their* goals, and there is not much overlap between their goals and *my* goals. They don't think about problems the same way, they don't work the same way, they don't manage the same way, they don't ship to the same schedules, they don't apply the same degree of seriousness to various endeavors... the list goes on and on and on. OSS people are doing "their thing," and it is not my thing. Even though, in the abstract, I'm perfectly willing to use BSD style licenses as part of my ongoing development. In fact, one can identify the locus of problems by simply asking, "How many OSS game developers are willing to work on something with a BSD license?" Precious few. Most BSD licenses out there are not game software. BSD is a good indicator that someone cares about commercial concerns. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Desperation is the motherfucker of Invention." - Robert Prestridge From hgeldenhuys at gims.com Wed Jan 21 10:00:03 2004 From: hgeldenhuys at gims.com (Herman Geldenhuys) Date: Wed, 21 Jan 2004 17:00:03 +0200 Subject: Dailing modem. References: Message-ID: <004001c3e02f$3fcab5c0$b10d10ac@metasalio> Thanks for the reply. Yes, it is on Windoze. Is the win32ras realy what I want? Basically what I am trying to do, is to convert my phone/voice-modem/computer into a "computer-phone". I need to dail a number and disconnect via an interface on the computer using python. So, I am dailing normal numbers and not RAS servers. Or am I missing something? Thanks again H ----- Original Message ----- From: "Tim Golden" To: "'Herman Geldenhuys'" ; Sent: Wednesday, January 21, 2004 4:29 PM Subject: RE: Dailing modem. > > I need to dail a modem from python and disconnect it again. > > Assuming you're on Windows (since you're talking about TAPI & COM) > look at the win32ras module in Mark Hammond's win32 extensions. > > 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 Thu Jan 29 09:52:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Jan 2004 09:52:13 -0500 Subject: crc-16 References: Message-ID: <40191E1D.D912C1BB@engcorp.com> eugene wrote: > > I looked for a crc-16(crc 16) function to use but couln't find one > that worked: > > This one is working .. > > def crc16(s): [snip] Since eugene started the thread, I'll continue it by posting one that we've been using. It's likely not as fast (eugene's used a lookup table for some of the work) but it has the added benefit of allowing you to specify which mask value will be used, so it is more general. You also have to call it once for each byte of data rather than wait for all the data to be collected but sometimes that's more appropriate anyway. # 16-bit CRCs should detect 65535/65536 or 99.998% of all errors in # data blocks up to 4096 bytes MASK_CCITT = 0x1021 # CRC-CCITT mask (ISO 3309, used in X25, HDLC) MASK_CRC16 = 0xA001 # CRC16 mask (used in ARC files) #---------------------------------------------------------------------------- # Calculate and return an incremental CRC value based on the current value # and the data bytes passed in as a string. # def updcrc(crc, data, mask=MASK_CRC16): # data_length = len(data) # unpackFormat = '%db' % data_length # unpackedData = struct.unpack(unpackFormat, data) for char in data: c = ord(char) c = c << 8 for j in xrange(8): if (crc ^ c) & 0x8000: crc = (crc << 1) ^ mask else: crc = crc << 1 c = c << 1 return crc & 0xffff -Peter From nav+posts at bandersnatch.org Thu Jan 8 11:58:54 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Jan 2004 11:58:54 -0500 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong writes: > I have this dict that maps a name to a sequence of other names. > I want to have it reversed, i.e., map the other names each to > the key they belong to (yes, the other names are unique and > they only occur once). Like this: That's almost spooky, I'm working on a project for which I needed something like this. I've just read the entire thread and my solution seems pretty naive: def invertdict(d): """Returns a dict whose key-value pairs are the value-key pairs of d.""" ret = {} for k in d: ret[d[k]] = k return ret I only need to do it once or twice, at program start-up, so time- efficiency wasn't a critical factor. I'm guessing the list comprehension tactics are faster, though. Sorry about being late to the party, I've been away from Usenet for about three weeks... 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 marco at bubke.de Wed Jan 7 03:33:28 2004 From: marco at bubke.de (Marco Bubke) Date: Wed, 07 Jan 2004 09:33:28 +0100 Subject: shelve and writeback Message-ID: Hi If I do shelve.open(filename='prim', protocol=pickle.HIGHEST_PROTOCOL, writeback=True) I get on some maschines(its the some python): Traceback (most recent call last): File "server.py", line 45, in ? daemon.connectPersistent(GridManager(),'gridmanager') File "server.py", line 10, in __init__ self.server = object_manager.PrimServer() File "/home/marco/projects/gridcomputing/ronny/object_manager.py", line 7, in __init__ self.values = shelve.open(filename='prim', protocol=pickle.HIGHEST_PROTOCOL, writeback=True) File "/usr/local/lib/python2.3/shelve.py", line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File "/usr/local/lib/python2.3/shelve.py", line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary) File "/usr/local/lib/python2.3/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.3/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.3/bsddb/__init__.py", line 186, in hashopen d.set_flags(hflags) bsddb._db.DBInvalidArgError: (22, 'Invalid argument') Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in ignored closing database Exception exceptions.AttributeError: "PrimServer instance has no attribute 'values'" in > ignored is this a bug? thx Marco From paul at prescod.net Tue Jan 20 12:07:07 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 20 Jan 2004 09:07:07 -0800 Subject: calling Pyrex results from C Message-ID: <400D603B.2010007@prescod.net> [cross-posted to the pyrex list for interest and then resent to the main list] Kyler says: > I need to submit C/C++ code for a class. > ... > I'd like to keep my sanity and satisfy the course > requirements by programming in Python and converting > the code to C. I have three questions: 1. How is your teacher going to react when you hand in obfuscated-ish C code that depends on the whole Python interpreter _and_ PIL? If they tried force you into a particular language it is probably because they want to avoid the interpreter dependency headache. 2. Would you mind if further discussion happend on the Pyrex mailing list? Someone there may have tried this before. 3. Are you initializing the Python interpreter at all? I am going to guess that this is related to your problem. After all you are "embedding" rather than "extending" Python. main() is in C. http://www.python.org/doc/current/ext/embedding.html Paul Prescod From jcarlson at nospam.uci.edu Mon Jan 26 01:56:45 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 22:56:45 -0800 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: >>Never underestimate the power of stupidity (or ignorance, or denial, > > or...). > >>Speaking of which... >>http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html >> >> - Josiah > > Amazing! I didn't know he could completely miss the point so much. Spend some time reading this guy's blog: http://livejournal.com/users/malcubed He links examples of the current administration's utter stupidity a couple times each day. We don't get along that well (for various reasons), but he's on top of the political scene. - Josiah From james at logicalprogression.net Thu Jan 15 05:25:48 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 15 Jan 2004 10:25:48 +0000 Subject: Bug or feature? In-Reply-To: References: Message-ID: <200401151025.48780.james@logicalprogression.net> On Thursday 15 January 2004 5:40 am, Alexey Nezhdanov wrote: > Hello. Found a strange python behaivoir while writing some object. I've > stripped out all other stuff so the problem is stright here: > ================================= > #!/usr/bin/python > > class Object: > def __init__(self,val): > self.val=val > > def Sub(self,delta): > self.val-=delta > return delta > > c=Object(1) > > ### case 1 ### > d=c.Sub(1) > c.val+=d > print 'case A:',c.val > > ### case 2 ### > c.val+=c.Sub(1) > print 'case B:',c.val > ================================= > Case 1 and case 2 prints out different calues (1 and 2 respectively). > Do not know - if this is a bug or feature of python. > > -- > Alexey Nezhdanov This is the expected behaviour. The terms on the RHS (c.val and c.Sub(1) in case 2) are evaluated left to right before being added together. If you'd reversed the terms of case 2 and written: c.val = c.Sub(1) + c.val c.val would end up as 1. James From nuffsaid at phreaker.net Fri Jan 30 10:30:36 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 30 Jan 2004 16:30:36 +0100 Subject: NEWLINE character problem References: Message-ID: On Fri, 30 Jan 2004 16:16:12 +0200, Dragos Chirila wrote: > I have a string and I want to split it by NEWLINE character. > > It is knowned that "Microsoft Windows, Apple's Macintosh OS and various > UNIX, all use different characters to mark the ends of lines in text files. > Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return > (ASCII character 13), and Windows uses a two-character sequence of a > carriage return plus a newline". So, PLEASE don't tell me to use 'split' by > '\n' because it won't work. > > I know about the Python support, opening files with 'U' flag, for reading in > universal newline mode. But this is not the case. My script receives a > string, can be the content of a file text from Windows or Unix system. I > want to make sure that I can split this string by NEWLINE character. Say your string is s; then you could use the following function (untested!) to make sure that s uses \n only: def fix_lineendings(txt): if txt.count('\r\n'): # MS DOS txt = txt.replace('\r\n', '\n') elif txt.count('\r'): # Mac txt = txt.replace('\r', '\n') return txt Simply write: s = fix_lineendings(s) HTH / Nuff From bkelley at wi.mit.edu Wed Jan 28 15:13:16 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 28 Jan 2004 15:13:16 -0500 Subject: Simple Database Package In-Reply-To: <8089854e.0401280622.4e145267@posting.google.com> References: <8089854e.0401280622.4e145267@posting.google.com> Message-ID: <4018176c$0$564$b45e6eb0@senator-bedfellow.mit.edu> Fuzzyman wrote: > I'm looking to build a simple database application for use on the > desktop (customer contact and feedback database). > > Anyone able to reccomend a simple module / package I can use... ? You might think about SQLObject. http://sqlobject.org/ It is basically an easy to program front end for various databases. It can use SQLite and a whole bunch of other databases. They even include the start for a contact database. I have found it pretty easy to use. Of course, you will also need a database backend like sqlite. Brian From ny_r_marquez at yahoo.com Thu Jan 1 08:58:26 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 1 Jan 2004 05:58:26 -0800 Subject: PythonWin problems References: Message-ID: <8a27e309.0401010558.598eb99c@posting.google.com> The bug you are experiencing has been posted already in the "Python for Windows Extensions" since 2003-08-08. See: https://sourceforge.net/tracker/index.php?func=detail&aid=785374&group_id=78018&atid=551954 Also, a workaround was posted by another user on 2003-09-10. See: https://sourceforge.net/tracker/index.php?func=detail&aid=804178&group_id=78018&atid=551954 Why this has not been fixed yet is a good question. -Ruben "Colin J. Williams" wrote in message news:... > PythonWin has been my favourite IDE for quite a while. > > When one right clicks on a .py file in the Windows Explorer, among the > options are Open and Edit. The former is the default and executes > Python, with the selected script. The latter activates the PythonWin > editor, with the selected script. > > Since, most frequently, I wish to edit the script, or execute it with > the debugger, I tried changing the default to Edit, using the Edit File > Type menu. > > Unfortunately, this leads to a couple of problems: > > 1. Any activity becomes horrendously slow, and > 2. The following message appears: > LoadBarState failed - LoadBarState failed (with win32 exception!) > [Dbg]>>> > > Does anyone have a workaround suggestion? > > Thanks. > > Colin W. From tim.golden at viacom-outdoor.co.uk Tue Jan 27 03:53:17 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 27 Jan 2004 08:53:17 -0000 Subject: winapi: mouseclick Message-ID: >-----Original Message----- >From: KNS [mailto:netquest at sympatico.ca] >Sent: 27 January 2004 08:19 >To: python-list at python.org >Subject: Re: winapi: mouseclick > > > >Just to add some clarification, this is in fact a Python question. >I'm just working within the Windows environment. And, now that >I'm here, I'm certain this is child's play for many of you, so >a bit of help would be most welcomed. > >Thanks. > >KNS wrote: >> >> Hello, >> >> Can someone please suggest how to test for a mouse click using >> the WinAPI? I have dispatched a windows application and would >> like to detect any mouseclicks (and keyboard entry for that >matter)... >> >> Thanks. >> > Your question is not the most precise one I've ever seen. If you have written a Windows app then you presumably understand how the Windows messaging setup works. In which case, what you need to do is to handle WM_LBUTTONDOWN and related messages. If you're not sure which messages to go for, look at this: http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/use rinput.asp which gives an overview. There's an example of doing this kind of thing in Python using the ctypes modules: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/208699 You can also do it with the win32all extensions from Mark Hammonds pages: http://starship.python.net/crew/mhammond/win32/Downloads.html If this isn't really what you were asking, could you post a segment of code showing what you're about and where you're stuck? 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 fuf at mageo.cz Fri Jan 30 06:33:38 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Fri, 30 Jan 2004 12:33:38 +0100 Subject: isinstance() bug In-Reply-To: <20040129170037.GF18498@unpythonic.net> References: <20040129170037.GF18498@unpythonic.net> Message-ID: <20040130113338.GA992@foof.i3.cz> Jeff Epler wrote: [snip] >So I guess that makes me at least -6 if I get a vote for each problem >I can imagine. uff - that was an exhaustive reasoning. thank you Jeff :) -- fuf (fuf at mageo.cz) From arian.novruzi at mathstat.uottawa.ca Thu Jan 15 09:13:05 2004 From: arian.novruzi at mathstat.uottawa.ca (A. Novruzi) Date: 15 Jan 2004 06:13:05 -0800 Subject: Can MayaVi visualize 3D functions in an unstructured grid ? Message-ID: <11d4728b.0401150613.1bfb4ca3@posting.google.com> Hi, I am looking for a free 3D visualization software, running in Linux, and able to visualize 3D functions in nonstructured mesh (basically, my mesh is a set of thetraheders used for some 3D FE computations). Can anyone confirm that indeed MayaVi can visualize 3D functions in nonstructured mesh? I went through the manuals but I didn't find that MayVi can do so. Thank you, Arian Novruzi From Mike at DeleteThis.Geary.com Mon Jan 19 22:27:53 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 19 Jan 2004 19:27:53 -0800 Subject: Launching Wordpad on Windows References: Message-ID: <100p81q3kshsuca@corp.supernews.com> > > I'm trying to find a clean way to launch a Wordpad > > editor on Windows. By "clean", I mean that it should > > work on as many versions of Windows as possible, > > and it shouldn't require installing any extra software. > > I assume everyone has win32api and its friends. > > > > The problem is to find the path to wordpad.exe. At > > first I just copied the path from my XP machine: > > c:\Program Files\Windows NT\Accessories\WORDPAD.EXE > > > > I verified that the same path works on W2K, but I > > don't know about older versions. Never hard code a path like that. It definitely won't work on all versions of Windows. It won't even work on all XP systems. The Program Files directory isn't always on the C: drive! > > With some labor I was able to come up with a > > longer, more obfuscated bit of code: > > > > [code using the App Paths registry key] > > > > I would like to solicit learned opinions about this. > > Which version will work in more versions of > > Windows? Is there a better approach? You can do it with App Paths, but that's way too much work. It's not the Windowsonic way to do it. :-) > This works for me: > (Using WinXP Pro) > > >>> import os > >>> os.system("start wordpad") > 0 > > Hope this helps. I wouldn't recommend os.system. The problem is that it starts a command shell. You didn't notice this because you're testing from a console window, so the secondary command shell runs in the same console window you're already using. But if you put this code in a non-console app, it will open a new console window in addition to the WordPad window. That window will close right away because you're using the 'start' command, but it's extra screen activity you don't want. So what's the right way to do it? The underlying Windows function you're looking for is ShellExecute(). That's the easiest way to launch an app. It knows all about App Paths and the environment PATH. It's the same function that gets called if you do a Start/Run... in the Windows UI. You can use win32api.ShellExecute, or better yet, the os.startfile function calls ShellExecute, so you don't even need win32api: >>> import os >>> os.startfile('wordpad.exe') -Mike From andymac at bullseye.apana.org.au Sun Jan 25 19:17:21 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 26 Jan 2004 11:17:21 +1100 (EST) Subject: xrange not hashable - why not? In-Reply-To: <20040125144724.GA13741@nl.linux.org> References: <20040125144724.GA13741@nl.linux.org> Message-ID: <20040126105606.F83014@bullseye.apana.org.au> On Sun, 25 Jan 2004, Gerrit Holl wrote: > why is an xrange object not hashable? xrange() returns an iterator. iterators seem universally unhashable, probably because they can't be deemed "concrete", though I can't find anything in the 2.3.3 docs about this - perhaps the relevant PEPs might. > I was trying to do something like: > > comments = { > xrange(0, 4): "Few", > xrange(4, 10): "Several", > xrange(10, 100): "A lot", > xrange(100, sys.maxint): "Can't count them"} > for (k, v) in comments.items(): > if n in k: > commentaar = v > break Even if it worked, there's a nasty performance trap in the sys.maxint case: if the sys.maxint case is the first returned by the items() method call and n < 100, the "in" will evaluate the sys.maxint xrange iterator. Without more info, I don't see why a dictionary is that useful in this case, so I would actually write the above as: comments = (((0, 4), "Few"), ((4, 10), "Several"), ((10, 100), "A lot")) commentaar= "Can't count them" for (k, v) in comments: if n in xrange(*k): commentaar = v break -- 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 jacek.generowicz at cern.ch Tue Jan 13 08:14:38 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2004 14:14:38 +0100 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <95aa1afa.0401130424.49749912@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > But it is successful! Look at people working on AI, theory of programming > languages, etc: they will (presumably) know Lisp. OTOH, look at people > working on number crunching: they will (presumably) know Fortran. > It turns out that the number of people working on numerical analysis (or > using numerical tools) is much larger than the number of people working on > abstract things, so you will have more people knowing Fortran than people > knowing Lisp. But this fact alone does not mean that one language is more > successfull than the other in its application niche. You could compare > Python and Perl (or Ruby) and say that one is more successful than > the other, but Lisp and Fortran have different audiences and you cannot > estimate their success just as number of users. Lest anyone infer that Lisp has an "application niche" consisting of AI and theory of programming languages ... take a look at http://www.franz.com/success/ and glance at the column on the left. I suspect that Aahz' working definition of "successful" had more to do with success in terms of popularity, rather than success in terms of technical excellence: please remember that quality and popularity are very weakly correlated. If you want to analyze the popularity of a technology, you will get far better insight by studying the sociological and historical contexts surrounding it rather then its actual technical merits. For example, how many readers of this post will be surprised to learn that (most) Common Lisp implementations compile to efficient native machine code, that Common Lisp has an ANSI standard which includes very powerful support for object-oriented programming (to name but two features that everybody "knows" it doesn't have) ? Go on, raise your hand if you thought that "Lisp" is a slow, interperted functional langugage. You will need to take, amongst many other things, the abundance of such (non-)facts into consideration, if you want to understand Lisp lack of "success". Similarly, the "success" of C++ probably has more to do with having introduced OOP to the C programmers of the world, that with its suitability for doing OOP. -- ...Please don't assume Lisp is only useful for Animation and Graphics, AI, Bioinformatics, B2B and E-Commerce, Data Mining, EDA/Semiconductor applications, Expert Systems, Finance, Intelligent Agents, Knowledge Management, Mechanical CAD, Modeling and Simulation, Natural Language, Optimization, Research, Risk Analysis, Scheduling, Telecom, and Web Authoring just because these are the only things they happened to list. -- Kent Pitman From luc.saffre at gmx.net Sat Jan 24 07:33:17 2004 From: luc.saffre at gmx.net (Luc Saffre) Date: Sat, 24 Jan 2004 14:33:17 +0200 Subject: "Bad file descriptor" after py2exe or Installer In-Reply-To: References: <3FD8B25A.7080103@gmx.net> <3FD97E83.2000703@gmx.net> <3FDDCE47.2000708@gmx.net> Message-ID: <4012660D.3050809@gmx.net> On 30/12/2003 0:20, Thomas Heller wrote: > Luc Saffre writes: >>I would consider this as a bug (in both py2exe and Installer) since >>they decide to pick some cygwin tcl/tk dll's who happen to hang around >>while the Python runtime won't... > > > This is part of the code (in build_exe.py). > > def find_dependend_dlls(self, use_runw, dlls, pypath, dll_excludes): > import py2exe_util > sysdir = py2exe_util.get_sysdir() > windir = py2exe_util.get_windir() > # This is the tail of the path windows uses when looking for dlls > # XXX On Windows NT, the SYSTEM directory is also searched > exedir = os.path.dirname(sys.executable) > syspath = os.environ['PATH'] > loadpath = ';'.join([exedir, sysdir, windir, syspath]) > > # Found by Duncan Booth: > # It may be possible that bin_depends needs extension modules, > # so the loadpath must be extended by our python path. > loadpath = loadpath + ';' + ';'.join(pypath) > > Can you try to change the last line into > > loadpath = ';'.join(pypath) + ';' + loadpath > > and report if this helps? Yes, this fixed the bug. Here is my test report: 1. I reproduced the bug by running a build with cygwin's tcltk package installed: again, some part of cygwin had been grabbed. This time however the behaviour was that the test.exe got stucked completely, needing to be killed using TaskManager. This difference may come because I upgraded meanwhile my copy of Cygwin. 2. I modified the line in build_exe.py as described. 3. Now the produced .exe runs well in both cases (tcltk installed during build or not) Sorry for the long delay before testing this. Luc From antonmuhin at rambler.ru Tue Jan 20 13:32:25 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Tue, 20 Jan 2004 21:32:25 +0300 Subject: simple class question In-Reply-To: References: Message-ID: C GIllespie wrote: > Dear all, > > I'm new to both python and OOP, so could I ask a simple question. > > I have class: > > class species: > __init__(self,pop=0): > self.pop=pop > > Now I want to do something like this: > > X=species(pop=10) > Y=species(pop=X.pop) > OK, but now I want to update X.pop and have that mirrored in Y.pop, i.e. if > X.pop=5, Y.pop now equals 5. > > What is the best/nicest/simplest way of doing this? > > Many thanks > > Colin > > In some cases pop should be class attribute. regards, anton. From tchur at optushome.com.au Mon Jan 19 17:57:58 2004 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 20 Jan 2004 09:57:58 +1100 Subject: Python and random oracles Message-ID: <200401192257.i0JMvw101524@mail011.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tjreedy at udel.edu Mon Jan 26 18:30:32 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jan 2004 18:30:32 -0500 Subject: How does compare work? References: <40158680$0$7044$ba620e4c@news.skynet.be> Message-ID: "Helmut Jarausch" wrote in message news:40158680$0$7044$ba620e4c at news.skynet.be... > what does Python do if two objects aren't comparable (to my opinion) Sorry, Python does what it does, which is generally to compare any two objects unless explicitly disabled as with complex numbers or in user-written method of user class. > If I've understood "Python in a Nutschell" correctly it should raise an > exception but it doesn't do for me. Perhaps you could quote the line that mislead you, and someone could explain, or suggest a change to the author. Terry J. Reedy From fBechmann at web.de Sat Jan 24 14:04:39 2004 From: fBechmann at web.de (Frank Bechmann) Date: 24 Jan 2004 11:04:39 -0800 Subject: closing database connections References: <71fd0ae5.0401230838.309e9b02@posting.google.com> Message-ID: there are two extra features to be taken into account when working with database-connections (assuming you are working on problems that require non-sequential DB-access): as already mentioned DB-connections are valuable resources, they are not only limited, their creation also is performance-relevant. so quite soon you will find yourself working w/ connection pooling. even more complicated are transactional problems because connections "wrap" transactions; so there might be times when you must make sure that consequent calls to the DB use the same transaction whereas in other cases you need to access the DB with parallel but isolated transactions. So in conclusion I don't think that there is just one golden rule for DB-connection creation and release, your golden rule will most of the time be golden just for your actual problem. From Mike at DeleteThis.Geary.com Thu Jan 22 01:22:40 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 21 Jan 2004 22:22:40 -0800 Subject: How to disable dos shell window popup for os.system call References: Message-ID: <100ur1n93l4smf0@corp.supernews.com> Peter Gordon wrote: > When I try to execute another program, the dos command shell > window pops up with the application. For example: > os.system("notepad") brings up the notepad but I also get the > command shell window. How do I prevent command shell > window to open? Wow, this seems to be the question of the week! (Third time in three days.) Use os.startfile. -Mike From nospam-deets at web.de Mon Jan 5 10:09:56 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Mon, 05 Jan 2004 16:09:56 +0100 Subject: Pyserial question References: Message-ID: Hi, > I am using Pyserial to work with a RS232 device. My question is, how do I > write hex to the device or cannot write hex to it pyserial? Look into the module struct - it will allow you to convert arbitrary data to strings representing this data as binary string. Then you simply write that to the serial connection. Reading is the same. I used that sucessfully for a Vernier LabPro. Regards, Diez From none at none.com Thu Jan 15 10:12:23 2004 From: none at none.com (Derek) Date: Thu, 15 Jan 2004 10:12:23 -0500 Subject: I come not to bury C++, but to praise it... References: <87ad4qrmut.fsf@pobox.com> Message-ID: "John J. Lee" wrote... > [...] > > Maybe I didn't make myself clear. I counted the ease > > with which memory can be corrupted in C++ as a minus for > > C++ and a plus for Python. I agree with you. > > No, you don't (assuming I understand Jp's post), because... > > > On the flip side, C++ can catch errors immediately that > > Python will not complain about until runtime, and in this > > imperfect world tests may not catch all such errors up > > front. In this respect I consider C++ safer. > > ...you made no evaluation of the relative importance of > these two qualities (memory-safety and static type-safety). > Nor of the fact that C++ comes unavoidably packaged with the > more-lines-of-code-per-function-point anti-feature -- KIS! Are you joking? Because if you have some magical way to assign a meaningful relative importance to unrelated language features that is sufficiently general to be useful, I'd like to hear it. For *me* memory safety in C++ is not an issue. I use range-checked containers, scoped pointers, shared pointers, etc. and don't encounter memory management/safety problems. For *me* the lack of static type safety in Python is an issue. We have a lot of developers working on a relatively large Python codebase, and sooner or later some edge case calls a function with an argument who's type makes no sense. Sometimes tests catch the problem early, sometimes they don't. From tomas at fancy.org Thu Jan 15 03:14:36 2004 From: tomas at fancy.org (Tom Plunket) Date: Thu, 15 Jan 2004 00:14:36 -0800 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: Brandon J. Van Every wrote: > Agreed, and more specifically, there is a huge *cultural divide* between > most OSS developers and proprietary commercial developers who simply want to > add some OSS "to get the boring bits over with." There are also huge > cultural divides between Linux and Windows developers, and again between > commercial game developers and hobbyist game developers. So why waste their time even asking if they would consider aligning their goals with yours? That seems like the ridiculous part- OF COURSE hobbyists are not going to want to take commercial concerns into account, THAT'S THE POINT. -tom! From skip at pobox.com Fri Jan 30 07:38:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 30 Jan 2004 06:38:40 -0600 Subject: mod_speling for python In-Reply-To: References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Message-ID: <16410.20560.586092.371558@montanaro.dyndns.org> >> I know there are drawbacks, disadvantages, this is "evil", etc. I >> only wanted to know what ways there are to add such a hook if it is >> possible without altering the C source for python itself. Josiah> Ambiguities during execution are bad. I've got two functions Josiah> Foo and foO, if I type in foo, what did I mean? I didn't interpret the OP's question as wanting to automatically map Foo to foO, but to give the user a more helpful error message, suggesting other candidate names which he might have mistyped. Skip From rays at blue-cove.com Fri Jan 30 19:15:30 2004 From: rays at blue-cove.com (Ray Schumacher) Date: Fri, 30 Jan 2004 16:15:30 -0800 Subject: win32com - .ocx won't Dispatch... In-Reply-To: References: Message-ID: <5.2.0.4.2.20040130161335.07032450@blue-cove.com> At 10:40 AM 1/31/2004 +1100, Mark Hammond wrote: >Ray Schumacher wrote: > >>So, the util class Dispatches, but all calls (properties and functions) >>give 'Catastrophic failure' >>Is this really some sort of types problem with this OCX? >>"pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None)" > >My guess is that your OCX is a true OCX, and therefore needs a full GUI >environment. Pythonwin can host these - see the pythonwin\pywin\demos\ocx >directory, and modify one of these to suit. wxPython can also apparently >host OCX controls in a similar way, but I have no details. Thank you Mark, I'll look into it next week, for now, I got the DLL drivers to work with ctypes. I'll post examples soon. Cheers, Ray From abulka at netspace.net.au Wed Jan 7 01:18:07 2004 From: abulka at netspace.net.au (Andy Bulka) Date: 6 Jan 2004 22:18:07 -0800 Subject: UML tools for python References: <13dc97b8.0312301543.39192aa2@posting.google.com> <13dc97b8.0401051848.11205ed4@posting.google.com> Message-ID: <13dc97b8.0401062218.71e5616@posting.google.com> Alexandre Fayolle wrote in message > Well, not necessarily. Of course I can only speek for myself (and a bit > for my company), but my prefered UML modelling tool is a whiteboard, > used in conjunction with Agile Modelling practices > (http://www.agilemodeling.com). And even then I tend to model lightly, > because the projects on which I work are generally fast moving targets, > which means that heavy up front modelling often results in waisted effort. Thanks for sharing how you work with regards to UML. I too use many Agile and XP practices - UML tends to get used in initial designs and in especially when communicating between programmers. Some long term documentation of important sub-systems exists in UML too. > We found that on demand modelling sessions on the whiteboard to answer > specific questions provided the best results. The code we produce ends > up being refactored very often as requirements change anyway, and > maintaining up to date models costs us too much time. If we had two-way tools for Python, then maintaining your models would not take up any time! ;-) For example, when I used to use Delphi (object pascal) a lot, I had a two way tool called ModelMaker http://www.modelmakertools.com. I used to do some modelling in UML, then switch to coding and compiling, then back to UML, then back to coding and refactoring. Delphi + ModelMaker cooperated seamlessly so that the UML was always up to date, as was the code. It was a dream come true. I always had UML diagrams of everything, and they never went out of date. TogetherJ http://www.togethersoft.com/products/index.jsp also works like this. P.S. Ideally such a tool would be free, but I would happily pay for such a tool too. E.g. If Borland built something like PyBuilder - a rock and roll solid IDE with GUI layout tools, refactoring support and UML - I would certainly lay down my cash. Andy Bulka http://www.atug.com/andypatterns From maoy at cis.upenn.edu Sun Jan 18 23:00:25 2004 From: maoy at cis.upenn.edu (Yun Mao) Date: Sun, 18 Jan 2004 23:00:25 -0500 Subject: secure unpickle? Message-ID: Hi, I'm looking for a way in unpickling, or equivalent, such that can only unpickle (or is limited to) simple data structure, such as number, string, list, tuples. The doc I found http://www.python.org/doc/2.2.3/lib/pickle-sec.html was helpful but still not very clear to me. Thanks! -Y From donn at u.washington.edu Fri Jan 2 13:50:35 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 02 Jan 2004 10:50:35 -0800 Subject: Problem building on BeOS... References: Message-ID: In article , Zoo Keeper wrote: > Thanks for the reply! I checked in my editor (pe) and it indicates just a > carriage return at the end of the line (visibles and tab stops on). I've never used pe. I would hope it doesn't do that, but to say for sure I'd run the file through "od". Like, $ fgrep '\' arrayobject.h | od -a If you see anything between "\" and "nl", that's your problem. Donn Cave, donn at u.washington.edu From tim.one at comcast.net Sun Jan 11 14:00:37 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 11 Jan 2004 14:00:37 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401110958.693e30d1@posting.google.com> Message-ID: [Aaron Watters] > BTW, I would like to see somewhere an explanation of how > ZODB concurrency control and recovery work. Please inform if > there is some information. I'm not encouraged by the fact that > in what documentation I can find the definitions are not the > standard ones. Of course you're much more likely to get a useful discussion of this on a ZODB list, like . "The standard" ones aren't all that standard. ANSI SQL-92 defines multiple isolation levels, and they've been (I think) fairly critiqued as incomplete and partly ambiguous; e.g., A Critique of ANSI SQL Isolation Levels Hal Berenson, et al. http://citeseer.nj.nec.com/berenson95critique.html To complicate matters, as Jeremy says here: http://www.python.org/~jeremy/weblog/030514.html ZODB uses optimistic concurrency control. It can be hard to describe what isolation guarantees it provides, because optimistic implementations don't map naturally onto the ANSI isolation levels. Jeremy's blog there also contains links to more recent papers. To complicate matters more (in theory, but nicer in practice for most uses), ZODB 3.3 introduces so-called Multiversion Concurrency Control as default behavior: http://zope.org/Wikis/ZODB/MultiVersionConcurrencyControl From hlubocky at uiuc.edu Tue Jan 13 11:58:51 2004 From: hlubocky at uiuc.edu (Brian Hlubocky) Date: 13 Jan 2004 08:58:51 -0800 Subject: Py2Exe and Outlook (array bounds change!?) Message-ID: <982e9537.0401130858.4d37dae5@posting.google.com> This one is really puzzling me. I am not that familiar with COM or py2exe, but I have tested this a fair amount and am pretty sure of what I am about to explain. The MSDN website says that the item list in Outlook has array bounds from 1 to length. Using this information, I wrote a program that adds contacts to outlook using an external database. When I went to try this out with py2exe however, I got an exception. What I found out is that when using py2exe, the bounds on the items list changes from 1 to len, to 0 to len-1. Does anyone have any idea why this might be? It seems goofy that this would happen. Testing is on the developer machine, so I don't think different dlls could be the problem. Thanks! --Brian From pythongnome at hotmail.com Thu Jan 29 20:09:13 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 30 Jan 2004 01:09:13 GMT Subject: Easy way to make EXEs... References: <4017C45F.D7501215@engcorp.com> Message-ID: "Xero Limit 126" wrote in message news:yzhSb.1910$jH6.736 at newsread1.news.atl.earthlink.net... > "What don't you understand about py2exe? How it works, or how to actually > execute it? Or something else? If you have trouble with it, perhaps there > could be some improvements in the documentation... but nobody will know > unless you help us figure out what the problem is. > > -Peter" > > > Okay, I created the following setup file: > > --- file setup.py > from distutils.core import setup > import py2exe > > setup( > console = ["calculator1.py"], > ) > > Then, I get the following error: > > ------------------------------- > Traceback (most recent call last): > File "C:/WINDOWS/Desktop/Programming/Python/Programs/setup", line 4, in ? > setup( > File "C:\WINDOWS\DESKTOP\PROGRAMMING\PYTHON\BASE\lib\distutils\core.py", > line 137, in setup > raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg > SystemExit: usage: setup [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] > ...] > or: setup --help [cmd1 cmd2 ...] > or: setup --help-commands > or: setup cmd --help > > error: no commands supplied > -------------------------- > > I also get a pop up window to the effect "Do you want to exit all together, > Yes/No"... > > I have a feeling that Im just inputing somthing incorectly, or I have > somthing installed incorrectly... > > (Sorry for not going too indepth before) > > I believe you have to go to the command prompt or whatever you're using, go to the directory where the file is located, and type (not the quotation marks): "python setup.py py2exe" From http Sat Jan 3 04:09:04 2004 From: http (Paul Rubin) Date: 03 Jan 2004 01:09:04 -0800 Subject: Creating a capabilities-based restricted execution system References: Message-ID: <7xznd58klr.fsf@ruckus.brouhaha.com> "Sean R. Lynch" writes: > Does anyone think I'm going in completely the wrong direction here? Am > I missing anything obvious? Well, I have a dumb question. Have you studied the security failures of rexec/Bastion and convinced yourself that they don't happen to your new scheme? You might look at the PyPy architecture doc if you haven't yet. Making a separate object space for restricted objects may fit PyPy's design quite naturally. From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 00:05:01 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 21:05:01 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: "Peter Ashford" wrote in message news:TQiNb.12052 > Brandon wrote: > > > > Is there something fundamentally *wrong* with recognizing how useless people > > are to your purposes? > > *Recognising* that people aren't useful for your purposes is sensible. > *Criticising* people for not being useful for your purposes when they've > never claimed or aspired to be is dumb. Why? I see no a priori reason whatsoever for your statement. It depends on one's own purposes, on their purposes, and what actually happens as a result of the criticism. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From jepler at unpythonic.net Mon Jan 26 22:34:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 26 Jan 2004 21:34:56 -0600 Subject: Python on portable storage In-Reply-To: References: Message-ID: <20040127033456.GA24260@unpythonic.net> One idea would be a directory structure that looks like the source tree: python23/python # linux executable python23/python.exe # windows executable python23/Lib # shared version of /usr/lib/python2.3 python23/Lib/site.py # modify this to add any extra tweaks needed for # things to work properly (it's loaded very early) python23/Lib/plat-linux # linux shared-object modules python23/Lib/plat-win32 # win32 shared-object modules In this setup, you are assuming some set of Linux shared objects, use ldd to find out which. (A script setting LD_LIBRARY_PATH to point at necessary libraries before calling python could help here) If you want to support multiple Unix architectures, make python a shell script, and include multiple python.ARCH binaries. Have the shell script determine the architecture, and then exec python.ARCH with arguments intact. This should not affect the way Python determines the default sys.path. I don't know much about windows .dll requirements or how to resolve problems there. Jeff From josecarlos at siadv.com Mon Jan 26 15:04:05 2004 From: josecarlos at siadv.com (José Carlos) Date: Mon, 26 Jan 2004 21:04:05 +0100 Subject: part string to block of information Message-ID: Hi. How can i part a big string to block of information of (4Kb for example).? i?m trying send it from a socket client to server and how can i calculate the time it?s coming. Thank you. Regards. Jos? Carlos www.siadv.com From gerrit at nl.linux.org Fri Jan 16 11:26:59 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 16 Jan 2004 17:26:59 +0100 Subject: PEP for new modules (I read PEP 2) In-Reply-To: References: Message-ID: <20040116162659.GA4378@nl.linux.org> "Martin v. L?wis" wrote: > Christoph Becker-Freyseng wrote: > >So basically I want to relocate the real Specification, because the more > >specific it gets the more it looks like a documentation and the prePEP > >grows and grows ... > > > > > >Is this a valid option for a PEP? > > If you are asking: "Can we have an implementation before we write the > PEP?", the answer is "Certainly, yes". I don't think that's what we're asking. The question is: what level of detail should the "Specification" part of the PEP have? The highest level of detail is the full documentation - but that would mean the PEP would be to large. Is it allowed to link the documentation - even if it is docuemntation for a not-yet-existing module - as the specification? > The PEP procedure is designed to avoid wasting efforts in implementing > ideas that have no chance to ever get accepted to the Python core. > If this is no concern for you (i.e. you are willing to accept the risk > of wasting efforts), you can certainly implement the thing, wait for > user feedback, and then write the PEP. Hmm, the earlier discussion did show there certainly is a chance it will ever get accepted, so that's not really the problem. But there are a lot of ways to do a Path class, and we don't want to spend too much effort into way A if way B has a lot more chance to be accepted. yours, Gerrit. P.S. Even a rejected PEP is not a waste of time: one can learn a lot from writing a PEP, and gets one name on the PEP-list ;-) -- 124. If any one deliver silver, gold, or anything else to another for safe keeping, before a witness, but he deny it, he shall be brought before a judge, and all that he has denied he shall pay in full. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From klaus.oberpichler at freenet.de Sat Jan 10 16:21:22 2004 From: klaus.oberpichler at freenet.de (Klaus Oberpichler) Date: Sat, 10 Jan 2004 22:21:22 +0100 Subject: Newbie question on self in classes Message-ID: Hello Python community, my simple question is: When is the self reference to a class valid? During playing around with python I got the following error message: >>> class Test: ... value = 1000 ... self.value = 2 ... Traceback (most recent call last): File "", line 1, in ? File "", line 3, in Test NameError: name 'self' is not defined When I do it a different way no error occurs: >>> class Test: ... value = 1000 ... def f(self): ... self.value = 2 ... >>> When is the reference to its own class is generated and valid? What is the reason bihind that behaviour? Best regards Klaus From http Tue Jan 6 15:58:38 2004 From: http (Paul Rubin) Date: 06 Jan 2004 12:58:38 -0800 Subject: Iterating over a binary file References: Message-ID: <7xznd04ww1.fsf@ruckus.brouhaha.com> "Derek" writes: > f = file(filename, 'rb') > data = f.read(1024) > while len(data) > 0: > someobj.update(data) > data = f.read(1024) > f.close() > > The above code works, but I don't like making two read() calls. Any > way to avoid it, or a more elegant syntax? Thanks. You can make it even uglier: f = file(filename, 'rb') while 1: data = f.read(1024) if len(data) <= 0: break someobj.update(data) f.close() There's been proposals around to add an assignment-expression operator like in C, so you could say something like f = file(filename, 'rb') while len(data := f.read(1024)) > 0: someobj.update(data) f.close() but that's the subject of holy war around here too many times ;-). Don't hold your breath waiting for it. From jeffplus at comcast.net Sun Jan 4 15:06:23 2004 From: jeffplus at comcast.net (Jeff Schwab) Date: Sun, 04 Jan 2004 15:06:23 -0500 Subject: Text-to-HTML processing program In-Reply-To: References: Message-ID: phil hunt wrote: > On Sat, 03 Jan 2004 11:05:54 -0500, Jeff Schwab wrote: > >>phil hunt wrote: >> >>>Does anyone know of a text-to-HTML processing program, ideally >>>written in Python because I'll probably be wanting to make small >>>modifications to it, which is simple and straightforward to use >>>and which uses a simple markup language (something like Wikipedia >>>markup would be ideal)? >> >>How about troff? Or if you really want to keep it simple, why not use >>the

 tag in HTML?
> 
> 
> I wasn't aware troff did HTML output.

There are separate utilities to do the translation.  I have 
groff/grohtml on my linux machine; I think there's something different 
on my Solaris box.

>>Or if you really want to keep it simple, why not use
>>the 
 tag in HTML? 
> 
> 
> Yuk. 

Simple.

Of course, one *could* just use HTML, and stop whining. :)



From goodger at python.org  Wed Jan 28 09:45:20 2004
From: goodger at python.org (David Goodger)
Date: Wed, 28 Jan 2004 09:45:20 -0500
Subject: r prefix bug ... or my lack of understanding?
In-Reply-To: 
References: 
Message-ID: <4017CB00.90807@python.org>

It's a FAQ:
http://www.python.org/doc/faq/general.html#why-can-t-raw-strings-r-strings-end-with-a-backslash
(or question 4.24 of http://www.python.org/doc/faq/general.html).

-- David Goodger




From scottdog at nospam.com  Tue Jan 20 15:32:21 2004
From: scottdog at nospam.com (Dog@will.hunt)
Date: Tue, 20 Jan 2004 12:32:21 -0800
Subject: Installing SpamBayes
Message-ID: <400c399b_2@newsfeed.slurp.net>

I am brand new to the whole Python thing and am trying to install SpamBayes
so that I can use the proxy server to filter spam at my office.  I am having
trouble following the instructions provided.  It says to run the setup.py
file using the following command in IDLE in the directory that I extracted
the spambayes files into: python setup.py install.

When I do this, it tells me that python is not a recognized command.

PLEASE HELP!!

Signed,

Frustrated.




From robin at jessikat.fsnet.co.uk  Mon Jan 12 17:42:12 2004
From: robin at jessikat.fsnet.co.uk (Robin Becker)
Date: Mon, 12 Jan 2004 22:42:12 +0000
Subject: Python is far from a top performer according to benchmark
	test...
References:  
	
	<6ee58e07.0401092129.302cb9d4@posting.google.com>
	
	<6ee58e07.0401120542.5d79090d@posting.google.com>
Message-ID: 

In article <6ee58e07.0401120542.5d79090d at posting.google.com>, Lothar
Scholz  writes
....
>
>Fortran does not have this problem so a lot of optimizations can be
>done and values can be hold in registers for a much longer time,
>resulting in much greater speed.
>

I'm not sure I agree with the above. Aliases could certainly occur in
fortran 77, I haven't used 90 so can't say for sure.
>Remember that on supercomputers a 25% spped enhancement (which a good
>fortran compiler is faster then C) can mean a few million dollars of
>saved hardware costs. The coding time is not importing compared to the
>running time. So real hard numerics are always done in Fortran.

-- 
Robin Becker


From bhv1 at psu.edu  Thu Jan 22 16:12:42 2004
From: bhv1 at psu.edu (Brian Victor)
Date: Thu, 22 Jan 2004 15:12:42 -0600
Subject: Program Python in VIM
References: <871xpsc5zf.fsf@tulip.whu.ca>
	
Message-ID: 

Fran?ois Pinard wrote:
> I do not know if there is a better way, but what I do for one is to
> create a small Makefile like:
>
> try:
> 	python test.py

I use a similar Makefile, and then I bind F4 to "make" in my .vimrc:

map ^[[14~ :make^M

To make that work, you have to make liberal use of control-V.  Type:

map  :make

into your .vimrc, and F4 should be bound to the make command.
One-keystoke running!  (Does that violate an amazon patent?...)

-- 
Brian


From andreas.lobinger at netsurf.de  Mon Jan 19 11:02:03 2004
From: andreas.lobinger at netsurf.de (Andreas Lobinger)
Date: Mon, 19 Jan 2004 17:02:03 +0100
Subject: Fw: PDF library for reading PDF files
References: 
Message-ID: <400BFF7B.95F21050@netsurf.de>

Aloha,

> Peter Galfi schrieb:
> I am looking for a library in Python that would read PDF files and I
> could extract information from the PDF with it. I have searched with
> google, but only found libraries that can be used to write PDF files.
> Any ideas?

Use file, split, zlib and a broad knowledge of the PDF-spec...

Accessing certain objects in the .pdf is not that complicated if
you f.e. try to read the /Info dictionary. Getting text from
actual page content could be very complicated.

Can you explain your 'information' further?

Wishing a happy day
		LOBI


From theaney at cablespeed.com  Mon Jan  5 20:08:06 2004
From: theaney at cablespeed.com (Tim Heaney)
Date: Mon, 05 Jan 2004 20:08:06 -0500
Subject: Quck question
References: <3125790e.0401051610.5e24de28@posting.google.com>
Message-ID: <87ad51yjd5.fsf@mrbun.watterson>

sinzcere at hotmail.com (J) writes:

> I have the following information in a file :
> r1kcch    Serial0/0/0    propPointToPointSerial
> Mon Jan 5 13:15:03 PST 2004 InOctets.1    0
> Mon Jan 5 13:15:05 PST 2004 OutOctets.1   0
>
> I want to be able to extract each line into a comma delimited list. 
> Bellow i am trying to print out my list print currentList but nothing
> is comming out.  I added a line after print test to make sure the file
> has the information.  Can someone help me with this?

I'm not certain I understand what you're doing, but perhaps you want
something like this?

  file = open("test.txt")
  for line in file:
      list = line.split()
      if len(list):
          print ','.join(list)

I hope this helps,

Tim


From Kuser-admin at kde.gr.jp  Wed Jan 28 00:04:38 2004
From: Kuser-admin at kde.gr.jp (Kuser-admin at kde.gr.jp)
Date: Wed, 28 Jan 2004 14:04:38 +0900
Subject: Fml status report (Kuser ML)
References: <20040128050434.41E251F801C@mail.kde.gr.jp>
Message-ID: <200401281404.FMLAAB19806.Kuser@kde.gr.jp>

ATTENTION! Your mail is too big, so not processed!!!
This ML  restricts the maximum mail size,
so pay attention to the mail with e.g. attachments.

--Kuser at kde.gr.jp, Be Seeing You!    

************************************************************

       Help: 
Unsubscribe: 

If you have any questions or problems,
   please contact Kuser-admin at kde.gr.jp
       or 
   send e-mail with the body "help"(without quotes) to
      Kuser-ctl at kde.gr.jp
      (here is the automatic reply, so more preferable)

e.g. on a Unix Machine
(shell prompt)% echo "help" |Mail Kuser-ctl at kde.gr.jp

************************************************************




From jzgoda at gazeta.usun.pl  Sat Jan 31 03:09:08 2004
From: jzgoda at gazeta.usun.pl (Jarek Zgoda)
Date: Sat, 31 Jan 2004 08:09:08 +0000 (UTC)
Subject: How to start a DTS Package on MS-SQL-Server?
References: 
	
Message-ID: 

Dirk  pisze:

> Sorry, I think I forgot to write that I want to start this from a remote 
> computer. So I can't simply use popen. But I know about this dtsrun 
> executable (that's how the sql-server does it itself...).

This can be painful... Try to schedule your package and look at
"Operating system comand" field in scheduled job properties. You will
get the idea on how packages are run by dtsrun.exe.

The other idea worth exploring is "MS OLE DB Provider for DTS Packages"
-- loosely documented component of any contemporary (>2.5) MDAC package.
When I needed to run packages from my program, I had no time to dig in
MSDN, so I cann't say anything more.

-- 
Jarek Zgoda
Unregistered Linux User #-1
http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/


From ods at strana.ru  Thu Jan 29 11:16:44 2004
From: ods at strana.ru (Denis S. Otkidach)
Date: Thu, 29 Jan 2004 19:16:44 +0300 (MSK)
Subject: regexp upward compatibility bug ?
In-Reply-To: 
Message-ID: 

On Thu, 29 Jan 2004, Gilles Lenfant wrote:

GL>    File "txt2html.py", line 27, in txt2html
GL>      pat =
GL> re.compile(r'((ftp|http)://[\w-]+(?:\.[\w-]+)*(?:/[\w-\.?=]*)
GL> *)')
GL>    File "/usr/local/lib/python2.1/sre.py", line 90, in
GL> compile
GL>      return _compile(pattern, flags)
GL>    File "/usr/local/lib/python2.1/sre.py", line 136, in
GL> _compile
GL>      raise error, v # invalid expression
GL> sre_constants.error: bad character range

The problem is in "[\w-\.?=]". "\w" is not a character, so it
cannot be a start of range.  Put "-" at the start or end of
group:

>>> re.compile(r'((ftp|http)://[\w-]+(?:\.[\w-]+)*(?:/[-\w\.?=]*)*)')
<_sre.SRE_Pattern object at 0x40277110>
>>> re.compile(r'((ftp|http)://[\w-]+(?:\.[\w-]+)*(?:/[\w\.?=-]*)*)')
<_sre.SRE_Pattern object at 0x402777a0>


-- 
Denis S. Otkidach
http://www.python.ru/      [ru]




From ramen at lackingtalent.com  Sun Jan 18 14:34:07 2004
From: ramen at lackingtalent.com (Dave Benjamin)
Date: Sun, 18 Jan 2004 19:34:07 -0000
Subject: Determining a replacement dictionary from scratch
References: <4b805376.0401181116.3b0adb41@posting.google.com>
Message-ID: 

In article <4b805376.0401181116.3b0adb41 at posting.google.com>, Dan wrote:
> I'd like to be able to take a formatted string and determine the
> replacement dictionary necessary to do string interpolation with it. 
> For example:
> 
>>>> str = 'his name was %(name)s and i saw him %(years)s ago.'
>>>> createdict( str )
> {'name':'', 'years':''}
>>>>
> 
> Notice how it would automatically fill in default values based on
> type.  I figure since python does this automatically maybe there is a
> clever way to solve the problem.  Otherwise I will just have to parse
> the string myself.  Any clever solutions to this?

Here's a solution that uses a regular expression. It only handles strings
and doesn't cache the regular expression; I'll leave this up to you. =)

import re
def createdict(fmt):
    keys = re.findall('%\(([A-Za-z]+)\)s', fmt)
    return dict(zip(keys, [''] * len(keys)))
        
The regular expression works like this:

 %\(         - match a percent character and opening parenthesis
 ([A-Za-z]+) - match a sequence of one or more alpha characters as a GROUP
 \)s         - match a closing parenthesis and 's' character

For more details on "re", see the documentation:
http://python.org/doc/current/lib/module-re.html

HTH,
Dave

-- 
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :


From mirko-lists at zeibig.net  Thu Jan 15 07:29:31 2004
From: mirko-lists at zeibig.net (Mirko Zeibig)
Date: Thu, 15 Jan 2004 13:29:31 +0100
Subject: Best Python IDE Code Completion!
In-Reply-To: 
References: 
Message-ID: 

John said the following on 01/15/2004 12:52 PM:
>   Wing IDE seems converse. The editor auto list members is great but
> has no calltips. The interactive window has no completion at all.
I second this, though the editor sometimes need a bit of help ...
and I do not like the MDI approach they have.

>   Python has great introspective capabilities and we have a great open
> contributing community. What technical difficulties keep us from
> having REAL code completion like MS, Borland and several Java IDEs
> (All of which have been funded at one time or the other if not
> entirely - perhaps this is the reason?)

Python is dynamically typed, so no editor in the world can guess the 
type of any function parameters correctly. If you know about the true 
nature of one, you may assist Wing IDE by using isinstance.

class Klass(object):

     def hello(self):
        print "Hello"

def foo(bar):
     assert isinstance(bar, Klass)
     bar.hello()

Without the assert line, it's impossible to detect which type bar has. 
Only during runtime the type of bar is known.

Regards
Mirko
-- 


From tjreedy at udel.edu  Mon Jan 26 17:29:23 2004
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 26 Jan 2004 17:29:23 -0500
Subject: Deleting objects
References: 
Message-ID: 


 wrote in message
news:a33a46fe50e2ab07720a1118aa22d576 at news.teranews.com...
> Say I have a database object 'db',
> that contains table objects, that contain field
> objects so that I can do things like this:
>
> print db.table.field.value()
>
>
> Now, after plundering the database for a while,
> the db objects heads a tree of lots of data.
>
> If I want to "reset" the object so that I get
> all of my memory back, can I just do:
>
> del db
>
> or maybe:
>
> for t in db.tables:
> del t
>
> and expect that I have cleaned up all of my
> memory?
>
> After writing this out, I see that the answer
> is clearly yes, but I will post anyway.

Why?

Actually, the issue is not so simple.  'del db' deletes the association
between name db and the database object.  If there is another reference to
the object, that is all that happens.  If not, memory cleanup depends on
the implementation.  CPython will 'free' memory immediately (and
recursively delete tables).  Jython waits for next garbage collection
cycle.  'Free' may just mean available for reuse by Python but not by other
programs.

Db objects often have a close method.  You may get more of what you want by
calling that before del.

Terry J. Reedy






From tdelaney at avaya.com  Tue Jan  6 18:00:53 2004
From: tdelaney at avaya.com (Delaney, Timothy C (Timothy))
Date: Wed, 7 Jan 2004 10:00:53 +1100
Subject: Pre-PEP: Dynamically evaluating default function arguments
Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01063345@au3010avexu1.global.avaya.com>

> From: Daniel Ehrenberg
> 
> One of the most common bugs that people have on the Python Tutor list
> are caused by the fact the default arguments for functions are
> evaluated only once, not when the function is called. The solution to
> this is usually to use the following idiom:

Please do write up this PEP formally and completely, covering every eventuality, and with the history and motivations expressed, so that it can be formally rejected. Then we will have somewhere simple to point to when people bring up this topic again.

Tim Delaney



From jepler at unpythonic.net  Wed Jan 28 16:08:14 2004
From: jepler at unpythonic.net (Jeff Epler)
Date: Wed, 28 Jan 2004 15:08:14 -0600
Subject: linking problems with Python C API
In-Reply-To: 
References: 
Message-ID: <20040128210813.GY18498@unpythonic.net>

Refer to the documentation that accompanies your shared library.  The
answer is "some libpython, but python-list can't tell you which one".

Jeff



From __peter__ at web.de  Sat Jan 24 16:55:19 2004
From: __peter__ at web.de (Peter Otten)
Date: Sat, 24 Jan 2004 22:55:19 +0100
Subject: time.time()
References: 
	<7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com>
	
Message-ID: 

Bart Nessux wrote:

> Terry Carroll wrote:
> 
>> It sounds like you're thinking time.time() does something else, which
>> you're trying to do.  What is that?  There might be another function for
>> you.
> 
> I should have been more clear... here's the code:

That's not only clearer - that's different :-)

> x = time.time()
> fp = os.popen("some_process", "r")
> fp.read()
> fp.close()
> print (time.time()-x/60)/60
> 
> If fp runs for many hours (in my case it does), I want time.time() to
> return the time it runs in seconds which I would then divide by 60 to
> get the total amount of minutes which I would then divide by 60 to get
> the total amount of hours that the process has ran... does that make
> sense? I don't need to be super precise, just within 1 minute or so of
> the actual amount of time that the process required to run.

>>> start = time()
>>> start
1074980579.623781
>>> sleep(7200)
>>> duration = time() - start 
>>> print "duration in hours:", duration/60/60
duration in hours: 2.0
>>> (time() - start) / 60 / 60
2.0

In the last expression, the parentheses are necessary, because - has lower
precedence than /, i. e. otherwise you would calculate time() -
(start/60/60). Note how I introduced an additional "duration" variable. If
a calculation does not yield the expected result, it is often helpful to
inspect some intermediate values.

Peter

PS: I cheated with my sleep() and time() functions:

>>> def time():
...     global _time
...     try:
...             return _time
...     except NameError:
...             import time
...             _time = time.time()
...     return _time
...
>>> def sleep(s):
...     global _time
...     try:
...             _time += s
...     except NameError:
...             import time
...             _time = time.time() + s



From jcarlson at nospam.uci.edu  Sat Jan 24 16:42:13 2004
From: jcarlson at nospam.uci.edu (Josiah Carlson)
Date: Sat, 24 Jan 2004 13:42:13 -0800
Subject: time.time()
In-Reply-To: 
References: 
	<7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com>
	
Message-ID: 

> x = time.time()
> fp = os.popen("some_process", "r")
> fp.read()
> fp.close()
> print (time.time()-x/60)/60

Parenthesis are your friend:
print (time.time()-x)/3600

  - Josiah


From nospam at nopes  Sat Jan  3 11:35:48 2004
From: nospam at nopes (Steve)
Date: Sun, 04 Jan 2004 03:35:48 +1100
Subject: Pass a variable to another python script
Message-ID: <3ff6ef44$1@clarion.carno.net.au>

Hi,

I've written a small cgi python script that collects feedback from a 
webform. I need to pass the values to another python script.. how do I 
do this? Is this even possible? Thanks

Steve



From usenet_spam at janc.invalid  Tue Jan 20 23:37:51 2004
From: usenet_spam at janc.invalid (JanC)
Date: Wed, 21 Jan 2004 04:37:51 GMT
Subject: Looking for very simple general purpose tokenizer
References:  
Message-ID: 

Maarten van Reeuwijk  schreef:

> I found a complication with the shlex module. When I execute the 
> following fragment you'll notice that doubles are split. Is there any way 
> to avoid numbers this?

>From the docs at 

wordchars
    The string of characters that will accumulate into multi-character 
    tokens. By default, includes all ASCII alphanumerics and underscore.

> source = """
>  $NAMRUN
>      Lz      =  0.15
>      nu      =  1.08E-6
> """
> 
> import shlex
> import StringIO
> 
> buf = StringIO.StringIO(source)
> toker = shlex.shlex(buf)
> toker.comments = ""
> toker.whitespace = " \t\r"

toker.wordchars = toker.wordchars + ".-$"   # etc.

> print [tok for tok in toker]


Output:

['\n', '$NAMRUN', '\n', 'Lz', '=', '0.15', '\n', 'nu', '=', '1.08E-6', '\n']

Is this what you want?

-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9


From __peter__ at web.de  Fri Jan 30 11:31:06 2004
From: __peter__ at web.de (Peter Otten)
Date: Fri, 30 Jan 2004 17:31:06 +0100
Subject: Simple list question
References: 
Message-ID: 

C GIllespie wrote:

> Dear all,
> 
> I have a list something like this: ['1','+','2'], I went to go through and
> change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing

If you really want the [1,'+',2] format, use int() instead of float(). 

> this? The way I done it seems wrong, e.g.
> 
> nod=['1','+','2']
> i=0
> while i     if nod[i] !='+' or nod[i] !='-' or nod[i]!='*' or nod[i] != '/' or
> nod[i] != '(' or nod[i] != ')':
>         nod[i] = float(nod[i])
>     i = i + 1
> 
> Comments?

Nothing is wrong with the above, although a  for loop is more common.

for i in range(len(nod)):
  # ...

Instead of testing for all non-floats, you could just try to convert the
list item, keeping it unchanged if an error occurs. Here's a full example
using enumerate() instead of range():

>>> nod = ["1", "+", "2"]
>>> for i, v in enumerate(nod):
...     try:
...             v = float(v)
...     except ValueError:
...             pass
...     else: # yes, try...except has an else (=no exception) branch, too
...             nod[i] = v
...
>>> nod
[1.0, '+', 2.0]

Peter



From mtk at qm.com  Wed Jan 14 13:58:18 2004
From: mtk at qm.com (Totte Karlsson)
Date: Wed, 14 Jan 2004 10:58:18 -0800
Subject: Printing to console (No Scroll)
References: 
	
Message-ID: 

Any alternatives to ncurses? It seems like a overkill for this...
cheers
/totte


"Diez B. Roggisch"  wrote in message
news:bu41k5$4in$00$2 at news.t-online.com...
> > How can I print to the console without having it scrolling to a new line
> > for each print statement?
> > I want to print a count down in the console, but for each count it
scrolls
> > the screen (of course).
>
> Use ncurses.
>
> Diez
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>






From twa at post.com  Thu Jan  1 09:24:54 2004
From: twa at post.com (Tom)
Date: Thu, 1 Jan 2004 14:24:54 +0000 (UTC)
Subject: Graph in wxPython - wxpyplot
In-Reply-To: 
References: 
Message-ID: 

http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html

Is that the sort of thing you mean?

Tom

Oh Kyu Yoon wrote:
> Does anyone know how to implement plots from scipy, chaco, etc
> into wxPython widget?
> 
> Thank you
> 
> 



From ods at strana.ru  Thu Jan 22 09:50:53 2004
From: ods at strana.ru (Denis S. Otkidach)
Date: Thu, 22 Jan 2004 17:50:53 +0300 (MSK)
Subject: utf8 encoding problem
In-Reply-To: <20040122141628.GJ7377@wiggy.net>
Message-ID: 

On Thu, 22 Jan 2004, Wichert Akkerman wrote:

WA> > P.S. According to HTML standard, with
WA> > application/x-www-form-urlencoded content type form data
WA> are
WA> > resricted to ASCII codes:
WA> >
WA> http://www.w3.org/TR/html4/interact/forms.html#form-data-set
WA> >
WA> http://www.w3.org/TR/html4/interact/forms.html#submit-format
WA>
WA> Luckily that is not true, otherwise it would be completely
WA> impossible to

It's true: "The "get" method restricts form data set values to
ASCII characters. Only the "post" method (with
enctype="multipart/form-data") is specified to cover the entire
[ISO10646] character set."

But almost nobody follow this rule.

WA> have websites using non-ascii input. To be specific, the

No, you can use "post" method with multipart/form-data content
type to do that.

WA> encoding used
WA> for HTML forms is determined by:
WA>
WA> 1. accept-charset attribute of the form element if present.
WA> This is
WA>    not handled by all browsers though.

accept-charset attribute can list several encodings.  Which one
to choose?

WA> 2. the encoding used for the html page containing the form

Pages are often re-coded by proxies, so the encoding of submitted
data is not always is one as assumed by form processing script.
The same issue apply for cross-site forms.

WA> 3. ascii otherwise

This is the only reliable encoding :)

WA> this is specified in section 17.3 of the HTML 4.01 standard
WA> you are
WA> referring to.

Sorry, there is no such specification in section 17.3 of the HTML
4.01 standard.  Certainly, your method to determine encoding is
OK for most cases.

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]




From peter at engcorp.com  Fri Jan  9 09:18:11 2004
From: peter at engcorp.com (Peter Hansen)
Date: Fri, 09 Jan 2004 09:18:11 -0500
Subject: Looking for a Python interface to TAPI on Win32
References: <2259b0e2.0307180401.5dae02f2@posting.google.com>
	
	<3f17f883$0$49107$e4fe514c@news.xs4all.nl>
	<2259b0e2.0307190529.57338b3f@posting.google.com>
	
	<2259b0e2.0307200604.44d343f4@posting.google.com>
	
	
Message-ID: <3FFEB823.C3FCFDDB@engcorp.com>

"Kent Hsu (Hsu, Chih-Peng)" wrote:
> 
> Try "ctypes" or "calldll" to call the Win32 api directly.

Specifically, ctypes.  I'm pretty sure calldll should be considered obsolete
and it doesn't appear there's an obvious place to find a calldll binary for 
Python 2.3, so it looks unsupported at this point.

-Peter


From skip at pobox.com  Tue Jan  6 11:38:19 2004
From: skip at pobox.com (Skip Montanaro)
Date: Tue, 6 Jan 2004 10:38:19 -0600
Subject: Why does this fail?
In-Reply-To: <878yklavnx.fsf@pobox.com>
References:  <878yklavnx.fsf@pobox.com>
Message-ID: <16378.58491.796532.530331@montanaro.dyndns.org>


    John> Also (advert ;-), if you're doing any kind of web scraping in
    John> Python (including functional testing), you might want to look at
    John> this little FAQ (though it certainly doesn't nearly cover
    John> everything relevant):

    John> http://wwwsearch.sf.net/bits/clientx.html

A possible addition to your "Embedded script is messing up my web-scraping"
section:  Wasn't there mention of the Mozilla project's standalone
JavaScript interpreter (don't remember what it's called) recently alongside
some Python interface?

Skip



From bart_nessux at hotmail.com  Sat Jan 24 18:40:58 2004
From: bart_nessux at hotmail.com (Bart Nessux)
Date: Sat, 24 Jan 2004 18:40:58 -0500
Subject: time.time()
In-Reply-To: 
References: 	<7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com>	
	
Message-ID: 

Jeff Epler wrote:
> bart,
> 
> a-b/c evaluates as a-(b/c)
> 
> Jeff
> 

Ah, yes... silly me. That's the problem.



From alan.gauld at btinternet.com  Tue Jan 13 18:13:53 2004
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Jan 2004 23:13:53 GMT
Subject: Does anyone else not find the fun in programming...?
References: 
Message-ID: <40047aec.796465196@news.blueyonder.co.uk>

On 13 Jan 2004 08:23:46 -0800, chris.lyon at spritenote.co.uk (Chris
Lyon) wrote:
> I find python very effective as a language and can generally project
> most of my hazy thoughts into it. But FUN !!! This is work dammit,

When I was a working programmer I kind of felt the same way.

But then I became a designer and now cherish the time I spend
writing code (and not just in Python, even C++, Lisp and 
Delphi)- because it is fun! :-)

> programming is fun. Football (association) is fun, walking along
> canals is fun, Arguing about quite how useless the British Government
> is fun but programming  ?

Its fun like doing a jigsaw is fun, or a crossword. Its about
problem solving. Its about finding elegant solutions to problems.
If you don't enjoy doing the puzzle page in your daily newspaper
you probably won't enjoy programming... Probably a bad example
since zillions of crossword haters will now say how much they
enjoy programming! :-)

But its in that ballpark IMHO.

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld


From fredrik at pythonware.com  Sat Jan  3 10:46:39 2004
From: fredrik at pythonware.com (Fredrik Lundh)
Date: Sat, 3 Jan 2004 16:46:39 +0100
Subject: Can this be reversed (Tkinter)?
References: <002d01c3d171$df2920b0$5501a8c0@markxp>
	<06a901c3d173$0a7e27f0$6401fea9@YODA>
Message-ID: 

Dave Brueck wrote:

> > I am looking at the format used by root.geometry().  The string returned
> > from root.geometry() is "%dx%d+%d+%d".  Is there a quick and painless
> > way to extract the values from that string (i.e., "100x150+25+25" =>
> > (100,150,25,25))?
>
> How about:
>
> s = '100x150+25+25'
> import re
> reg = re.compile('(\d+)x(\d+)\+(\d+)\+(\d+)')
> [int(x) for x in reg.match(s).groups()]

note that the offsets may be negative; this pattern should work
a bit better:

    "(\d+)x(\d+)([-+]\d+)([-+]\d+)"








From simoninusa2001 at yahoo.co.uk  Sat Jan 31 21:35:52 2004
From: simoninusa2001 at yahoo.co.uk (simo)
Date: 31 Jan 2004 18:35:52 -0800
Subject: wxPython documentation
References: <401c25a3$0$11357$636a55ce@news.free.fr>
	
Message-ID: <30260531.0401311835.2246510f@posting.google.com>

Jonathan Daugherty  wrote:

> > Where could I find a good documentation about wxPython (a documentation
> > which is not for C++ !!!)

> There are some wxpython tutorials and documents but the official wxPython
> documentation is the wxWindows documenation itself -- wxPython notes are
> sprinkled throughout.

This is what I found off-putting about PyQt - the documentation
basically points you to the Qt C++ docs:

http://www.riverbankcomputing.co.uk/pyqt/docs/PyQt.html

If we've got to figure out the C++ code and convert it to Python, we
may as well just skip Python and write in C++!

The wxPython Wiki is OK, it's a bit brief though, but I've just looked
at wxPython today and figured out how to make a basic Windows
application "shell" in 3 hours or so:

http://wiki.wxpython.org/index.cgi/FrontPage

TKinter has the best documentation, although TKinter is a bit dated
looking, slow and has few widgets:

http://www.pythonware.com/library/tkinter/introduction/index.htm

At least [with a manifest file] py2exe makes an XP-looking program,
that's better than TKinter (not tried the commercial Windows PyQT,
just GPL Linux).


From jjl at pobox.com  Tue Jan 13 12:52:34 2004
From: jjl at pobox.com (John J. Lee)
Date: 13 Jan 2004 17:52:34 +0000
Subject: C++ bad-mouthing (was: Why learn Python ??)
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	<7xisjh1e3i.fsf@ruckus.brouhaha.com>
	<10064loqc7sd7e3@corp.supernews.com>
	<7xeku496wx.fsf@ruckus.brouhaha.com>
	
	<7xhdz08xgy.fsf@ruckus.brouhaha.com>
Message-ID: <877jzvag7x.fsf@pobox.com>

Paul Rubin  writes:

> Donn Cave  writes:
[...re Python...]
> > language.  Full of neat tricks that work like magic, but does it
> > really even attempt to offer anything in the area you're talking about?
> 
> It makes some feeble ones but is somewhat hobbled by its origins as a
> scripting or "glue" language.

Are you referring to *anything* other than the lack of static type
checking and execution speed?


> Also, Python is really still in its
> infancy.  Maybe after PyPy is completed, someone can try writing a
> serious compiler for it, and the issues brought out by writing the
> compiler can drive the design of a successor language, Python II or
> whatever.
[...]

I'm sure you're right that things will advance.  Not sure it would be
best to make a "Python II", though -- Python seems close to a local
maximum.


John


From max at alcyone.com  Fri Jan 23 04:07:14 2004
From: max at alcyone.com (Erik Max Francis)
Date: Fri, 23 Jan 2004 01:07:14 -0800
Subject: I support PEP 326
References: 	<401081A1.E4C34F00@alcyone.com>	
	
	
Message-ID: <4010E442.8D13AEF3@alcyone.com>

Paul Prescod wrote:

> Calling min with no arguments need not be the same as calling it with
> an
> empty sequence argument.

Since min(S) and min(*S) behave identically, I submit to you that they
_should_ be.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ The only source of knowledge is experience.
    -- Albert Einstein


From jjl at pobox.com  Mon Jan 19 16:09:45 2004
From: jjl at pobox.com (John J. Lee)
Date: 19 Jan 2004 21:09:45 +0000
Subject: secure unpickle?
References: 
Message-ID: <87zncjabmu.fsf@pobox.com>

"Tim Peters"  writes:

> [Gandalf]
> > ...
> >> I'm using this module (based on the documentation you mentioned):
> >> ...
> 
> [John J. Lee]
> > What does this have to do with the question?  He was worried about
> > security of pickle, not asking how to call dumps() and loads().
> 
> Look at Gandalf's code again.  The pickler is unremarkable, but the
> unpickler contains the assignment:
> 
>     p.find_global = None
> 
> As his loads docstring said, "this function will not unpickle globals and
> instances" as a result.

Aha.

I see from past messages that this is thought to solve the security
problems (for this restricted case), at least by Martin v. Loewis, but
also that Paul Rubin believes a careful audit would be required to
have confidence in it (whether that's FUD, as Martin accuses, or
sensible caution, I have no idea...).

http://www.google.com/groups?threadm=mailman.1012591743.10841.python-list%40python.org


John


From adinospam at logilab.fr  Thu Jan 29 03:34:22 2004
From: adinospam at logilab.fr (Adrien Di Mascio)
Date: Thu, 29 Jan 2004 09:34:22 +0100
Subject: "static" checking
References: <160Sb.19106$fo1.10783@newssvr25.news.prodigy.com>
Message-ID: 

Le Thu, 29 Jan 2004 04:37:17 +0000, Moosebumps a ?crit?:

Hi,
> I'm wondering what kind of checking I can do on a python program before
> running it (besides reading over every line).  I hate running a long python
> script, only to have it fail at the end because I misspelled a function
> name, or made some other silly mistake that a compiler would normally catch.
> Then I have to run it all over again to see what happened or come up with
> some sort of short test.

Have a look at pylint (http://www.logilab.org/projects/pylint)

Cheers,

-- 
Adrien Di Mascio
LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr   http://www.logilab.org




From nospam at here.com  Tue Jan 13 15:13:04 2004
From: nospam at here.com (Richard Townsend)
Date: Tue, 13 Jan 2004 20:13:04 -0000
Subject: tkinter canvas postscript fontmap
References: 
Message-ID: <1074024577.27787.0@damia.uk.clara.net>

> I want to set the fontmap to be used when saving the file. I write to
> the canvas using Arial and would like to get either Arial or Courier in
> the resulting .ps instead of MsSansSerif... I haven't found any sample
> on the net. Has anyone done this before with success ? What is the
> format of the "fontmap" option ?
>

I needed to do something similar some time ago and also found no examples.

I'm not sure if it is the correct way to do it, but the code below appears
to work.

When you press the 'Print' button it creates a fontmap array which
substitutes 'Arial 12' for all occurences of 'Courier 12' and 'Arial-Bold
14' for 'Courier 14'. It then dumps the postscript to a file.

Hope that helps,
Richard Townsend

----------------------------------------------------------------------------
------------------------------------
from Tkinter import *

font1 = "Courier 12"
font2 = "Courier 14"

class Demo:

    def __init__(self):
        self.root = Tk()

        self.canvas = Canvas(self.root, height=300, width=300, bg="white")
        self.canvas.pack()

        frame = Frame(self.root)
        frame.pack()

        print_pb = Button(frame, text="Print", command=self.genPostscript)
        print_pb.pack(side=LEFT)

        quit_pb = Button(frame, text="Quit", command=self.quit)
        quit_pb.pack(side=LEFT)

        text = 'This is in %s' % font1
        self.canvas.create_text(10, 10, text=text, anchor=NW, font=font1)

        text = 'This is in %s' % font2
        self.canvas.create_text(10, 40, text=text, anchor=NW, font=font2)

        self.canvas.update_idletasks()
        self.root.mainloop()


    def genPostscript(self):
        # Create fontmap array
        self.root.tk.call('set', 'fontmap(%s)' % font1, 'Arial 12')
        self.root.tk.call('set', 'fontmap(%s)' % font2, 'Arial-Bold 14')

        #res = self.root.tk.call('array', 'get', 'fontmap')
        #print res

        # Generate the postscript data using the fontmap
        postscript = self.canvas.postscript(fontmap='fontmap')

        filename = 'dump.ps'
        fd = open(filename, 'w')
        fd.write(postscript)
        fd.close()


    def quit(self):
        self.root.quit()


if __name__ == "__main__":

    Demo()




From borkxorfoo at hotmail.com  Tue Jan 27 21:05:13 2004
From: borkxorfoo at hotmail.com (bor)
Date: Tue, 27 Jan 2004 18:05:13 -0800
Subject: makeExe.py
References: <20040127134802.27165.qmail@web8302.mail.in.yahoo.com>
Message-ID: 

I use this:

http://sourceforge.net/project/showfiles.php?group_id=91562&package_id=96755
&release_id=188884

sits on top of py2exe and is very handy for click/compile when needed.

----- Original Message -----
From: "Premshree Pillai" 
To: ; 
Sent: Tuesday, January 27, 2004 5:48 AM
Subject: Re: makeExe.py


> > if you're interested
> > in integrating the
> > changes, and maintaining it, I'll forward our own
> > script which you can
> > pull apart and reuse as required...
>
> I'd be interested in that.
>
>
>  --- Peter Hansen  wrote: >
> Premshree Pillai wrote:
> > >
> > > Wrote a simple Python script that makes life a wee
> > bit
> > > easier when using py2exe:
> > >
> > > """
> > > makeExe.py
> > > - Simple Python script to automate the creation
> > >   of Python executables using py2exe.
> > >
> > [snip]
> > > fp = open("setup.py","w")
> > > temp = """from distutils.core import setup
> > > import py2exe
> > > setup(name = "%s",
> > >      scripts = ["%s"],
> > > )""" % (package,fileName)
> > > fp.write(temp)
> > > fp.close()
> >
> > You could save yourself a fair bit of trouble, and
> > avoid writing a
> > "setup.py" file to the filesystem (possibly
> > overwriting an existing
> > one which might be important) by just calling the
> > setup() method
> > directly yourself.  The only trick is that it checks
> > sys.argv[] for
> > the "py2exe" argument, so you have to fake that
> > first:
> >
> > sys.argv[1:] = ['py2exe']
> >
> > from distutils.core import setup
> > setup(name=package,
> >     scripts=[fileName])
> >
> > That should do the trick....  if you're interested
> > in integrating the
> > changes, and maintaining it, I'll forward our own
> > script which you can
> > pull apart and reuse as required...
> >
> > -Peter
> > --
> > http://mail.python.org/mailman/listinfo/python-list
>
> =====
> -Premshree
> [http://www.qiksearch.com/]
>
> ________________________________________________________________________
> Yahoo! India Mobile: Download the latest polyphonic ringtones.
> Go to http://in.mobile.yahoo.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


---
As of 2nd December 2003, Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.481 / Virus Database: 277 - Release Date: 5/13/2003



From exarkun at intarweb.us  Tue Jan  6 22:24:16 2004
From: exarkun at intarweb.us (Jp Calderone)
Date: Tue, 6 Jan 2004 22:24:16 -0500
Subject: Iterating over a binary file
In-Reply-To: 
References: 
Message-ID: <20040107032416.GB10140@intarweb.us>

On Tue, Jan 06, 2004 at 03:25:11PM -0500, Derek wrote:
> Pardon the newbie question, but how can I iterate over blocks of data
> from a binary file (i.e., I can't just iterate over lines, because
> there may be no end-of-line delimiters at all).  Essentially I want to
> to this:
> 
> f = file(filename, 'rb')
> data = f.read(1024)
> while len(data) > 0:
>     someobj.update(data)
>     data = f.read(1024)
> f.close()
> 
> The above code works, but I don't like making two read() calls.  Any
> way to avoid it, or a more elegant syntax?  Thanks.
> 

      f = file(filename, 'rb')                                                                                                                                          
      for data in iter(lambda: f.read(1024), ''):                                                                                                                       
        someobj.update(data)                                                                                                                                            
      f.close()                                                                                                                                                         
                                                                                                                                                                        
  Jp                                                                                                                                                                    



From derekledbetter at mindspring.com  Sun Jan  4 06:02:41 2004
From: derekledbetter at mindspring.com (Derek Ledbetter)
Date: Sun, 04 Jan 2004 11:02:41 GMT
Subject: Integer math question
References: <3987e01c.0401030832.114c6f2a@posting.google.com>
Message-ID: <0001HW.BC1D32D80155EE2AF0284600@netnews.comcast.net>

On Sat, 3 Jan 2004 8:32:07 -0800, Frank wrote
(in message <3987e01c.0401030832.114c6f2a at posting.google.com>):

> In C++
> 
> i = 5 / 10 	and
> i = -5 / 10 	both have the same result 0.

Actually this is implementation defined in C89 and standard C++.  Either
-5/10 == 0 and -5%10 == -5, as in your implementation, or -5/10 == -1
and -5%10 == 5, like Python.  In C99, and possibly a future version of
C++, it's always done the first way (rounding towards zero).

-- 
Derek Ledbetter
derekl at serve.com

Heavy boots of lead 
fills his victims full of dread 
Running as fast as they can 
Iron Man lives again! 




From elainejackson7355 at home.com  Fri Jan 30 03:19:59 2004
From: elainejackson7355 at home.com (Elaine Jackson)
Date: Fri, 30 Jan 2004 08:19:59 GMT
Subject: newbie py2exe difficulty
Message-ID: 

Hi. I'm trying to use py2exe (http://starship.python.net/crew/theller/py2exe/)
in Windows 98. I copied the necessary files into my Python23 directory (where I
have a module called 'mastermind.py'), and in the same directory I saved a
Python source file called 'setup.py' containing the following text:

from distutils.core import setup
import py2exe
setup(console=["mastermind.py"])

At this point the instructions say the following:

"""
Running

python setup.py py2exe --help

will display all available command-line flags to the py2exe command.

Now you can call the setup script like in this way:

python setup.py py2exe

and a subdirectory dist will be created, containing the files myscript.exe,
python23.dll, and library.zip.
"""

My problem is that, when I attempt to follow the first instruction (details
follow), it opens a DOS window that may indeed display all available
command-line flags to the py2exe command, but isn't very helpful because it
immediately disappears. (In fact I'm really not sure what a command-line flag
is, or what I'm supposed to do with it.) I've also tried simply running
setup.py: the DOS window disappeared immediately and there was no 'dist'
directory in evidence.

Here is what I tried regarding the first instruction:

i) Creating a shortcut to setup.py, setting its 'target' property to
'C:\Python23\setup.py --help', and double-clicking on its icon.

i) Setup | Run... | C:\Python23\python.exe setup.py py2exe --help | OK

Any help with this problem will be very much appreciated. Knowing how to create
standalone executables would give me lots of incentive to keep learning more
Python (which, incidentally, rocks).

Peace




From dave at pythonapocrypha.com  Sat Jan 24 00:19:56 2004
From: dave at pythonapocrypha.com (Dave Brueck)
Date: Fri, 23 Jan 2004 22:19:56 -0700
Subject: Batch commands on Windows
References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com>
	
Message-ID: <03fb01c3e239$b4a1ed30$6401fea9@YODA>

Moosebumps wrote:
[snip]
> # this actually does the same thing as Python, I was mistaken.  I was
> mislead by the IDLE behavior.
[snip]

> The general idea is that it would be nice if there weren't any differences
> between the batch file and python.  From a practical standpoint, it would
> encourage a lot of people to switch from nasty batch files to Python scripts
> if you could just surround the entire thing with os.batch(' ') or some
> similar sort of mechanical textual substitution.  Then you could clean it up
> gradually.

Ah, now I understand what you meant. In practical terms, there isn't much of a
difference between executing Python commands in batch mode or interactively
from the *Python* command prompt (the interactive interpreter), and I think
that's what this all boils down to. A DOS window is an interactive command
prompt for the MS-DOS batch language; Python is a different language and has
its own command prompt, so it wouldn't really make sense for commands in one
language to be valid in the other. It's easy to miss this point though since
its common to access the Python "command prompt" by first launching the DOS
command prompt, but they really are two different languages with two different
purposes.

> > > What's the deal with that?  I thought Python started out as a scripting
> > > language.  And that seems like the most basic thing that a scripting
> > > language should do.
> >
> > Dunno, although MS-DOS shell scripting is certainly a small subset of
> scripting
> > in general. Maybe with a concrete example somebody will be able to give
> you a
> > hand.
>
> It is a small subset, but an important subset.  Shell scripting started
> probably when people got sick of typing the same commands into the prompt.
> For a language to really support shell scripting, it should provide a way of
> automating the process of typing in the commands.  As in, there should be no
> difference whether you're actually typing, or you're running the script.

Right, and there is little difference between batch and interactive modes of
Python, and little difference between batch and interactive modes of MS-DOS,
but what you're wishing for is for batch mode of language A to be the same as
interactive mode of language B. Unless one language is a subset of the other,
that just doesn't make sense (and I'm very pleased that Python is not a
superset of DOS batch files! :) )

> If there is a way and I don't know about it, I would be happy to hear about
> it.  But I do think it is a pretty big hole.

I don't - Python is a general purpose programming language that happens to be
pretty good for so-called "shell scripting" too, but the language is useful in
so many other domains that it wouldn't make sense to tailor it too heavily to
this particular type of problem. Further, if it were to be tailored to make
shell scripting even easier, I really doubt that basing it on the MS-DOS batch
language would be a good idea - even something as quirky as bash would be far
better.

-Dave




From swalters_usenet at yahoo.com  Thu Jan  8 19:00:12 2004
From: swalters_usenet at yahoo.com (Samuel Walters)
Date: Fri, 09 Jan 2004 00:00:12 GMT
Subject: What psyco is goot at [Was: Rookie Speaks]
References: <3FFC9855.3070901@lawson.com>
	
	<3FFC9A22.3020507@lawson.com>
	
	
	
	
Message-ID: 

|Thus Spake Tim Churches On the now historical date of Fri, 09 Jan 2004
09:10:58 +1100|

> Does that mean that Armin Rigo has slipped some form of Einsteinian,
> relativistic compiler into Psyco?

No, no.  It means one of two things:  either you didn't adjust constant
that tries to factor out the overhead of profiling, or the call took so
long that the timer actually overflowed.

This will help you set the proper constant:

-----
import profile
import pprint

tests = 20
cycles = 10000
pr = profile.Profile()
proflist = []
for x in xrange(1, tests + 1):
    proflist.append(pr.calibrate(cycles))

pprint.pprint(proflist)
-----

Increase cycles until your results don't exhibit much of a spread, then
take the lowest of those values.  This is the constant you set when
instantiating a profiling object.  It is specific to each individual
machine.

If it *still* gives you negative times, then the timer is overflowing and
you need to adjust the original script so that you're not running through
such a big list of numbers.

Then your apparent problems with causality should be solved.

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""



From jepler at unpythonic.net  Sun Jan 18 13:13:31 2004
From: jepler at unpythonic.net (Jeff Epler)
Date: Sun, 18 Jan 2004 12:13:31 -0600
Subject: re question - finiding matching ()
In-Reply-To: <1074445520.18656.30.camel@dev.internal>
References: <4f0a9fdb.0401180751.4b66d974@posting.google.com>
	<1074445520.18656.30.camel@dev.internal>
Message-ID: <20040118181331.GB24401@unpythonic.net>

Perhaps you'd like to enhance your test-suite:
	# Do improperly-nested parens cause an exception? (part 1)
        text = 'add((1,2,3)'
        self.assertRaises(RuntimeError, findOperands, 'add', text)

	# Do improperly-nested parens cause an exception? (part 2)
        text = 'add(1,2,3))'
        self.assertRaises(RuntimeError, findOperands, 'add', text)

	# Do multiple statements on one line behave as expected?
        text = 'add(1,2); add(1,2)'
        expected = ['2', '3']
        self.assertEquals(operands, expected)

Jeff



From sidharthk at hotmail.com  Thu Jan 29 11:43:19 2004
From: sidharthk at hotmail.com (Sidharth Kuruvila)
Date: Thu, 29 Jan 2004 22:13:19 +0530
Subject: Get number of iteration
References: 
	
Message-ID: 

there is a function in python 2.3 called enumerate.


>>> l = range(0,51,5)
>>> e = enumerate(range(0,51,5))
>>> e

>>> list(e)
[(0, 0), (1, 5), (2, 10), (3, 15), (4, 20), (5, 25), (6, 30), (7, 35), (8,
40), (9, 45), (10, 50)]
>>> e = enumerate(range(0,51,5))
>>> for index, value in e:
...  print "The index of value %i is %i" % (value, index)
...
The index of value 0 is 0
The index of value 5 is 1
The index of value 10 is 2
.
.
.

if you are using an older version of python which doesn't have enumerate
you could do this
>>> l = range(0,51,5)
>>> zip(range(len(l)), l)
[(0, 0), (1, 5), (2, 10), (3, 15), (4, 20), (5, 25), (6, 30), (7, 35), (8,
40), (9, 45), (10, 50)]







From sebb at linuxcult.com  Sun Jan 11 18:19:37 2004
From: sebb at linuxcult.com (sebb)
Date: 11 Jan 2004 15:19:37 -0800
Subject: Search and replace a specific word in a file object.
Message-ID: <56f42e53.0401111519.2da31b8a@posting.google.com>

I want to know how to search for a word in a file object and then
replace that word with another string. I would like to know the
easiest way to do it.

Thanks.


From Scott.Daniels at Acm.Org  Sun Jan 18 18:25:40 2004
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Sun, 18 Jan 2004 15:25:40 -0800
Subject: Printing variable names
In-Reply-To: 
References: 
	
Message-ID: <400b207a$1@nntp0.pdx.net>

Mark McEahern wrote:
> Mike wrote:
>> mylist = [a, b, c]
>>
>> I want to print out the names of the variables in mylist (not the
>> values of a, b, and c).  How do I go about doing this.  Thanks.
>> Mike
> ... One idea is to use a dictionary instead.  Then:
> for key, value in mydict.iteritems():
>    print '%(key)s = %(value)s' % locals()
> I'm curious what problem you're trying to solve.

Mark's questions are very much on target.  If the purpose is debugging,
you might be satisfied with something like:

     def vnames(value, *dicts):
         """From a value and some dictionaries and give names for the 
value"""
         result = []
         for d in dicts:
             result.extend([key for key, val in d.iteritems()
                            if val is value])
         result.append(repr(value))
	return result

Which you might use like:

     a,b,c = 1,2,3
     d,e,f = 5,4,3

     for v in range(10):
         print v, vnames(v, locals(), globals())

Note: You probably need only locals or globals if you are at the top
       level of an interpreter such as Idle or the python shell.
        You might prefer '==' to 'is', but remember that 0.0 == 0 == 0L.

-Scott David Daniels
Scott.Daniels at Acm.Org


From astoltz at yahoo.com  Thu Jan 22 13:04:39 2004
From: astoltz at yahoo.com (Al Stoltz)
Date: 22 Jan 2004 10:04:39 -0800
Subject: cgi.fieldstorage not getting POST data
Message-ID: <606892f8.0401221004.68aac4e2@posting.google.com>

Greetings all.  

I've got a small web application (just a web interface to a MS-access
database) and I recently upgraded ActiveState's python dist. from 2.2
to their latest (2.3.2 I think). In the process, I broke some of my
cgi scripts.  A little troubleshooting reveals that the
cgi.fieldstorage() method is not receiving any data at all when using
an HTTP POST request in my HTML.  If I change to a GET request, all is
well.

I'll add that the scripts were working fine with the POST request
under version 2.2.  A quick glance through the change log at both
ActiveState and Python.org didn't yield any clues that the cgi module
might have changed from 2.2 to 2.3

OS is windows2000 and I'm using ActiveState's version because I need
the ODBC module that it comes with it.

Code snippets are below.  If I change method="post" to method="get",
the value of id get passed into test1.py like you would expect.
Otherwise the value that form.getvalue('id') returns is 'none'.

Anyone have any insight?  Thanks for looking.

--------------- HTML Page---------------

This is a test.

--------------- test1.py ----------------------------- #!d:/python/python.exe import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() id = form.getvalue('id') print "Content-Type: text/html" print print"" print "

value of id is: %s

" % id print "" From jcarlson at uci.edu Thu Jan 22 11:43:33 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 08:43:33 -0800 Subject: Checking for duplicate instances of a script... References: <400e4638$0$19274$626a54ce@news.free.fr> <8b146afd37580ecc733f713e953b542c@news.teranews.com> Message-ID: <20040122084154.0261.JCARLSON@uci.edu> > >Hello, python beginner here, > >How can I make sure that a given script is never run more than once at the > >same time in a system ? > >Besides checking 'ps' for its own name. Most modern langages have a direct > >way to do that. > >Thanks > What modern language has a direct way to do that? You can register a COM or CORBA interface (is this what they are called?) and attempt to connect to it during startup. If you can connect to yourself, don't start up, if you can't, start up. - Josiah From seanl at chaosring.org Mon Jan 5 20:06:05 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Mon, 05 Jan 2004 17:06:05 -0800 Subject: Scoped Lock In-Reply-To: References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: How about: def lock_call(mutex, func, *args, **kwargs): mutex.acquire() try: res = func(*args, **kwargs) finally: mutex.release() return res def do_something(blah): # do stuff m = threading.Lock lock_call(m, do_something, "some data") From jeff at corrt.com Thu Jan 1 23:20:19 2004 From: jeff at corrt.com (Jeff Kunce) Date: Thu, 1 Jan 2004 22:20:19 -0600 Subject: [Image-SIG] PIL: jpeg comment In-Reply-To: <20031223221724.GA2701@nl.linux.org> Message-ID: <000601c3d0e7$c4aab350$b9c3930a@jjkc100> I don't know for sure, but try looking in the "app" attribute (a dictionary) of an image object. For example: im = Image.open('myimage.jpg') print im.app EXIF data is stored there, so maybe comments are, too --Jeff > -----Original Message----- > From: image-sig-bounces at python.org [mailto:image-sig-bounces at python.org] > On Behalf Of Gerrit Holl > Sent: Tuesday, December 23, 2003 4:17 PM > To: image-sig at python.org > Cc: python-list at python.org > Subject: [Image-SIG] PIL: jpeg comment > > Hi, > > how do I read a JPEG comment with the Python Imaging Library? > > yours, > Gerrit Holl. > > -- > Asperger's Syndrome - a personal approach: > http://people.nl.linux.org/~gerrit/english/ > > _______________________________________________ > Image-SIG maillist - Image-SIG at python.org > http://mail.python.org/mailman/listinfo/image-sig From ville.vainio at spamster_tut_remove.fi Sun Jan 11 05:43:59 2004 From: ville.vainio at spamster_tut_remove.fi (Ville Vainio) Date: 11 Jan 2004 12:43:59 +0200 Subject: The indentation & the blind (was Re: help with Python Environment For Blind User References: Message-ID: >>>>> "eltronic" == eltronic writes: eltronic> notepad.exe . it indents, can put spaces when you hit eltronic> tab and handles larger files than notepad. BTW, how does the indentation block structure work for blind people? Obviously it would be great if the source-reading program could pronounce the logical structure as "indent"/"dedent", but that is probably not the case? Could people with such needs benefit from an "explicit block structure" format for the code and a preprocessor, e.g.: def a(x): (. print a .) (this would also be needed in whitespace-lossy environments such as some websites) Certainly such a preprocessor could be hacked together quickly, but it might be nice to have the format standardized across the whole Pythonia, and the preprocessor bundled in Tools/ of the distributions. Will I get prize for being the 1000th guy to propose this? -- Ville Vainio http://www.students.tut.fi/~vainio24 From paul at boddie.net Mon Jan 26 06:01:12 2004 From: paul at boddie.net (Paul Boddie) Date: 26 Jan 2004 03:01:12 -0800 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: <23891c90.0401260301.14baecb8@posting.google.com> malcolmny_1 at lycos.com (malcolm) wrote in message news:<64cff82f.0401251143.328388bd at posting.google.com>... > Why you can't get something for nothing > Jack Schofield Jan 22 2004 I'd forgotten about Schofield - regarded in various circles as having been clueless for at least the past decade, and obviously still an apologist for the 1980s-style proprietary software industry. > "There are also undoubted benefits from running open source software, > though the financial ones can be small or even negative. Companies are > bound to be tempted by the idea of getting something for nothing .." Interestingly, Schofield then links to a Stallman essay describing the "free as in freedom" motivations of the FSF. Anyway, when intelligent companies adopt open source software they work with the community; when clueless companies download "this free stuff" they work against the community and ultimately cause more problems for themselves later on. > "The facility to fix bugs yourself and to modify programs also sounds > attractive. However, fixing bugs is not practical for most companies, > and modifications can be positively dangerous. Obviously, employees at The Office aren't likely to be rebuilding their word processor from source, but Schofield seems to think that there's an army of penguins forcing people at gunpoint to do just that. Given the reference to Stallman, one would have thought that the "free as in freedom" slogan would have sunk in and he would have realised that "freedom" and "compulsion" are quite separate concepts. > If you are really going to do these things, you need to hire several > reliable programmers with kernel-level skills" Or you're a company working in software development who hopefully have skilled developers working for you anyway. > "Indeed, the whole progress of commercial computing has been from > expensive hand-written, bug-ridden, company-specific programs to > cheaper but more powerful off-the-shelf packages. From that point of > view, open source is a throwback." Yes, a history of computing as you'll read in any low-end "computer studies for business" textbook from circa 1983. But I suppose that after so long in technology journalism you don't have to learn anything new or adapt to the reality of the day but instead just stand on the sidelines cheering for your favourite brand. > - http://www.guardian.co.uk/online/story/0,3605,1127802,00.html Some other interesting links: http://www.sheffieldhallam.org.uk/blog/2004/01/12/19.40.04/ (Responses to Mr Schofield's latest piece which could have been titled "Free Software - something I don't understand and so it must be bad".) http://handelaar.org/index.php?p=77&c=1 (A more "robust" critique of Mr Schofield's journalism.) http://www.computerweekly.com/Article20541.htm (Pragmatism or just apologist rhetoric?) Paul From ykingma at accessforall.nl Fri Jan 16 14:42:36 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Fri, 16 Jan 2004 20:42:36 +0100 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> Message-ID: <40083eac$0$321$e4fe514c@news.xs4all.nl> Andrae Muys wrote: > Found myself needing serialised access to a shared generator from > multiple threads. Came up with the following > > def serialise(gen): > lock = threading.Lock() > while 1: > lock.acquire() > try: > next = gen.next() > finally: > lock.release() > yield next Is there any reason why the lock is not shared among threads? >From the looks of this, it doesn't synchronize anything between different threads. Am I missing something? Kind regards, Ype email at xs4all.nl From no.spam at at.all Sun Jan 25 04:29:38 2004 From: no.spam at at.all (solo) Date: Sun, 25 Jan 2004 09:29:38 +0000 (UTC) Subject: Test Message-ID: thanks for all! ---Posted by ME! From mike at odyne.com Sun Jan 18 14:22:08 2004 From: mike at odyne.com (Mike) Date: 18 Jan 2004 11:22:08 -0800 Subject: Printing variable names Message-ID: mylist = [a, b, c] I want to print out the names of the variables in mylist (not the values of a, b, and c). How do I go about doing this. Thanks. Mike From teeloranTakeThisAway at sunpoint.net Tue Jan 13 09:54:55 2004 From: teeloranTakeThisAway at sunpoint.net (Teuvo Eloranta) Date: Tue, 13 Jan 2004 14:54:55 GMT Subject: newbie list handling question Message-ID: <400406F9.40D64EE6@sunpoint.net> Hi, Any help to this? ## why a changes also when only av should change? ## outcome is: ## av is [[1, 10], [2, 20], [3, 30]] ## a is [[1, 10], [2, 20], [3, 30]] ## av is [[1, 20], [2, 20], [3, 20]] ## a is [[1, 20], [2, 20], [3, 20]] a = [[1, 10], [2, 20], [3, 30]] av = [] for i in a: av.append(i) #av = a[:] print "av is", av print "a is", a aver = 20 #for y in av: # y[1] = aver for i in range(len(av)): # this should change only av, not a? av[i][1]=aver #for i in range(len(a)): # this solution works! # av.append([i+1,aver]) print "av is", av print "a is", a Thank's in advance. -Teuvo From ir4u4 at yahoo.com Thu Jan 22 17:57:45 2004 From: ir4u4 at yahoo.com (Equis Uno) Date: 22 Jan 2004 14:57:45 -0800 Subject: My Python cannot find wxPython Message-ID: <692feddd.0401221457.18d40480@posting.google.com> Hi, I'm trying to run some Python software I downloaded off of sf.net. It's called Boa. It uses wxPython. It appears my install of Python cannot see my install of wxPython. My question: How can I tell Python where wxPython lives? Does Python have a concept like PATH or CLASSPATH? Some more details about my Python-wxPython problem: When I run Python on my Linux box I see this: dhcpclient-220-7:/# python Python 2.3.3 (#1, Jan 9 2004, 22:14:55) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> So, I'm running Python 2.3.3. When I look in /usr/local/share I see wxPython: dhcpclient-220-7:/# du /usr/local/share/wx/2.4 228 /usr/local/share/wx/2.4/afm 420 /usr/local/share/wx/2.4/gs_afm 652 /usr/local/share/wx/2.4 dhcpclient-220-7:/# When I run this "Boa" software I downloaded, I see this: dhcpclient-220-7:/pt/TThier/Languages/python/boa-constructor-0.2.3# ./Boa.py Starting Boa Constructor v0.2.3 importing wxPython Traceback (most recent call last): File "./Boa.py", line 179, in ? from wxPython import wx ImportError: No module named wxPython dhcpclient-220-7:/pt/TThier/Languages/python/boa-constructor-0.2.3# How do I get past this error: ImportError: No module named wxPython thanks, -moi From sidharthk at hotmail.com Thu Jan 29 11:41:39 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Thu, 29 Jan 2004 22:11:39 +0530 Subject: Get number of iteration References: Message-ID: there is a function in python 2.3 called enumerate. >>> l = range(0,51,5) >>> e = enumerate(range(0,51,5)) >>> e >>> list(e) [(0, 0), (1, 5), (2, 10), (3, 15), (4, 20), (5, 25), (6, 30), (7, 35), (8, 40), (9, 45), (10, 50)] >>> e = enumerate(range(0,51,5)) >>> for index, value in e: ... print "The index of value %i is %i" % (value, index) ... The index of value 0 is 0 The index of value 5 is 1 The index of value 10 is 2 . . . if you are using an older version of python which doesn't have enumerate you could do this >>> l = range(0,51,5) >>> zip(range(len(l)), l) [(0, 0), (1, 5), (2, 10), (3, 15), (4, 20), (5, 25), (6, 30), (7, 35), (8, 40), (9, 45), (10, 50)] From cookedm+news at physics.mcmaster.ca Tue Jan 20 16:06:17 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 20 Jan 2004 16:06:17 -0500 Subject: efficent test for array with only one value? References: <00ird1-dmd.ln1@jowls.lairds.org> <25mud1-s1m.ln1@jowls.lairds.org> Message-ID: At some point, Kyler Laird wrote: > Robert Kern writes: > >>However, alltrue(a.flat == a.flat[0]) will work but won't short-circuit. > > How did I miss that?! Yes, that's the kind of operation I sought. > I'm surprised that it doesn't short-circuit. It *should*, right? > > It's a shame that it only works along a single axis. The use of > "flat" is a problem for me. I'm looking at sections of an image > (building a quadtree) so the arrays I'm checking are not contiguous. > I think that means I have to resort to something ugly like this. > Numeric.alltrue(Numeric.alltrue(a == a[0,0])) > That eliminates many opportunities for short-circuiting. > > I can also flatten the array using reshape() before checking it. I > assume that also means a lot of possibly unnecessary operations. > (Does reshape() return a copy of the array or just an array with > the original data and a new shape?) In general, use ravel() instead of .flat. ravel() is a simple wrapper around reshape(), which will make a contiguous only if necessary. .flat will fail for non-contiguous arrays (like views into another array). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From loic at yermat.net1.nerim.net Sat Jan 24 05:27:17 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Sat, 24 Jan 2004 11:27:17 +0100 Subject: Python & Databases ? In-Reply-To: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> References: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> Message-ID: Peter Moscatt a ?crit : > Will Python work with any of the databases like MySQL... ? > > Pete http://www.python.org/topics/database/ http://www.python.org/topics/database/modules.html From carroll at tjc.com Sun Jan 18 20:29:55 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon, 19 Jan 2004 01:29:55 GMT Subject: Simple (?) Regular Expression Question References: <6747bc9d.0401181545.2b4ffb14@posting.google.com> Message-ID: On 18 Jan 2004 15:45:31 -0800, slzatz at hotmail.com (Steve Zatz) wrote: >Is '@' a special character in regular expressions? I am asking >because I don't understand the following: > >>>> import re >>>> s = ' @' >>>> re.sub(r'\b@','*',s) >' @' >>>> s = ' a' >>>> re.sub(r'\ba','*',s) >' *' > >Have googled atsign and regular expressions but have not found >anything useful. System is Win XP, Python 2.3.3. Any help would be >appreciated. I suck at regular expressions, but I think that what's going on here is that \b matches an empty string, but only at the start or end of a word. In the first case ("\b@" and " @"), there is no start-of-word, so no match, no substitution. In the second case ("\ba" and " a", you have \b matching the empty string between the blank and the "a", because the "a" is considered a word. "a" is going to be considered a word, because it's entirely composed of letters and numbers (a single letter), while "@" is not. From a.schmolck at gmx.net Sun Jan 11 07:54:50 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 11 Jan 2004 12:54:50 +0000 Subject: Emacs python mode question References: Message-ID: jblazi writes: > On Sat, 10 Jan 2004 16:25:59 -0600, Skip Montanaro wrote: > > > (define-key esc-map [g] 'goto-line) > > For one reason or the other, this does not work. It doesn't work because the above will specifically set ESC-g to goto-line, which isn't what you want, I guess. Try either of the following: (global-set-key [(meta g)] 'goto-line) (global-set-key "\eg" 'goto-line) Before you save your .emacs you can verify that the command works by pressing C-xC-e right after the closing ')' and then M-g. 'as From afriere at yahoo.co.uk Tue Jan 13 19:22:19 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 13 Jan 2004 16:22:19 -0800 Subject: Does anyone else not find the fun in programming...? References: Message-ID: <38ec68a6.0401131622.2725b690@posting.google.com> chris.lyon at spritenote.co.uk (Chris Lyon) wrote in message news:... > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, > I have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along > canals is fun, Arguing about quite how useless the British Government > is fun but programming ? > > Do I need help ? > Maybe you just need another vocation. Work and fun are not necessarily mutually exclusive. Considering the proportion of your life you will spend at work, you ought to make damn sure they aren't! Programming is such fun that I'm happy (almost) every day to be going to work. Which is more than I can say about various other jobs I've had. OK so maybe it can be painful at times (like when I have to work with XSLT :o), but designing and implementing solutions in Python (or watching my little creatures take on a life of their own - which is how I look at OOP - hmm maybe I need help?), is just plain fun. Which is not to say football, walking and arguing are not. From hatespam at fakeemail.com Tue Jan 13 23:32:56 2004 From: hatespam at fakeemail.com (Dan Olson) Date: Tue, 13 Jan 2004 22:32:56 -0600 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: On Tue, 13 Jan 2004 19:00:43 -0800, Brandon J. Van Every wrote: > I'm curious what sky is going to fall if I don't follow your advice? It's just advice. I think it would have been smoother for everyone if you'd followed it, but apparently you prefer to piss on my advice so that's cool too. From reply.in.the.newsgroup at my.address.is.invalid Tue Jan 20 16:06:10 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 20 Jan 2004 22:06:10 +0100 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> Message-ID: Dog at will.hunt: >It says to run the setup.py file using the following command in IDLE Where does it say that? The wordt "idle" doesn't appear on http://cvs.sourceforge.net/viewcvs.py/*checkout*/spambayes/spambayes/README.txt?rev=HEAD&content-type=text/plain >in the directory that I extracted the spambayes files into: python setup.py >install. > >When I do this, it tells me that python is not a recognized command. ^^ What exactly is "it"? Is it a Unix/Linux shell, or the Windows command interpreter? -- Ren? Pijlman From carroll at tjc.com Thu Jan 8 21:55:14 2004 From: carroll at tjc.com (Terry Carroll) Date: Fri, 09 Jan 2004 02:55:14 GMT Subject: books References: <3FFDC029.AB0A4097@unet.univie.ac.at> Message-ID: <5r5svvccvt4lqjnlaurftejbgluu1fepoc@4ax.com> On Thu, 08 Jan 2004 20:40:08 GMT, Thomas Mang wrote: >I have programmed mostly in C++ lately, and I want to start learning >Python now. > >Which books would you recommend to buy? > >I am both looking for an introduction into the language, as well as >complete guides. As an intro, I really liked O'Reilley's "Learning Python." As a reference, I *really* like their "Python In A Nutshell." I didn't care much at all for their "Programming Python," but lots of people swear by it, so your milage may vary. From anthony at interlink.com.au Sat Jan 10 23:34:32 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Sun, 11 Jan 2004 15:34:32 +1100 Subject: RELEASED: Shtoom 0.1 Message-ID: <200401110434.i0B4YXK6008384@localhost.localdomain> I'm happy to announce the first release of Shtoom. Shtoom is a Python implementation of a voice over IP software phone, using the standard SIP protocol. The first release features: - basic calling functionality (can make and receive calls), - Qt, Gtk, Tkinter and text user interfaces (of varying degrees of functionality), - audio support for Linux/FreeBSD (using ossaudiodev) and Windows/MacOS X (using PortAudio), - audio codecs G711 (64kbit/s) and GSM 06.10 audio (3kbit/s) with an optional extension, - firewall traversal via STUN. It's been tested against Cisco IOS 12.3, Asterisk, kphone and linphone. It's available from the website: http://shtoom.sf.net/ Future plans include: - error handling - SIP registration support - A number of other applications, including shtam (answering machine) and shtoomcu (conferencing server). Anthony -- Anthony Baxter It's never too late to have a happy childhood. From noemail at noemail4u.com Thu Jan 29 08:10:23 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 29 Jan 2004 13:10:23 GMT Subject: comparing booleans References: <40185112.264898A4@alcyone.com> Message-ID: On Wed, 28 Jan 2004 16:17:22 -0800, Erik Max Francis wrote: >Gerrit Holl wrote: > >> is it proper to compare booleans? It is possible, of course, because >> they're compatible with numbers, but booleans aren't truly numbers. >> I'm >> tempted to write: >> >> return cmp(self.extends, other.extends) > >Even if you're seriously worried about the correctness of comparing >Booleans, you can always explicitly turn them into integers: > > return cmp(int(self.extends), int(other.extends)) > >> (Hmm, makes me wonder, for booleans, are != and ^ equal?) > >Easily checked: > >>>> for x in (True, False): >... for y in (True, False): >... print x, y, x != y, x ^ y >... >True True False False >True False True True >False True True True >False False False False It's not always the same, as shown here: >>> True != True != True False >>> True ^ True ^ True True >>> True != False != True != True False >>> True ^ False ^ True ^ True True Not that I've never used this (cool) Python syntax in practice, but I thought it was worth mentioning that using != and ^ in boolean expressions does not always give the same result. It does give the same result when there are only two operands. Interestingly, and I'm not sure why: >>> (True != True) != True True >>> True != (True != True) True >>> True != True != True False --dang From sidharthk at hotmail.com Wed Jan 28 09:57:02 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Wed, 28 Jan 2004 20:27:02 +0530 Subject: type() for new style classes - buggy? References: Message-ID: In the case of new style classes type actually doubles up as a class constructor, so all classes including type itself are instances type. >>> class A(object): ... pass ... >>> a = A() >>> type(a) >>> type(A) >>> isinstance(A, type) True >>> isinstance(a, type) False >>> isinstance(type, type) True >>> hope this helps there is some documentation on new style classes you might want to read. http://www.python.org/doc/newstyle.html particularly the first essay by Guido. From tjreedy at udel.edu Mon Jan 26 16:43:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jan 2004 16:43:45 -0500 Subject: compress string of data References: Message-ID: "Josiah Carlson" wrote in message news:bv3bdd$a0j$3 at news.service.uci.edu... > Piet van Oostrum wrote: > > >>>>>>Gerrit Holl (GH) wrote: > > > > > >>>How i could compress string of data?. > >>> > >>>>>import zlib > >>>>>zlib.compress("Hello, world") > > > > GH> 'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' > > > > GH> http://www.python.org/doc/current/lib/module-zlib.html > > > > Waw, that compresses it from 12 bytes to 20 bytes :=) > > > There is no such thing as universal compression Only if you specify invertibility (losslessness). f(s) == '' compressess everything except '' itself ;-) and that len(f(s)) < len(s) for some s and not just <= for all s (which allows identity 'compression' f(s) == s). > - some compressions result in expansion. Which is to say that if a 1-1 function maps some strings to smaller strings, it must correspondingly map others to larger strings. An interesting CS tidbit that people keep discovering by stumbling over. Lossless universal expansion is possible: f(s) == ' '+s. But it is into rather than onto, so only strings starting with ' ' can be inversely mapped. Terry J. Reedy From jcarlson at nospam.uci.edu Mon Jan 26 02:00:17 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 23:00:17 -0800 Subject: efficient updating of nested dictionaries In-Reply-To: References: Message-ID: > Although, that's probably kind of lame - I bet others will have much > better suggestions. I'm interested in how other people do this too. > Rich String concatenation is not that lame, but I'd use tuples: MY_DICT[(KEY_X, KEY_Y, KEY_Z)] = FOO Tuples save on string operations. - Josiah From ih8spam at spamtrap.com Tue Jan 13 13:37:52 2004 From: ih8spam at spamtrap.com (WTH) Date: Tue, 13 Jan 2004 13:37:52 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <1008ek75iso5ca5@corp.supernews.com> You have the greatest inherent ability to insult the largest number of people with the smallest amount of effort. You are truly a legend in your own mind. WTH From bh at intevation.de Fri Jan 9 06:41:06 2004 From: bh at intevation.de (Bernhard Herzog) Date: Fri, 09 Jan 2004 12:41:06 +0100 Subject: PRE-PEP: new Path class; mutability, __hash__, __eq__, __cmp__ References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <6qad4xmjsd.fsf@salmakis.intevation.de> Christoph Becker-Freyseng writes: > So for __eq__ it follows naturaly > def __eq__(self, other): > FIXME: isinstance checking > return (str(self.normalized()) == str(other.normalized())) > It cares about nonexistent paths, too. (The samefile-solution won't --- > we might code a special case for it ...) What exactly does normalized() do? If it's equivalent to os.path.normpath, then p1 == p2 might be true even though they refer to different files (on posix, a/../b is not necessarily the same file as b). OTOH, if it also called os.path.realpath too to take symlinks into account, __eq__ would depend on the state of the filesystem which is also bad. IMO __eq__ should simply compare the strings without any modification. If you want to compare normalized paths you should have to normalize them explicitly. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From mahasamatman at nm.ru Thu Jan 1 11:34:18 2004 From: mahasamatman at nm.ru (Rimidalv) Date: Thu, 01 Jan 2004 18:34:18 +0200 Subject: UML tools for python In-Reply-To: <13dc97b8.0312301543.39192aa2@posting.google.com> References: <13dc97b8.0312301543.39192aa2@posting.google.com> Message-ID: Andy Bulka wrote: > Whilst almost responding to the 'dream project' thread I decided that > this post warranted its own thread. What about a solid UML tool with > round trip functionality for the Python Community? > > Some attempts at reverse engineering python are > PyReverse http://www.logilab.org/projects/pyreverse/ > PyUt http://pyut.sourceforge.net/ > PyNSource http://www.atug.com/andypatterns/pynsource.htm > Boa Constructor http://sourceforge.net/projects/boa-constructor/ > IDLE's class browser > PythonWin 's class browser > all of which have their problems and limitations. > > E.g. PyUt will hang if it cannot __import__ successfully and its GUI > has no zoom nor scroll etc. PyReverse is hard to use, misses a lot of > basic information and then what do you do with the XML files? - who > will read these? I have to edit them manually to import them into > Enterprise Architect > http://www.sparxsystems.com.au > and the last time I tried, you couldn't import into > Poseidon http://www.gentleware.com/products/index.php4 > community edition, which is the better descendant of the free Argo. > > Some Java-centric UML tools I believe do export python, though this is > usually very simple and usually broken. For example > Object Domain http://www.objectdomain.com/products/od/overview.do > claims to import python code, but the last I looked, this particular > functionality was fragile. > > Potential powerful technology that could be used is > Bicycle Repair Man http://bicyclerepair.sourceforge.net/ > a refactoring tool for Python which could be combined with some sort > of Java GUI (with zoom and all those niceties) - since the hard bit of > the problem is parsing python reliably and knowing how to change it / > regenerate it nicely. Bicycle Repair Man already treads deeply in > this territory. Also > PyChecker http://pychecker.sf.net/ > walks similar territory. > > Ideal tools would look and behave something like > ModelMaker (for Delphi) http://www.modelmakertools.com/ > TogetherJ http://www.togethersoft.com/products/index.jsp > where you can work in code or in diagrams and the two are seamlessly > kept in synch. Its truly cool, and I wish I could do these sorts of > things in Python. > > Does anybody know of any other work being done in this area? > > Do we think that having a solid UML tool with full round trip > facilities plus gorgeous GUI - build specifically for Python is a > worthy goal? Is anybody going to bother to build such a tool for > free? > > Andy Bulka > http://www.atug.com/andypatterns Try Dia http://www.lysator.liu.se/~alla/dia/ also autodia http://droogs.org/autodia/ and if you Google a little i guess that you can find dia2code (sorry couldn't find url) From oren-py-l at hishome.net Mon Jan 5 16:43:37 2004 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 5 Jan 2004 16:43:37 -0500 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <20040105214337.GA87075@hishome.net> On Mon, Jan 05, 2004 at 10:06:59AM -0500, John Roth wrote: > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q > > Frankly, I like the idea. It's about time that all of the file > and directory stuff in the os module got objectified > properly (or at least with some semblance of OO propriety!) "Peroperly"? There is nothing particularly "proper" or "improper" about objects or any other programming paradigm supported by Python. Objectifying is not a goal in itself. I like the Path object because the interface is easier to learn and use, not because it is "objectified". > 5) Should == operator be the same as os.path.samefile()? > > Why not... No. Symbolic links are something you would sometimes want to treat as distinct from the files they point to. > walk is a nice function, but it should be redone to > use the visitor pattern directly, with different method > names for files, directories and whatever else a > particular file system has in it's warped little mind. I find a generator and a couple of elifs are much easier to read. No need to define a class, pass context information to the methods of that class, etc. > 13) chdir, chmod, etc? > > No. This has nothing to do with pathname. What's the difference between chmod and touch? They both affect the file metadata in similar ways. Oren From neilmacgaffey at yahoo.com Fri Jan 23 09:38:08 2004 From: neilmacgaffey at yahoo.com (Neil MacGaffey) Date: Fri, 23 Jan 2004 06:38:08 -0800 (PST) Subject: file open problem Message-ID: <20040123143808.80139.qmail@web14702.mail.yahoo.com> Hi - I'm new to python and am stymied by something that should be simple. The file open command below works fine on my desktop machine, but I cant get it to work on my laptop. Since using Python on my laptop is realistically the only way I'm going to find the time to learn Python, this is a big problem for me. Here's what I'm up against: PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> fobj = open(r'c:\temp\pytest.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\temp\\pytest.txt' The laptop is a Sony VIAO that's about 2 years old. Its running Windows 2000, SP4. The desktop is an older machine, but with the same Windows environment. I've obtained a fresh download of Python 2.3.3 and the Win32 extension and have re-installed both a couple of times with no apparent problems. I also tried dropping back to Python 2.3.2, but had same result. Any ideas as to what I should be looking at on this laptop that might be causing the problem? Thank you Neil __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From borco at go.ro Fri Jan 16 07:53:56 2004 From: borco at go.ro (Ionutz Borcoman) Date: 16 Jan 2004 04:53:56 -0800 Subject: Project dream References: Message-ID: <80dac0f4.0401160453.a36ff7d@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > Suppose you have the time and the money to start a new project in > Python. What would you like to do? I want to do a 'Where Is It?' clone in Python. Probably use Metakit and e4graph as the database. PyGTK or WxPython for the GUI (most probably PyGTK). I'll probably do it anyway, but money would help a lot :) ionutz From Kyler at news.Lairds.org Sun Jan 18 17:12:06 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Sun, 18 Jan 2004 22:12:06 GMT Subject: Does MLab.std() dislike Numeric.UnsignedInt8? Message-ID: Python 2.3.3 (#2, Jan 4 2004, 12:24:16) [GCC 3.3.3 20031229 (prerelease) (Debian)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Numeric >>> import MLab >>> import Scientific.Statistics >>> MLab.std(Numeric.array([255,255], Numeric.Int0)) 0.0 >>> MLab.std(Numeric.array([255,255], Numeric.UnsignedInt8)) 181.01933598375618 >>> Scientific.Statistics.standardDeviation(Numeric.array([255,255], Numeric.UnsignedInt8)) 0.0 It seems to me that the return values should all be the same. Am I missing something simple? --kyler From hans at zephyrfalcon.org Fri Jan 23 14:14:46 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 23 Jan 2004 14:14:46 -0500 Subject: C compilers In-Reply-To: References: Message-ID: <401172A6.40000@zephyrfalcon.org> Lucas Raab wrote: > I realize that this is a Python newsgroup, but do any of you know any good > C/C++ compilers?? I'm interested in imbedding C with Python. Hmm, gcc? You don't mention the platform you're using, but it's available for just about any OS. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From axel.mittendorf at transfertech.de Thu Jan 15 07:19:31 2004 From: axel.mittendorf at transfertech.de (axel.mittendorf at transfertech.de) Date: Thu, 15 Jan 2004 13:19:31 +0100 Subject: [PyQT] NULL tstate Message-ID: <40068553.3E80025A@transfertech.de> Hi, I got a problem in a multithreaded PyQT application that uses the translate method from the QApplication class. The last thing it does is: self.cmd_anything.setAccel(self.__tr("Alt+S")) __tr is: def __tr(self,s,c =None): return qApp.translate( "Form_anything", s,c) after this the application quits with this error message: Fatal Python error: PyEval_SaveThread: NULL tstate Does anyone know what this is? TIA, Axel From theller at python.net Wed Jan 28 14:35:05 2004 From: theller at python.net (Thomas Heller) Date: Wed, 28 Jan 2004 20:35:05 +0100 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: runed at stud.cs.uit.no (Rune) writes: > Hey > > I'm trying to build a gui application and need to know if the user is > actually holding down the shift or ctrl key. That is, if the user > currently is holding down the shift key. In pseudo code this will boil > down to something like this: > > def test: > if user presses shift: > return SHIFT_IS_PRESSED > elif user presses ctrl: > return CTRL_IS_PRESSED > else > return false > > It's important to notice here that I'm not interested if the user has > already pressed shift or ctrl. I'm only interested in knowing if he is > currently holding down one of these keys. (I have looked into msvcrt > and the like but have found no answer..) The function should also work > in both windows and Linux. No idea about linux, but on windows you use win32api.GetKeyState(). Thomas From goodger at python.org Mon Jan 26 11:18:18 2004 From: goodger at python.org (David Goodger) Date: Mon, 26 Jan 2004 11:18:18 -0500 Subject: unittest In-Reply-To: References: Message-ID: <40153DCA.8090401@python.org> Zunbeltz Izaola wrote: > Tnaks, why is this so? From the fine manual (http://www.python.org/doc/current/lib/minimal-example.html): A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters "test". This naming convention informs the test runner about which methods represent tests. The convention is necessary because you might want methods that are *not* tests. -- David Goodger From tim.one at comcast.net Fri Jan 23 01:06:04 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 23 Jan 2004 01:06:04 -0500 Subject: Mixing protocols in pickles? In-Reply-To: <40107C70.13CA8495@alcyone.com> Message-ID: [Erik Max Francis] > Is there any prohibition against mixing different protocols within the > same pickle? No. The unpickling implementation has no idea which protocol is in use. There's a ton of info about unpickling in 2.3's undocumented new pickletools.py library module, BTW, and a symbolic pickle disassembler (which would be especially useful here). Try getting gzip out of your test program; pickles are exercised more heavily than gzip. Try it with both pickle and cPickle; it might matter. ... > So I thought it would be clever to write the tag string with > protocol 0 so it would show up in a file viewer as plain text > and then write the rest of the data with protocol 1 A protocol 1 string pickle just contains the raw string bytes; that's the same stuff for printable ASCII as proto 0 produces, and is *more* readable if you're using "funny characters" (a proto 0 string pickle replaces funny characters with Python string escape sequences). ... > This works fine on Unix, but on Windows it generates the (utterly > puzzling) error: ... > File "C:\My Documents\botec-0.1x1\botec.py", line 1666, in load > system = pickle.load(inputFile) > ImportError: No Module named copy_reg > >>> That's especially puzzling to me because that error message isn't one Python produces: all messages of this form produced by the core spell it "module" instead of "Module". > ... > So I guess there are a few questions: Why is the error being > generated so obscure and seemingly incorrect? Not enough info to say. > Is it really the case that mixing multiple protocols within the same > pickle isn't allowed, No, the unpickler doesn't care (read pickletools.py for a full explanation of why it doesn't care). > or is this truly a bug Somewhere, yes, but not necessarily in pickle. > (or, say, a Windows-specific problem because protocol 0 requires that > the pickle file be in text mode?)? No, that protocol 0 used to be called "text mode" was a horrid mistake. Pickle files should always be opened (for both reading and writing) in binary mode, regardless of the pickle protocol. It so happens you can *get away* with using text-mode files on Windows for (only) protocol 0 pickles, but that's more by accident than design. From none at none.com Wed Jan 14 09:42:52 2004 From: none at none.com (Derek) Date: Wed, 14 Jan 2004 09:42:52 -0500 Subject: I come not to bury C++, but to praise it... References: Message-ID: "Rainer Deyke" wrote: > > You also seem to have a narrow view of C++ as a > > strictly OO language when in fact it supports several > > programming paradigms (write whatever you want: template > > metaprograms, modules, procedures, classes, etc.). > > C++ is rather similar to Python in this respect. ;-) > > I currently have two languages that I regularily use: C++ > and Python. C++ produces faster programs, gives direct > access to the hardware, and has many third-party libraries > that Python doesn't have. Python is more concise, more > flexible, safer, and has its own set of libraries that C++ > doesn't have. Both have their place. None of the other > languages I've looked at (with the possible exception of > Common Lisp) seem to offer me anything that I can't find in > either Python or C++, and many of them (Java in particular) > are far too restrictive for my taste. I also use C++ and Python as my main languages and I agree with your comments. However, I don't agree that Python is inherently "safer" than C++. At best I see it as a tie. For example, C++ let's you corrupt memory among other "unsafe" things, most of which can be avoided by using standard containers, smart pointers, etc. Python lets you do "unsafe" things such as passing an object to a function when it makes no sense to do so, which can lead to nasty runtime surprises. From mhammond at skippinet.com.au Fri Jan 30 18:37:06 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 31 Jan 2004 10:37:06 +1100 Subject: Problems with python23_d.lib built with Visual Studio 7.1 In-Reply-To: References: Message-ID: Paton J. Lewis wrote: > I built the Python 2.3.3 sources with Visual Studio 7.1 (the > conversion of the Visual C++ 6 project files appeared to work > without a hitch). Everything seems fine except when I try to link my > project with the debug Python library, in which case I get > unresolved symbols apparently because the Python debug library > symbol names have been modified in an unexpected fashion. For > example, the calling code asks for symbol __imp__Py_InitModule4 > (which exists in python23.lib) but python23_d.lib contains > __imp__Py_InitModule4TraceRefs. Has anyone run into this problem > before? It sounds to me like you are trying to link your non-debug built extension module with a debug built Python. A debug built extension module will not have a reference to __imp__Py_InitModule4. Make sure the code you are trying to link against Python23_d.dll is compiled with /DDEBUG /D_DEBUG and /MDd. Mark. From mborgerding at cinci.rr.com Thu Jan 15 21:46:31 2004 From: mborgerding at cinci.rr.com (Mark Borgerding) Date: Fri, 16 Jan 2004 02:46:31 GMT Subject: python & mathematical methods of picking numbers at random In-Reply-To: References: <7xd69largm.fsf@ruckus.brouhaha.com> Message-ID: Bart Nessux wrote: > Paul Rubin wrote: > >> Bart Nessux writes: >> >>> I am using method 'a' below to pick 25 names from a pool of 225. A >>> co-worker is using method 'b' by running it 25 times and throwing out >>> the winning name (names are associated with numbers) after each run >>> and then re-counting the list and doing it all over again. >>> >>> My boss thinks that 'b' is somehow less fair than 'a', >> >> >> >> Both are the same, as you can see by calculating the probability of >> any given name being selected. What is the application, and the >> computer environment? You may also need to worry about correlations >> in the underlying Mersenne Twister PRNG. If the application is >> something where randomness is very important (you're picking winners >> for a big lottery or something) then you should use a better RNG. > > > We're raffling off crock-pots... that's why I think this is OK for our > purposes. > Some will claim you cooked the numbers, even if it is a crock. Let 'em blow off some steam, but don't chicken out. If you let them stew for a day, they'll soften up and you'll eventually reach a cord. From opengeometry at yahoo.ca Sun Jan 18 02:51:13 2004 From: opengeometry at yahoo.ca (William Park) Date: 18 Jan 2004 07:51:13 GMT Subject: Best way to do this? References: <100jg9er3qak890@corp.supernews.com> Message-ID: Wil Schultz wrote: > One of the exercises asks for a program to ask for a password three > times. Surprisingly this took me much longer that it probably should > have so I am curious if the following is the easiest way this is done. > Thanks much! > > ************************************************* > #!/usr/local/bin/python > > count = 0 > password = "null" > > while count < 3: > count = count + 1 > password = raw_input("what's the pass: ") > if password == "mypass": > print "Access Granted" > count = 3 > else: > if count < 3: > print "Try Again" > else: > print "Too Bad" > ************************************************* For crying out loud, here's 3 times for you... password = raw_input("what's the pass: ") password = raw_input("what's the pass: ") password = raw_input("what's the pass: ") -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From paul at prescod.net Thu Jan 29 11:31:12 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 29 Jan 2004 08:31:12 -0800 Subject: Get number of iteration In-Reply-To: References: Message-ID: <40193550.5000502@prescod.net> Diez B. Roggisch wrote: >>If I iterate through a list, is there a way I can get the number of the >>iteration: first, second, third, ... >> >>l = ["three", "four", "five", "six"] >>for x in l >> print x >> print x.iteration() # <- That's what I'm looking for! >> print "next" > ... > > So usually x won't have an iteration-method. But of course you can alwas do > this: > > for i in xrange(len(l)): > x = l[i] > print x > print i > print "next" In recent versions of Python there is an easier way: >>> for index, value in enumerate(["three", "four", "five", "six"]): ... print index, value ... 0 three 1 four 2 five 3 six Paul Prescod From nicolas.torzec at enssat.fr Wed Jan 28 09:46:10 2004 From: nicolas.torzec at enssat.fr (Torzec Nicolas) Date: Wed, 28 Jan 2004 15:46:10 +0100 Subject: strtotime? In-Reply-To: References: Message-ID: have a look at the parsedate() method in the RFC822 package. It may help you if your date is in "Internet format" "parsedate(StringDate) Attempts to parse a date according to the rules in RFC 2822. however, some mailers don't follow that format as specified, so parsedate() tries to guess correctly in such cases. date is a string containing an RFC 2822 date, such as 'Mon, 20 Nov 1995 19:12:08 -0500'. If it succeeds in parsing the date, parsedate() returns a 9-tuple that can be passed directly to time.mktime(); otherwise None will be returned. Note that fields 6, 7, and 8 of the result tuple are not usable." Leif K-Brooks wrote: > PHP has a very nice strtotime function (http://php.net/strtotime) which > converts a date/time in virtually any format into a timestamp. Does > Python have a similar function? > From pyxpcom at quixs.com Thu Jan 15 13:38:43 2004 From: pyxpcom at quixs.com (Lars Heuer) Date: Thu, 15 Jan 2004 19:38:43 +0100 Subject: needed PyXPCOM tutorial. In-Reply-To: <425cc8d1.0401150908.287de0d8@posting.google.com> References: <425cc8d1.0401150908.287de0d8@posting.google.com> Message-ID: <1689232226.20040115193843@quixs.com> Hello, > i m in need of a PyXPCOM tutorial. it should explain using python > (instead of JavaScript) for creating apps. if any body can point me to > some web resources or a printed book . I'm also interested, but my searches via Google etc. brings no specific pyXPCOM tutorial. It seems, that the pyXPCOM architecture isn't widely used; this mailinglist is also very silent. ;) The pyXPCOM Mozilla page is also dead or under construction: http://pyxpcom.mozdev.org/ If someone has a tutorial or something, please send a link to the mailinglist. :) Best regards, Lars From na Sat Jan 3 20:50:03 2004 From: na (Andrew) Date: Sat, 3 Jan 2004 17:50:03 -0800 Subject: mysql python Newbie Question Message-ID: Hi I would like to create a program that accesses mysql from a gui on my local computer "mysql is on a server" but I am fairly new to python and programming GUI's in general What I would like this program to do is be able to access my server and change update add and delete records from my databases without having to write sql. I can create the GUI fairly easily but I do not know how I or what functions and modules would be needed to do this or how to write them "Forgive me if I sound to Newb" If someone out there could help me out maybe offer advice or even better some code to build on that would be cool Thanks in advance Cheers Andrew From bik.mido at tiscalinet.it Mon Jan 26 14:45:19 2004 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Mon, 26 Jan 2004 20:45:19 +0100 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: On 24 Jan 2004 21:31:36 -0800, xah at xahlee.org (Xah Lee) wrote: >Just bumped into another irresponsibility in perl. [snip] >expletive Perl and Perl slinging morons. Taking into account the aggressive and trollish tone of your post I'm surprised by how polite the answers you got are. Nay, I found interesting the OT about OSes and file versions: a proof that a bad seed can give good fruits! I don't know why I'm taking care of answering you seriously, but if you don't like "Perl's nature", why are you bothering with it in the first place? If you can't stand its real/presumed *nix-isms, why are you using it? Also, you may have noticed it, but this is a discussion group about *Perl* and people here is highly likely to be fond of Perl, appreciate its "nature" and so on... so what did you expect to receive as an answer to your post? What do you gain in particular by criticizing an excellently and *clearly* written piece of documentation (of an useful package!), by exposing your failing to understand it because of your stupidity and ignorance about a basic concept of the language like "pattern"? >you'll see that it shouldn't be so. AND, the writting as usuall is >fantastic incompetent. To illustrate, i quote: Haha, thanks! I'll make that a .sig! Michele -- # This prints: Just another Perl hacker, seek DATA,15,0 and print q... ; __END__ From d.chirila at bucarest.finsiel.ro Fri Jan 23 03:30:46 2004 From: d.chirila at bucarest.finsiel.ro (Dragos Chirila) Date: Fri, 23 Jan 2004 10:30:46 +0200 Subject: private class members and hasattr Message-ID: <04ff01c3e18b$330d28b0$2f01a8c0@dchirila> Hi I have the following class: class PropTest: def __init__(self): self.prop1 = 1 self._prop2 = 2 self.__prop3 = 3 def testprops(self): print 'has prop1 %s' % hasattr(self, 'prop1') print 'has _prop2 %s' % hasattr(self, '_prop2') print 'has __prop3 %s' % hasattr(self, '__prop3') and the following test lines: a = PropTest() a.testprops() The output of this is: has prop1 1 has _prop2 1 has __prop3 0 Why hasattr method doesn't return 1(true) for private member '__prop3' ?? I tested it with Python 2.2.1 and 2.1.3 . Thanks Dragos From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 3 05:34:31 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 03 Jan 2004 11:34:31 +0100 Subject: End of file? References: <3ff665fb$1@clarion.carno.net.au> Message-ID: Steve: >I'm having trouble finding out if output from a pipe has finished (i.e. >I can't find tell if there's a EOF in output.readlines()). How do I do >this? Because readlines() can return empty lines and I can't simply >check if the line is empty. You don't get an EOF from readlines(). "readlines([sizehint]) Read until EOF using readline() and return a list containing the lines thus read." http://www.python.org/doc/current/lib/bltin-file-objects.html -- Ren? Pijlman From jacek.generowicz at cern.ch Tue Jan 6 08:43:11 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Jan 2004 14:43:11 +0100 Subject: Programming language from python References: Message-ID: "Alejandro Lombardo" writes: > Dear sirs: > I need to create a programming language. Can this be done with the > latest version of python? Is python the best computer programming > language development tool in the entire universe? If it isn?t could you > please tell me the name of the best computer programming language > development tool in the entire universe? Lisp. From jepler at unpythonic.net Sun Jan 4 20:28:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 4 Jan 2004 19:28:43 -0600 Subject: Python for Embedded Devices? In-Reply-To: <221e7b06.0401041537.2896b22d@posting.google.com> References: <221e7b06.0401041537.2896b22d@posting.google.com> Message-ID: <20040105012843.GC1075@unpythonic.net> On Sun, Jan 04, 2004 at 03:37:46PM -0800, Phil Schmidt wrote: > I am one such developer who works with very small systems: 8-bit > micros with under 128K flash and 4K RAM. [...] Luxury! My current interest runs to microcontrollers with 2k flash, 128 bytes sram, and 128 bytes eeprom. Yours sounds a lot like one of the larger models in the same line, though. (Atmel AVR) It's actually quite fun, and since 128 bytes is too little to use recursion or dynamic allocation for anything, stuff like reference counting and GC are unneeded---not a lot of strings, either. C is a not a bad language for this hardware. Jeff From corrada at dandenong.cs.umass.edu Fri Jan 2 10:55:01 2004 From: corrada at dandenong.cs.umass.edu (Andres Corrada-Emmanuel) Date: Fri, 2 Jan 2004 10:55:01 -0500 (EST) Subject: optparse bug? Message-ID: Hi, I'm getting a conflict between options defined between two different scripts and I'm wondering if it is a bug or the intended effect. script foo: script bar: from foo import some_function When I do ./bar --help I get foo's options! This is fixed by rewriting bar.py so the import from foo occurs after parsing bar's options: from optparse import OptionParser options, args = parser.parse_args() from foo import some_function This is mildly annoying behavior. Do I really have to reorder my import statements to avoid importing options from other scripts? Andres Corrada-Emmanuel Senior Research Fellow Center for Intelligent Information Retrieval University of Massachusetts, Amherst From webmaster at beyond-thoughts.com Thu Jan 8 18:22:43 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 09 Jan 2004 00:22:43 +0100 Subject: PRE-PEP: new Path class; mutability, __hash__, __eq__, __cmp__ In-Reply-To: References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <3FFDE643.7090404@beyond-thoughts.com> Gerrit Holl wrote: > Christoph Becker-Freyseng wrote: > >>Should Path be immutable like string? > > > I have though about this, too. It should certainly not be fully mutable, > because if a path changes, it changes. But maybe we could have a > .normalise_inplace() which mutates the Path? What consequences would > this have for hashability? > > I like paths to be hashable. so they probably should be immutable. > Yes. (already in the PEP) While paths aren't strings they have a lot in common because paths (as I now think of them) are not directly associated with files. (Paths can be nonexistent or even invalid) Moreover the basic operations like __eq__ shouldn't be reading methods ()! __hash__ has to be compatible with __eq__. hash(p1) == hash(p2) <<<=== p1 == p2 Also hash(p1) == hash(p2) ===>>> p1 == p2 should be true as far as possible. I think def __hash__(self): return hash(str(self.normalized())) would do this fine. So for __eq__ it follows naturaly def __eq__(self, other): FIXME: isinstance checking return (str(self.normalized()) == str(other.normalized())) It cares about nonexistent paths, too. (The samefile-solution won't --- we might code a special case for it ...) What about __cmp__? I've to admit that __cmp__ comparing the file-sizes is nice (__eq__= samefile is attractive, too --- they're both evil temptations :-) ) However __eq__ and __cmp__ returning possibly different results is odd. Finaly implementing __cmp__ that way would make it a reading method and is problematic for nonexistent paths. I'd like an implementation of __cmp__ which is more path specific than just string.__cmp__. But it should be consistent with __eq__. Could we do something about parent and sub dirs? Christoph Becker-Freyseng From francisgavila at yahoo.com Fri Jan 9 16:04:03 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 9 Jan 2004 16:04:03 -0500 Subject: Name of the function References: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> <9e5ea2c4.0401081103.6fa93bf9@posting.google.com> Message-ID: anton muhin wrote in message ... >Olaf Meding wrote: >> Is there a way to do this w/o importing another module? You could use sys instead, which is IIRC initialized at python start-up, even though the name isn't put in the namespace until 'import sys'. So strictly speaking, it's still importing, but there is no overhead. sys._getframe().f_code.co_name >> Yes this is what I was looking for except the code below requires >> importing module inspect. >I'm afraid that there is no way, at least none I'm aware of (except for >Terry Reed suggestion, but I think it's not what you are looking for). > >Why you don't want to import a module? I'll second that. I'll even ask why you want the original binding name of the function. (When functions are first-class, the "name of the function" becomes a bit meaningless.) What are you doing? We might be able to suggest something better. -- Francis Avila From miki.tebeka at zoran.com Wed Jan 28 02:48:14 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 27 Jan 2004 23:48:14 -0800 Subject: Easy way to make EXEs... References: Message-ID: <4f0a9fdb.0401272348.58eb7f62@posting.google.com> Hello Xero, > Okay, I am completely new to Python, and I really dont understand much, but > I was wondering how to make a python script/program into a standalone .EXE? > I dont understand py2exe at all, so if someone could tell me or find me an > easy (For a newbie) to convert Python scripts to EXEs, please let me know! Do try and read the FAQ. http://www.python.org/doc/faq/programming.html#how-can-i-create-a-stand-alone-binary-from-a-python-script HTH. Miki From jjl at pobox.com Tue Jan 27 07:13:50 2004 From: jjl at pobox.com (John J. Lee) Date: 27 Jan 2004 12:13:50 +0000 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> Message-ID: <87znc9mvwh.fsf@pobox.com> > Josiah Carlson wrote: [...] > > http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html [...] > I'm sorry, really, to bring this up, but as a Canadian I might be a little > thick on this point, so help me out: was that site hacked? Or is this for > real? I half expect him to be unmasked as Jim Carrey, and we're all in some cheesy Hollywood movie... Mind you, Peter: A proof is a proof. What kind of a proof? It's a proof. A proof is a proof. And when you have a good proof, it's because it's proven. -- Jean Chretien (some wag suggested this should be sung to the tune of "Mr. Ed" :-) John From ababo_2002 at hotmail.com Sun Jan 4 11:42:09 2004 From: ababo_2002 at hotmail.com (Daniel Pryde) Date: Sun, 04 Jan 2004 16:42:09 +0000 Subject: Array neighbourhoods Message-ID: Thanks a lot for the advice. I'll give it a try. :) Daniel >"Daniel Pryde" wrote in message >news:mailman.42.1072799018.8134.python-list at python.org... > > Hi again. > > > > One thing I forgot to include in my post the other day. I was wondering >if > > anyone knew of any fast algorithms for returning the surrounding >neighbours > > of an array element, or even the neighbours of a group of array >elements. > > >Try this (requires Python 2.3, since it uses sets). Can't say how fast it >is, but it handles all cases I can think of (edge effects, disjoint cells, >etc.). Maybe start with this to get going, then make it faster if it needs >to be. > > ># matrixNeighbors.py >from sets import Set > >def neighborhoodOf(cells, rows, cols): > ret = Set() > if type(cells) == tuple: > row,col = cells > for i in (-1,0,1): > for j in (-1,0,1): > ret.add( (row+i, col+j) ) > # remove original cell > ret.remove( cells ) > > elif type(cells) == list: > for cell in cells: > for neighbor in neighborhoodOf(cell,rows,cols): > ret.add(neighbor) > # remove original cells > ret -= Set( cells ) > > # remove all entries in ret with negative values, > # or values greater than number of cols/rows > for x,y in ret.copy(): > if x < 0 or y < 0 or x >= COLS or y >= ROWS: > ret.remove( (x,y) ) > > return list(ret) > ># define matrix boundaries >ROWS = 4 >COLS = 6 > >print neighborhoodOf( (0,0), ROWS, COLS ) >print neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS ) >print neighborhoodOf( (COLS,ROWS), ROWS, COLS ) >print neighborhoodOf( [(0,0),(0,1)], ROWS, COLS ) >print neighborhoodOf( neighborhoodOf( (1,1), ROWS, COLS), ROWS, COLS ) >print neighborhoodOf( neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS), ROWS, >COLS ) >print neighborhoodOf( neighborhoodOf( (COLS,ROWS), ROWS, COLS), ROWS, COLS >) > > > _________________________________________________________________ Tired of 56k? Get a FREE BT Broadband connection http://www.msn.co.uk/specials/btbroadband From jzgoda at gazeta.usun.pl Wed Jan 28 14:21:30 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 28 Jan 2004 19:21:30 +0000 (UTC) Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: Rune pisze: > It's important to notice here that I'm not interested if the user has > already pressed shift or ctrl. I'm only interested in knowing if he is > currently holding down one of these keys. (I have looked into msvcrt > and the like but have found no answer..) The function should also work > in both windows and Linux. This event *is* available in WinAPI, but don't ask me where. I'm sure, because VCL (which is built on top of WinAPI and uses standard Windows messages) distinguishes KeyUp and KeyDown events. If you want to have it available also in linux, use Qt/PyQt. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From donald.welch.nospam at hp.com Sat Jan 10 14:28:09 2004 From: donald.welch.nospam at hp.com (djw) Date: Sat, 10 Jan 2004 11:28:09 -0800 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> <40004743@usenet01.boi.hp.com> <40005064$0$1162$ba620e4c@news.skynet.be> Message-ID: <4000526e@usenet01.boi.hp.com> broebel wrote: > If you look at this as a homework or not is of no interest to me but I > like the way you explained which way to go to find the resolution. > thanks (i solved it in a jiffy now) > I think you missed my point (and Paul Rubin's). If this is indeed homework or a class assignment, you should not be asking people on this newsgroup to do the work for you. We are happy to give some small hints or some guidance as a teacher or instructor would. -d From skip at pobox.com Wed Jan 21 16:47:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 15:47:20 -0600 Subject: shelve slow in python 2.3.3 for windows In-Reply-To: References: Message-ID: <16398.62312.71037.418610@montanaro.dyndns.org> Marco> Try this program on Windows with python 2.3.3 and with python 2.2: Marco> import shelve Marco> a=shelve.open("a", "c") Marco> for x in xrange(10000): Marco> a[str(x)]=x Marco> print str(x) + "\r", Marco> a.close() Marco> After about 7000/8000 insertions, the program gets so slow... Marco> With python 2.2 it ends in a blink! Marco> Really strange, isn't it? Perhaps not. After running your script, what does whichdb.whichdb("a") report under both versions? My wild-ass guess is that the underlying anydbm module finds dumbdbm under 2.3.3 and something more industrial strength like bsddb under 2.2. Skip From newsgroups at jhrothjr.com Thu Jan 22 13:23:31 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 22 Jan 2004 13:23:31 -0500 Subject: I support PEP 326 References: Message-ID: <10105bn3bsi63c9@news.supernews.com> "Gary Robinson" wrote in message news:mailman.654.1074788734.12720.python-list at python.org... > I've recently had a couple of cases of needing exactly what it proposes, and > having to kluge around the fact that it's not there. It's a great idea. > > If there anywhere else I should be expressing my opinion on this, let me > know. Just in case anyone can't find the PEP - it's the one that proposes specific objects that will always sort highest and lowest. I'm mildly in favor; it seems to be useful for some cases, and it also seems easy enough to do. Of course, it would make None the second smallest object. John Roth > > --Gary > > -- From aaron at reportlab.com Sat Jan 17 10:50:09 2004 From: aaron at reportlab.com (Aaron Watters) Date: 17 Jan 2004 07:50:09 -0800 Subject: C# vs (stackless) python Re: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <877jzwg1v2.fsf@pobox.com> Message-ID: <9a6d7d9d.0401170750.65a3bf06@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<877jzwg1v2.fsf at pobox.com>... > "Bicho Verde" writes: > C#: Java for MS .NET users (to first order, anyway). .NET has broader > goals than Java for language interoperation, so even though Jim Hugunin > and others have done some initial work on a .NET implementation of > Python, dynamic languages like Python will likely never be full .NET > citizens (thanks to the design of the .NET CLR). If that full > citizenship is important to you, C# has that advantage, but I'm > reliably informed it's fairly well-described as "a Java clone" > (implying programmer-inefficiency), so I'd be inclined to look for a > better language with a good .NET implementation. Lisp? Smalltalk? > (there was talk of an excellent .NET smalltalk implementation, but I'm > not sure whether that was vapourware or not...) C# also fixes a lot of stupidities in java: for example a method can "return" more than one new value and there is a syntax for first class-ish callback methods (delegates) among the more prominent improvements. Also C# is far friendlier to "legacy" code (than java was originally intended to be). >From a pure code beauty point of view (or point of me/us :) ) Python is still easier to read thanks to things like slicing, list/dictionary displays, and keyword arguments but type safety is a really big win for larger projects, and of course C# is much faster. And once you get some feeling for the namespace hierarchy and the development environment I think it is a fairly productive work environment. Maybe more productive than python? There are some easily fixable problems/irritations -- like the way IO uses preallocated buffers in C++ style, which is irritating but easy to wrap away. To my taste I'd definitely prefer C# over lisp or smalltalk. There is the portability thing, of course. And python is free... OTOH *stackless* python has some *really* compelling advantages over C# -- like the ability to feasibly manage thousands of microthreads, which I wouldn't advise in C#, java, or "normal" python.... -- Aaron Watters === WIND THE FROG! From james at logicalprogression.net Mon Jan 19 11:29:27 2004 From: james at logicalprogression.net (James Henderson) Date: Mon, 19 Jan 2004 16:29:27 +0000 Subject: subclassing "file" In-Reply-To: References: Message-ID: <200401191629.27636.james@logicalprogression.net> On Monday 19 January 2004 4:14 pm, Uwe Mayer wrote: > Hi, > > when extending a build in class, what does the constructor __init__(...) > have to return? > and how does the constructor call its base-class construtor? (or is this > done automatically?) > > I want to derive from "file" to create a class that reads record from a > binary file: > > class myFile(file): > def __init__(self, filename, mode="r", bufsize=-1): > ....?... > > just calling the basename and the constructor does not work: > >>> f = myFile("testfile") > >>> f > > ', mode '' at ...> > > What am I missing? You don't show the second line of you __init__ method. It should be: file.__init__(self, filename, mode, bufsize) James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From jacek.generowicz at cern.ch Thu Jan 8 05:43:01 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Jan 2004 11:43:01 +0100 Subject: What psyco is goot at [Was: Rookie Speaks] References: <3FFC9855.3070901@lawson.com> <3FFC9A22.3020507@lawson.com> Message-ID: Samuel Walters writes: > If you'd like to see an example of both the psyco and profile modules in > action, let me know and I'll give you some more understandable code that I > once wrote to see what types of things psyco is good at optimizing. I think this is generally interesting, and would be curious to see it, if you'd care to share. From jjl at pobox.com Wed Jan 14 19:55:59 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 00:55:59 +0000 Subject: PyQT: qt.qApp References: Message-ID: <87r7y2rpwg.fsf@pobox.com> "Axel Mittendorf" writes: [...] > in my application I want to subclass qt.QApplication and > use this subclass instead of QApplication for my gui. Some > of my modules are automatically generated by pyuic and > I am not allowed to change their source code. The problem > is these modules do "from qt import *" and use an object > called 'qApp' which seems to be an instance of qt.QApplication IIRC, qApp is *the* QApplication (there's only one QApplication instance per application). > and I want them to use my subclass (exactly its instance) > instead of 'qApp'. How can I solve this? I have a vague recollection that you can't, due to an obscure limitation of either Qt or PyQt (or sip, maybe). That might have changed by now, though: ask on the PyKDE list. > Can someone tell me what qt.qApp is and what it is used for? > (I'm using PyQT 3.6.) See above. John From sross at connectmail.carleton.ca Sat Jan 3 14:05:09 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 14:05:09 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> Message-ID: Here's an interactive Python example to help clarify the previous response: >>> a = 5 >>> b = 10 >>> q , r = divmod(a,b) >>> q 0 >>> r 5 >>> a = -a >>> a -5 >>> q , r = divmod(a,b) >>> q -1 >>> r 5 >>> b*q + r # division algorithm -5 >>> -5 == a True >>> From fuf at mageo.cz Wed Jan 28 15:08:00 2004 From: fuf at mageo.cz (Michs Vitecek) Date: Wed, 28 Jan 2004 21:08 +0100 Subject: isinstance() bug Message-ID: On Wed, 28 Jan 2004 11:32:19 -0600 Skip Montanaro wrote: >You need to compare inode numbers to see if you have the same or different >files. > > >>> import stat > >>> os.stat(a.__file__)[stat.ST_INO] > 37041L > >>> os.stat(b.__file__)[stat.ST_INO] > 37041L > this could also be used to verify whether the imported module, class etc. comes from the same file without messing with the absolute path and problems related to it. really a good idea, Skip. -- fuf fuf at mageo.cz From __peter__ at web.de Tue Jan 6 15:44:27 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Jan 2004 21:44:27 +0100 Subject: Iterating over a binary file References: Message-ID: Derek wrote: > Pardon the newbie question, but how can I iterate over blocks of data > from a binary file (i.e., I can't just iterate over lines, because > there may be no end-of-line delimiters at all). Essentially I want to > to this: > > f = file(filename, 'rb') > data = f.read(1024) > while len(data) > 0: > someobj.update(data) > data = f.read(1024) > f.close() > > The above code works, but I don't like making two read() calls. Any > way to avoid it, or a more elegant syntax? Thanks. You can tuck away the ugliness in a generator: def blocks(infile, size=1024): while True: block = infile.read(size) if len(block) == 0: break yield block #use it: for data in blocks(f): someobj.update(data) Peter From peter at engcorp.com Tue Jan 13 10:57:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jan 2004 10:57:42 -0500 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> Message-ID: <40041576.D070723E@engcorp.com> Donn Cave wrote: > > Python has the advantage of a clean start, but > from a software engineering standpoint it really seems like a > hacker language. Ohh.... nice controversial statement. :-) I would strongly disagree with the above statement for a number of reasons, including (random thoughts): - packages - interactive interpreter - no static typing - high productivity - ease of testing - flexibility - extremely broad library support - low learning curve and probably a dozen others. I think this has all been discussed before, though, so I won't belabour the point. Basically, as a software engineer (nominally a "Systems Design Engineer") I find Python to be hands down *the* best language I've encountered for use in serious work. I can't actually think of another which excels on so many fronts. -Peter From fnord at u.washington.edu Fri Jan 2 14:14:25 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 2 Jan 2004 11:14:25 -0800 Subject: Abstract Syntax Tree conundrum Message-ID: Hello, It looks like the compiler and parser modules both implement Python ASTs. Is one of these preferred over the other, or do they play different roles? What I'm trying to do is this- (1) Inspect a block of python source (2) Execute selected statements from the source The compiler's AST implementation seems better for (1), but I can't for the life of me figure out how to compile it into a code object, and there's not even an apparent way to convert it back into source (I suppose I could write a function to do this, but it seems like there should be a better way). On the other hand, the parser's AST implementation can easily be executed, but for inspection it's not so good--- there's the extra hassle of translating all of the numeric symbols. Decompyle might be useful, but it's tricky to use third party modules at work... Any suggestions are heartily appreciated =) And Happy New Year. -ljp For reference, compiler AST: ------------- Module(None, Stmt([Function('function1', ['x', 'y', 'z'], [Const(3.0)], 0, None,Stmt([Return(Mul((Mul((Name('x'), Name('y'])), Function('sumall', ['args'], [], 4, None, Stmt([Return(CallFunc(Name('reduce'), [Lambda(['a', 'b'], [], 0, Add((Name('', Name('args')], None, None))]))])) parser.st AST of the same code: ------------------------------- [257, [264, [285, [259, [1, 'def'], [1, 'function1'], [260, [7, '('], [261,[262, [1, 'x']], [12, ','], [262, [1, 'y']], [12, 'z']], [22, '='], [292, [293, [294, [295, [297, [298, [299, [300, [301, [302, [303, [304, [305, [2, '3.0']]]]]]]]]]]]]]],':'], [291, [4, ''], [5, ''], [264, [265, [266, [272, [275, [1, 'return'], [313, [292, [293, [294, [295, [297, [298, [299, [ [303, [304, [305, [1, 'x']]]], [16, '*'], [303, [304, [305, [1, 'y']]]], [16, '*'], [303, [304, [305, [1, 'z']]]]]]]]]]]]]] [6, '']]]]], [264, [285, [259, [1, 'def'], [1, 'sumall'], [260, [7, '('], [261, [16, '*'], [1, 'args']], [8, ')']], [11, ':], [5, ''], [264, [265, [266, [272, [275, [1, 'return'], [313, [292, [293, [294, [295, [297, [298, [299, [300, [301, [302, [ [1, 'reduce']], [308, [7, '('], [317, [318, [292, [307, [1, 'lambda'], [261, [262, [1, 'a']], [12, ','], [262, [1, 'b']]], [293, [294, [295, [297, [298, [299, [300, [301, [302, [303, [304, [305, [1, 'a']]]]], [14, '+'], [302, [303, [304, [305, [1]]]]]], [12, ','], [318, [292, [293, [294, [295, [297, [298, [299, [300, [301, [302, [303, [304, [305, [1, 'args']]]]]]]]]]]]]]]]]]]]]]]]]]], [4, '']]], [6, '']]]]], [4, ''], [0, '']] From jmob at nospam__unm.edu Thu Jan 15 19:55:52 2004 From: jmob at nospam__unm.edu (Jason Mobarak) Date: Thu, 15 Jan 2004 17:55:52 -0700 Subject: Redefining __call__ in an instance In-Reply-To: <73b00f0c.0401151529.676347b6@posting.google.com> References: <73b00f0c.0401151529.676347b6@posting.google.com> Message-ID: def firstFunc (s, word='up'): print "foo" class callNoWork(object): def __new__ (cls): cls.__call__ = firstFunc return object.__new__(cls) callNoWork()() # Dunno if you've read this, but it explains this: # http://python.org/2.2.1/descrintro.html Robert Ferrell wrote: > I have a question about assigning __call__ to an instance to make that > instance callable. I know there has been quite a bit of discussion > about this, and I've read all I can find, but I'm still confused. > > I'd like to have a factory class that takes a string argument and returns > the appropriate factory method based on that string. I'd like the > instances to be callable. Like this: > > fact = Factory('SomeThing') > aSomeThing = fact(some args) > > anotherFact = Factory('SomeThingElse') > anotherThing = anotherFact(some other args) > > The way I thought to do this was to assign the __call__ attribute of > the fact instance to the appropriate factory method in __init__. That does not > work, as many others have pointed out. I know there are workarounds. > The appended code shows the variants I know of. I can use one of > them, but they are not quite what I am looking for. > > Have I missed the key message that explains how to make new-style > classes callable, with the called method unique to each instance? > > thanks, > -robert > > """Test use of __call__ in a (new style) class. > The classes below show various ways of making instances > of a class callable. The goal is to make an instance callable, > with the called method defined distincly for each instance. > """ > > > def firstFunc(word = 'up'): > """This is the method to call, when an instance is invoked.""" > print "This is firstFunc, word %s." % word > return > > class callWorks(object): > """This works, since the called method is defined in the class.""" > def __init__(self): > pass > def __call__(self, word = 'up'): > print 'This is inside callWorks, word %s.' % word > return > > class callNoWork(object): > """This doesn't work, since __call__ is defined for the method, > not the class.""" > def __init__(self): > # This does not make an instance of callNoWork callable > self.__call__ = firstFunc > > class callWorksNoFun(object): > """This works, but since the class's method is being called, the > default arguments are defined by the class, and do not > properly reflect the default arguments of the method that > wants to be called.""" > def __init__(self): > self._callFunc = firstFunc > def __call__(self, word = None): > # Although an instance of callWorksNoFun is callable, > # the default arguments are wrong > self._callFunc(word) > return > > class addCallAttribute(object): > """Add the attribute 'callMe', which is the callable function. > This works fine, but requires the user to invoke this as > instance.callMe(), rather than just instance().""" > def __init__(self): > self.callMe = firstFunc > > # Simplest thing > cw = callWorks() > cw() > > # Natural thing to try, but doesn't work > cnw = callNoWork() > # The instance, cnw, is not callable. > try: > cnw() > except Exception, exception: > print 'Call did not work, gave exception: %s.' % exception > > # Works, but actually invoking class method, not instance's method > cwNF = callWorksNoFun() > # The instance cwNF is callable, but the default value for the callable is wrong. > # This works fine > cwNF('No up') > # This should default to print 'Up', but instead it defaults to None. > cwNF() > > # Fine, but requires user to invoke instance.callMe(), rather than just instance(). > aCA = addCallAttribute() > # To call the instance, use the callMe attribute. That respects defaults fine. > aCA.callMe() -- (------------------------------( )~~~~~ Jason A. Mobarak ~~~~~~~) (~~ aether_at_gentoo_dot_org ~~( )~~~~ jmob_at_unm_dot_edu ~~~~~) (------------------------------( From Mike at DeleteThis.Geary.com Wed Jan 7 04:01:46 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 7 Jan 2004 01:01:46 -0800 Subject: Syntax highlighting in .NET IDE References: <4iPKb.764$K_3.702@newssvr29.news.prodigy.com> Message-ID: Moosebumps wrote: > Is there a way to have the .NET IDE do syntax highlighting for > python? I haven't looked into it that much, but perhaps there > is some config file one can download. > > Don't ask why, I know there are better editors, but I have > special circumstances. : ) Visual Python integrates full Python support into VS.NET. It's not cheap but it's very good: http://www.activestate.com/Products/Visual_Python/ There is also Komodo, which runs separately from VS.NET but feels so much like VS.NET that it's hard to tell the difference: http://www.activestate.com/Products/Komodo/?_x=1 -Mike From moskow23 at yahoo.com Sun Jan 18 14:16:31 2004 From: moskow23 at yahoo.com (Dan) Date: 18 Jan 2004 11:16:31 -0800 Subject: Determining a replacement dictionary from scratch Message-ID: <4b805376.0401181116.3b0adb41@posting.google.com> Hello, I'd like to be able to take a formatted string and determine the replacement dictionary necessary to do string interpolation with it. For example: >>> str = 'his name was %(name)s and i saw him %(years)s ago.' >>> createdict( str ) {'name':'', 'years':''} >>> Notice how it would automatically fill in default values based on type. I figure since python does this automatically maybe there is a clever way to solve the problem. Otherwise I will just have to parse the string myself. Any clever solutions to this? Thanks -dan From jcb at iteris.com Sat Jan 3 17:06:58 2004 From: jcb at iteris.com (MetalOne) Date: 3 Jan 2004 14:06:58 -0800 Subject: NEWBIE: map | zip | list comp References: Message-ID: <92c59a2c.0401031406.3bd93364@posting.google.com> The following produces the same result but in a 2 dimensional list. However, it is darn near impossible to read. print map(lambda x: map(lambda (c1,c2): map(lambda ix: (c1*length)[:ix]+c2+(c1*length)[ix:-1], range(length)), filter(lambda (c,d): c!=d, map(lambda y: (x,y), base_seq))), base_seq) for base_seq = "ABCD" The (x,y) pairs produced are (A,A), (A,B), (A,C), (A,D), (B,A), (B,B), (B,C), (B,D), ... The filter removes the duplicate pairs (A,A),(B,B),(C,C),(D,D) for (c1,c2) in [(A,B), (A,C), (A,D)] the rotation function gets applied. From p.magwene at snet.net Thu Jan 22 07:48:27 2004 From: p.magwene at snet.net (netnews.upenn.edu) Date: Thu, 22 Jan 2004 07:48:27 -0500 Subject: prog/lib to draw graphs In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hello, > I'm looking for a program or python library to draw graphs. > They should look like the that: > > > /--------\ /--------\ > | Node A | ------ belongs to ----> | Node B | > \--------/ \--------/ > > Which is a result of the function call like that: > > connectNodes(firstNode, secondNode, description, lineStyle) > connectNodes("Node A", "Node B", "belongs to", dashed) > > It should have a open scalable vector format as output (DVI, SVG, PDF, ...) > and should be able to make automatic optimal placement of the items. > Do you know something like that? > Thx, > Florian Try graphviz: http://www.research.att.com/sw/tools/graphviz/ I think there's a python interface to graphviz floating around (Google it), but it's trivial to write a Python routine that spits out valid Graphviz "dot" files. In the case of your example, the contents of the dot file would be something like: digraph G{ "Node A" -> "Node B" [label="belongs to"]; } --Paul From amk at amk.ca Sat Jan 31 22:46:59 2004 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 31 Jan 2004 21:46:59 -0600 Subject: OT: why do web BBS's and blogs get so slow? References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: On 31 Jan 2004 14:56:15 -0800, Paul Rubin <> wrote: > an ISP on a fast computer with plenty of net bandwidth. I'm wondering > what those programs are doing, that makes them bog down so badly. > Anyone know what the main bottlenecks are? I'm just imagining them > doing a bunch of really dumb things. Oh, interesting! I'm sporadically working on a Slashdot clone, so this sort of thing is a concern. As a result I've poked around in the Slashdot SQL schema and page design a bit. Skipping ahead: > Am I being naive and/or > missing something important? Slashdot itself uses a tremendous amount > of hardware by comparison. Additional points I can think of: * Some of that slowness may be latency on the client side, not the server. A heavily table-based layout may require that the client get most or all of the HTML before rendering it. Slashdot's HTML is a nightmare of tables; some weblogs have CSS-based designs that are much lighter-weight. * To build the top page, Slashdot requires a lot of SQL queries. There's the list of stories itself, but there are also lists of subsections (Apache, Apple, ...), lists of stories in some subsections (YRO, Book reviews, older stories), icons for the recent stories, etc. All of these may need an SQL query, or at least a lookup in some kind of cache. It also displays counts of posts to each story (206 of 319 comments), but I don't think it's doing queries for these numbers; instead there are extra columns in various SQL tables that cache this information and get updated somewhere else. * I suspect the complicated moderation features chew up a lot of time. You take +1 or -1 votes from people, and then have to look up information about the person, and then look at how people assess this person's moderation... It's not doing this on every hit, though, but this feature probably has *some* cost. * There are lots of anti-abuse features, because Slashdot takes a lot of punishment from bozos. Perhaps the daily traffic is 10,000 that get displayed plus another 10,000 messages that need to be filtered out but consume database space nonetheless. * Slashcode actually implements a pretty generic web application system that runs various templates and stitches together the output. A Slashcode "theme" consists of the templates, DB queries, and cron jobs that make up a site; you could write a Slashcode theme that was amazon.com or any other web application, in theory. However, only one theme has ever been written, AFAICT: the one used to run Slashdot. (Some people have taken this theme and tweaked it in small stylistic ways, but that's a matter of editing this one theme, not creating a whole new one.) This adds an extra level of interpretation because the site is running these templates all the time. > 3) The message store would be two files, one for metadata and one for > message text. Both of these would be mmap'd into memory. There would > be a fixed length of metadata for each message, so getting the > metadata for message #N would be a single array lookup. The metadata I like this approach, though I think you'd need more files of metadata, e.g. the discussion of story #X starts with message #Y. (Note that this is basically how Metakit works: it mmaps a region of memory and copies data around, provided a table-like API and letting you add and remove columns easily. It might be easier to use Metakit than to reinvent a similar system from scratch. Anyone know if this is also how SQLite works?) Maybe threading would be a problem with fixed-length metadata records. It would be fixed-length if you store a pointer in each message to its parent, but to display a message thread you really want to chase pointers in the opposite directory, from message to children. But a message can have an arbitrary number of children, so you can't store such pointers and have fixed-length records any more. In my project discussions haven't been implemented yet, so I have no figures to present. --amk From paul at pfdubois.com Mon Jan 19 23:59:10 2004 From: paul at pfdubois.com (Paul Dubois) Date: Mon, 19 Jan 2004 20:59:10 -0800 Subject: [Numpy-discussion] Status of Numeric In-Reply-To: References: Message-ID: <400CB59E.3050307@pfdubois.com> Having two array classes around is a terrible idea. Once you have two popular array classes the entire world bifurcates. This plot package accepts those and that FFT accepts these, ad nauseum. I only suggested we do numarray because Numeric was, by general agreement, unmaintainable. It was hard to work on and lacked the kind of robustness necessary to get permission to put it in the core. We all agreed Numeric would cease. Let's stick to the plan. If there is enough spare energy in the system for SciPy to be talking about doing a NEW array class, surely there is enough energy to make a real try at getting everyone over to numarray and having it suffice. This means the whole community has to contribute, not just sit back and ask for things. This is OPEN source, right? I apologize for my lack of participation lately but I'm on a project that doesn't use Numeric and is several people short. And one of the people had a short person. I'll be at PyCon, BTW. From try_vanevery_at_mycompanyname at yahoo.com Tue Jan 13 21:38:51 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 18:38:51 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> Message-ID: "G.I.L" wrote in message news:40047290$1 at news.012.net.il... > > Brandon, why the fuck on Earth couldn't you spend that exact amount of time > doing what you did BEFORE posting and arguing with the entire newsgroup? Hey GIL, you're here wasting time of your own free will. Don't look to me to be the purveyor of your quality discourse. To me this is just hours between implementing stuff. Although actually, there's another agenda. I know *someone* out there is going through the same shit I have / I am. The posts are for their benefit, to give them warnings / inklings. > It > was an unbelievable waste of time, since you've managed to convice (maybe > still wrongfully) all the people that you are completely clueless. Why, because I turned around a project in 3 weeks while having the flu half the time? I laugh, over and over again, at all the people who declare 3D spherical icosahedral planetary display engines to be trivial, or VS .NET 2003 ports of Freeciv to be trivial, or any other project I've sunk blood into and run into difficulties. I know better. It's water off my back because I know what an armchair peanut gallery sounds like. You try to do something big, you put your money on the line to do it, you fail or don't entirely succeed, you give postmortem, you lay all your cards out for others to examine... *then* I will worry about your opinion. > I see your point in many of the issues you raised. But the only reason I > don't compare myself to you, is that I have a shitload of games to prove my > point. I've never had a major failure, so I never needed to use one to > leverage my projects. All the things I learned from, were simply bad habits, > mostly coding habits. I constantly evolve, in small steps, from one success > to another. That's how it should be. You do the math. Those who never taste failure are haughty. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "The pioneer is the one with the arrows in his back." - anonymous entrepreneur From ods at strana.ru Fri Jan 23 05:43:14 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 23 Jan 2004 13:43:14 +0300 (MSK) Subject: [ANN] ip2cc 0.2 released Message-ID: ip2cc: Lookup country country by IP address =========================================== WHAT IS IT If you want to gather web statistics by countries (not by top-level domains) or implement targeting, here is solution: ip2cc. This module allows to resolve country from IP address. USAGE ip2cc.py -update - build/update database ip2cc.py
- print country name for which
is registered For example: $ ./ip2cc.py python.org python.org (194.109.137.226) is located in NETHERLANDS $ ./ip2cc.py google.com.ru google.com.ru (216.239.33.100) is located in UNITED STATES Module can be used as CGI. WHERE TO GET Homepage: http://ppa.sf.net/#ip2cc Download: http://prdownloads.sf.net/ppa/ip2cc-0.2.tar.gz?download LICENSE Python-style ACKNOWLEDGEMENTS Jason R. Mastaler Fredrik Lundh CHANGES 0.2 - Adopted to new format of registrars. - Added LACNIC to sources. - Fixed contry code map and added -check option to simplify maintainance. 0.1 Initial release -- Denis S. Otkidach http://www.python.ru/ [ru] From http Sat Jan 10 13:39:08 2004 From: http (Paul Rubin) Date: 10 Jan 2004 10:39:08 -0800 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> Message-ID: <7xfzen3ayb.fsf@ruckus.brouhaha.com> That sounds like a homework problem, so rather than write the code for you, here's a hint -- use another variable, and update it every time you decide how many coins of any specific size you'll use. From http Mon Jan 12 04:49:51 2004 From: http (Paul Rubin) Date: 12 Jan 2004 01:49:51 -0800 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Message-ID: <7xbrp9h4xs.fsf@ruckus.brouhaha.com> Robin Becker writes: > 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. > >>> from __future__ import division > >>> eval('1/2') > 0.5 > >>> > > so I guess pythonwin is broken in this respect. Huh? you get the expected result with both python and pythonwin. Neither one is broken. The surprising result is from input(), not eval(): $ 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. >>> from __future__ import division >>> print input('expression: ') expression: 1/2 0 >>> print eval('1/2') 0.5 >>> That's because input evaluates its string in the context of a different module which was compiled with old-style division. I don't know of other functions that use eval like that, and input() should be deprecated or eliminated anyway, so this isn't a big deal. From peter at engcorp.com Mon Jan 19 09:38:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 09:38:01 -0500 Subject: Python Text Adventure Authoring System References: Message-ID: <400BEBC9.8549D0DD@engcorp.com> Jp Calderone wrote: > > There are a few modules in Twisted's CVS repository that are handy in this > area (as a few people are aware, Twisted is actually a support framework for > multiplayer interactive fiction or text adventure games). Just to clarify, though I know Jp knows this very well :-), Twisted is *much more* than just a support framework for multiplayer interactive fiction, although it had its origins in that area and is still being developed for it. -Peter From lubowiecka at go2.pl Wed Jan 7 07:17:54 2004 From: lubowiecka at go2.pl (Sylwia) Date: 7 Jan 2004 04:17:54 -0800 Subject: 'Interrupted function call' in time.sleep(1000) after relogging Message-ID: Hi! I have implemented a Python services. It behaves as a supervisor for log files. If the space used by log files is bigger than a given upper limit, then it starts to delete log files until the space is less than a given lower limit. It checks the space every 1000 secs. After that it falls asleep. It is configured to start up automatically on system boot. Everything works ok except one thing ... :( The service should run even when I log off, so I made an experiment. It turned out that after relogging (I have to press Ctrl+Ald+Del) the following exception was raised: The instance's SvcRun() method failed File "C:\Python23\lib\site-packages\win32\lib\win32serviceutil.py", line 663, in SvcRun self.SvcDoRun() File "C:\SEE\modules\adminapps\purgeLogFilesService.py", line 158, in SvcDoRun time.sleep(1000) exceptions.IOError: (4, 'Interrupted function call') Here is the part of my code (inside SvcDoRun) that generates the error: #check if the service is going to be stopped timeout=5 waitHandles = self.hWaitStop, stp = win32event.WaitForMultipleObjects(waitHandles, 0, timeout) if stp == win32event.WAIT_OBJECT_0: #print "Received Quit from Win32" break else: time.sleep(1000) # <--- Exception generated here!!! How can I solve it? Maybe I should try to patch a new timemodule.c file? I have no idea :( I would be greatful for any hints. I use Windows XP operating system. Best wishes, Sylwia From nuffsaid at phreaker.net Sat Jan 31 16:50:52 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 31 Jan 2004 22:50:52 +0100 Subject: Running External Programs from Within Python References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: On Sat, 31 Jan 2004 11:23:42 -0800, Bob=Moore wrote: > > Can I run (call? exec? eval?) an external program from inside a Python > program? > Check out os.popen (in all it's variants); e.g. something like the following will do what you want: import os stdin, stdout, stderr = os.popen3('your program goes here') output = stdout.read() errors = stderr.read() stdin.close(); stdout.close(); stderr.close() ... do something with 'output' and 'errors' ... HTH / Nuff From wweston at att.net Fri Jan 30 09:28:17 2004 From: wweston at att.net (wes weston) Date: Fri, 30 Jan 2004 14:28:17 GMT Subject: conditional expression sought In-Reply-To: <6PjSb.138487$6y6.2697536@bgtnsc05-news.ops.worldnet.att.net> References: <6PjSb.138487$6y6.2697536@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <5StSb.35726$6O4.994965@bgtnsc04-news.ops.worldnet.att.net> oops; The code: A.append(bool(randint(0,1))) will always yield an A of [true,true,true] WRONG; was thinking it was a rand float;. Thanks for replying to all who tried to help. wes wes weston wrote: > Elaine, > The last code line: > > print "I would have liked this to be B[2] = ",B[2] > > prints the value of B[2]; the value you don't want. > I think what you meant was that you want B[2] to be > 0.0 not false. bool(0.0) does equal false. > --------------------------------------------------- > The code: > > A.append(bool(randint(0,1))) > > will always yield an A of [true,true,true] > --------------------------------------------------- > I didn't know this about python, and I'm not sure I > like it: > > wes at linux:~/amy> python > > >>> print 1.1 and 2.2 > 2.2 > >>> print 2.2 and 1.1 > 1.1 > >>> print (1.1 and 2.2) > 2.2 > > The order is important. To me, it should be printing true > and not either number or the last number. > From claird at lairds.com Sat Jan 3 13:01:10 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Jan 2004 18:01:10 -0000 Subject: Python for Embedded Devices? References: <425cc8d1.0401030826.59a9d4ca@posting.google.com> Message-ID: In article <425cc8d1.0401030826.59a9d4ca at posting.google.com>, mir nazim wrote: . . . >It should possible to create complete J2EE like platform for python >for creating complex applications. [ i m no expert. lokking for a >simple discussion.] This thread interests me, if only because you and the original poster have such different perspectives from mine. I'm confi- dent that Python can support something like J2EE in a technical sense, and also that J2EE is an important part of Java--but is it a *good* part? I'm sincerely unconvinced that there's much there Python *should* emulate (apart from what Python already has). J2EE's certainly a marketing success; I don't know what it teaches us about how to rationalize application development, though. I'm even more certain that there's no model in prospect for organizing the current Python development team to create such a framework. Briefly, I see J2EE, like .NET, as aimed at the commodification of application development. It's aimed at "Enterprise" teams of mediocre, alienated coders. I have no enthusiasm for Python competing with that approach. -- Cameron Laird Business: http://www.Phaseit.net From james.kew at btinternet.com Fri Jan 30 16:38:25 2004 From: james.kew at btinternet.com (James Kew) Date: Fri, 30 Jan 2004 21:38:25 -0000 Subject: Confused about a list.sort() References: Message-ID: "wes weston" wrote in message news:xsQRb.28535$6O4.748063 at bgtnsc04-news.ops.worldnet.att.net... > Switch from windoze to linux and provide screen dumps. > > wes at linux:~> python > Python 2.3.3c1 (#3, Dec 26 2003, 16:36:50) Ah, that's nice: a simple question about list.sort()'s behaviour answered with a dose of Linux advocacy. Everyone else managed to answer the question at hand. FWIW, Python works very nicely at the Windows command-line too, "screen dumps" and all: C:\>python ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> although I have to admit I usually prefer PythonWin's interactive window. ISTR discussion on python-dev about adding a sorted() method to list, returning a sorted copy of the list -- did that ever reach a conclusion? James From even at pondie.com Wed Jan 14 20:50:04 2004 From: even at pondie.com (Ben Floyd) Date: 14 Jan 2004 17:50:04 -0800 Subject: baffling os.system behavior - differs from command line Message-ID: <604fc0ca.0401141750.4dc57782@posting.google.com> It goes like this: Im converting a perl script that executes a command on each result of a directory listing. In perl, all is well. In Python, using approximately the same logic creates a seemingly random problem I can't pin down. I hesitated to ask this question since it's so Slackware Linux-centric, and im new to Python. It's hard to ask in a generic way, but im out of options... The command is Slackware's package creation utility, makepkg. It uses the current working directory as package source and takes a filename as an argument to output the newly created package to. Makepkg is essentially a tarball creator, wrapped in a nice command. Simple stuff. Here is my code: I have a for loop that reads a file list, like so: pkg_srcdir = '/packages_source' pkg_dir = '/packages_tgzs' ls = os.listdir(pkg_srcdir) for name in ls: build_src = pkg_srcdir + '/' + name new_filename = pkg_dir + '/' + name + '.tgz' # Valid directory? if not os.path.isdir(build_src): sys.exit("\nInvalid directory \'" + pkg_srcdir + "\'\n") # Go into the new directory try: os.chdir(build_src) except os.error, value: sys.exit("\nInvalid directory: \'" + build_src + "\': " + value[1]) # I then execute the command on each result, like so: # new_filename is correctly assembled, which i can verify # from printing it out on each loop iteration os.system('/sbin/makepkg --chown n --linkadd y ' + new_filename) When all is done running, which take a good 7 minutes, I get varied results. It looks like its working... pauses, has lots of disk activity on the drive (verified with ps and vmstat), but in the end only a couple of packages are created. I can actually watch the output of makepkg and see it creating the tarballs. Here is the truly whacky part: Changing pkg_dir to anything else, say /tmp/beavis, will create the packages correctly for a while, then mysteriously stop with no warning or change to the script - just run it a few times and it stops working. Im running as root, so its not a permission problem - its far to erratic anyway. I dont think this problem has anything to do with os.system, per say, since it also happens with os.popen. I thought it might be a buffering problem, so i tried using Python's -u switch and flushing stdout with sys.stdout.flush() - no go. I tried sleeping for long periods of time in each loop iteration - no go. I tried writing each individual makepkg command out to a file and running it with perl, doing all the proper filehandling. I also tried bash for kicks - no go In the end, I put an ampersand at the end of the makepkg command, like so: os.system('/sbin/makepkg --chown n --linkadd y ' + new_filename + ' &') This sort of works: it creates 95% of the packages most of the time - results varies. It always seems to leave out the same packages. The packages it misses are in the middle of the list, so its not just skipping the first or the last few. Im baffled. Any ideas? From fuf at mageo.cz Wed Jan 28 08:22:25 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 14:22:25 +0100 Subject: isinstance() bug Message-ID: <20040128132225.GA10842@foof.i3.cz> hello, please consider the following situation: under the current directory there's a subdirectory 'package' with two files: __init__.py and module.py ./package: __init__.py module.py module.py contains: class A(object): pass aModule = A() now, let's do: current directory: >>> import package.module >>> type(package.module.aModule) >>> isinstance(package.module.aModule, package.module.A) # so far good 1 >>> a = package.module.A() >>> isinstance(a, package.module.A) # so far good >>> import sys >>> sys.path.append('package') >>> import module >>> a = module.A() >>> isinstance(a, package.module.A) # will return 0 !!! 0 >>> isinstance(package.module.aModule, module.A) # will return 0 !!! 0 >>> how is it possible that it IS important how you imported a class definition for isinstance() to work? it's insane! -- fuf (fuf at mageo.cz) From nospam at nowhere.hu Sat Jan 31 15:06:22 2004 From: nospam at nowhere.hu (Miklós) Date: Sat, 31 Jan 2004 21:06:22 +0100 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: Software patents are evil. Hell to them. Mikl?s "Stan Schwartz" wrote in message news:2da21d6c.0401310807.671be3b7 at posting.google.com... > My name is Stan Schwartz, and I'm a University of Pennsylvania > Ph.D. and an independent inventor. I'm submitting two computer > graphics patents to the USPTO during the next several weeks. From deets_noospaam at web.de Wed Jan 28 12:25:54 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 28 Jan 2004 18:25:54 +0100 Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Message-ID: Diez B. Roggisch wrote: > Hi, > >> is there something like "JpGraph" for python ? >> For those who don't know this PHP library: It is a high level >> drawing library that generates gif files with all kind of charts. > > there has been a thread about this lately: Many people (including me) use > graphviz for that. As long as you don't need interactivity, it does a > really great job. Oops - got confused by the name JpGraph - AFAIK charts aren't the subject of graphviz.... Diez From jensthiede at webgear.co.za Fri Jan 9 14:07:58 2004 From: jensthiede at webgear.co.za (Jens Thiede) Date: 9 Jan 2004 11:07:58 -0800 Subject: Variable Scope Message-ID: In the following terminal; could someone inform me as to why it is posible to print a global variable without having to declare it using global. This has affected some source of mine, and allows you to modify a global in a local scope *without* the global keyword, for instance, you can append to a global list, but *not* assign it a new value, for then, you create a new local variable. -- Why. Python 2.3.2 (#1, Jan 3 2004, 23:02:08) [GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r3, propolice)] on linux2 IDLE 1.0 >>> x = 10; >>> def test(): x += 1; >>> test(); Traceback (most recent call last): File "", line 1, in -toplevel- test(); File "", line 2, in test x += 1; UnboundLocalError: local variable 'x' referenced before assignment >>> def test2(): print x; >>> test2(); 10 Any help would be appreciated, Jens Thiede. From peter at engcorp.com Mon Jan 12 09:13:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 09:13:54 -0500 Subject: QOTW? References: Message-ID: <4002ABA2.D756F129@engcorp.com> Ganesan R wrote: > > >>>>> "Samuel" == Samuel Walters writes: > > > I/O is one of our strengths, because we understand that most programs are > > not algorithmically bound, but rather I/O bound. I/O is a big > > bottle-neck, so we should be damn good at it. The fastest assembly > > program won't do much good if it's always waiting on the disk-drive. > > Actually, Python is much slower than Perl for I/O. See the thread titled > "Python IO Performance?" in groups.google.com for a thread started by me on > this topic. I am a full time C programmer but do write occasional > Python/Perl for professional/personal use. > > To answer the original question about how much percentage of time I spend > optimizing my Python programs - probably never. However I did switch back to > using Perl for my most of my text processing needs. For one program that was > intended to lookup patterns in a gzipped word list, performance of the > original python version was horribly slow. Instead of rewriting it in Perl, > I simply opened a pipe to zgrep and did post processing in python. This > turned out to be much faster - I don't remember how much faster, but I > remember waiting for the output from the pure python version while the > python+zgrep hybrid results were almost instantaneous. I didn't consider this sort of thing in my poll, but I'd have to say you actually *are* optimizing your Python programs, even if you did it by falling back on another language... -Peter From ramen at lackingtalent.com Fri Jan 9 01:15:52 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 09 Jan 2004 06:15:52 -0000 Subject: Python and Jython are kinda different Message-ID: Hey good people, I've been doing a lot of simultaneous Jython and CPython programming lately, and just wanted to say, with no intended ill will toward any of the individuals who have been generous enough to make the two languages possible, that, well, they're kinda different. I guess it was inevitable, but with Jython stuck at Python 2.1, it's not really the same language as CPython is today. You still have to type "from __future__ import nested_scopes", and there are no generators or properties, and the type/class dichotomy is still in that awkward state, and you have to inherit from UserList/Dict, and there are no sets, and you have to roll your own enumerate() and dict(), and files don't close themselves automatically (yeah, I know, dream on, hehe...), no csv module, no importing from zips... wow... it's amazing where CPython has come in such a short time. Well, anyway. I've never tried the 2.2a0 version (of Jython), mostly because the message on the site about it being somewhere between 2.1 and 2.3 left me a bit uncomfortable. ;) Jython is still a dream to program in compared to Java. So I can't complain. But it's frozen in a particular state, while CPython is continuing to aggressivly pursue new ground--like lazy iteration--in ways that change the Python style; ways that leave me re-implenting not-so-cool versions of the new style for Jython. In a sense, it's made me really think hard about what new Python features are really useful, and what are merely new. I definitely like having the enumerate() function around. And dict(), how could you live without a complement to dict.items? That should have been in Python -1.0. =) Is there anyone here that works on Jython? Do you need help? What kind of help do you need? What's your estimation of the amount of work needed? Is the work done with PyPy helpful? I'm really curious. One Love. One Python. That sounds dirty. Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From klapotec at chello.at Fri Jan 30 13:12:34 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 30 Jan 2004 18:12:34 GMT Subject: PEP 327: Decimal Data Type References: <6ltk10h30riel0lghd18t5unjco2g26spi@4ax.com> Message-ID: <6i7l109qaq1lbv5da6sckp904tq56mmr32@4ax.com> On Fri, 30 Jan 2004 16:03:55 +0000, Stephen Horne wrote: [snip] > >That said, there are cases where a decimal type would be genuinely >useful. Given that, my only comment on the PEP is that a decimal >literal might be a good idea - identical to float literals but with a >'D' appended, for instance. Or, maybe if money is being represented, appending a '$'? *ducks* Just-couldn't-resist-ly yours, -- Christopher From hopper at omnifarious.org Sun Jan 11 04:06:45 2004 From: hopper at omnifarious.org (Eric Mathew Hopper) Date: Sun, 11 Jan 2004 01:06:45 -0800 Subject: pydoc patch for Subversion Message-ID: <20040111090645.GA2398@omnifarious.org> I have a patch that allows pydoc to deal with Subversion (http://www.subversion.tigris.org) style version strings. Subversion does not do '$Revsion: num$' style tags. The closest it will get is '$Rev: num$'. So, I included a check for that type as well. It's a patch to this version of pydoc.py __version__ = "$Revision: 1.86.8.1 $" Thanks, -- "It does me no injury for my neighbor to say there are twenty gods or no God. It neither picks my pocket nor breaks my leg." --- Thomas Jefferson "Go to Heaven for the climate, Hell for the company." -- Mark Twain -- Eric Hopper (hopper at omnifarious.org http://www.omnifarious.org/~hopper) -- -------cut--------- --- /sw/lib/python2.3/pydoc.py Sat Jan 3 15:43:56 2004 +++ pydoc2.3.py Sun Jan 11 00:56:39 2004 @@ -528,8 +528,11 @@ info = [] if hasattr(object, '__version__'): version = str(object.__version__) - if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) + if (version[0] == '$') and (version[-1] == '$'): + if version[1:11] == 'Revision: ': + version = strip(version[11:-1]) + elif version[1:6] == 'Rev: ': + version = strip(version[6:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) @@ -1004,8 +1007,11 @@ if hasattr(object, '__version__'): version = str(object.__version__) - if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': - version = strip(version[11:-1]) + if (version[0] == '$') and (version[-1] == '$'): + if version[1:11] == 'Revision: ': + version = strip(version[11:-1]) + elif version[1:6] == 'Rev: ': + version = strip(version[6:-1]) result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) -------cut--------- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dkuhlman at rexx.com Sat Jan 10 19:30:55 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 10 Jan 2004 16:30:55 -0800 Subject: What is best for web application development?? References: Message-ID: ketulp_baroda wrote: > i am developing a web application and i am really confused on what > should i use. > should i use just python and use the cgi module availabe. > Or should i use application like WebWare.Also there is PSP > available. I am really confused and need help There are a number of Python web frameworks, for example, Quixote, which is well supported, Zope, which is huge, and Twisted, which is ingenious, cutting edge, and avant-garde. See the following for more information: http://www.python.org/sigs/web-sig/ And, the following provides information that will enable you to compare your options: http://www.python.org/cgi-bin/moinmoin/WebProgramming You may also want to join the web-sig email list and ask your question there. But, no matter what you do, the answer is: It depends. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From jcarlson at nospam.uci.edu Mon Jan 26 15:27:57 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 12:27:57 -0800 Subject: Unique ID for CD or DVD In-Reply-To: References: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: Hoang wrote: > thanks everyone for your suggestions. I have decided to use MD5 since it is > included as a module with Python. Finding a unique string from the CD won't > be that hard and makes the approach more straight forward than any other > method. Using MD5 makes it less proprietary than it needs to be. > > Hoang Do > http://jotsite.com Using md5 on what? The track lengths, filenames, raw data on the disk? - Josiah From tim.golden at viacom-outdoor.co.uk Tue Jan 27 03:46:22 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 27 Jan 2004 08:46:22 -0000 Subject: Py2exe and WMI module Message-ID: >From: Thomas Heller [mailto:theller at python.net] > > >Tim Golden writes: > >>>From: nekiv at start.no [mailto:nekiv at start.no] >>> >>>I'm having a problem when I try to make a standalone >installation of a >>>Python program using Tim Goldens WMI-module. The py2exe produce the >>>exe-file as expected, but it fails to execute. >> >> [... snip my long-winded explanation of generating typelib params ...] >> > >I think the 'official' way is to run makepy with the '-i' flag, then it >prints out this: > >c:\>\python23\lib\site-packages\win32com\client\makepy.py -i >Microsoft WMI Scripting V1.2 Library > {565783C6-CB41-11D1-8B02-00600806D9B6}, lcid=0, major=1, minor=2 > >>> # Use these commands in Python code to auto generate .py support > >>> from win32com.client import gencache > >>> >gencache.EnsureModule('{565783C6-CB41-11D1-8B02-00600806D9B6}', > 0, 1, 2) Ah. I knew there had to be some other way of doing it. While I'm on the subject, is there anything I can offer to do within the wmi module itself which will make it easier to py2exe it? It doesn't look like it, but I thought I'd make the offer. 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 gerrit at nl.linux.org Sat Jan 3 08:09:48 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 3 Jan 2004 14:09:48 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: <20040103130948.GA30485@nl.linux.org> Martin v. Loewis wrote: > Gerrit Holl wrote: > >Any comments? > > It should be possible to implement that type without modifying > Python proper. It should indeed. But it isn't what I had in mind, and it's not exactly the same as a filename type in the language: for example, the name attribute of a file will still be a string, just as the contents of os.listdir, glob.glob, etc. (it seems glob follows listdir). > It might make a good recipe for the cookbook. If the type would be created without changing python proper, the type would probably just call os.path.foo for the filename.foo method. It would be the other way around if the type would become part of the language: os.path would only be there for backward compatibility, like string. But in order for os.listdir (and probably more functions) to return Path objects rather than strings, a C implementation would be preferable (necessary?). On the other hand, would this type ever be added, a python implementation would of course be a must. > Any volunteers? I may have a look at it. When thinking about it, a lot more issues than raised in my first post need to be resolved, like what to do when the intializer is empty... curdir? root? I guess there would a base class with all os-independent stuff, or stuff that can be coded independently, e.g: class Path(str): def split(self): return self.rsplit(self.sep, 1) def splitext(self): return self.rsplit(self.extsep, 1) def basename(self): return self.split()[1] def dirname(self): return self.split()[0] def getsize(self): return os.stat(self).st_size def getmtime(self): return os.stat(self).st_mtime def getatime(self): return os.stat(self).st_atime def getctime(self): return os.stat(self).st_ctime where the subclasses define, sep, extsep, etc. yours, Gerrit. -- 168. If a man wish to put his son out of his house, and declare before the judge: "I want to put my son out," then the judge shall examine into his reasons. If the son be guilty of no great fault, for which he can be rightfully put out, the father shall not put him out. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jjl at pobox.com Tue Jan 13 13:46:13 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 18:46:13 +0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> Message-ID: <87smijit56.fsf@pobox.com> Donn Cave writes: [...] > code that all these teams is writing will eventually come > together and work like it's supposed to, and from that > point of view it's tempting to look for some support for > architectural consistency, like "interfaces" and that sort > of thing. Not sure about "that sort of thing" , but more explicit interfaces do seem like a real issue here. It's interesting to note that Zope, a notable large Python project, has moved (and is moving) in this direction. John From Mike at DeleteThis.Geary.com Thu Jan 15 03:15:48 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 15 Jan 2004 00:15:48 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: <100cj1ke8h4b781@corp.supernews.com> Brandon J. Van Every wrote: > Is there something fundamentally *wrong* with recognizing how > useless people are to your purposes? It gives people the impression that you have a bad attitude, that you want something from them and don't want to give anything in return. As a result, people will not want to help you achieve your purposes. Is it wrong? That's for you to decide. It's certainly self-defeating. -Mike From miki.tebeka at zoran.com Thu Jan 8 07:57:57 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 8 Jan 2004 04:57:57 -0800 Subject: Chaning self? Message-ID: <4f0a9fdb.0401080457.3d60adb5@posting.google.com> Hello, I'm trying to create a class which is a bit array. I've done the following: class bitarray(long): def __init__(self, value): super(long, self).__init__(value) def __getitem__(self, index): if self & (1 << index): return 1 else: return 0 def __setitem__(self, index, value): if value not in (0, 1): raise ValueError("must be 0 or 1") if value: self |= (1 << index) else: self &= (~ (1 << index)) However the __setitem__ does not work: >>> b = bitarray(5) >>> b[0] 1 >>> b[1] 0 >>> b[2] 1 >>> b[0] = 0 >>> b 5L >>> b[0] 1 What am I missing? Thanks. Miki From cawilcoxREMOVE at NO_SPAMcharter.net Wed Jan 14 00:19:01 2004 From: cawilcoxREMOVE at NO_SPAMcharter.net (cadprogrammer) Date: Tue, 13 Jan 2004 23:19:01 -0600 Subject: Python implementation of XForms viewer Message-ID: <1009ka5kh8i3efa@corp.supernews.com> Anyone working on, or know of a Python implementation of an XForms viewer? All I've found so far are mostly written in Java... Christian From mcfletch at rogers.com Fri Jan 30 03:49:48 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 30 Jan 2004 03:49:48 -0500 Subject: newbie py2exe difficulty In-Reply-To: References: Message-ID: <401A1AAC.6050709@rogers.com> Open a command-prompt window. (You'll find the command-prompt's icon in Start|Programs or Start|Programs|Accessories, it may be called "MSDOS Prompt".) Switch to the directory where your setup.py file is (use the shell's cd command to move between directories, you can use the "dir" command to see what files are in the current directory to confirm that the setup.py file is present), P:\>cd OpenGLContext P:\OpenGLContext>dir setup.py Volume in drive P is DATASTORE Volume Serial Number is 74A4-1C80 Directory of P:\OpenGLContext 27/01/2004 06:01p 3,853 setup.py 1 File(s) 3,853 bytes 0 Dir(s) 11,575,771,136 bytes free *then* run: python setup.py py2exe --help from that command prompt. You may need to specify the full path to python if you haven't added your python installation directory to the path, something like: P:\OpenGLContext>c:\bin\lang\py23\python.exe setup.py build running build running build_py running build_ext depending on where you installed python. HTH, and good luck, Mike Elaine Jackson wrote: >Hi. I'm trying to use py2exe (http://starship.python.net/crew/theller/py2exe/) >in Windows 98. I copied the necessary files into my Python23 directory (where I > > ... >My problem is that, when I attempt to follow the first instruction (details >follow), it opens a DOS window that may indeed display all available >command-line flags to the py2exe command, but isn't very helpful because it >immediately disappears. (In fact I'm really not sure what a command-line flag >is, or what I'm supposed to do with it.) I've also tried simply running >setup.py: the DOS window disappeared immediately and there was no 'dist' >directory in evidence. > > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From gerrit at nl.linux.org Sat Jan 17 14:46:59 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 17 Jan 2004 20:46:59 +0100 Subject: yield In-Reply-To: <20040117181510.GA21559@mrna.tn.nic.in> References: <20040117170808.GA21486@mrna.tn.nic.in> <20040117165920.GA31881@nl.linux.org> <20040117181510.GA21559@mrna.tn.nic.in> Message-ID: <20040117194659.GA9147@nl.linux.org> Hi km, km wrote: > Hi gerrit, > > i ran the snippet but i am sorry, i couldnt get what u were saying. > kindly enlighten, If a function reads a 'return' statement, it is finished. It returns the value, and never reaches the part after the 'return' statement. If a generator reaches a 'yield' statement, it returns the result of the expression behind the 'yield' statement. When you call a function which returns values not with 'return' but with 'yield', it returns a generator. When you call the 'next' method of the generator, the body is executed, until it reaches a 'yield' statement. When you call the body again, it is executed again, until it reaches a 'yield' statement again, etc, until it does not reach any 'yield' statement again, and then it raises StopIteration. This way, you can for example implement something which returns the Fibonacci series: >>> def f(): ... a, b = 0, 1 ... while True: ... a, b = b, a+b ... yield a You can now define a generator by calling f(): >>> g = f() >>> g.next() 1 >>> g.next() 1 >>> g.next() 2 >>> g.next() 3 >>> g.next() 5 >>> g.next() 8 >>> g.next() 13 ...etc. It would be difficult to do this with a function. You could use a global variable, or create a class with some methods, but the first way is ugly and the second way is really a different way to create a generator (I think it's called an 'explicit generator' whereas a function with a yield statement is an 'implicit generator' - I'm not sure, maybe someone can clarify?). An 'iterator' is anything you can put 'for' in front of. You could do 'for i in g:' here, but it would be an endless loop, so we'll break out of it: >>> for i in g: ... print i, ... if i > 100: ... break 21 34 55 89 144 It started at 21 because that's where we stopped with our last .next() method. Generators are documented at different places in the documentation. The tutorial: http://www.python.org/doc/current/tut/node11.html What's new: http://www.python.org/doc/2.3.3/whatsnew/section-generators.html PEP 255: http://www.python.org/peps/pep-0255.html There is also information in the Language Reference, but this is probably not very useful. yours, Gerrit. -- 40. He may sell field, garden, and house to a merchant (royal agents) or to any other public official, the buyer holding field, house, and garden for its usufruct. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From nospam at nopes Sat Jan 3 01:50:04 2004 From: nospam at nopes (Steve) Date: Sat, 03 Jan 2004 17:50:04 +1100 Subject: End of file? Message-ID: <3ff665fb$1@clarion.carno.net.au> Hi, I'm having trouble finding out if output from a pipe has finished (i.e. I can't find tell if there's a EOF in output.readlines()). How do I do this? Because readlines() can return empty lines and I can't simply check if the line is empty. Please somebody help me! Thanks. Steve From premshree_python at yahoo.co.in Tue Jan 13 15:07:04 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 13 Jan 2004 20:07:04 +0000 (GMT) Subject: Automating the Creation of Python Executables Message-ID: <20040113200704.46040.qmail@web8309.mail.in.yahoo.com> Here's a Windows Batch file that helps creating Python executables for simple programs (using py2exe) just a tad: http://www.premshree.resource-locator.com/j/post.php?id=152 ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From a.schmolck at gmx.net Tue Jan 6 23:23:02 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 07 Jan 2004 04:23:02 +0000 Subject: selecting a random item from a set References: Message-ID: [sorry for the late reply the server here had been down a couple of days and then I was busy] "Tim Peters" writes: > [Tim, asks which algorithms require random selection, as opposed > to arbitrary selection, from a set] > > [Alexander Schmolck] > > Feature selection schemes, for example? > > Eh? That's like "numerical methods" . IOW, too vague. Well, pretty much any scheme where the feature space is to large to explore exhaustively, IOW from forward-backward feature selection to markov chain monte carlo. If that's still to vague, I'd be happy to provide more detail. > You can do it in O(1) space now at essentially full C speed via, e.g., > > i = random.randrange(len(some_set)) > random_elt = itertools.islice(some_set, i, None).next() > some_set.remove(random_elt) > > That tricks it into finding the starting point with a C loop, and then the > iterator is discarded after extracting its first element. Yes, this is a much better (more readable and efficient) > But (of course) that still takes average time proportional to the # of > elements in the set. Well, that wishes away a detail: this can actually be > arbitrarily expensive, as there's no bound on how sparse a Python dict can > get, and the C dict iteration code has to visit every slot, occupied or not, > to find "the next" occupied slot. Sure. > If the sets are small, you're not going to beat random.choice(tuple(s)). Yep, I had a vague feeling this might be the case and because it's also simple and clear, so that's in fact what I used (almost -- I did list(s), which ought to be only marginally slower I would think). > If the sets are large, low-level optimization of an approach with the wrong > O() behavior is just a monumentally bad idea. Unlikely, for the current application they should be < 100 elements. So I guess I shall stick to the tuple-cast for the time being. Thanks -- this has been quite informative (and the other suggestions you made might still come in handy at some point). 'as From jjl at pobox.com Wed Jan 14 20:48:17 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 01:48:17 +0000 Subject: wxPython worries References: <9d1c4d6d.0401141221.22c587f5@posting.google.com> Message-ID: <87eku2rnha.fsf@pobox.com> James Goldwater writes: > It's not the RADdish-ness (is that a word?) - drag'n'drop, property > assignment etc - that concerns me, it's the ease of gui building - by > hand is fine (oh how I've come to 'love' Java's layout managers...) I'll make my usual comment, which is that nobody has yet contradicted me (unusual on USENET ;-) that Qt is the most well-designed Python GUI framework. (Qt Designer is very good, too.) And, strangely, the PyQt commercial license is far cheaper than (C++) Qt. $400 for former (Blackadder, from theKompany.com), $2500-odd for the latter! (before somebody asks: no, you *don't* need both licenses -- only the cheap one from theKompany, who have an agreement with trolltech) I believe Blackadder comes with Python-specific docs for PyQt, but they're actually completely redundant, IMHO -- it's trivial to translate the C++ docs to Python code, using the list of exceptions distributed with PyQt. Another BTW: their FAQ page still says Blackadder is in beta, but I think somebody here mentioned the final version was actually released some while back (PyQt itself has been stable for years, of course). > Custom controls is the biggie then. I think I'll have a punt at [...] PyQt is certainly good at this. John From jcarlson at nospam.uci.edu Fri Jan 23 15:21:59 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 12:21:59 -0800 Subject: when x process isn't running... do something In-Reply-To: References: Message-ID: Bart Nessux wrote: > Bart Nessux wrote: > >> Howdy, >> >> I'm trying to time how long it takes dd to run on a G5, versus how >> long it takes to run on a G4 (PATA vs. SATA). Both sytems have Mac OS >> X 10.3.2 and Python 2.3. Could someone demonstrate how I might use >> Python to monitor for the presense of a process and to do something >> (in this case send an email which I know how to do) as soon as that >> process is no longer present? Any suggestions on how to monitor? Call >> top every 5 secs and read it's output searching for 'dd'??? >> >> TIA, >> Bart >> > > I forgot to mention the fact that I already know when the process began. > All I need to know is when it ends and then I can calculate the part in > between those two points. > Why not just: import time import os start = time.time() s = os.system('dd ') print time.time()-start - Josiah From gamasutra1000 at yahoo.com Thu Jan 1 20:31:49 2004 From: gamasutra1000 at yahoo.com (Julia Osip) Date: 1 Jan 2004 17:31:49 -0800 Subject: newbie question References: <4ebabbc5.0312311614.2446e31c@posting.google.com> Message-ID: <4ebabbc5.0401011731.6f33a396@posting.google.com> Didnt realise I was posting into an existing topic. Whitespace was the problem, its working now. Will consider the mailing list in the future. Thanks very much for your help! Sean 'Shaleh' Perry wrote in message news:... > On Wednesday 31 December 2003 16:14, Julia Osip wrote: > > Hi, just started fiddling around with python, having some difficulty > > getting the following small play program to execute. Furious > > searching in the docs, manual, newsgroup did not avail me, does anyone > > have any ideas what might be the problem? Some sort of whitespace > > issue (im still unsure of whitespace rules)? I'm running Mac OS > > 10.2.8, with MacPython 2.3. > > > > you might consider joining the tutor at python.org mailing list. It is meant to > help people new to python. > > > Thanks for any help you can give... > > > > the code > > ...snip... > > > > the error > > ...snip... > > File "", line 7 > > def __init__(self): > > ^ > > SyntaxError: invalid syntax > > ...snip... > > As you guessed it is a whitespace problem. So, let's clear up the whitespace > rules for you. > > There is one key rule -- be consistent. Python does not really care if you > use 4 space indents or 8. It does care if you try to use both. Same goes > for mixing spaces and tabs. As Python reads your code it figures out what > your indent style is and then enforces that for the rest of the block. > > When Python read your class definition the first indentation it found was for > the docstring which was 4 spaces. Then it went to the next line of code and > found an indentation of 8. This is what caused the error. Now, maybe this > is because you hand indented the docstring by four spaces and then used a tab > on the line starting with 'def'. Or maybe you thought you needed to indent > again (you don't). From mcherm at mcherm.com Thu Jan 15 11:52:14 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 15 Jan 2004 08:52:14 -0800 Subject: Does anyone else not find the fun in programming...? Message-ID: <1074185534.4006c53ea395f@mcherm.com> Chris Lyon writes: > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, > I have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along > canals is fun, Arguing about quite how useless the British Government > is fun but programming ? > > Do I need help ? Well, I can only speak for myself, but *I* _DO_ find programming fun. When I was in college, I used to practically disapear every once in a while for nearly a week at a time while working furiously on a program. These days, when I get a free weekend (which is somewhere between hardly ever and never), I will sometimes spend it writing a program for something like a game I was inspired to create. The fact that in my day job they pay me to do programming is just, well, great! Of course, I don't enjoy every moment. Right now I really need to spend the rest of the day writing up release notes and deployment plans for the latest version of our software, and that's not my favorite part of the job. But I couldn't take the same kind of pride in my work if I didn't see to it that even our release notes are of the same high quality as our code. Perhaps I'm just VERY fortunate... but then before I worked as a programmer, I used to be a teacher, and I ALSO enjoyed doing that job. My recomendation is to try to find a job which you really enjoy doing. After all, why waste such a large portion of your life on something that isn't rewarding? Sure, you still need to eat, but (at least in the USA where I live) it doesn't take NEARLY as much money to live on as most people seem to think, and there are many different ways of earning a living. -- Michael Chermside From kkzuberi at yahoo.com Tue Jan 13 11:00:55 2004 From: kkzuberi at yahoo.com (Khalid Zuberi) Date: Tue, 13 Jan 2004 11:00:55 -0500 Subject: Accessing "GIS (ESRI shape file)" files from Python ? In-Reply-To: <282f826a.0401130315.5b92b2aa@posting.google.com> References: <282f826a.0401121907.498543e6@posting.google.com> <282f826a.0401130315.5b92b2aa@posting.google.com> Message-ID: Richard Shea wrote: > That's great - thanks very much just downloading Thuban now. > > thanks again. > > richard shea. And if that doesn't work out, you might also try: http://openev.sourceforge.net/ which appears to have ESRI Shapefile support, and to be scriptable in python. - Khalid From beliavsky at aol.com Fri Jan 16 08:36:07 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 16 Jan 2004 05:36:07 -0800 Subject: do loop Message-ID: <3064b51d.0401160536.5d80fa97@posting.google.com> In a Python 'for' loop, one can change the value of looping variable, so that for i in range(3): i = i*5 print i is legal code In Fortran 90 and 95, the analogous code do i=0,2 i = i*5 print*,i end do is illegal, because variable 'i' cannot be changed inside the loop. The constraint of not allowing the loop variable to change within the body of the loop can prevent errors in logic when the body of the loop is large. Is there a way to write a loop in Python that enforces this constraint? Should such functionality be added to the language? From Markus.Franke at informatik.tu-chemnitz.de Fri Jan 2 10:56:56 2004 From: Markus.Franke at informatik.tu-chemnitz.de (Markus Franke) Date: Fri, 2 Jan 2004 15:56:56 +0000 (UTC) Subject: Python and Tk: Error on Memory Access References: Message-ID: Hi, In article , Martin v. Loewis wrote: > > On Redhat 9, you should either use the packages that the > system vendor provides, or you should compile Python yourself. > Installing a foreignly-built Python is likely to give problems > with Tk. I have already installed the packages for Red Hat 9, but the Error still comes. Could this be perhaps a problem of my Developer-Kernel. Greets Markus Franke From http Sun Jan 11 21:15:39 2004 From: http (Paul Rubin) Date: 11 Jan 2004 18:15:39 -0800 Subject: Division oddity References: Message-ID: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Tim Rowe writes: > If I do from __future__ import division then eval(1/2) gives me 0.5 as > expected. But if I do print input("enter a sum: ") and enter 1/2 as > the sum I get 0 as if I hadn't done the import. I thought input was > supposed to give the same behaviour as an eval on raw input -- why the > difference here? The input function is calling eval from the context of the module where 'input' itself is defined. If you use "from __future__ import division" in module A and have "print 3/2" in module B, the value of 3/2 in module B shouldn't be affected by the input, since module B may depend on integer division having the old behavior. The result is a little bit surprising at first glance though, so it should probably be documented. From newsgroups at jhrothjr.com Sat Jan 3 19:44:42 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 19:44:42 -0500 Subject: Creating a capabilities-based restricted execution system References: <9Jecnc6TZdy4lGqiXTWc-w@speakeasy.net> Message-ID: "Aahz" wrote in message news:bt7lbp$ovg$1 at panix2.panix.com... > In article , > John Roth wrote: > >"Sean R. Lynch" wrote in message > >news:9Jecnc6TZdy4lGqiXTWc-w at speakeasy.net... > >> John Roth wrote: > >>> > >>> Yes, you're missing something really obvious. Multi-level security > >>> is a real difficult problem if you want to solve it in a believable > >>> (that is, bullet-proof) fashion. The only way I know of solving it > >>> is to provide separate execution environments for the different > >>> privilege domains. In the current Python structure, that means > >>> different interpreters so that the object structures don't intermix. > >> > >> Hmmm, can you give me an example of a Python application that works > >> this way? Zope seems to be doing fine using RestrictedPython. > >> RestrictedPython is, in fact, an attempt to provide different > >> execution environments within the same memory space, which is the > >> whole point of my exercise. Now, I know that the lack of an example > >> of insecurity is not proof of security, but can you think of a way to > >> escape from RestrictedPython's environment? DoS is still possible, > >> but as I'm not planning on using this for completely untrusted users, > >> I'm not too concerned about that. > > > >Restricted Python was withdrawn because of a number of holes, of which > >new style classes were the last straw. > > RestrictedPython was *not* withdrawn; rexec was withdrawn. This is a > difficult enough issue to discuss without confusing different modules. See > http://dev.zope.org/Wikis/DevSite/Projects/SupportPython21/RestrictedPython I'm not sure what you're trying to say. The Zope page you reference says that they were (prior to 2.1) doing things like modifying generated byte code and reworking the AST. That's fun stuff I'm sure, but it doesn't have anything to do with "Restricted Execution" as defined in the Python Library Reference, Chapter 17, which covers Restricted Execution, RExec and Bastion (which was also withdrawn.) If I confused you with a subtle nomenclature difference, sorry. I don't care what Zope is doing or not doing, except for the fact that it seems to come up in this discussion. I'm only concerned with what Python is (or is not) doing. The approach in the Wiki page you pointed to does, however, seem to be a substantially more bullet-proof approach than Python's Restricted Execution. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Weinberg's Second Law: If builders built buildings the way programmers wrote > programs, then the first woodpecker that came along would destroy civilization. From mwh at python.net Thu Jan 22 05:17:45 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 22 Jan 2004 10:17:45 GMT Subject: SystemError while execing bad code References: Message-ID: Skip Montanaro writes: > Gerrit> exec CodeType(0,0,0,0,"",(),(),(),"","",0,"") > ... > Gerrit> But I guess this is a case of "so don't do it" :-)? > > Michael> Definitely. It's easy enought to crash the interpreter this > Michael> way (think LOAD_CONST 30000, for just one easy way). > > In fact, help(types.CodeType) describes it thusly: > > Create a code object. Not for the faint of heart. > > Should this sort of stuff be published on the Wiki? I don't understand what you're suggesting here. Cheers, mwh -- Python enjoys making tradeoffs that drive *someone* crazy . -- Tim Peters, comp.lang.python From mwh at python.net Thu Jan 15 07:26:39 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 15 Jan 2004 12:26:39 GMT Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: miki.tebeka at zoran.com (Miki Tebeka) writes: > Hello All, > > On a different thread Skip wrote: > > Yes, you're right. Starting at 2**1000 I found three safe primes quite > > quickly. Using my version I gave up waiting after seeing one safe prime > > float by. > > Which made me think why Python don't use gmp as it's primary math > package - we'll get fast results, a lot of number types and much more. > > Can't think of any reason why Python is implementing its own long > numbers... > Can you enlighten me? Licensing? IIRC, GMP is GPL. Also, possibly, portability. Cheers, mwh -- 34. The string is a stark data structure and everywhere it is passed there is much duplication of process. It is a perfect vehicle for hiding information. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From rmkrauter at yahoo.com Mon Jan 26 20:11:39 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon, 26 Jan 2004 20:11:39 -0500 Subject: efficient updating of nested dictionaries In-Reply-To: References: Message-ID: <1075165899.15570.60.camel@vaio> >> String concatenation is not that lame, but I'd use tuples: >> MY_DICT[(KEY_X, KEY_Y, KEY_Z)] = FOO >> Tuples save on string operations. What a nice way to simplify this common task. That's great. Thanks for the advice. Rich -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcfletch at rogers.com Sat Jan 3 17:23:41 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 03 Jan 2004 17:23:41 -0500 Subject: Filename type (Was: Re: finding file size) In-Reply-To: <20040103165041.GA31412@nl.linux.org> References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <20040103165041.GA31412@nl.linux.org> Message-ID: <3FF740ED.9020909@rogers.com> Gerrit Holl wrote: >Peter Otten wrote: > > >>http://mail.python.org/pipermail/python-list/2002-June/108425.html >> >>http://members.rogers.com/mcfletch/programming/filepath.py >> >>has an implementation of your proposal by Mike C. Fletcher. I think both >>filename class and os.path functions can peacefully coexist. >> >> > >Thanks for the links. >(I think they don't, by the way) > > You hawks, always seeing war where we see peace :) ;) . Seriously, though, a path type would eventually have ~ the same relation as the str type now does to the string module. Initial implementations of a path type are going to use the os.path stuff, but to avoid code duplication, the os.path module would eventually become a set of trivial wrappers that dispatch on their first argument's method(s) (after coercian to path type). Is that peaceful? I don't know. If there's a war, let's be honest, os.path is going to take a good long while to defeat because it's there and embedded directly into thousands upon thousands of scripts and applications. We can fight a decent campaign, making a common module, then getting it blessed into a standard module, encouraging newbies to shun the dark old os.path way, encouraging maintainers to use the new module throughout their code-base, etceteras, but os.path is going to survive a good long while, and I'd imagine that being friendly toward it would keep a few of our comrades off the floor. Just as a note, however, we haven't had a *huge* outpouring of glee for the current spike-tests/implementations. So it may be that we need to get our own little army in shape before attacking the citadel :) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mark at mceahern.com Tue Jan 20 20:33:51 2004 From: mark at mceahern.com (Mark McEahern) Date: Tue, 20 Jan 2004 19:33:51 -0600 Subject: regular expression question In-Reply-To: References: Message-ID: <1074648830.5354.81.camel@dev.internal> On Tue, 2004-01-20 at 18:38, Steve Lamb wrote: > Ok, this just seems convluted. > > import re > line = 'match this' > foo = re.search(r'.*(this)', line) > foo.groups()[0] > > To me there seems there should be a way to return a group without having > to get the tuple and then slice it out from there. However foo.group(0) will > return the entire string (only one argument given) and groups doesn't seem to > do anything significant with any entry I give it. Am I missing something > obvious or is this the final solution? Have you bothered to read the docs on Match objects? import re line = 'match this' match = re.search(r'.*(this)', line) print match.group(1) // m From axel.mittendorf at transfertech.de Thu Jan 15 10:03:21 2004 From: axel.mittendorf at transfertech.de (Axel Mittendorf) Date: Thu, 15 Jan 2004 16:03:21 +0100 Subject: QT usage confusion References: <40069912$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: <4006ABB9.D25CBB35@transfertech.de> "Guyon Mor?e" wrote: [snip] > I have read multiple docs about it and searched this newsgroup I came to the > conclusion that, as I am a windows user, I have only 2 options: > > - buy a commercial qt license > - try it out for 30 days (!) you can get qt working with cygwin (since KDE works on windows this way), but I got no information about pyqt. HTH, Axel From aahz at pythoncraft.com Wed Jan 14 11:38:47 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Jan 2004 11:38:47 -0500 Subject: Multiple interpreters in a single process References: Message-ID: In article , Maciej Sobczak wrote: > >I'm interested in embedding the Python interpreter in a C++ application. >What I miss is the possibility to create many different interpreters, so >that the stuff that is running in one interpreter does not influence the >other. In essence, the interpreter can be used in different modules of a >single application. It would be nice to isolate them. Unfortunately, it's not really possible to do that. The problem is that Python is designed to interface to C libraries, many of which use global static variables. So Python doesn't really try to allow isolated Python instances. Your best bet if you need true isolation is to run multiple processes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From emile at fenx.com Sat Jan 3 14:14:19 2004 From: emile at fenx.com (Emile van Sebille) Date: Sat, 3 Jan 2004 11:14:19 -0800 Subject: Newbie question about memory management References: Message-ID: Oh Kyu Yoon: > I am writing my first python program, and I have to deal with several lists > of double precision numbers that are about 10,000,000 in length. > If I have 5 such lists, 5 x 10,000,000 x 8bytes ~ 400 MB which is too much > for the computer memory. > Does anyone have better strategies to do this? How about numeric with Kragen Sitaker's memory mapped files. http://www.pfdubois.com/numpy/ http://pobox.com/~kragen/sw/arrayfrombuffer/ HTH, Emile van Sebille emile at fenx.com From francisgavila at yahoo.com Sun Jan 11 14:17:47 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 11 Jan 2004 14:17:47 -0500 Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: <10038cpbu23hv93@corp.supernews.com> Jens Thiede wrote in message ... >OK, thanks for sorting that out, but what do I replace in the >following to avoid referancing: > >x = [[0]*5]*5 >x is [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] > >and after > >x[0][0] = 1; >x is [[1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0]] Ah, the joy of list comprehensions! >>> x = [ [ 0 for i in range(5)] for j in range(5)] >>> x [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> x[0][0] = 1 >>> x [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> There are other ways, but using list comprehensions is the usual idiom now. -- Francis Avila From d.chirila at finsiel.ro Fri Jan 30 11:18:57 2004 From: d.chirila at finsiel.ro (Dragos Chirila) Date: Fri, 30 Jan 2004 18:18:57 +0200 Subject: NEWLINE character problem References: Message-ID: <013601c3e74c$c34bc780$2f01a8c0@dchirila> Thanks a LOT !! I will give it a try and see how it works... the problem is that I have realy big strings (more than 50000 characters) Dragos ----- Original Message ----- From: "Tim Peters" To: Sent: Friday, January 30, 2004 5:49 PM Subject: RE: NEWLINE character problem > [Nuff, replying to someone who has strings with various line-end > conventions] > > > Say your string is s; then you could use the following > > function (untested!) to make sure that s uses \n only: > > > > def fix_lineendings(txt): > > if txt.count('\r\n'): # MS DOS > > txt = txt.replace('\r\n', '\n') > > elif txt.count('\r'): # Mac > > txt = txt.replace('\r', '\n') > > > > return txt > > > > Simply write: s = fix_lineendings(s) > > That's in the right direction. There's no need to count the *number* of > each kind of oddball, and .count() does all the work that .replace() does > anyway if there aren't any oddballs. So the one-liner: > > return s.replace('\r\n', '\n').replace('\r', '\n') > > does the same, but quicker. Note that, as an internal optimization, > .replace() doesn't build a new string object unless it finds something to > replace, so it's actually slower to do an "if" test first. > > >>> s = 'abcdefghi\n\n' # doesn't contain any oddballs > >>> t = s.replace('\r\n', '\n').replace('\r', '\n') > >>> s == t > True # nothing was replaced > >>> s is t > True # more, the same string object was returned by both .replace()s > >>> > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jjl at pobox.com Fri Jan 9 15:16:54 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jan 2004 20:16:54 +0000 Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> Message-ID: <871xq8ri6h.fsf@pobox.com> Terry Carroll writes: > On 9 Jan 2004 05:09:41 -0800, michael at foord.net (Fuzzyman) wrote: > > [ wants to change the user-agent in HTTP request from urllib ] > > Fuzzy -- > > I take the easy way out, and use urllib2, instead: [...] > req = urllib2.Request(url, None, req_headers) or again, you can set .addheaders on OpenerDirector (which will cause those headers to be added to all requests). John From http Fri Jan 2 06:07:35 2004 From: http (Paul Rubin) Date: 02 Jan 2004 03:07:35 -0800 Subject: question: Python or Lua for rejuvenation of old PCs? References: Message-ID: <7xisjupq14.fsf@ruckus.brouhaha.com> fBechmann at web.de (Frank Bechmann) writes: > having read your application specs FORTH came to my mind, having the > advantage that it is even more crude, so you have even less chances to > intermix both languages. and no one will doubt that it is usefull for > embedded controller tasks. He's not asking about a tiny embedded processor. Something with a 1 MB image would be fine. FORTH would be over (under?) kill. That level of inconvenience is not needed. From wxyisok at hotmail.com Fri Jan 2 01:15:47 2004 From: wxyisok at hotmail.com (wang xiaoyu) Date: 1 Jan 2004 22:15:47 -0800 Subject: how to use activex in wxpython with event support Message-ID: Hello: i want use activex in wxpython program,but when i use MakeActiveXClass an exception occurs. this is my source code dealing the DICOM ocx.I must note that in this program "hwtxcontrol" is a ocx developed my me use vc6,this ocx works fine in wxpython. but you can see i only change this ocx with a new DICOM ocx and set up eventClass, but the exception occure: File ".\site-packages\wxPython\lib\activexwrapper.py", line 105, in axw__init__ File "D:\Py22\lib\site-packages\win32com\gen_py\3A75EE8D-8E68-43FF-A90A-E4835B9A3DBDx0x1x0.py", line 187, in __init__ cookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy)) com_error: (-2147220990, 'CONNECT_E_CANNOTCONNECT', None, None) the ocx and the source code (in delphi) you can down at: http://www.psychology.nottingham.ac.uk/staff/cr1/dicomcom.html from wxPython.wx import * from wxPython.lib.rcsizer import RowColSizer import pywin.mfc.activex import activexwrapper,win32ui if wxPlatform == '__WXMSW__': from wxPython.lib.activexwrapper import MakeActiveXClass import win32com.client.gencache import win32com.client try: import hwtxcontrol hwtxocx=hwtxcontrol #import ezdicom #dicomocx=ezdicom #dicomocx=win32com.client.gencache.EnsureModule("{3A75EE8D-8E68-43FF-A90A-E4835B9A3DBD}",0,1,0) #dicomocx=win32com.client.Dispatch("ezDICOMax.ezDICOMX") dicomocx=win32com.client.gencache.EnsureModule('{3A75EE8D-8E68-43FF-A90A-E4835B9A3DBD}', 0, 1, 0) except: raise ImportError("IE4 or greater does not appear to be installed.") class DicomControl(pywin.mfc.activex.Control, dicomocx.ezDICOMX): def __init__(self): pywin.mfc.activex.Control.__init__(self) dicomocx.ezDICOMX.__init__(self) def OnDCMmouseDown(self, X ,Y ,Button ,Shift): print "DICOM ocx Click!" class HwtxControl(pywin.mfc.activex.Control, hwtxocx.Hwtx): def __init__(self): pywin.mfc.activex.Control.__init__(self) hwtxocx.Hwtx.__init__(self) def OnClick(self): print "hwtx click!" class TestPanel(wxWindow): def __init__(self, parent, log, frame=None): wxWindow.__init__(self, parent, -1, style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) sizer = wxBoxSizer(wxVERTICAL) hwtxCtls=RowColSizer() theClass2 = MakeActiveXClass(dicomocx.ezDICOMX,eventClass=DicomControl) #theClass2 = MakeActiveXClass(hwtxocx.Hwtx,eventClass=HwtxControl) self.ie4=theClass2(self,-1) self.ie4.SetSize(wxSize(300,300)) #self.ie4.filename="e:\\d02.img" #self.ie4.palnumber=12 #self.ie4.state=1 hwtxCtls.Add(self.ie4, row=2, col=2) sizer.Add(hwtxCtls, 0, wxEXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) EVT_WINDOW_DESTROY(self, self.OnDestroy) def OnDestroy(self, evt): if self.ie4: self.ie4.Cleanup() self.ie4 = None def runTest(frame, nb, log): if wxPlatform == '__WXMSW__': win = TestPanel(nb, log, frame) return win else: dlg = wxMessageDialog(frame, 'This demo only works on MSW.', 'Sorry', wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() overview = __doc__ if __name__ == '__main__': class TestFrame(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "ActiveX test -- Internet Explorer", size=(640, 480), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self.CreateStatusBar() self.tp = TestPanel(self, sys.stdout, self) EVT_CLOSE(self, self.OnCloseWindow) def OnCloseWindow(self, evt): self.tp.Destroy() self.Destroy() app = wxPySimpleApp() frame = TestFrame() frame.Show(True) app.MainLoop() i am a new python programer but i was really attracted by it elegant code.i really want use wxpython as my framework,but if i cant use activeX,i will have to change to vb:( can you help me.Best regards. sincerely wangxiaoyu From jjl at pobox.com Sun Jan 18 07:27:57 2004 From: jjl at pobox.com (John J. Lee) Date: 18 Jan 2004 12:27:57 +0000 Subject: yield References: <7iy8s5lx0x.fsf@enark.csis.hku.hk> Message-ID: <8765f9qw4y.fsf@pobox.com> Isaac To writes: > >>>>> "km" == km writes: > > km> Hi all, i didnt understand the purpose of 'yield' keyword and the > km> concept of 'generators' in python. can someone explain me with a > km> small example how generators differ from normal function calls? > > Normally, when you define a function and call it, the code within the > function gets executed, until the function returns, and at that point the > function disappear altogether. For example: [...] That's a misleading way of putting it: the *function* doesn't disappear (you can still call it after it's finished), but its state of execution does (you can't access its local variables after it's finished, except by calling it again and getting a *new* set of local variables). John From swalters_usenet at yahoo.com Sun Jan 18 05:22:53 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 10:22:53 GMT Subject: CGI Python user/group permission weirdness References: Message-ID: | Aienthiwan said | > Ok - this one's a baffling one. > I have confirmed that it's the www-data user by calling a > os.system('whoami') in my script for debugging. > The only inconsistancy is in dbtest and cvs. Have you tried os.system('groups') to verify that the user is in groups dbtest and cvs? Though I can't think of a reason why, maybe the script or the calling process is dropping it's privileges to these groups. Have you tried making all the directories leading up to the path of the file executable by dbtest and cvs? Some oddball code may be walking to the path, rather than jumping to the file. How about world executable? If you're just testing, you might also try making the files 777 for a minute and testing to see if the problem persists. (Don't leave this in production, only use it to isolate the error.) Try making a link from the file you want into another directory. Can you access it with the same permissions as the original, or perhaps with different permission? What www-daemon is this running on? Some www-daemons can be configured to lock down certain directories and var is a likely candidate for that. Can you access other files withing the var directory? If you fail this test, and succeed with the previous two tests, consider that it might be the daemon with an out-of-box configuration to keep web-processes out of sensitive system areas. HTH I'll post if I think of anything else. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From Z_kline at hotmail.com Mon Jan 19 00:31:52 2004 From: Z_kline at hotmail.com (Zachary) Date: Sun, 18 Jan 2004 21:31:52 -0800 Subject: Python Text Adventure Authoring System References: Message-ID: "Jp Calderone" wrote in message news:mailman.489.1074478463.12720.python-list at python.org... > On Sun, Jan 18, 2004 at 05:44:00PM -0800, Zachary wrote: > > Hello, > > > I've recently thought of how ideal Python is for the development of what > > used to be called text adventures. In case any of you don't know, these > > were basically sort of a computer game in which the player guided the > > story by typing in natural language commands, e.g. get ball. > > > > Some popular games of the 1980's include Zork, A Mind Forever Voyaging, > > among others. > > > > I was just wondering if anyone has any module that might help in the > > implementation of a text parser, something to read player commands. My > > idea is to have each room, item, creature, etc. Be represented as a > > Python instance. > > > > For example, the following code might setup a room class: > > > > class room: > > def __init__(self, rdesc, exit): > > self.desc = rdesc > > #Add Other code here > > > > If anyone has any idea how this might be done, I would love to hear from > > you. > > > > P.S: > > > > I have already seen another text adventure development system written in > > Python, called Paws. I thought this would be a sort of first project. > > > > There are a few modules in Twisted's CVS repository that are handy in this > area (as a few people are aware, Twisted is actually a support framework for > multiplayer interactive fiction or text adventure games). Documentation is > sparse, but much of the code is pretty simple (a *few* parts are mind > bendingly complex, but none of those are related to text parsing ;) > > cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co Reality > cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co NewReality > cvs -d:pserver:anon at cvs.twistedmatrix.com:/cvs co Imagination > > There was also a presentation about Reality at last year's PyCon. The > paper is available in Twisted CVS (history docs directory), or with viewcvs > at: > > http://cvs.twistedmatrix.com/cvs/doc/historic/2003/pycon/twisted-reality/ > > Imagination represents the most current thinking on the topic, but Reality > and NewReality have more infrastructure for actually dealing with user input > (Imagination is like a hyper distillate of our ideas currently, and so can't > be bothered to cover such things as handling user input ;). > > And of course, many of the developers frequent #twisted on irc.freenode.net > and just *love* it when someone wants to talk about Reality instead of boring > things like HTTP and IMAP4 ;) > > Hope this helps, > > Jp > Thanks for the advice, but I believe that the project could be considered shelved for now. I'll content myself with creating something smaller scale. From fperez528 at yahoo.com Tue Jan 6 14:02:39 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 06 Jan 2004 12:02:39 -0700 Subject: Python as a numerical prototyping language. References: <67n0966wsz.fsf@aster.homelinux.net> Message-ID: Lonnie Princehouse wrote: > About a year ago, I attempted to answer the question "Can Python > replace Matlab?" for my workplace. The conclusion was "Not quite > yet", for two reasons. > > The first was purely human: Matlab is entrenched, and there's always > resistance to change (note: lots of people here still swear by Fortran > '77). > > The second reason: there's no unified Python environment that gives > you easy access to plotting capability and an interpreter, a la > Matlab. Python has the ability to do everything Matlab can (and much > more!) but it still requires just enough expertise to find, install, > and learn the various scipy and plotting modules that only the > early-adopter types are willing to do it. While I completely agree with you that it still requires a fair amount of manual labor to get a nice scientific python environment going, you may want to take a look at ipython at http://ipython.scipy.org. It tries to provide as good of an interactive shell as is feasible, along with improving on the default Gnuplot support which Gnuplot.py provides (basically giving simpler syntax for the plotting commands). With its concept of profiles, you can simply say ipython --profile numeric and have a command-line shell which preloads a complete matlab-like environment. It's not perfect, but users seem to like it. Regards, Fernando. From aahz at pythoncraft.com Tue Jan 6 17:31:18 2004 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2004 17:31:18 -0500 Subject: prePEP "Decimal data type" v0.2 References: Message-ID: In article , Batista, Facundo wrote: >aahz at pythoncraft.com wrote: ># >#- One major correction: "Rationale" means "reason"; "rational" >#- refers to >#- fractions. Several times you use "rationale" when you mean >#- "rational". > >Paul Moore pointed that too, sorry for my english, :( De nada; we're used to that around here. Just needs fixing, is all. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From skip at pobox.com Wed Jan 28 12:32:19 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 11:32:19 -0600 Subject: isinstance() bug In-Reply-To: References: Message-ID: <16407.61987.454687.705426@montanaro.dyndns.org> Sidharth> i dont know unix. Sidharth> how does abs path work with sym-links. Not well. Seems that os.path.realpath does the right thing though: % ls -l /etc/rc2.d lrwxrwxrwx 1 root root 10 May 21 2002 /etc/rc2.d -> rc.d/rc2.d/ % python Python 2.2.3 (#1, Jun 21 2003, 08:08:22) [GCC 3.0.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.abspath("/etc/rc2.d") '/etc/rc2.d' >>> os.path.realpath("/etc/rc2.d") '/etc/rc.d/rc2.d' As someone else pointed out, the issue of multiple hard links to the same file is a bit tougher nut to crack. % cd ~/tmp % cat > a.py class A: pass % ln a.py b.py % python Python 2.2.3 (#1, Jun 21 2003, 08:08:22) [GCC 3.0.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import a >>> import b >>> a.A == b.A 0 You need to compare inode numbers to see if you have the same or different files. >>> import stat >>> os.stat(a.__file__)[stat.ST_INO] 37041L >>> os.stat(b.__file__)[stat.ST_INO] 37041L Skip From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jan 22 18:21:31 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 23 Jan 2004 00:21:31 +0100 Subject: strtotime? In-Reply-To: References: Message-ID: <40105afb$0$319$e4fe514c@news.xs4all.nl> Leif K-Brooks wrote: > PHP has a very nice strtotime function (http://php.net/strtotime) which > converts a date/time in virtually any format into a timestamp. Does > Python have a similar function? I guess you're looking for: time.strptime --Irmen From nhodgson at bigpond.net.au Fri Jan 16 15:31:38 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 16 Jan 2004 20:31:38 GMT Subject: Retrive unicode keys from the registry References: Message-ID: Thomas Heller: > def RegQueryValue(root, subkey): > if isinstance(subkey, unicode): > return _winreg.QueryValue(root, subkey.encode("mbcs")) > return _winreg.QueryValue(root, subkey) > > Does this look ok? It will fail for keys that can not be encoded in your current code page. That will not often be a problem but if you want to be safe then access to the wide version is needed. Neil From martin at v.loewis.de Sun Jan 25 13:25:32 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 25 Jan 2004 19:25:32 +0100 Subject: trouble w/ unicode file In-Reply-To: References: Message-ID: Serge Orlov wrote: > Sorry, I was confused by your words "with some iso8859-1 strings". > I thought you were using simple (unaware of encodings) editor and > just added #-*- coding: utf-8 -*- with hope that it will work. You're > right the coding should stay utf-8. After that you have two options: > either use -U option or put u before every string. There is a third option: Programmatically convert the strings to Unicode, e.g. # -*- coding: utf-8 -*- s = "????????????" s = unicode(s, 'utf-8') This assumes that you know thy source encoding at the point of conversion. Regards, Martin From dlmurray at micro-net.com Mon Jan 5 01:54:57 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Sun, 4 Jan 2004 23:54:57 -0700 Subject: intellectual property agreements and open source . was - Re: Why does this fail? [2] References: <84fc4588.0401042209.60cdb724@posting.google.com> Message-ID: After re-reading this part, I can see that it is an idea that I like. How does participating in open source work for someone (me) who has signed the customary intellectual property agreement with the corporation that they work for? Since programming is part of my job, developing test solutions implemented on automatic test equipment (the hardware too) I don't know if I would/could be poison to an open source project. How does that work? I've never participated. If all the work is done on someone's own time, not using company resources, yadda-yadda-hadda-hadda, do corporate lawwwyaahhhs have a history of trying to dispute that and stake a claim? No doubt, many of you are in the same position. Regards, Dave "Anand Pillai" wrote in message news:84fc4588.0401042209.60cdb724 at posting.google.com... > This is the main reason why developers release programs as > opensource. Help the community, and help yourselves. Re-inventing > the wheel is perhaps not the way to go. From mwilson at the-wire.com Fri Jan 23 09:51:21 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 23 Jan 2004 09:51:21 -0500 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: In article , Josiah Carlson wrote: >> Or, expressing the idea that they're the ends of a number line: >> >> PosInf, NegInf >> PosInfinity, NegInfinity >> PositiveInfinity, NegativeInfinity Highest and Lowest? Regards. Mel. From lubowiecka at go2.pl Mon Jan 26 15:50:39 2004 From: lubowiecka at go2.pl (Ringwraith) Date: Mon, 26 Jan 2004 21:50:39 +0100 Subject: python service running on Win Xp, but failing on Win NT Workstation :( References: Message-ID: maybe another hint ... While installing I got the error message: "The procedure entry point RegisterServiceCtrlHandlerExW could not be located in the dynamic link library ADVAPI32.dll" Best wishes, Sylwia -> aka Nazgul From sross at connectmail.carleton.ca Fri Jan 2 12:34:53 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 2 Jan 2004 12:34:53 -0500 Subject: finding file size References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: "Martin v. Loewis" wrote in message news:bt3l9i$pog$07$3 at news.t-online.com... > Sean Ross wrote: > > > My question is this: Is there a reason why file objects could not have a > > size method or property? > > Yes. In Python, file objects belong to the larger category of "file-like > objects", and not all file-like objects have the inherent notion of a > size. E.g. what would you think sys.stdin.size should return (which > actually is a proper file object - not just file-like)? > > Other examples include the things returned from os.popen or socket.socket. > > Regards, > Martin > I see what you mean. I suppose the only option I could think of for sys.stdin, os.popen, and socket.socket would be to return the number of bytes written to these objects so far. But, then, those objects, or something else, would have to track that information. Also, pipes and sockets could be written to from two directions, so is the size the total number of bytes written from both sides, or would you prefer to know how much you'd written as the size, or how much the other side had written (Perhaps all three would be nice). Another option would be to return '-1', or 'None', to let people know that the request is unsupported for this file-like object. Still another option would be to raise an exception. And, of course, there's the ever popular, leave-well-enough-alone option. Anyway, thank you for your response. I see it's merit. Sean From gerrit at nl.linux.org Tue Jan 20 06:41:02 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 20 Jan 2004 12:41:02 +0100 Subject: Getting a process's output [solved] In-Reply-To: References: <82104858-4ACB-11D8-A692-0003934ACDEC@zdome.net> <20040119221350.GB11631@nl.linux.org> Message-ID: <20040120114102.GA3264@nl.linux.org> Dietrich Epp wrote: > On Jan 19, 2004, at 2:13 PM, Gerrit Holl wrote: > >Try commands.getstatusoutput() or the various popen functions. > > Thanks, although getstatusoutput requires arguments to be quoted. I > looked at the source code to getstatusoutput() and popen() to come up > with a replacement which doesn't need quoted arguments and doesn't > create a shell. I don't think it portable, and it will undoubtedly do > something very nasty if one of the system calls should fail. I think > this would be very cool in the library (the function, not its > deficiencies). You may want to have a look at PEP 324, about a new process module: http://www.python.org/peps/pep-0324.html yours, Gerrit. -- 20. If the slave that he caught run away from him, then shall he swear to the owners of the slave, and he is free of all blame. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From anton at vredegoor.doge.nl Sat Jan 10 17:33:34 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 10 Jan 2004 23:33:34 +0100 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> <7xfzen3ayb.fsf@ruckus.brouhaha.com> <40005e17$0$6084$ba620e4c@news.skynet.be> Message-ID: <40007ec6$0$7527$3a628fcd@reader2.nntp.hccnet.nl> "broebel" wrote: >If you look at this as a homework or not is of no interest to me but I like >the way you explained which way to go to find the resolution. >thanks (i solved it in a jiffy now) Now that it is solved it's fair game for anyone :-) I have no information whether this is homework for you or not, and posting in a public newsgroup defeats cheating. Anton def split(units,coins): for c in coins : n, units = divmod(units, c) if n: yield c, n if not units: raise StopIteration raise ValueError, 'no change!' def test(): coins = [200,100,50,20,10,5,2,1] for i in range(501): D = dict(split(i,coins)) nc = sum(D.values()) check = sum([c*n for c,n in D.items()]) print "%3i: %i coins:" %(i,nc) , D assert check == i if __name__=='__main__': test() From francisgavila at yahoo.com Sat Jan 10 11:15:49 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 10 Jan 2004 11:15:49 -0500 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> <3fff1245@usenet01.boi.hp.com> <400018e8$0$294$ba620e4c@news.skynet.be> Message-ID: <10009bujbbsn8b5@corp.supernews.com> broebel wrote in message <400018e8$0$294$ba620e4c at news.skynet.be>... >Just like you don't speak dutch, I don't write python (that's a good reason >to learn, isn't it) so I'm not trying out your proposal to see wheather it >works or not. >I kept it aside to check as soon as I understand more of the language. So >thanks any way. >btw is there a special reason why someone should speak dutch to programm in >python.? > Guido van Rossum created Python, and is currently its BDFL (Benevolent Dictator For Life). He's Dutch. It's a sort of an inside joke that Python makes sense if you're dutch (type 'import this' into an interactive Python prompt). -- Francis Avila From fowlertrainer at anonym.hu Fri Jan 9 10:29:39 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Fri, 9 Jan 2004 16:29:39 +0100 Subject: How to globalize vars ??? Message-ID: <6128860589.20040109162939@anonym.hu> Hello ! I have get a strange problem in mod_python site. More modules I have, and think, to I initialize my Session handler from main module. Like this: -- main -- import BHASession # Session info BHASessionDir="C:/bhaweb/sessions" BHASession.SSInit(BHASessionDir) -- Session -- SSDefaultDir="c:/bhaweb/sessions" SSLockObj=threading.Lock() def SSLock(): SSLockObj.acquire() def SSUnlock(): SSLockObj.release() def SSInit(SessionDir): SSLock() try: if SSDefaultDir.strip()=="": # <- # UnboundLocalError: local variable 'SSDefaultDir' referenced before assignment SSDefaultDir=SessionDir finally: SSUnlock() -------------- When I not use SSInit, only I write the global variable in BHASession module like this: SSDefaultDir="c:/bhaweb/sessions" then it is working good !!! Why ? How to force python to module see his variable ? Thanx for any advance ! -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From grey at despair.dmiyu.org Fri Jan 23 16:23:34 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 23 Jan 2004 21:23:34 -0000 Subject: [OPINION] - does language really matter if they all do the same thing? References: <20040123183127.GA35281@mail.hitmedia.com> Message-ID: On 2004-01-23, Jonathan Daugherty wrote: > On a more conjectural note, spoken languages are more than just ways of > expressing ideas; by virtue of being evolving systems of communication, they > serve as an insight into the culture and people that developed them. > Programming languages are the same in that respect. Which is a rather interesting statement as quite a few people who study languages tend to ignore or discount certain languages because they are artifical (Esperanto, for example). :) -- 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 gandalf at geochemsource.com Mon Jan 19 02:09:54 2004 From: gandalf at geochemsource.com (Gandalf) Date: Mon, 19 Jan 2004 08:09:54 +0100 Subject: secure unpickle? References: Message-ID: <400B82C2.8080800@geochemsource.com> >Hi, I'm looking for a way in unpickling, or equivalent, such that can only >unpickle (or is limited to) simple data structure, such as number, string, >list, tuples. > >The doc I found http://www.python.org/doc/2.2.3/lib/pickle-sec.html was >helpful but still not very clear to me. > >Thanks! > >-Y > > > I'm using this module (based on the documentation you mentioned): import cStringIO import cPickle def dumps(obj): """Dumps an object into a string. @param obj: The object to dump. It should not be a user defined object nor a global. It should only contain built-in types. (Will not raise an exception anyway.) @return: The dumped object as a string. """ f = cStringIO.StringIO() p = cPickle.Pickler(f,1) p.dump(obj) return f.getvalue() def loads(s): """Loads an object from a string. @param s: The string to load the object from. @return: The object loaded from the string. This function will not unpickle globals and instances. """ f = cStringIO.StringIO(s) p = cPickle.Unpickler(f) p.find_global = None return p.load() From jcarlson at nospam.uci.edu Fri Jan 23 03:48:28 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 00:48:28 -0800 Subject: Batch commands on Windows In-Reply-To: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: > So, after reading some messages about os.system, and looking at the popen > stuff and trying it a bit, I still have not found a way to keep a command > window open for several commands (on Windows 2000/XP), while seeing the > normal output in a command window. All I want to do is do what a batch file > does, but I want to actually have functions and associative arrays and all > the other niceties of python. Q: "How do I get python to run these other things, and keep the window open so that I can see their output?" A: Making sure to run your script with the console version of Python (python.exe, NOT pythonw.exe): #insert the body of your script here raw_input("press enter to continue..."); # or even #os.system('pause'); Q: "I'm running the non-console version of Python, how do I capture the output of my scripts so that I can do something with it afterwards?" A: I'll answer this one tomorrow, it is getting late. - Josiah From jjl at pobox.com Wed Jan 14 21:24:08 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 02:24:08 +0000 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> Message-ID: <8765ferltj.fsf@pobox.com> "Derek" writes: [...] > Yes, I prefer compile-time checks to run-time checks. I don't know > which method is "better" by any objective measure, but I prefer to > know if there is a problem as early as possible. It's not hard to It would certainly be better if Python had some kind of optional static type checking (though that seems unlikely to happen). Many people (eg. Alex Martelli in this group) have argued that requiring *everything* to be statically checked is harmful because of the cost it imposes in terms of inflexibility and lines of code. > make a change in Python that will go unnoticed until much later, and > in the real world test suites often don't have enough coverage to > catch every runtime error up front. The argument runs like this: If you don't have near-100% test coverage, you are missing many bugs that static typechecking will not catch. So don't do that (the fact that it's perfectly feasible to have near-100% coverage, when given support from bosses where relevant, has been repeatedly demonstrated recently). OTOH, if you do have 100% coverage, the set of bugs that *are* caught by the static typechecks, but *not* by the tests is usually very small, in practice. So, you can catch bugs by introducing static checks, but you introduce *even more* bugs (so the argument runs) if you pay the cost (see above) of static checking for *everything*, as you must in C++. So, though Python beats C++ here, the even-happier medium is achieved with systems like the static type-inference of ML and Haskell. Whether this argument holds in general is hard to answer, but in the particular case of C++ and Python, I find it extremely persuasive. John From NAVMSE-MAIL at fisherisland.com Wed Jan 28 10:10:47 2004 From: NAVMSE-MAIL at fisherisland.com (NAVMSE-MAIL) Date: Wed, 28 Jan 2004 10:10:47 -0500 Subject: Norton AntiVirus detected a virus in a message you sent. The infected attachment was deleted. Message-ID: <4E4869025E6E7A4DA67978DC08DC1D89DACD2A@mail.fisherisland.com> Recipient of the infected attachment: MAIL, First Storage Group\Mailbox Store (MAIL), Liz Martinez/Inbox Subject of the message: Test One or more attachments were deleted Your email address will be blocked to this server!!!! Thank you, FISHER ISLAND IT DEPT. Attachment document.zip was Deleted for the following reasons: Virus W32.Novarg.A at mm was found. Virus W32.Novarg.A at mm was found in document.txt .scr. From peter at engcorp.com Fri Jan 9 09:44:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:44:18 -0500 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> <6AlLb.134$hd.7718@news2.e.nsc.no> <3FFEB6D6.BF92551E@engcorp.com> <+vXesJAXsr$$EwJL@jessikat.fsnet.co.uk> Message-ID: <3FFEBE42.80962511@engcorp.com> Robin Becker wrote: > > In article <3FFEB6D6.BF92551E at engcorp.com>, Peter Hansen > writes > .. > ... > >enlighten me. > > > >Thomas, you're completely ON track here... I just wanted to emphasize that > >Twisted is much more polished and sophisticated. I'd even have to say, > >as a programmer using them, that Twisted does actually provide a simpler and > >cleaner API. It and Medusa are much closer in concept than either is to > >Zope, though, as you say. > > > In another thread http://snakelets.sf.org was mentioned. I get at least a temporary "server not found" error when I try that name. In any case, anything added on top of Twisted and Medusa are, of course, not Twisted and Medusa. Zope is added on top of Medusa, and doubtless there are and will be many things added on top of Twisted, some of which may be similar in purpose to Zope (specifically, content-management systems rather than just frameworks for application writing). -Peter From hgeldenhuys at gims.com Fri Jan 23 03:44:34 2004 From: hgeldenhuys at gims.com (Herman Geldenhuys) Date: Fri, 23 Jan 2004 10:44:34 +0200 Subject: Modem beeping Message-ID: <001c01c3e18d$260b02c0$b10d10ac@metasalio> I am dialing a modem(COM3) from python on windoze and I connect successfully to a remote phone, but there is an annoying beeping sound that keeps on ringing in the background. Would anybody happen to know what command and in what sequence I should send to the modem to make it stop? Thanks H -------------- next part -------------- An HTML attachment was scrubbed... URL: From SBrunning at trisystems.co.uk Tue Jan 6 11:44:19 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Tue, 6 Jan 2004 16:44:19 -0000 Subject: Why does this fail? Message-ID: <31575A892FF6D1118F5800600846864D01200E1E@intrepid> > From: Skip Montanaro [SMTP:skip at pobox.com] > A possible addition to your "Embedded script is messing up my > web-scraping" > section: Wasn't there mention of the Mozilla project's standalone > JavaScript interpreter (don't remember what it's called) recently > alongside > some Python interface? Yup - see http://simon.incutio.com/archive/2003/12/29/seamonkey. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ -LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From cygnus at cprogrammer.org Sun Jan 25 09:34:39 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sun, 25 Jan 2004 09:34:39 -0500 Subject: [OPINION] - does language really matter if they all do the same thing? In-Reply-To: <6ee58e07.0401250521.2e26e370@posting.google.com> References: <20040123183127.GA35281@mail.hitmedia.com> <6ee58e07.0401250521.2e26e370@posting.google.com> Message-ID: <20040125143439.GA19693@mail.theserver.ath.cx> # > that english and arabic are, in the same sense, just two sides # > of the same coin, which is a gross oversimplification of the # > matter and a disrespect to the qualities of the languages # # english and arabic are quite equal. compare it with tonal asian # languages then you find some real difference. For example in the thai # language there is no word that means "No", you can only politely deny # "yes". This is mental difference. Either you are a troll or you have missed the point entirely. :) -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From LittleDanEhren at yahoo.com Fri Jan 30 20:10:16 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 30 Jan 2004 17:10:16 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <711c7390.0401301710.4353274@posting.google.com> > Hey, if I wanted to to, I could add functions and all that that would > make Python look like Lisp, or IO, or whatever. > > But, why? If I wanted to write Lisp or Io, I'd use those. > > Your example I'd write in Python as > > for key, value in dict(x=1, y=2, z=3): > print '%s: %s\n" % (key, value) > > I didn't have to write 43 lines of support code, and it's also two > lines. I don't think "this isn't builtin" is a selling point -- you > need a critical mass of builtins to make a language useful. I know. Maybe in the future, it can be builtin, but it just shows how flexible Io is. Io has its own version of a for loop (in addition to being able to iterate directly over a dictionary or list) which in some cases makes more sense than Python's. It's like this: for(x, 1, 10, #goes through x with values 1-10 write(x, "\n") ) IMHO, this makes more sense than iterating over a list created just for a specific loop. On my computer, Io's loops are faster than Python's (probably because they are lazy). >> [stuff about size of communities and bindings to stuff] > > Yep. That's a *big* difference, I'd say. But the community will grow larger in time. The Io community is bigger than the Python community two years after Python was released (although that's probably because it wasn't publicly released for two years). > > Can you elaborate a bit on why Python is inflexible? I find Python to > be extremely flexible. There's still a difference between types and classes in Python. Try this in Python: >>> x = object() >>> x.number = 5 It raises an error. But the same thing in Io works (which is x := Object clone; x number := 5). To do it in Python, you have to do >>> class goodObject(object): pass >>> x = goodObject() >>> x.number = 5 Also, Python has statements (as opposed to just expressions) even for the simplest things like writing things to the command line. In Io, flow control is in functions, which can be overwritten if you want to change them. The Python philosophy is that if you allow this and other flexible things to happen, you will have inconsistent code. If someone asks on the Tutor mailing list how to change that, everybody responds "Why would you want to do that?". While that's a valid viewpoint, it's not the most flexible. > > Python is 14 years old, and it's still working on global domination; > Io's got some catching up to do :-) I don't think world domination is a practical goal for either language. Daniel Ehrenberg From francisgavila at yahoo.com Fri Jan 23 04:37:38 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 23 Jan 2004 04:37:38 -0500 Subject: private class members and hasattr References: Message-ID: <1011qtlk906t9d1@corp.supernews.com> Dragos Chirila wrote in message ... >Why hasattr method doesn't return 1(true) for private member '__prop3' ?? Because that's how private members work. See "5.2.1 Identifiers (Names)" in the Python Language Reference. >>> class PropTest: ... def __init__(self): ... self.__prop3 = 3 ... def testprops(self): ... print hasattr(self, '__prop3') ... print hasattr(self, '_PropTest__prop3') ... >>> dir(PropTest()) ['_PropTest__prop3', '__doc__', '__init__', '__module__', 'testprops'] >>> PropTest().testprops() False True >>> You're probably better off not using private members anyway. -- Francis Avila From vincent at visualtrans.de Wed Jan 7 02:03:50 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 7 Jan 2004 08:03:50 +0100 Subject: Finaly found a simple enough task for python, took the plunge, but..... References: <3FFB5312.1030803@connection.com> <3FFB8071.9070107@connection.com> <3FFBA228.7070403@connection.com> Message-ID: "Sambo" schrieb im Newsbeitrag news:3FFBA228.7070403 at connection.com... | Well, I was hopeful but no luck under w2000 and python 2.3.3 | The window is just as obscured as under w95 | Must be p2.3.3, oh well 9Mb of junk, good think I upgraded to UNLIMITED access, | hehe. The example should work absolutely fine on 2.3.3 - which is what I am running. So there's someting at your end that is causing this. How do you invoke the script? Have you tried invoking the script directly from the command line? Vincent | | Ciao. | | | engsolnom at ipns.com wrote: | | > (top posting..sorry) | > | > I tried Vincent's suggested code and it works just fine with Win2000, Python2.3. | > I did change the code to return the path to a selected file, rather than just a directory. | > Shows the value of the newsgroups...I was unaware (of course us newbies are unaware of lots of | > things) of tkFileDialog...and was about to write a tk interface to do the same thing. Saved a ton of | > time, and probably newsgroup bandwidth. | > Thanks, Vincent! | From brian at sweetapp.com Tue Jan 27 18:10:55 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 27 Jan 2004 15:10:55 -0800 Subject: map float string '0.0' puzzle In-Reply-To: Message-ID: <060101c3e52a$d16f5f30$0000fea9@dell8200> > >>> row = ('0.0', '1.0', None) > >>> map(lambda setting: setting and float(setting) or None, row) > Specifically, why is the return value of the first map operation: > [None, 1.0, None] > > I was expecting: > [0.0, 1.0, None] Can you explain why you were expecting that? The expression is: [('0.0' and 0.0) or None, ('1.0' and 1.0) or None, (None and ?) or None)] ^ False ^ True ^ False You can look at and/or like this (except that function calls don't do short-circuit evaluation): def and(*args): for a in args: if not a: return a return args[-1] def or(*args): for a in args: if a: return a return args[-1] So you have: or(and(settings, float(setting)), None) Cheers, Brian From jepler at unpythonic.net Mon Jan 26 10:41:31 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 26 Jan 2004 09:41:31 -0600 Subject: need something like threads, or just multiple simulateous exec's In-Reply-To: References: Message-ID: <20040126154131.GA19863@unpythonic.net> I'm not sure why you need to use threads here. popen()ed processes execute asynchronously, blocking when they create enough unread output. In this case, they'll generate very little output. Why not try this? # Create all processes at once pipes = [os.popen(...) for ip in hosts] # Read their output output = [pipe.read for pipe in pipes] Suppose you decide you want to run only N os.popen()s at a time. Here you'll want to use select() instead of threads. Something like this: remaining_hosts = hosts[:] pipes = [] output = [] for i in range(nthreads): while remaining_hosts or pipes: while remaining_hosts and len(pipes) < npipes: host = remaining_hosts.pop() pipes.append(os.popen(...)) ready = select.select([pipes], [], [])[0] for pipe in ready: # Assuming output arrives all at once # (it should since it's one line) output.append(pipe.read()) pipes.remove(pipe) pipe.close() Jeff From Florian.Lindner at xgm.de Sun Jan 4 15:49:30 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 04 Jan 2004 21:49:30 +0100 Subject: Problems compiling python Message-ID: Hello, I want to compile that small python script: bastet:/ # cat test.py #!/usr/bin/python import sys, os username = os.getlogin() print username os.spawnv(os.P_WAIT, "/root/mailboxmgm.py", sys.argv) Python 2.3.2 (#1, Oct 12 2003, 14:27:24) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import py_compile >>> py_compile.compile("test.py") >>> bastet:/ # chmod u+x test.pyc bastet:/ # ./test.pyc ./test.pyc: line 1: syntax error near unexpected token `;' '/test.pyc: line 1: `;? bastet:/ # What is wrong? Thanks, Florian From jcarlson at nospam.uci.edu Fri Jan 23 14:55:04 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 11:55:04 -0800 Subject: Ordered dictionary? In-Reply-To: References: Message-ID: Carmine Moleti wrote: > Hi Dragos, > > >>def filterList(p_list, p_value): >> l_len = len(p_list) >> l_temp = map(None, (p_value,)*l_len, p_list) >> l_temp = filter(lambda x: x[1].find(x[0])==0, l_temp) >> return map(operator.getitem, l_temp, (-1,)*len(l_temp)) > > >>phones_dict = {'jansen' : '0000', 'xxx' : '1111', 'jan2' : '2222'} >>names_list = filterList(phones_dict.keys(), 'jan') >>phones_list = map(phones_dict.get, names_list) > > >>This extracts from the dictionary the telephone(values) numbers for >>names(keys) starting with 'jan'... > > > Why you didn't used the string.startswith(...) method? > > I wrote this: > > d={'carmine':'123456','carmela':'4948399','pippo':'39938303'} > for name,number in d.items(): > if name.startswith('car'): > print name,number > > This also extract from the dictionay all the (name,number) pairs whose > name starts with a given substring ('car' in the example). > > Thanks for your answer Something strange is that for short 'other' strings string[:len(other)] == other #is faster than string.startswith(other) Maybe find is faster than startswith. - Josiah From moskow23 at yahoo.com Sun Jan 18 23:47:22 2004 From: moskow23 at yahoo.com (Dan) Date: 18 Jan 2004 20:47:22 -0800 Subject: Determining a replacement dictionary from scratch References: <4b805376.0401181116.3b0adb41@posting.google.com> Message-ID: <4b805376.0401182047.434af5d6@posting.google.com> Brilliant, thank you all for your help. -Dan From aahz at pythoncraft.com Mon Jan 5 14:53:37 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Jan 2004 14:53:37 -0500 Subject: Optimized quoting (was Re: Speed?) References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: In article , Michael Hudson wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> John Hunter wrote: >>> >>>Donald Knuth, God of Computer Science, said "Premature optimization is >>>the root of all evil". >> >> If Knuth is God, then Hoare is God's father: >> >> "Premature optimization is the root of all evil in programming." >> --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) > >Cite? http://www.haskell.org/pipermail/haskell-cafe/2001-January/001461.html Anybody have a copy of _Literate Programming_ to check? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From miki.tebeka at zoran.com Sun Jan 25 11:55:23 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 25 Jan 2004 08:55:23 -0800 Subject: Changing endian format References: Message-ID: <4f0a9fdb.0401250855.1620b1a3@posting.google.com> Hell Amit, > I have a binary file and i need to change the endian format..little to big as > well as vice versa..could anyone help me out. Warning: Not tested! #!/usr/bin/env python from sys import argv from array import array a = array("H", open(argv[1], "rb").read()) a.byteswap() open(argv[2], "wb").write(a.tostring()) HTH. Miki From jepler at unpythonic.net Wed Jan 14 17:07:25 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 14 Jan 2004 16:07:25 -0600 Subject: C++ bad-mouthing (was: Why learn Python ??) In-Reply-To: <878yka2sze.fsf@pobox.com> References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <7xhdz08xgy.fsf@ruckus.brouhaha.com> <1073978329.887910@yasure> <87brp7agl7.fsf@pobox.com> <7xvfnfmzy8.fsf@ruckus.brouhaha.com> <878yka2sze.fsf@pobox.com> Message-ID: <20040114220725.GC17742@unpythonic.net> On Wed, Jan 14, 2004 at 08:08:37PM +0000, John J. Lee wrote: > according to pycount.py run on the old version of Twisted that's > sitting on my hard drive -- again, it seems to spit out multiple total > lines, so I hope it's working right...! "find | xargs foo" can invoke foo multiple times. linux has a surprisingly small upper bound on commandline length, on the order of a 128k, and xargs is probably more conserative than that. >>> os.system("/bin/true " + "x" * 129000) 0 >>> os.system("/bin/true " + "x" * 130000) 32512 Jeff From rainerd at eldwood.com Wed Jan 28 14:50:17 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Wed, 28 Jan 2004 19:50:17 GMT Subject: isinstance() bug References: <20040128132225.GA10842@foof.i3.cz><16407.54576.283608.505067@montanaro.dyndns.org> Message-ID: Michal Vitecek wrote: > it's my belief that if i'm instantiating a class from the same > location no matter how i imported its definition, its instances are > always of the same class. Your belief is incorrect. 'package.module.A' and 'module.A' are distinct classes. Modifications to one do not show up in the other. If 'isinstance' reported that an instance of 'package.module.A' is an instance of 'module.A', 'isinstance' would be broken and unusable. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From support at alcanet.com.au Fri Jan 30 19:55:01 2004 From: support at alcanet.com.au (support at alcanet.com.au) Date: Sat, 31 Jan 2004 11:55:01 +1100 Subject: ALCATEL POLICY : your message has been refused Message-ID: <200401310055.i0V0t1Hq005754@mailgate.alcanet.com.au> ******************** e-mail Manager Notification ********************** As a security precaution this mail was blocked and discarded since it contains attachments with file extensions not allowed by our email policy (.exe, .vbs etc ...) Source mailbox : Destination mailbox : Message Subject : Hello Attachment: application/octet-stream; name="eekdco.pif" Our mail system policy does not accept certain attachment types. See http://www.alcatel.com/mail_policy/email_attachments.htm for additional details. Please zip up the file and send again or use an alternate method to send the file. If you have questions, contact your local email support representative. ********************** End of message *************************** From jjl at pobox.com Sat Jan 31 15:20:05 2004 From: jjl at pobox.com (John J. Lee) Date: 31 Jan 2004 20:20:05 +0000 Subject: Simple web proxy - help needed References: Message-ID: <87ektfkgzu.fsf@pobox.com> forshtat at hotmail.com (Ziv Forshtat) writes: [...] > Problem is - I don't have to much background in writing proxies, nor > in writing plugins. [...] Plugins: For MSIE, all the docs are on MSDN. Try a Google search for "MSDN reusing webbrowser control". Get Hammond and Robinson's book on Python & win32. For Konqueror, start here: http://www.boddie.org.uk/david/Projects/Python/KDE/ http://www.boddie.org.uk/david/Projects/Python/KDE/Docs/ Warning: plugin support for PyKDE is quite new. For Mozilla, MozPython might set you off in the right direction. Building PyXPCOM is a pain. BTW, Mozilla doesn't seem to want to build on Debian woody, so don't do that. Read the installation instructions for the MozPython & PyXPCOM binaries on that page carefully (so as not to piss off Thomas when you get it wrong ;-) http://www.thomas-schilz.de/MozPython/README.html (BTW, you're probably NOT interested in "Netscape plugins") John From skip at pobox.com Thu Jan 15 10:04:28 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Jan 2004 09:04:28 -0600 Subject: Why gmp is not in the standard library? In-Reply-To: <4f0a9fdb.0401150211.615a7f45@posting.google.com> References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: <16390.44028.327189.842557@montanaro.dyndns.org> Miki> Which made me think why Python don't use gmp as it's primary math Miki> package - we'll get fast results, a lot of number types and much Miki> more. Miki> Can't think of any reason why Python is implementing its own long Miki> numbers... Can you enlighten me? In addition to the reasons Michael Hudson provided, I'll add: * Python's native longs have been around much longer than gmpy, perhaps even predating gmp itself. * Converting from Python's longs to gmpy would probably be at least a moderately nontrivial undertaking. Skip From skip at pobox.com Sat Jan 10 13:26:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 12:26:09 -0600 Subject: module for parsing email Received headers? In-Reply-To: References: Message-ID: <16384.17345.19471.709420@montanaro.dyndns.org> forte> Does anyone know the existence of such module? I bet 90% of the forte> chance that the wheel was invented before. Thanks! No module, but SpamBayes has some regex hacks in its tokenizer to pull out interesting bits of Received: headers. Skip From andy47 at halfcooked.com Tue Jan 13 10:47:21 2004 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 13 Jan 2004 15:47:21 +0000 Subject: id3v2 module In-Reply-To: References: Message-ID: Dusausoy Bruno wrote: > Hi, > > I'd like to know if there is a third-party module for reading/writing > id3v2 informations. > Thanks http://www.nedbatchelder.com/code/modules/id3reader.html Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From me at here.there.com Wed Jan 14 16:50:44 2004 From: me at here.there.com (Peter Ashford) Date: Thu, 15 Jan 2004 10:50:44 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: >>>>There are plenty of things you can get out of starting, getting > > involved > >>>>with, and approaching open source projects. A legion of personal >>>>servants is not going to be one of them, and only a crass idiot would >>>>think otherwise. >>> >>>As far as I've been able to discover, life is just one long cocktail >>>party in Brandon's honour. So it isn't exactly surprising that >>>everyone appears to him as just another waiter with a tray of drinks. > > > Is there something fundamentally *wrong* with recognizing how useless people > are to your purposes? *Recognising* that people aren't useful for your purposes is sensible. *Criticising* people for not being useful for your purposes when they've never claimed or aspired to be is dumb. From dietrich at zdome.net Sun Jan 25 18:47:25 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 25 Jan 2004 15:47:25 -0800 Subject: [OPINION] - does language really matter if they all dothe samething? In-Reply-To: References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com><028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net><4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: On Jan 24, 2004, at 9:30 AM, Terry Reedy wrote: > I slightly prefer my Python version, but I suspect you will not, so you > remain safe. You prefer infinite recursion? Thank you, but I like my functions to return once in a while. From okyoon at stanford.edu Thu Jan 1 20:54:27 2004 From: okyoon at stanford.edu (Oh Kyu Yoon) Date: Thu, 1 Jan 2004 17:54:27 -0800 Subject: Graph in wxPython References: Message-ID: Thank you all. You guys have been very helpful. From cygnus at cprogrammer.org Wed Jan 21 16:01:42 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Wed, 21 Jan 2004 16:01:42 -0500 Subject: Need help with Python class idioms In-Reply-To: <200401212101.33605.james@logicalprogression.net> References: <200401212051.50411.james@logicalprogression.net> <200401212101.33605.james@logicalprogression.net> Message-ID: <20040121210142.GA27469@mail.theserver.ath.cx> # P.S. Since you're asking about idiom, it would be more Pythonic to write: # # if self.mandatoryVar1 is None: # # using the identity test "is" rather than equality test "==", since there is # only one None. I'd write if not self.mandatoryVar1: but the first method works, too. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From skip at pobox.com Wed Jan 14 11:35:46 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 10:35:46 -0600 Subject: Safe prime numbers in Python In-Reply-To: <4005725d$1@nntp0.pdx.net> References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> <4005725d$1@nntp0.pdx.net> Message-ID: <16389.28642.425686.771599@montanaro.dyndns.org> >> Here's what I came up with using gmpy: ... Scott> I suspect it might be faster if you looked for the lower prime: Scott> def safe_primes(last=1): Scott> while True: Scott> last = gmpy.next_prime(last) Scott> other = last * 2 + 1 Scott> if gmpy.is_prime(other): Scott> yield other Yes, you're right. Starting at 2**1000 I found three safe primes quite quickly. Using my version I gave up waiting after seeing one safe prime float by. Note that the meaning of the last arg changes when converting to your formulation. Suppose I call safe_primes(2**1000). In my formulation, last identifies the smallest safe_prime I'm interested in. In your formulation, last identifies the smallest prime which defines a larger safe prime. To make them the same, your definition would have to change slightly: def safe_primes(last=1): last = long((last-1)/2) # assuming future float division... while True: last = gmpy.next_prime(last) other = last * 2 + 1 if gmpy.is_prime(other): yield other From michi.goettsche at gmx.de Thu Jan 1 08:45:40 2004 From: michi.goettsche at gmx.de (Michael_Goettsche) Date: Thu, 1 Jan 2004 14:45:40 +0100 Subject: Uploading a file with ftplib Message-ID: <200401011445.40820.michi.goettsche@gmx.de> Hi all, happy new year to all of you. i'm trying to upload a file called "log.txt" with ftplib and tried the following: Python 2.3.3 (#1, Dec 28 2003, 10:44:03) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ftplib import * >>> ftp = FTP( "ftp.tuxipuxi.de" ) >>> ftp.login( "xxxxxx", "xxxxx" ) '230 Login successful.' >>> #what now? i've tried out different things for "what now", for example: ftp.storlines( "STOR log.txt", open( "log.txt", "r" ) ) fh = open( "log.txt", "r" ) ftp.storlines( "STOR log.txt", fh ) ftp.storbinary( "STOR log.txt", fh ) a file with size 0 is created on the server, but it's empty. can anybody please tell me how to upload it properly? thanks in advance, regards, Michael. From gst at infrae.com Thu Jan 15 06:16:50 2004 From: gst at infrae.com (Guido Goldstein) Date: 15 Jan 2004 12:16:50 +0100 Subject: When I installed Silva-0.9.3 and restart Zope, I found ImportError like this - cannot import name ExpatError - References: Message-ID: Hi! On 13 Jan 2004 18:27:41 -0800 jangseungwook at nate.com (jang, seungwook) wrote: [...] > ImportError: cannot import name ExpatError > ------ [...] First of all, you should have asked this on the silva mailinglist. See http://lists.infrae.com/mailman/listinfo/silva-general To come to your actual problem: Please check if the python-xml package is installed and if so, if it's fully installed. HIH Guido G. -- Infrae, Rotterdam, The Netherlands http://www.infrae.com From gerrit at nl.linux.org Sun Jan 4 03:52:55 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 09:52:55 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: <3FF740ED.9020909@rogers.com> References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <20040103165041.GA31412@nl.linux.org> <3FF740ED.9020909@rogers.com> Message-ID: <20040104085255.GB13987@nl.linux.org> [Peter Otten] > >>I think both filename class and os.path functions can peacefully coexist. [Gerrit Holl (me)] > >Thanks for the links. > >(I think they don't, by the way) [Mike C. Fletcher] > Is that peaceful? I don't know. If there's a war, let's be honest, > os.path is going to take a good long while to defeat because it's there > and embedded directly into thousands upon thousands of scripts and > applications. We can fight a decent campaign, making a common module, > then getting it blessed into a standard module, encouraging newbies to > shun the dark old os.path way, encouraging maintainers to use the new > module throughout their code-base, etceteras, but os.path is going to > survive a good long while, and I'd imagine that being friendly toward it > would keep a few of our comrades off the floor. Sure, I don't think os.path would die soon, it will surely take longer than the string module to die. But I think there is a number of places where Python could be more object-oriented than it is, and this is one of them. The first step in making those modules more object-oriented is providing a OO-alternative: the second step is deprecating the old way, and the third step is providing only the OO-way. The third step will surely not be made until Python 3.0. The string module has made the first two steps. In my view, the time module has made the first step, although I'm not sure whether that's true. I would like to see a datetime module that makes the time module totally reduntant, because I never liked the time module: it doesn't fit into my brain properly, because it's not object oriented. Now, I try to use the datetime module whenever I can, but something like strptime isn't there. PEP 321 solves this, so I'd like time to become eventually deprecated after something DateUtil-like inclusion as well, but it probably won't. Hmm, the Zen of Python is not very clear about this: Now is better than never. Although never is often better than *right* now. ...so there must be a difference between 'now' and 'right now' :) > Just as a note, however, we haven't had a *huge* outpouring of glee for > the current spike-tests/implementations. So it may be that we need to > get our own little army in shape before attacking the citadel :) . Sure :) yours, Gerrit. -- 147. If she have not borne him children, then her mistress may sell her for money. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From theller at python.net Fri Jan 16 14:58:35 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 20:58:35 +0100 Subject: Python COM Server with C++ References: Message-ID: andre.bernemann at gmx.de (Andre Bernemann) writes: > Hi, > > I have written a Python COM Server with the help of Mark Hammond's > Book Programming Python on Win32. I used the CreateObjects method in > VB to access the COM Methods and all worked fine. Unfortunately, that > is not what i really want. First I'd like to make the COM Server > accessible from C++ and as a beside product I want to use early > binding within VB with the NEW operator. I've googled around alot, but > I still have not the complete picture of what to do. > > So far I think I have to create an IDL file to describe the interface > and compile it with the MIDL Compiler. There ist my first question. > What do I have to create first, the IDL file or the Python COM Server? > I'm a little bit confused about dispid's, the GUID's and naming > conventions. Do i need to make use of the makepy Utility in any way? I think you should create the typelib first, and then write a com object implementing the interfaces. I don't have done it myself, but I suggest to look into the spambayes project. It contains an outlook plugin, written by Mark Hammond. Most certainly a bag full of ideas. Thomas From aahz at pythoncraft.com Thu Jan 29 17:02:44 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2004 17:02:44 -0500 Subject: Get error "ImportError: No module named _tkinter" References: Message-ID: In article , Sebastian Stelzer wrote: > > import _tkinter # If this fails your Python may not be configured for Tk >ImportError: No module named _tkinter > >I'am using Suse Linux 9.0 with Python 2.3.3. You need to install Tck/Tk devel package, then rebuild Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From tjreedy at udel.edu Sat Jan 24 12:30:57 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Jan 2004 12:30:57 -0500 Subject: [OPINION] - does language really matter if they all dothe samething? References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com><028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net><4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: "Dietrich Epp" wrote in message news:58587302-4E30-11D8-8FAB-0003934ACDEC at zdome.net... > The rest of the post is dedicated to two examples of patterns which > don't quite fit into Python, but are used well in some projects written > in other languages. ... > My Lisp project related to an RPG and random > generation of items. It had lots of code like the following: > > (defun random-sword-magic-power (quality) > (choose-random-assoc > quality (poor medium good) > ((5 0 0) (glows-in-the-dark)) > ((3 3 0) (magically-silent)) > ((1 5 1) (elemental-power (select-random '(earth water air fire)))) > ((0 2 4) (magical-keen-edge)) > ((0 0 2) (append (random-sword-magic-power 'medium) > (random-sword-magic-power 'medium))))) > > The numbers on the left are probabilities relative to the other > probabilities in the same column. So, when generating a random 'poor' > magic quality of a sword, you have a 5/9 chance of getting 'glow in the > dark'. For a 'good' quality, you have a 2/7 chance of getting two > 'medium' qualities instead. It is difficult for me to imagine how one > would go about making this function more concise, to me it looks > downright minimal. The only thing I could see making it smaller would > be removing the parentheses, but they would have to be replaced by > something else such as commas or tabs. This seems straightforward: define a function by partial application of another, more general function. Nothing obviously Lisp specific. A Python equivalent needs _ instead of - in names and , instead of ' ' to separate seq items (with spaces optional). Maybe something like def random_sword_magic_power(quality): return choose-random-assoc( quality, (poor,medium,good), ((5,0,0), glows_in_the_dark), ... ((0,0,2), random_sword_magic_power(medium)+ random_sword_magic_power(medium)) ) perhaps with some of the apparent names quoted as literal strings instead, depending on programming style. > I'm not trying to say that all applications are like my application, > and I'm not trying to say that my application can't be written in > Python. I'm just saying that using macros, a paradigm that Python > doesn't even come close to supporting, makes reading and writing > functions like the above a lot easier. I knows of things for which this is true, but your example is not obviously one of them ;-). Does c_r_a really have to be evaluated at compile rather than run time? > You don't even need to know that 'choose-random-assoc' is a macro I didn't, but I am sure a Lisp programmer would have. > you just need to know how to use it. Part of knowing that is knowing what to quote and not to quote. Since macros quote args while functions evaluate them, (at least for some lisps, but I have not read CL rules), it would seem that maybe I would have to know. If c_r_a were a function, would the call be *exactly* the same? > I challenge anyone to come up with a better way to express the above > function in Python. If I think it's better, I'll write "PYTHON RULZ" > on my forehead and post a photo on the web. I slightly prefer my Python version, but I suspect you will not, so you remain safe. > I agree that functions are objects in Python. However, not everything > in Python is an object. Python is a language for manipulating defined types of information objects, and only such. Python code is a specific set of directions for doing so. That is what 'Everything in Python is an object' means and truthfully states. > For example, names are not objects. Of course not. Names, as such, are part of the Python grammar, with their own syntax (production) rule. They, along with statements, expressions, operators, puctuation, literals, and comments (etc), are parts of the programs in which we express our object manipulation intent. They, along with all the other grammatical units, are not the objects manipulated. However, a particular Python interpreter may choose to convert names to runtime objects for use in its runtime operations. (CPython does this for global names and generally for attributes but usually not for function locals.) And it may choose to make them available as strings at runtime. And it may have functions that 'dereference' runtime strings as if the equivalent sequence of chars had been written (unquoted) in the code. Hence some of the confusion. > In Objective C: ... > In Python, first try: > > def reset_settings(self): > try: > self.set_settings(self.delegate.default_settings(self)) > except AttributeError: > self.set_settings(some_fallback_value) > > But wait! What if there is an error in > self.delegate.default_settings() which raises an AttributeError? It > might confuse the hell out of a programmer who might go looking for the > bug in reset_settings(), because it's using the fallback value for some > odd reason. So we should reimplement it. If multiple parts of an expressions can raise the same exception, and you want to tell which part of the expression one comes from (so as to handle it differently), yes, you will have to compute the expression in stages, as you do here: > Python, second try: > > def reset_settings(self): > method = None > try: > method = self.delegate.default_settings > except AttributeError: > pass > if method: > self.set_settings(method(self)) > else: > self.set_settings(some_fallback_value) An alternative would have been to 'not do that'. Instead, differentiate the exceptions. Something like class MyAttributeError(AttributeError): pass def default_settings(self): try: ... except AttributeError: raise MyAttributeError Then 'first try' would, I believe, work same as 'second try' (but callers might need to know of MyAttributeError). > If you think this example is contrived, maybe you haven't worked with > the paradigms used in Objective-C very much. The example above was > used dozens of times in a class that I wrote in Objective-C which draws > a grid to the screen, for example, when it asks itself or its delegate > what color the grid should be, or the maximum scale allowed. The > practice is also used heavily by Apple's Cocoa libraries, which are my > favorite UI libraries of all time to program with. If you program in one language using idiomatic patterns from another language, you may need to write adapter functions, like reset_settings, that embody the pattern, to ease the translation. Or stick with the other language, if you prefer it, or switch patterns, which many of us have done, at least in part. Terry J. Reedy From quiteblack at yahoo.com Thu Jan 1 21:38:47 2004 From: quiteblack at yahoo.com (black) Date: Thu, 1 Jan 2004 18:38:47 -0800 (PST) Subject: undo and redo ? Message-ID: <20040102023847.78427.qmail@web21326.mail.yahoo.com> I'm coding with Tkinter and i wonder whether we could get current OS' clipboard available, and event more, anyone can inspires me how we can achieve undo and redo function ? thanx~ --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: From kevin at sb.org Thu Jan 29 13:40:15 2004 From: kevin at sb.org (Kevin Ballard) Date: Thu, 29 Jan 2004 13:40:15 -0500 Subject: Webhosting with Python References: <8089854e.0401290012.465ba364@posting.google.com> Message-ID: <2004012913401516807%kevin@sborg> On 2004-01-29 03:12:41 -0500, michael at foord.net (Fuzzyman) said: > > On 2004-01-28 11:34:43 -0500, michael at foord.net (Fuzzyman) said: > > > > I've recently starting using a very cheap web hoster who has python > > > 2.2 installed.... almost free hosting (but not quite)..... > > > > > Thought some of you guys might be interested.......... > > > > > http://www.xennos.com > > > > > Fuzzyman > > > How do you plan to make money off of this? > > I don't intend to make any money off it...... it's not my hosting firm > - but I know how long it took me to find cheap hosting with Python - > so I thought others might be interested. Oh, I misunderstood, I thought you were running that. So, then, how do *they* plan to make money off of that? -- "Remember, no matter where you go, there you are." -Buckaroo Banzai Kevin Ballard http://kevin.sb.org From mike at mhuffman.com Fri Jan 23 12:13:05 2004 From: mike at mhuffman.com (Mike Huffman) Date: 23 Jan 2004 09:13:05 -0800 Subject: Program Python in VIM References: <871xpsc5zf.fsf@tulip.whu.ca> <40103ee7.108130723@news.blueyonder.co.uk> Message-ID: <3ae9c53d.0401230913.64c7150d@posting.google.com> > > > :!python test.py > > > > > > > > > Is there any other way? I don't want to type 'python test.py' every time > > :!! > > repeats the last command. % is the symbol for "current file name," so I use: :w :!python % then thereafter in the current vi session: :!! It would be nice to be able to combine the write and shell command in one single command... Mike From sdfATexpertuneDOTcom Mon Jan 19 15:14:33 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Mon, 19 Jan 2004 20:14:33 -0000 Subject: HowTo distinguish between File and Directory References: <400C35C2.2C46EE3C@engcorp.com> Message-ID: Peter Hansen wrote in news:400C35C2.2C46EE3C at engcorp.com: > Scott F wrote: >> >> On Win32, is there a function in the standard modules that can >> take a pathname and return whether it refers to a File or a >> Directory? > > import os > os.path.isfile(name) > os.path.isdir(name) > > Is that adequate? Yes. I only did a dir(os) and thus didn't see the items under path. Thanks Peter (and Erik). Scott From JTesser at nbbc.edu Thu Jan 15 08:29:45 2004 From: JTesser at nbbc.edu (Jason Tesser) Date: Thu, 15 Jan 2004 07:29:45 -0600 Subject: wxwindows question Message-ID: <04875CB4331F0240A0AD66F97097865101137748@paul> Have you developed many apps that run on both Linux and Windows?? > -----Original Message----- > From: python-list-bounces+jtesser=nbbc.edu at python.org [mailto:python-list- > bounces+jtesser=nbbc.edu at python.org] On Behalf Of Jorge Godoy > Sent: Thursday, January 15, 2004 7:21 AM > To: python-list at python.org > Subject: Re: wxwindows question > > On Tuesday 13 January 2004 11:31 Jason Tesser wrote in > : > > > I am looking into using wxwindows for a gui to develop applications. > > The > > Apps need to be cross-platform Mac, Windows, Linux. I work > > For a bible college and will be developing applications ranging from > > online > > Registration to business office software. My question is what is > > your guys > > Experiences with wxwindows/python? What is the best tool that is > > stable > > I can use? I am looking into using wxDesigner with maybe Wing or > > Komodo. > > What do you guys think? > > I'm used to use wxGlade to create GUIs, but you can do it with other > tools as well. A friend of mine likes more BOA Constructor. But my > development platform is Linux... > > With regards to wxPython, I'm all for it. This a very good GUI and the > fact of it having native look on the OSs you cited above is a plus: > users won't be surprised with a new look in your application and > everything will be where they are used to get it. > > You can take a look at GNUMed for a nice design using wxPython. > > > See you, > -- > Godoy. > -- > http://mail.python.org/mailman/listinfo/python-list From john at doe.com Fri Jan 23 13:58:34 2004 From: john at doe.com (Brian Donovan) Date: Fri, 23 Jan 2004 18:58:34 GMT Subject: libxml2 w/ xpath python bindings Message-ID: Hi All, I'm trying to get xpath to work with the libxml2 python bindings. I'm using the following doc = libxml2.parseFile(filename) result = doc.xpathEval('//*') My test XML file has 10 nodes in it and I'm trying to get an element named 'element' (from an relaxng schema). If I use the xpath expression '//*' I'll get a list with 10 nodes including the element element as expected. If I try '//element' I'm getting an empty list with no errors. Any idea where I could be going wrong? Brian From christoph at mmc-startup.com Fri Jan 16 12:20:50 2004 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Fri, 16 Jan 2004 18:20:50 +0100 Subject: [Python-Dev] No more releases of MacPython-OS9? In-Reply-To: References: <20040115212700.GA7170@panix.com> Message-ID: <40081D72.2050607@mmc-startup.com> Jack Jansen wrote: > > On 15-jan-04, at 22:27, Aahz wrote: > >> On Thu, Jan 15, 2004, Jack Jansen wrote: >> >>> >>> 2. Buy an Installer VISE license. If I read >>> correctly this would cost $500 >>> per year, probably for the next 2 years. This will only happen if >>> someone else comes up with the money: I don't have it... >> >> >> Looks like 2.3 is the latest release currently available. There've been >> a lot of bugfixes since then. Do you have any download statistics for >> the OS9 version? (I.e. rough idea of how many people care.) > > > I have now:-) > > I'm a bit surprised at the results: MacPython-OS9 is a *lot* more > popular than I had thought.... Over the last few months I see about > 6000 MacPython downloads per month from my site (I didn't check > versiontracker and such, that'll be a couple hundred more, I guess). > For december the breakdown is 2000 downloads for 10.2, 2000 downloads > for 10.3 and 1700 downloads for OS9. The other 300 are various things > like source and such. 10.2 downloads are slowly declining, 10.3 > downloads increasing. > > But the fact that 30% of the MacPython users are still downloading the > OS9 binary really surprises me... > > So it seems MacPython-OS9 does have a place, still... What about asking if someone of these Mac Users has such a license? Christoph Becker-Freyseng From fumanchu at amor.org Sat Jan 3 03:47:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 3 Jan 2004 00:47:21 -0800 Subject: Project dream Message-ID: eltronic at juno.com wrote: > On 26 Dec 2003 12:36:48 -0800 hwlgw at NOSPAMhotmail.com (Will > Stuyvesant) writes: > > Suppose you have the time and the money to start a new project in > > Python. What would you like to do? > > What would your favorite be? > > a timer capable of alarms or starting programs with > various ways of specifying the event, weekly monthly > don't start untill, stop after date, user defined, etc. I've been needing to write this, as well, for my own apps. Here is a first attempt (*very* alpha); feedback/additions appreciated. http://www.aminus.org/rbre/python/recur.py http://www.aminus.org/rbre/python/test_recur.py Robert Brewer MIS Amor Ministries fumanchu at amor.org From virus.manager at st.com Tue Jan 27 09:50:11 2004 From: virus.manager at st.com (virus.manager at st.com) Date: Tue, 27 Jan 2004 14:50:11 -0000 Subject: Virus Alert Message-ID: <20040127145011.EABCBF986@zeta.dmz-eu.st.com> The mail message (file: kddh.zip) you sent to contains a virus. (on zeta) From gee_arr_why at ll.mit.edu Fri Jan 9 15:12:45 2004 From: gee_arr_why at ll.mit.edu (George Young) Date: Fri, 09 Jan 2004 15:12:45 -0500 Subject: Database interfacing References: Message-ID: On Fri, 09 Jan 2004 10:45:06 -0500, Michael T. Babcock wrote: > I'm working with databases (MySQL primarily) more and more with Python, > and having used PERL in the past for similar work, I'm wondering if > there are good tools for doing 'intelligent' selects/inserts to/from > dictionaries, etc. For example: > > data = {'FirstName': 'Michael', 'LastName': 'Babcock', 'Age': 99} > lastid = db.insert('Users', data) > > ... which would execute "INSERT INTO Users (FirstName, LastName, Age) > VALUES ('Michael', 'Babcock', 99)" > > And also helpful would be: > > data = db.query("dbname", "SELECT * FROM Users WHERE Age >= 99)") > > ... which would return me an array of dictionary items like: > > [ {'ID': 143, 'FirstName': 'Michael' ... }, {'ID': 242, ... }, ... ] > > Just curious, thanks (I've written a piece of code to generate the array > of dictionary results myself actually, but I'm sure someone else's is > better). You might find dbrow helpful: http://opensource.theopalgroup.com/ http://opensource.theopalgroup.com/files/db_row-0.8.tgz http://opensource.theopalgroup.com/files/db_row.py -- George Young gee arr why at ll.mit.edu [three letter username] From no at spam.edu Fri Jan 30 18:30:09 2004 From: no at spam.edu (Doug Holton) Date: Fri, 30 Jan 2004 17:30:09 -0600 Subject: Building a Course Management System In-Reply-To: References: Message-ID: Graham Fawcett wrote: > My employer (University of Windsor, Canada) has given me the go-ahead > to prototype a CMS (Course Management System, not Content > Management), written in Python, to be released under an open-source > license (choice of license is TBA). > > Course Management is a rather broad domain, covering content > management, communications tools (e.g., announcements, mail, chat, > discussion), assessment (quizzes, surveys, assignments, gradebook), > activity tracking, etc. Ideally a good CMS will be portal-based, to > aid in managing information- and work-flow. ... > -- Are there other Python-based CMS (Course management systems) that > I've overlooked? (Zope4Edu came to mind, but it's commerical, I think; > at least, there's no public CVS that I can find.) There is Fle3 (Zope-based): http://fle3.uiah.fi/ and http://www.zschool.org/main (Fle3 + Plone) See also Eclass.Builder: http://www.eclass.net/ Are you sure you wouldn't want to just adapt one of the existing PHP tools like ATutor or Moodle?: http://www.edtechpost.ca/pmwiki/pmwiki.php/EdTechPost/OpenSourceCourseManagementSystems http://holton.ltc.vanderbilt.edu/wiki/LearningManagementSystem That would be easier, esp. if you only have 8 weeks. But if you do start a python CMS, you have to first decide which web framework to use: http://www.python.org/cgi-bin/moinmoin/WebProgramming http://colorstudy.com/docs/shootout.html Good luck with it, -Doug From exarkun at intarweb.us Mon Jan 19 19:52:19 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 19 Jan 2004 19:52:19 -0500 Subject: speedy Python strings? In-Reply-To: References: Message-ID: <20040120005219.GA4873@intarweb.us> On Tue, Jan 20, 2004 at 01:43:24AM +0100, Uwe Mayer wrote: > Hi, > > thanks to previous help my wrapper for an abstract file type with variable > record length is working now. > I did some test runs and its awfully slow: > > I didn't want to read in the whole file at once and I didn't like to read it > step by step (contains 32 bit length terminated strings (Delphi) and 32bit > integers), so I read in i.e. 2MB, work on that buffer and if the buffer > goes empty i load some more 2MB, etc. > For this buffer I use ordinary strings: > > class myFile(file): > def read(self, *args): > ... > self.buffer += file.read(self, *args) > ... Doing the above in a loop has quadratic complexity. > > and after reading information from the buffer I remove the read part from > it: > > text = struct.unpack("L", self.buffer[:4]) > self.buffer = self.buffer[4:] The same is true for this line. Your program will be much faster if you make fewer string copies. "self.buffer[4:]" is a string copy, as is "self.buffer += anotherString". The buffer() builtin is one way to avoid copying, but another way is to simply keep track of how far into the string you are and use both low and high indexes when slicing, instead of repeatedly chopping the front off the string. Jp From craspe at mvtools.net Mon Jan 26 15:29:40 2004 From: craspe at mvtools.net (chris) Date: Mon, 26 Jan 2004 15:29:40 -0500 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <40156FB6.F71C19B0@engcorp.com> References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> Message-ID: <401578B4.9010300@mvtools.net> An HTML attachment was scrubbed... URL: From uce at ftc.gov Sun Jan 25 13:48:19 2004 From: uce at ftc.gov (Gordon Airport) Date: Sun, 25 Jan 2004 13:48:19 -0500 Subject: Text Animation In-Reply-To: <7b454334.0401242038.11404dac@posting.google.com> References: <7b454334.0401242038.11404dac@posting.google.com> Message-ID: <0cCdnahKj7_1kondRVn_iw@comcast.com> Fazer wrote: snip > Or maybe even > a rotating " | " that I have seen before in some installation > programs. > On each loop use the \b backspace character to move the cursor back, then overwrite with progressive characters for the spinner. This can look bad if the cursor is visible. From __peter__ at web.de Wed Jan 28 11:42:04 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jan 2004 17:42:04 +0100 Subject: isinstance() bug References: <20040128132225.GA10842@foof.i3.cz> <16407.54576.283608.505067@montanaro.dyndns.org> Message-ID: Michal Vitecek wrote: > does it make sense? Which reminds me - why do you want to put a package directory into your python path in the first place?. Before spending to much effort on fixing the problems that this practice entails, what are the benefits? Peter From antonmuhin at rambler.ru Thu Jan 8 10:53:57 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Thu, 08 Jan 2004 18:53:57 +0300 Subject: Calling a function dynamically In-Reply-To: <924a9f9c.0401080742.39eba581@posting.google.com> References: <924a9f9c.0401080742.39eba581@posting.google.com> Message-ID: Paradox wrote: > I would like to call a function whose name I supply at runtime. > Something like this but it didn't work > > functionName = 'run' > instance = ClassDef() > args = [1, 2] > > #want the dynamic equivalant of > #instance.run(*args) > > #This didn't work cause there was no __call__ attribute. Why? > value = instance.__call__[functionName](*args) > > > > > Thanks Joey This should work: getattr(instance, functionName)(*args) regards, anton. From JoeyTaj at netzero.com Sat Jan 10 15:43:30 2004 From: JoeyTaj at netzero.com (Paradox) Date: 10 Jan 2004 12:43:30 -0800 Subject: Calling a function dynamically References: <924a9f9c.0401080742.39eba581@posting.google.com> Message-ID: <924a9f9c.0401101243.6ad98242@posting.google.com> Thanks to all. The getattr was exactly what I need and the __getitem__ override is a nice touch. Dave Benjamin wrote in message news:... > In article , Peter Otten wrote: > > Paradox wrote: > > > >> I would like to call a function whose name I supply at runtime. > >> [snip] > > > > Here's a way to abuse the [] operator (implemented by __getitem__()) to > > dynamically select a method... > > > >>>> t["run"]("alpha", "beta", "gamma") > > run('alpha', 'beta', 'gamma') > > I wouldn't necessarily consider this abuse. This behavior (where > square-bracket- and dot-syntax are functionally equivalent) is the normal > behavior of JavaScript, and it makes dynamic lookup of method names a snap. > Python is more flexible in giving you the option to have separate namespaces > for items and attributes, but if it makes more sense for an object to merge > the two, I see nothing wrong with it. From nid_oizo at yahoo.com_remove_the_ Mon Jan 12 16:17:54 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 12 Jan 2004 16:17:54 -0500 Subject: How to call a system command with flexibility on Windows Message-ID: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> Hi everyone, I have a hard time trying to call a system command with the following capability on Windows: - Redirection of stdout and stderr. - Have the return code. The documentation seems to say it's only possible on Unix, have I missed something. Thx for your help. Nicolas From webmaster at keyphrene.com Fri Jan 9 15:11:45 2004 From: webmaster at keyphrene.com (webmaster at keyphrene.com) Date: Fri, 09 Jan 2004 20:11:45 GMT Subject: ANN: Naja 0.9.7 is now available Message-ID: <3fff0c13$0$29083$636a55ce@news.free.fr> Naja is a download manager and a website grabberl written in Python/wxPython. You can add some plugins (newsreader, newsposter, client FTP, client WebDAV) and take the control on your downloads since your office. Naja supports proxy (HTTP, HTTPS, FTP, SOCKS v4a, SOCKS v5), and use some authentication methods. The downloading maybe achieved by splitting the file being downloaded into several parts and downloading these parts at the same time (HTTP, HTTPS, FTP). Donwload speeds are increased by downloading the file from the mirrors sites, when the sites propose it. Others features: Csv filter Cheksums (CRC32, MD5, SHA1) newsreader, newsposter (uue, yEnc) CGI & WebDAV Server (only PROPFIND method for the moment) Web Interface basic and digest authentication for client and server Naja is available for download from the Keyphrene web site: http://www.keyphrene.com/products/naja From hat at se-126.se.wtb.tue.nl Fri Jan 16 03:37:42 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Fri, 16 Jan 2004 08:37:42 +0000 (UTC) Subject: data structures module References: <92c59a2c.0401152306.1c6a17f5@posting.google.com> Message-ID: On 15 Jan 2004 23:06:44 -0800, MetalOne wrote: > I am fairly new to Python. > Today, I wanted a priority queue. > I notice that Python does not have any sorted lists. > I know that I can call list.sort(), but that seems rather inefficient > to call every time an element is added. It is (probably). Instead, sort the list once, then for each element you insert, find the place using binary search, then insert the element with insert(). > I am wondering why there is not a module or modules containing many > common data structures. Probably because the native data structures of Python are rich enough to solve most problems in an adhoc way. > Has such a thing been decided against? Is it No, but what do you want added that isn't there, and is not easily constructed by a few lines of Python? Albert -- Unlike popular belief, the .doc format is not an open publically available format. From Florian.Lindner at xgm.de Sun Jan 4 14:06:45 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 04 Jan 2004 20:06:45 +0100 Subject: Let users execute but not view Message-ID: Hi! I have a python script which should be executed my normal users but they should not be able to view the sourcecode. Setting permissions to x only does not help, the python interpreter can not read the file. How can I do that? Thanks, Florian From alan_salmoni at yahoo.com Sun Jan 18 06:43:56 2004 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 18 Jan 2004 03:43:56 -0800 Subject: Python used in Freedom Force References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> <4006911e$0$327$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<4006911e$0$327$e4fe514c at news.xs4all.nl>... > Roberto Amorim wrote: > > > Not only Freedom Force, but also Severance: Blade of Darkness (3rd-person > > action medieval game) and Bridge Commander (Star Trek TNG simulator). > > And also Cyan's URU:Ages Beyond Myst. > I discovered some Python dlls and files in the game directory... > > --Irmen Perhaps all this stuff could be put onto the "Python Success Stories" part of the python.org website? It's not public, but if the language is clearly being used... Alan. From rays at blue-cove.com Thu Jan 29 18:19:50 2004 From: rays at blue-cove.com (Ray Schumacher) Date: Thu, 29 Jan 2004 15:19:50 -0800 Subject: wxNotebook question In-Reply-To: <40198A0D.70704@geochemsource.com> Message-ID: <5.2.0.4.0.20040129151313.02127918@blue-cove.com> At 02:32 PM 1/29/2004, Gandalf wrote: >How can I hide/show a page (wxNotebookPage) invisible of a wx.wxNotebook instance? >There is a GetPage() method which returns a wxNotebookPage but I could not find >any documentation in the help about this class. I use: C:\Python23\Lib\site-packages\wxPython\docs\wx.chm always, but http://www.orbtech.com/www/wx/epydoc/ is great, and shows inherited properties >I thought there will be a 'SetVisible' >or 'SetTabvisible' method but it seems to be a proxy for the root control on that page. >So I cannot even get method names by dir(self.notebook.GetPage(0)). Check the "Show()" method Show(self, show) (inherited from Window) Ray -------------- next part -------------- An HTML attachment was scrubbed... URL: From just at xs4all.nl Sat Jan 3 07:27:38 2004 From: just at xs4all.nl (Just) Date: Sat, 03 Jan 2004 13:27:38 +0100 Subject: Filename type (Was: Re: finding file size) References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: In article , Gerrit Holl wrote: > I propose to add a "filename" type to Python. > [ ... ] > A different solution to this problem would be to introduce "filename" > type to Python, a subclass of str. The "name" attribute of file would be of > this > type. This type would inherit a lot of os.path stuff: getsize becomes > simpler, more readable, and more object oriented, as do other os.path > functions. I think the alternatives look a lot more prety: > > OLD NEW > os.path.realpath(fn) fn.realpath() > os.path.getmtime(fp.name) fp.name.getmtime() > os.path.ismount(os.path.dirname(fp.name)) fp.name.dirname().ismount() > > It's more beatiful, simpler, flatter (#3), practical, obvious, easy. This has been proposed a few times, and even implemented at least once: http://www.jorendorff.com/articles/python/path/ I'm very much in favor of adding such an object, but I don't like Jason Orendorff's design all that much. There has been a discussion about it in the past: http://groups.google.com/groups?q=g:thl1422628736d&dq=&hl=en&lr=&ie=UTF-8 &oe=UTF-8&safe=off&selm=mailman.1057651032.22842.python-list%40python.org Just From peter at engcorp.com Mon Jan 12 12:11:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 12:11:26 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <4002D53E.CD17D2F6@engcorp.com> Ville Vainio wrote: > > If you choose Perl, you will at some regret your choice and consider > porting the app to Python. You save a lot of time/frustration by not > going there in the first place. This is only true if you actually know Python. If you carefully avoid acquiring any knowledge of or ability in Python, you will rarely regret the decision not to use Python for your project. -Peter From bdelmee at advalvas.REMOVEME.be Sat Jan 10 10:33:52 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Sat, 10 Jan 2004 16:33:52 +0100 Subject: Writing Files In-Reply-To: References: Message-ID: <40001b70$0$1115$6c56d894@feed0.news.be.easynet.net> Which statement did you try? Here's a one-liner that works: file( 'mydata.txt', 'w' ).write( "the python sleeps tonight" ) From claird at lairds.com Wed Jan 14 10:42:00 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 14 Jan 2004 15:42:00 -0000 Subject: I come not to bury C++, but to praise it... References: <40055560.7A0DCD0D@engcorp.com> Message-ID: <100aoq8efq3nt1e@corp.supernews.com> In article <40055560.7A0DCD0D at engcorp.com>, Peter Hansen wrote: . . . >John, thanks for the reminder about the origins of C++. (I suspect the majority >of readers in this group were not even programming during the CFront era >(roughly 1983-85?), and a history lesson is always good from time to time.) . . . I was still fussing with cfront in the early '90s. Its era *had* passed by then, though. -- Cameron Laird Business: http://www.Phaseit.net From eddie at holyrood.ed.ac.uk Mon Jan 26 12:33:42 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 26 Jan 2004 17:33:42 +0000 (UTC) Subject: BaseHTTPServer and class variables References: <88caaeda.0401260825.4db9a07d@posting.google.com> Message-ID: yin_12180 at yahoo.com (Yin) writes: >Hello. >I am using the basehttpserver to implement the HTTP protocol to serve >a fairly large lexicon that I have loaded as a dictionary in python. >Rather than writing a whole server, I would like to reuse the >BaseHTTPserver classes. I am interested in finding a way to serve the >dict without loading the whole dict into memory everytime an HTTP >request is made. The dict lives in local memory when it is loaded and >takes a long time to load. >Unfortunately with the basehttpserver.httpserver and >basehttpserver.requesthandlerclass, I am not finding it easy to define >a method to load the dict initially. Any thoughts are appreciated. >Ideally, in a do_GET for the requesthandlerclass, it'd be nice to be >able to access the dict as a class variable, but this doesn't work for >me. import BaseHTTPServer class Serv (BaseHTTPServer.BaseHTTPRequestHandler): def do_GET (self): path = self.path.strip('/').split('/') self.send_response (200) self.send_header ('Content-type', 'text/html') self.end_headers() self.wfile.write (self.dict[path[-1]]) # load dictionary D={'foo':1, 'bar':2} server = BaseHTTPServer.HTTPServer (('', 8080), Serv) server.RequestHandlerClass.dict = D server.serve_forever() Possibly not the best way but it should do unless someone less lazy than I responds. (Assuming I'm understanding your request correctly). Eddie From Kyler at news.Lairds.org Sun Jan 18 19:12:06 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Mon, 19 Jan 2004 00:12:06 GMT Subject: efficent test for array with only one value? Message-ID: <00ird1-dmd.ln1@jowls.lairds.org> I'm trying to discover if there's an efficient way to determine if all of the values of a Numeric array are the same. In C, I would search from the second value, checking each against the first value. The first one that doesn't match would trigger a False return value. If the loop completes, True would be returned. Looking through array functions, I'm not finding anything like that. I'm imagining that there should be something like an equal function (Is that Lisp I'm recalling?) that performs a[0,0] == a[0,1] == a[0,2] == ... and returns False as soon as it is known. I don't see that. I can, of course, iterate through all of the values, but it seems like there should be an efficient built-in function to do it. Thank you. --kyler From peter at engcorp.com Thu Jan 29 12:48:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Jan 2004 12:48:44 -0500 Subject: crc-16 References: <40191E1D.D912C1BB@engcorp.com> <1xpihkbe.fsf@python.net> Message-ID: <4019477C.82E8468F@engcorp.com> Thomas Heller wrote: > > Peter Hansen writes: > > [code snipped] > > Since you didn't post the unit tests, the code seems incomplete. > From a TDD kind of view, at least. I'm disappointed of you . It was developed in 2000, before the invention of TDD and before my group started doing XP or TDD, and by a co-op student at that. :-) -Peter From sombDELETE at pobox.ru Tue Jan 20 16:44:02 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Wed, 21 Jan 2004 00:44:02 +0300 Subject: New to Python: my impression v. Perl/Ruby References: Message-ID: "Ville Vainio" wrote in message news:du71xpue3rm.fsf at mozart.cc.tut.fi... > >>>>> "Phil" == Phil Tomson writes: > > Phil> Different strokes for different folks, I guess. I remember > Phil> that one of the first things I saw about Ruby was that even > Phil> interger literals were objects that can receive messages and > Phil> thinking how wonderful that was. As you say, you're not > > Ints are objects in python too: > > >>> a=1 > >>> a.__lshift__(1) > 2 > > Though "sending messages" to int literals is a syntax error. Try this: >>> (1).__lshift__(1) 2 -- Serge. From mir4uu at yahoo.com Thu Jan 15 12:08:46 2004 From: mir4uu at yahoo.com (mir nazim) Date: 15 Jan 2004 09:08:46 -0800 Subject: needed PyXPCOM tutorial. Message-ID: <425cc8d1.0401150908.287de0d8@posting.google.com> hi i m in need of a PyXPCOM tutorial. it should explain using python (instead of JavaScript) for creating apps. if any body can point me to some web resources or a printed book . thankz From raims at dot.com Tue Jan 20 15:52:50 2004 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 20 Jan 2004 21:52:50 +0100 Subject: an example of a singleton design pattern in python? References: Message-ID: <87ad4ifil9.fsf@mobile.foo> Daniel Ortmann writes: > Does anyone have an example of a singleton design pattern in python? Take a look at "Thinking in python" http://www.mindview.net/Books/TIPython -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From hgeldenhuys at gims.com Wed Jan 28 09:56:09 2004 From: hgeldenhuys at gims.com (Herman Geldenhuys) Date: Wed, 28 Jan 2004 16:56:09 +0200 Subject: Fw: Security validation issue Message-ID: <005201c3e5ae$dd781310$b10d10ac@metasalio> Oops! Sorry guys, wrong list... Apologies. ----- Original Message ----- From: Herman Geldenhuys To: python-list at python.org Sent: Wednesday, January 28, 2004 4:54 PM Subject: Security validation issue I've written a Zope product that exposes a "MenuItem". I add a menuItem in a Zope folder, and I have no difficulty accessing and editing it via the ZMI. I've written an xml-rpc-like protocol for Zope, that basically validates the security "manually". This menuItem has an attribute called "def getVersion(self):" which returns an int. This is the Code that prevents me from accessing the method in python, via my protocol: if not AccessControl.getSecurityManager().validate(None, object, attributes[-1]): raise UnauthorisedAccessException('Unauthorised: ' + originalAddress) object = > This is the method getVersion attributes[-1] = "getVersion" (string) UnauthorisedAccessException: Unauthorised: menus.administration.addUser.getVersion This code works for any other default Zope type, but not mine. Did I perhaps forgot a permission or something? I can access this fine via the ZMI, but when I validate it this way, python just starts cursing at me. Can somebody help? Thanks H -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Jan 8 13:48:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jan 2004 13:48:46 -0500 Subject: Why " ".some_string is often used ? References: Message-ID: "John Roth" wrote in message news:vvqghojub1dl07 at news.supernews.com... > And I agree, it's not entirely obvious why it's a string > method rather than a list method, Because, as I and others have posted several times in previous threads, and explicated with several examples, .join is NOT, NOT, NOT a list method, anymore than it is a tuple, dict, array, generator-iterator, or any other iteratable method. Taking 'string' genericly (as either type str or unicode), .join joins a sequence (iterable) of strings with a string. >since it operates on a list, not on a string. Huh? It operates on a sequence of strings. It has nothing to do with lists in particular. The builtinness and mutability of lists is irrelevant to this generic read-only operation. >>> help(str.join) # or ''.join or unicode.join or u''.join join(...) S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. Notice the absence of 'list'. Please do not confuse newbies with misinformation. > The only explanation that makes > sense is that, as a list method, it would fail if the list > contained something other than a string. This is true for any iterable that contains or yields something other than a string. Again, this function/method has nothing in particular to do with lists other than the fact that lists are one of several types of iterables. That is why join cannot be a list method and certain not just a list method. If 'iterable' were a concrete type/class/interface that all iterables had to inherit from in order to be recognized as an iterable, rather that an abstract protocol to be implemented, then one might suggest that join be an iterable method. But the statement above, with 'list' replaced by 'iterable', would still be true. Given that only a small finite subset of the unbounded set of iterable functions could be designated as basic by being made a method, one could easily argue that such designation should be restricted to functions potentially applicable to any iterable. Count, filter, map, reduce, iterate (apply for-loop body), and others in itertools would be such candidates. If there were an iterable-of-basestrings object subbing the hypothetical iterable object, then join might an appropriate method for that. But that is not the Python universe we have. Not do I necessarily wish it. The beauty of the abstract iterable/iterator interfaces, to me, is that they are so simple, clean, and genericly useful, without having to privilege anyone's idea of which sequence functions are 'basic'. Terry J. Reedy From http Sat Jan 24 03:59:56 2004 From: http (Paul Rubin) Date: 24 Jan 2004 00:59:56 -0800 Subject: efficient matching of elements a list References: Message-ID: <7xzncd67sj.fsf@ruckus.brouhaha.com> omission9 writes: > Suppose I have a lists of tuples > A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)] > and an int > i=1 > What is the fastest way in python to get out all the tuples from the > list whose first element is equal to i? t = [x for x in A_LIST if x[0] == i] > Seems to be very slow and there must be some super quick pythonic way > to do this maybe? > Any avice would be much appreciated!! Maybe there's some obscure faster way to do it but if you're really in a hurry, use psyco or pyrex or write a C extension. From featherstone80 at hotmail.com Thu Jan 15 19:34:14 2004 From: featherstone80 at hotmail.com (Narsil) Date: 15 Jan 2004 16:34:14 -0800 Subject: Quick question..... References: Message-ID: <379178f1.0401151634.556bb405@posting.google.com> I tried that. I get the following error message Traceback (most recent call last): File "E:\python\fun4b.py", line 80, in ? menu() File "E:\University\python\assign4b.py", line 49, in menu print sum(weektotlist) NameError: global name 'sum' is not defined What did I do wrong? TomN "Batista, Facundo" wrote in message news:... > featherstone80 wrote: > > #- numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] > #- > #- How would I get the total, and how would I get the average? > > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > ... > >>> numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] > >>> sum(numberlist) > 174 > >>> len(numberlist) > 10 > >>> sum(numberlist)/len(numberlist) > 17 > >>> from __future__ import division > >>> sum(numberlist)/len(numberlist) > 17.399999999999999 > > . Facundo From eric.brunel at N0SP4M.com Wed Jan 21 13:16:09 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Wed, 21 Jan 2004 19:16:09 +0100 Subject: Tkinter bitmap bug ? References: Message-ID: klappnase wrote: > Hello everyone, > > I have seen several threads here on this problem, but still cannot figure out > the solution. I want to create a window icon for a Tkinter application and tried > several things that are supposed to work. Here is a little demo of what I tried: > > #################################from Tkinter import * > > icon1 = ('''#define im_width 26 > #define im_height 25 > static char im_bits[] = { > 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,0x00,0x7e, > 0x00,0x00,0xe0,0x7f,0x00,0x00,0xff,0x63,0x00,0x00,0x3f,0x70,0x00,0x00,0x03, > 0x7e,0x00,0x00,0xe3,0x7f,0x00,0x00,0xff,0x63,0x00,0x00,0x3f,0x60,0x00,0x00, > 0x03,0x60,0x00,0x00,0x03,0x60,0x00,0x00,0x03,0x78,0x00,0x00,0x03,0x7c,0x00, > 0x00,0x03,0x7e,0x00,0xc0,0x03,0x7e,0x00,0xe0,0x03,0x3c,0x00,0xf0,0x03,0x18, > 0x00,0xf0,0x03,0x00,0x00,0xe0,0x01,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00, > 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };''') > > icon2 = ('R0lGODlhEAAMAKEAAAAAAAC18////////yH5BAEAAAIALAAAAAAQAAwAAAI' > 'glIFgyxcfVFsAQtmS3rjaH1Hg141WaT5ouprt2HHcUgAAOw==') > > def test0(): > root = Tk() > root.iconbitmap('@/somepath/window_icon.xbm') > root.mainloop() > > def test1(): > root = Tk() > root.bit = BitmapImage(data=icon1) > root.iconbitmap(root.bit) > root.mainloop() > > def test2(): > root = Tk() > bit = BitmapImage(data=icon1) > img = PhotoImage(data=icon2) > try: > b1 = Button(root, bitmap=bit) > b1.icon_ref = bit > b1.pack() > except: > pass > try: > b2 = Button(root, image=img) > b2.icon_ref = img > b2.pack() > except: > pass > root.mainloop() > > def test3(): > root = Tk() > img = PhotoImage(data=icon2) > top = Toplevel(root) > l = Label(top, image=img) > l.icon_ref = img > l.pack() > root.iconwindow(top) > root.mainloop() > > if __name__=='__main__': > test0() > > ############################################# > > Running the test0() function works fine, however I wanted to not to carry an > external bitmap file around, so I tried to pass the bitmap data to a BitmapImage > object. As you saw, this won't work: the only way I found to set an iconbitmap on a window is using the '@/path/to/file' syntax. Why not keep the data for your image in the code and generate a temporary file from this data? Then you can use the '@...' stuff without having to carry an external file everywhere. Just don't forget to delete the file when your application exits. We do that all the time and it works quite fine. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From peter at engcorp.com Mon Jan 12 09:34:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 09:34:34 -0500 Subject: Writing Files References: Message-ID: <4002B07A.47479678@engcorp.com> Lucas Raab wrote: > > What is the best way to go about writing to files?? Whenever I insert a > statement to write results to a file there's nothing in it. Any > suggestions?? Always post example code and/or the exception traceback when asking such a question. You might also take a glance at http://www.catb.org/~esr/faqs/smart-questions.html -Peter From adalke at mindspring.com Sat Jan 3 13:25:24 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 03 Jan 2004 18:25:24 GMT Subject: Abstract Syntax Tree conundrum References: Message-ID: Lonnie Princehouse: > The compiler's AST implementation seems better for (1), but I can't > for the life of me figure out how to compile it into a code object, Does this help? >>> a Traceback (most recent call last): File "", line 1, in -toplevel- a NameError: name 'a' is not defined >>> import compiler >>> compiler.parse("a=3+4") Module(None, Stmt([Assign([AssName('a', 'OP_ASSIGN')], Add((Const(3), Const(4))))])) >>> x=_ >>> x.filename = "" >>> compiler.pycodegen.ModuleCodeGenerator(x).getCode() at 00A28360, file "", line 1> >>> c = _ >>> exec c >>> a 7 >>> The compiler module is somewhat cumbersome (eg, the need to force a 'filename' attribute above) and woefully underdocumented, but much better to use than the results of the parser structure. > and there's not even an apparent way to convert it back into source (I > suppose I could write a function to do this, but it seems like there > should be a better way). That one I don't know about. decompyle seems like your best bet. Andrew dalke at dalkescientific.com From mcfletch at rogers.com Fri Jan 30 04:08:18 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 30 Jan 2004 04:08:18 -0500 Subject: what is the use of weakref? In-Reply-To: <1jipe1-fqq.ln1@news.slu.edu.ph> References: <1jipe1-fqq.ln1@news.slu.edu.ph> Message-ID: <401A1F02.7030101@rogers.com> Well, for the last few versions of Python, it's primary use has been finding ways to crash the interpreter ;) . Seriously, they are used when you want to avoid having cycles in your data structures, so that, for instance, variables will be immediately garbage collected rather than hanging around waiting for the garbage collector to find them. They are also useful in some decoration patterns where you want to cache compiled values for a large number of objects with uncertain lifetimes. If you were to use hard-refs to the client objects from the cache you'd keep the objects alive (presumably the cache is reachable all the time). A weak-ref allows the client objects to go away so that the cached values can be cleared and the memory reclaimed (OpenGLContext does this with compiled scenegraph node representations, btw). HTH, Mike ali wrote: >i've seen a lot of times in programs but until now i still dont know the use >of the weakref module... any help will be appreciated... thanks... > >ali > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From peter at engcorp.com Tue Jan 6 08:30:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 08:30:33 -0500 Subject: question: Python or Lua for rejuvenation of old PCs? References: Message-ID: <3FFAB879.32FBC22B@engcorp.com> David LeBlanc wrote: > > I have seen discussion of Python being run on small x86 systems with 64mb of > ram and a 64mb CF card "disk". More specifically, we have Python running on 100MHz 486-compatible systems with 32MB of RAM and 32MB of CF, without significant issues. -Peter From mhammond at skippinet.com.au Mon Jan 26 18:16:14 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 27 Jan 2004 10:16:14 +1100 Subject: python service running on Win Xp, but failing on Win NT Workstation :( In-Reply-To: References: Message-ID: Ringwraith wrote: > maybe another hint ... > > While installing I got the error message: > > "The procedure entry point RegisterServiceCtrlHandlerExW > could not be located in the dynamic link library ADVAPI32.dll" > Slowly but surely, support for Win95 and NT are being dropped off (generally in the process of enhancing the framework, as was done for services in this case). I would accept contributions that fall-back to the previous behaviour, but I have no problems with suggesting that people who use a very old OS can also use an old Python/win32all to suit. Mark. From skip at pobox.com Wed Jan 21 19:37:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 18:37:17 -0600 Subject: shelve slow in python 2.3.3 for windows In-Reply-To: <322u00ppo44l8g003dgtcu8lna432to411@4ax.com> References: <322u00ppo44l8g003dgtcu8lna432to411@4ax.com> Message-ID: <16399.6973.312882.309012@montanaro.dyndns.org> >> whichdb.whichdb("a") >> report under both versions? My wild-ass guess is that the underlying >> anydbm module finds dumbdbm under 2.3.3 and something more industrial >> strength like bsddb under 2.2. Marco> Skip, Marco> you are right! Sort of. Marco> Under 2.3.3: 'dbhash' Marco> Under 2.2: 'bsddb185' 'dbhash' and 'bsddb185' are really the same beast. Marco> Now the question is: is it possible to use bsddb185 with python Marco> 2.3.3? You're barking up the wrong tree. That's not the problem. Skip From jmeile at hotmail.com Tue Jan 6 13:27:23 2004 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 6 Jan 2004 19:27:23 +0100 Subject: Programming language from python References: <4f0a9fdb.0312300447.47c421ec@posting.google.com> Message-ID: <3ffafe0b$1@pfaff2.ethz.ch> > I've heard they have some very good programming languages over at > Venus :-) > > A programming language is like a tool, it's good for some things and > not good for other things. As a general purpose langauge it's as good > a they come. I agree. I think you can't say that a language is the best because you like it. Indeed, you can't do such affirmation, for languages have their weaknesses too. Afterall languages are made by people and we aren't perfect. Another think is that you can say that a language is good because it's easy to code (like python), or because it offers a programming environment like the visual suite of microsoft, or because it's fast when excecuting the code written on it, or because of its comunity, or because of its number of modules. I think there are many factors and needs depending on the person who is going to use it. So, for each person this selection will be different. Anyway, sometime ago, somebody posted this links here: http://www.bagley.org/~doug/shootout/index2.shtml http://www.ipd.uka.de/~prechelt/Biblio/jccpprt_computer2000.pdf They may help you on your election. Regards, Josef From http Mon Jan 19 15:31:00 2004 From: http (Paul Rubin) Date: 19 Jan 2004 12:31:00 -0800 Subject: secure unpickle? References: <8765f8xe8p.fsf@pobox.com> Message-ID: <7xsmiby92z.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > marshal > > The docs have similar warnings, though. Marshal has an additional problem, which is that the format can change incompatibly between one Python version and another. So if you use marshal for object persistence and upgrade your Python instance, you can be screwed. There is no clearly good solution to this issue. There are a couple of bug entries in Sourceforge about it. From bkelley at wi.mit.edu Thu Jan 8 19:28:59 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 09 Jan 2004 00:28:59 GMT Subject: MySQLDB multiple cursor question In-Reply-To: References: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu> <3ffd7dbe$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: AdSR wrote: > > See PEP 249, read about the "threadsafety" global variable. > There you have it. MySQLdb has a threadsafety level of 1 which means that connections can't be shared but the module can. I guess I'm doing it the right way now :) > HTH, > > AdSR From peter at engcorp.com Fri Jan 9 09:12:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:12:38 -0500 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> <6AlLb.134$hd.7718@news2.e.nsc.no> Message-ID: <3FFEB6D6.BF92551E@engcorp.com> Thomas Weholt wrote: > > "Peter Hansen" wrote: > > Twisted is similar to Medusa in about the same way that Linux is similar > to, say, CPM... > > Ok, my point was that they are similar type of frameworks, if we compare > medusa and the webserver-part of Twisted. They don't do much without a bit > of work/coding. Unlike Zope which comes with a UI, user-management etc > running the minute you finish the installation procedure. > > I might not know the entire technical aspect of medusa and twisted, not > really enough to compare them in detail. I was referring to the way a > programmer will have to use them, based on my experience using the two. In > that regard they're somewhat similar and different from zope. If I'm > completly off track here feel free to enlighten me. Thomas, you're completely ON track here... I just wanted to emphasize that Twisted is much more polished and sophisticated. I'd even have to say, as a programmer using them, that Twisted does actually provide a simpler and cleaner API. It and Medusa are much closer in concept than either is to Zope, though, as you say. -Peter From mnations at airmail.net Sat Jan 3 16:36:30 2004 From: mnations at airmail.net (Marc) Date: 3 Jan 2004 13:36:30 -0800 Subject: Freezing win32com with multi platform/version support References: <4378fa6f.0312310903.1ea2d50b@posting.google.com> Message-ID: <4378fa6f.0401031336.66ddabb5@posting.google.com> ttt Hopefully someone will reply to my message in a bottle... From sombDELETE at pobox.ru Sat Jan 10 09:08:21 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 10 Jan 2004 17:08:21 +0300 Subject: Python And Internationalization maybe a pre-pep? References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> Message-ID: "Brian Kelley" wrote in message news:YSKLb.10550$5V2.17781 at attbi_s53... > Martin v. Loewis wrote: > > Brian Kelley wrote: > >> So, am I being silly, redundant or just plain different? > > > > I do wonder what kind of application are you looking at. How > > many strings? How many different translators? How often do > > the strings change? Are the strings presented to the immediate > > user of the application sitting in front of the terminal where > > the application is running, or are there multiple simultaneous > > accesses to the same application, e.g. through a Web server? > > The number of strings doesn't really matter I think as long as you can > automatically generate the ones that need to be translated. Both > mechanisms do this. > > I hadn't previously thought about multiple simultaneous users but this > could fit in nicely. After some experimentation with the string > classes, it turns out that as long as the __repr__ of the string stays > unchanged, i.e. in this case the original english version, then the > __str__ of a string (the locale specific changes) can change willy-nilly > and not affect things like dictionaries and class name lookups. If you keep translator instance in a global variable then users won't be able to select different languages. > I suppose that there really isn't much difference in the long run as > long as tools exist that make these translations relatively easy but I > can't quite shake the thought of trying to teach my brother, a > biologist, how to enable localization in his code in an easy manner. > > Anyway, you have made good points and maybe all I need are some better > integrated tools for localizing my applications. Exactly. At the link you provided, the description of creating database of strings for translation takes 120 words whereas the whole text is about 2500 words. And I beleive collection of strings to translate should take place only before a release. How often is it? > > Since you brought it up, how does gettext handle multiple users? Does > each user get a different gettext library (dll) instance? No. Different translator class instances. Your pre-pep doesn't help here. -- Serge. From martin at v.loewis.de Fri Jan 16 02:38:23 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 16 Jan 2004 08:38:23 +0100 Subject: Binary strings, unicode and encodings In-Reply-To: <265368cb.0401151138.37a3a47b@posting.google.com> References: <265368cb.0401151138.37a3a47b@posting.google.com> Message-ID: <400794EF.8080002@v.loewis.de> Laurent Therond wrote: > Now, if I write bencode('failure reason') into a socket, what will I get > on the other side of the connection? Jp has already explained this, but let me stress his observations. > a) A sequence of bytes where each byte represents an ASCII character A sequence of bytes, period. 'failure reason' is a byte string. The bytes in this string are literally copied from the source code .py file to the cStringIO object. If your source code was in an encoding that is an ASCII superset (such as ascii, iso-8859-1, cp1252), then yes: the text 'failure reason' will come out as a byte string representing ASCII characters. Python has a second, independent string type, called unicode. Literals of that type are not simply written in quotes, but with a leading u''. You should never use the unicode type in a place where byte strings are expected. Python will apply the system default encoding to these, which gives exceptions if the Unicode characters are outside the characters supported in the system default encoding (which is us-ascii). You also should avoid byte string literals with non-ASCII characters such as 'string?'; use unicode literals. The user invoking your script may use a different encoding on his system, so he would get moji-bake, as the last character in the string literal does *not* denote LATIN SMALL LETTER E WITH ACUTE, but instead denotes the byte '\xe9' (which is that character only if you use a latin-1-like encoding). HTH, Martin From tleese22 at yahoo.com Sun Jan 18 18:16:14 2004 From: tleese22 at yahoo.com (Taylor Leese) Date: Sun, 18 Jan 2004 15:16:14 -0800 (PST) Subject: FreeBSD 4.8 and Python-2.2.3 compiling error Message-ID: <20040118231614.67193.qmail@web60506.mail.yahoo.com> I'm hoping somebody can point me in the right direction. I am getting this error when trying to compile Python-2.2.3 on FreeBSD 4.8: gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c In file included from Include/Python.h:62, from Modules/python.c:3: Include/pyport.h:462: #error "could not set LONG_MAX in pyport.h" *** Error code 1 Stop in /home/cleverli/public_html/Python-2.2.3. gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c In file included from Include/Python.h:62, from Modules/python.c:3: Include/pyport.h:462: #error "could not set LONG_MAX in pyport.h" *** Error code 1 Here's the config.log: This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. configure:628: checking MACHDEP configure:671: checking for --without-gcc configure:723: checking for --with-cxx= configure:760: checking for c++ configure:795: checking whether the C++ compiler (c++ ) works configure:811: c++ -o conftest conftest.C 1>&5 configure:837: checking whether the C++ compiler (c++ ) is a cross-compiler configure:854: checking for gcc configure:967: checking whether the C compiler (gcc ) works configure:983: gcc -o conftest conftest.c 1>&5 configure:1009: checking whether the C compiler (gcc ) is a cross-compiler configure:1014: checking whether we are using GNU C configure:1042: checking whether gcc accepts -g configure:1076: checking how to run the C preprocessor configure:1156: checking for AIX configure:1181: checking for minix/config.h configure:1230: checking for Cygwin environment configure:1263: checking for mingw32 environment configure:1294: checking for executable suffix configure:1325: checking for --with-suffix configure:1343: checking for case-insensitive build directory configure:1381: checking LIBRARY configure:1414: checking LINKCC configure:1443: checking LDLIBRARY configure:1480: checking for ranlib configure:1513: checking for ar configure:1583: checking for a BSD compatible install configure:1648: checking for --with-pydebug configure:1721: checking whether gcc accepts -OPT:Olimit=0 configure:1758: checking whether gcc accepts -Olimit 1500 configure:1799: checking whether pthreads are available without options configure:1851: checking whether gcc accepts -Kpthread configure:1898: checking for ANSI C header files configure:2023: checking for dlfcn.h configure:2023: checking for fcntl.h configure:2023: checking for grp.h configure:2023: checking for limits.h configure:2023: checking for langinfo.h configure:2023: checking for locale.h configure:2023: checking for ncurses.h configure:2023: checking for poll.h configure:2023: checking for pthread.h configure:2023: checking for signal.h configure:2023: checking for stdarg.h configure:2023: checking for stddef.h configure:2023: checking for stdlib.h configure:2023: checking for thread.h configure:2023: checking for unistd.h configure:2023: checking for utime.h configure:2023: checking for termios.h configure:2023: checking for sys/audioio.h configure:2023: checking for sys/file.h configure:2023: checking for sys/lock.h configure:2023: checking for sys/modem.h configure:2023: checking for db_185.h configure:2023: checking for db.h configure:2023: checking for sys/param.h configure:2023: checking for sys/poll.h configure:2023: checking for sys/select.h configure:2023: checking for sys/socket.h configure:2023: checking for sys/time.h configure:2023: checking for sys/times.h configure:2023: checking for sys/un.h configure:2023: checking for sys/utsname.h configure:2023: checking for sys/wait.h configure:2023: checking for pty.h configure:2023: checking for term.h configure:2023: checking for libutil.h configure:2023: checking for ndbm.h configure:2023: checking for db1/ndbm.h configure:2023: checking for gdbm/ndbm.h configure:2023: checking for sys/resource.h configure:2023: checking for netpacket/packet.h configure:2070: checking for dirent.h that defines DIR configure:2108: checking for opendir in -ldir configure:2194: checking for clock_t in time.h configure:2235: checking for mode_t configure:2268: checking for off_t configure:2301: checking for pid_t configure:2334: checking return type of signal handlers configure:2375: checking for size_t configure:2408: checking for uid_t in sys/types.h configure:2444: checking size of int configure:2483: checking size of long configure:2522: checking size of void * configure:2561: checking size of char configure:2600: checking size of short configure:2639: checking size of float configure:2678: checking size of double configure:2717: checking size of fpos_t configure:2757: checking for long long support configure:2767: gcc -c -g -O2 conftest.c 1>&5 configure:2781: checking size of long long configure:2822: checking for uintptr_t support configure:2832: gcc -c -g -O2 conftest.c 1>&5 configure: In function `main': configure:2828: syntax error before `x' configure:2828: `x' undeclared (first use in this function) configure:2828: (Each undeclared identifier is reported only once configure:2828: for each function it appears in.) configure:2828: `uintptr_t' undeclared (first use in this function) configure:2828: syntax error before `0' configure: failed program was: #line 2825 "configure" #include "confdefs.h" int main() { uintptr_t x; x = (uintptr_t)0; ; return 0; } configure:2888: checking size of off_t configure:2930: checking whether to enable large file support configure:2945: checking size of time_t configure:2993: checking for pthread_t configure:3003: gcc -c -g -O2 conftest.c 1>&5 configure:3015: checking size of pthread_t configure:3059: checking for --enable-toolbox-glue configure:3111: checking for --enable-framework configure:3134: checking for dyld configure:3157: checking SO configure:3172: checking LDSHARED configure:3241: checking CCSHARED configure:3277: checking LINKFORSHARED configure:3322: checking CFLAGSFORSHARED configure:3338: checking for dlopen in -ldl configure:3385: checking for shl_load in -ldld configure:3468: checking for t_open in -lnsl configure:3508: checking for socket in -lsocket configure:3595: checking for --with-libs configure:3612: checking for --with-signal-module configure:3638: checking for --with-dec-threads configure:3655: checking for --with-threads configure:3713: checking for _POSIX_THREADS in unistd.h configure:3741: checking for mach/cthreads.h configure:3780: checking for --with-pth configure:3806: checking for pthread_create in -lpthread configure:3818: gcc -o conftest -g -O2 conftest.c -lpthread 1>&5 /usr/libexec/elf/ld: cannot find -lpthread configure: failed program was: #line 3808 "configure" #include "confdefs.h" #include void * start_routine (void *arg) { exit (0); } int main() { pthread_create (NULL, NULL, start_routine, NULL) ; return 0; } configure:3835: checking for pthread_detach configure:3888: checking for kernel/OS.h configure:3927: checking for pthread_create in -lpthreads configure:3972: checking for pthread_create in -lc_r configure:4183: checking if PTHREAD_SCOPE_SYSTEM is supported configure:4231: checking for pthread_sigmask configure:4286: checking for usconfig in -lmpc configure:4332: checking for thr_create in -lthread configure:4400: checking if --enable-ipv6 is specified configure:4439: gcc -o conftest -g -O2 conftest.c -lc_r 1>&5 /usr/lib/libc.so: WARNING! setkey(3) not present in the system! /usr/lib/libc.so: warning: this program uses gets(), which is unsafe. /usr/lib/libc.so: warning: mktemp() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: WARNING! des_setkey(3) not present in the system! /usr/lib/libc.so: WARNING! encrypt(3) not present in the system! /usr/lib/libc.so: warning: tmpnam() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: warning: this program uses f_prealloc(), which is not recommended. /usr/lib/libc.so: WARNING! des_cipher(3) not present in the system! /usr/lib/libc.so: warning: tempnam() possibly used unsafely; consider using mkstemp() configure:4456: checking if RFC2553 API is available configure:4467: gcc -c -g -O2 conftest.c 1>&5 configure:4497: checking ipv6 stack type configure:4662: checking for --with-cycle-gc configure:4684: checking for --with-pymalloc configure:4703: checking for --with-wctype-functions configure:4725: checking for --with-sgi-dl configure:4749: checking for --with-dl-dld configure:4778: checking for dlopen configure:4835: checking DYNLOADFILE configure:4866: checking MACHDEP_OBJS configure:4889: checking for alarm configure:4889: checking for chown configure:4889: checking for chroot configure:4889: checking for clock configure:4889: checking for confstr configure:4889: checking for ctermid configure:4889: checking for ctermid_r configure:4889: checking for execv configure:4889: checking for flock configure:4889: checking for fork configure:4889: checking for fsync configure:4889: checking for fdatasync configure:4889: checking for fpathconf configure:4889: checking for ftime configure:4889: checking for ftruncate configure:4889: checking for gai_strerror configure:4889: checking for getgroups configure:4889: checking for getlogin configure:4889: checking for getpeername configure:4889: checking for getpid configure:4889: checking for getpwent configure:4889: checking for getwd configure:4889: checking for hstrerror configure:4889: checking for inet_pton configure:4889: checking for kill configure:4889: checking for link configure:4889: checking for lstat configure:4889: checking for mkfifo configure:4889: checking for mktime configure:4889: checking for mremap configure:4889: checking for nice configure:4889: checking for pathconf configure:4889: checking for pause configure:4889: checking for plock configure:4889: checking for poll configure:4889: checking for pthread_init configure:4889: checking for putenv configure:4889: checking for readlink configure:4889: checking for select configure:4889: checking for setegid configure:4889: checking for seteuid configure:4889: checking for setgid configure:4889: checking for setgroups configure:4889: checking for setlocale configure:4889: checking for setregid configure:4889: checking for setreuid configure:4889: checking for setsid configure:4889: checking for setpgid configure:4889: checking for setuid configure:4889: checking for setvbuf configure:4889: checking for snprintf configure:4889: checking for sigaction configure:4889: checking for siginterrupt configure:4889: checking for sigrelse configure:4889: checking for strftime configure:4889: checking for strptime configure:4889: checking for symlink configure:4889: checking for sysconf configure:4889: checking for tcgetpgrp configure:4889: checking for tcsetpgrp configure:4889: checking for tempnam configure:4889: checking for timegm configure:4889: checking for times configure:4889: checking for tmpfile configure:4889: checking for tmpnam configure:4889: checking for tmpnam_r configure:4889: checking for truncate configure:4889: checking for uname configure:4889: checking for unsetenv configure:4889: checking for waitpid configure:4889: checking for _getpty configure:4889: checking for getpriority configure:4947: checking for openpty configure:4997: checking for openpty in -lutil configure:5045: checking for forkpty configure:5145: checking for fseek64 configure:5145: checking for fseeko configure:5145: checking for fstatvfs configure:5145: checking for ftell64 configure:5145: checking for ftello configure:5145: checking for statvfs configure:5201: checking for dup2 configure:5201: checking for getcwd configure:5201: checking for strdup configure:5201: checking for strerror configure:5201: checking for memmove configure:5258: checking for getpgrp configure:5312: gcc -c -g -O2 conftest.c 1>&5 configure: In function `main': configure:5308: too many arguments to function `getpgrp' configure: failed program was: #line 5305 "configure" #include "confdefs.h" #include int main() { getpgrp(0); ; return 0; } configure:5331: checking for setpgrp configure:5385: gcc -c -g -O2 conftest.c 1>&5 configure:5404: checking for gettimeofday configure:5458: gcc -c -g -O2 conftest.c 1>&5 configure:5480: checking for getaddrinfo configure:5496: gcc -o conftest -g -O2 conftest.c -lc_r -lutil 1>&5 /usr/lib/libc.so: WARNING! setkey(3) not present in the system! /usr/lib/libc.so: warning: this program uses gets(), which is unsafe. /usr/lib/libc.so: warning: mktemp() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: WARNING! des_setkey(3) not present in the system! /usr/lib/libc.so: WARNING! encrypt(3) not present in the system! /usr/lib/libc.so: warning: tmpnam() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: warning: this program uses f_prealloc(), which is not recommended. /usr/lib/libc.so: WARNING! des_cipher(3) not present in the system! /usr/lib/libc.so: warning: tempnam() possibly used unsafely; consider using mkstemp() configure:5501: checking getaddrinfo bug configure:5596: gcc -o conftest -g -O2 conftest.c -lc_r -lutil 1>&5 /usr/lib/libc.so: WARNING! setkey(3) not present in the system! /usr/lib/libc.so: warning: this program uses gets(), which is unsafe. /usr/lib/libc.so: warning: mktemp() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: WARNING! des_setkey(3) not present in the system! /usr/lib/libc.so: WARNING! encrypt(3) not present in the system! /usr/lib/libc.so: warning: tmpnam() possibly used unsafely; consider using mkstemp() /usr/lib/libc.so: warning: this program uses f_prealloc(), which is not recommended. /usr/lib/libc.so: WARNING! des_cipher(3) not present in the system! /usr/lib/libc.so: warning: tempnam() possibly used unsafely; consider using mkstemp() configure:5636: checking for getnameinfo configure:5691: checking whether time.h and sys/time.h may both be included configure:5726: checking whether struct tm is in sys/time.h or time.h configure:5760: checking for tm_zone in struct tm configure:5830: checking for st_rdev in struct stat configure:5864: checking for st_blksize in struct stat configure:5898: checking for st_blocks in struct stat configure:5935: checking for time.h that defines altzone configure:5969: checking whether sys/select.h and sys/time.h may both be included configure:5982: gcc -c -g -O2 conftest.c 1>&5 configure:5996: checking for addrinfo configure:6030: checking for sockaddr_storage configure:6067: checking whether char is unsigned configure:6130: checking for working const configure:6207: checking for working volatile configure:6216: gcc -c -g -O2 conftest.c 1>&5 configure:6233: checking for working signed char configure:6242: gcc -c -g -O2 conftest.c 1>&5 configure:6259: checking for prototypes configure:6268: gcc -c -g -O2 conftest.c 1>&5 configure:6283: checking for variable length prototypes and stdarg.h configure:6302: gcc -c -g -O2 conftest.c 1>&5 configure:6318: checking for bad exec* prototypes configure:6327: gcc -c -g -O2 conftest.c 1>&5 configure:6344: checking if sockaddr has sa_len member configure:6355: gcc -c -g -O2 conftest.c 1>&5 configure:6371: checking for bad static forward configure:6419: checking whether va_list is an array configure:6434: gcc -c -g -O2 conftest.c 1>&5 configure:6450: checking for gethostbyname_r configure:6631: checking for gethostbyname configure:6697: checking for __fpu_control configure:6743: checking for __fpu_control in -lieee configure:6795: checking for --with-fpectl configure:6820: checking for --with-libm=STRING configure:6841: checking for --with-libc=STRING configure:6865: checking for hypot configure:6923: checking what malloc(0) returns configure:6976: checking for wchar.h configure:7017: checking size of wchar_t configure:7061: checking what type to use for unicode configure:7136: checking whether byte ordering is bigendian configure:7229: checking whether right shift extends the sign bit configure:7272: checking for getc_unlocked() and friends configure:7318: gcc -E conftest.c >/dev/null 2>conftest.out configure:7352: checking for rl_pre_input_hook in -lreadline configure:7397: checking for rl_completion_matches in -lreadline configure:7441: checking for broken nice() configure:7487: checking whether mvwdelch is an expression configure:7525: checking whether WINDOW has _flags configure:7571: checking for socklen_t configure:7632: checking for build directories - Taylor __________________________________ Do you Yahoo!? Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes http://hotjobs.sweepstakes.yahoo.com/signingbonus From swalters_usenet at yahoo.com Mon Jan 5 14:17:52 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 19:17:52 GMT Subject: intellectual property agreements and open source . was - Re: Why does this fail? [2] References: <84fc4588.0401042209.60cdb724@posting.google.com> Message-ID: |Thus Spake Dave Murray On the now historical date of Sun, 04 Jan 2004 23:54:57 -0700| > After re-reading this part, I can see that it is an idea that I like. > How does participating in open source work for someone (me) who has > signed the customary intellectual property agreement with the > corporation that they work for? Since programming is part of my job, > developing test solutions implemented on automatic test equipment (the > hardware too) I don't know if I would/could be poison to an open source > project. How does that work? I've never participated. If all the work is > done on someone's own time, not using company resources, > yadda-yadda-hadda-hadda, do corporate lawwwyaahhhs have a history of > trying to dispute that and stake a claim? No doubt, many of you are in > the same position. IANAL (I Am Not A Lawyer) As suggested elsewhere, consult your legal counsel. Dig up that NDA. Go to the corporate lawwwyaahhhs and ask them to provide you with a clear delineation in writing. Have your legal counsel look over that document to make sure it says what you think it says. Be prepared to explain the difference between general purpose tools and special purpose tools directly related to the job. Specifically, be prepared to explain how contributing to general purpose tools can allow you to more quickly (and inexpensively, time is money yadda-yadda) develop the special purpose tools. By contributing to, say, a web spider when your business involves stress-testing web servers would allow you to leverage the knowledge and work of others towards the companies goals. As I understand it, no open-source license has yet been tested in court, so your guess is as good as anyone's about how much risk is involved. That's why everyone is waiting with baited breath over the SCO vs IBM fiasco. It may be that first legal test. In fact, go to www.groklaw.net and read up on the SCO vs IBM suit. That's as good of a starting place as any. Oh, and be sure to take a look at the specific license involved in a project you contribute to. Some licenses, like BSD, have little to no restrictions on how an individual or company uses the code. Most, such as GPL require that you simply distribute the source and any changes you've made if and only if you distribute the product or any products including code from the project to a third party (in the case of companies, that means outside the companies.) YMMV and again, IANAL HTH Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From sombDELETE at pobox.ru Sat Jan 10 08:12:10 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 10 Jan 2004 16:12:10 +0300 Subject: LC_MONETARY formatting References: <3FFF38DE.1050603@v.loewis.de> Message-ID: "Colin Fox" wrote in message news:pan.2004.01.10.00.01.07.962349 at cfconsulting.ca... > On Sat, 10 Jan 2004 00:27:26 +0100, Martin v. Loewis wrote: > > > Colin Fox wrote: > <..> > >> I would like to be able to print "$12,345.60" > >> > >> Is there a format string, or function, or *something* that will take > >> advantage of the monetary formatting info in the locale object? > > > > No. > > I can't believe that I'm the first person who ever wanted to print a > number as a currency value. Why go to the great lengths of what's provided > in localeconv(), only to leave it up to every single programmer to > re-implement the solution? What a waste of time and effort! Compared to the effort of all humanity to move forward the waste of time and effort is dwarf > > I can't see any reason not to provide a monetary converter within locale, > particularly when it's obviously got all the info it needs. It's not as simple as you think. The proper way to do it is to have locale aware money type. > > > > > IOW, LC_MONETARY is useless for financial applications - if the amount > > is in ?, using the locale's currency symbol would be wrong. > > That's true whether you use LC_MONETARY or not. Unless you know the units > your number is in, you can't assign a symbol to it. That's why LC_MONETARY (strfmon) is broken. Have you read strfmon manual? > In my case, I have > numbers that are always in either Canadian or US dollars, so the dollar > sign is fine, and the thousands-separator value is fine. You should have money class. It should be a subclass of FixedPoint class. If you want to deal with Canadian or US dollars only it's as simple as: class Dollars(FixedPoint): def __init__(self,amount): super(Dollars,self).__init__(amount) def __str__(self): if self < 0: return locale.format("-$%.2f",-self,True) else: return locale.format("$%.2f",self,True) No warranty, of course, that it works and fulfills all your needs. >>> locale.format("$%.2f",1000000000000,True) '$1,000,000,000,000.00' -- Serge. From gsmith at oxfam.org.uk Thu Jan 29 10:41:25 2004 From: gsmith at oxfam.org.uk (Graham) Date: Thu, 29 Jan 2004 15:41:25 -0000 Subject: Pausing python programs Message-ID: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> How can I cause a python program to pause/suspend execution for a period of time? I am checking status of an external system and only want to check every second as opposed to my current which checks may times a secnod and hogs my cpu in the process!!! Thank you to anyone who can help. Graham Smith PeopleSoft Technical Team Leader OXFAM GB +44 (1865) 313255 gsmith at oxfam.org.uk From mwh at python.net Tue Jan 6 07:29:44 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 6 Jan 2004 12:29:44 GMT Subject: Tkinter and OS X 10.3? References: <7ba1cb43.0312301205.30156acf@posting.google.com> Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article , > Russell E. Owen wrote: > > > >You are almost certainly typing python instead of pythonw at the > >terminal prompt. This results in exactly the error described. (I'm not > >sure why there are two commands instead of python doing whatever extra > >magic pythonw does.) > > I'd guess that pythonw imports more stuff; if you want to run a non-GUI > application (say in a cron job), that would be wasteful. pythonw connects to the window server. If there is no window server (logged in in text mode or via ssh) this could be considered a disadvantage. I don't know if it's possible to try to connect and do something sensible if it fails, but given the separatedness of python & pythonw, I'd guess not. Cheers, mwh -- If I had wanted your website to make noise I would have licked my finger and rubbed it across the monitor. -- signature of "istartedi" on slashdot.org From jjl at pobox.com Tue Jan 20 09:49:25 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jan 2004 14:49:25 +0000 Subject: personal document mgmt system idea References: Message-ID: <87wu7mwu8a.fsf@pobox.com> sandskyfly at hotmail.com (Sandy Norton) writes: > I have been mulling over an idea for a very simple python-based > personal document management system. The source of this possible > solution is the following typical problem: > > I accumulate a lot of files (documents, archives, pdfs, images, etc.) > on a daily basis and storing them in a hierarchical file system is > simple but unsatisfactory: > > - deeply nested hierarchies are a pain to navigate > and to reorganize > - different file systems have inconsistent and weak schemes > for storing metadata e.g. compare variety of incompatible > schemes in windows alone (office docs vs. pdfs etc.) . > > I would like a personal document management system that: [...] > The system should promote the following simple pattern: [...] Pybliographer 2 is aiming at these features (but a lot more besides). Work has been slow for a long while, but several new releases of pyblio 1 have come out recently, and work is taking place on pyblio 2. There are design documents on the web at pybliographer.org. Why not muck in and implement what you want with Pyblio? [...] > My initial prototyping efforts involved creating a single test table > in > mysql (later to include fields for dublin-core metadata elements) > and a BLOB field for the data itself. My present dev platform is > windows XP pro, mysql 4.1.1-alpha, MySQL-python connector v.0.9.2 > and python 2.3.3 . However, I will be testing the same app on Mac OS X > and Linux Mandrake 9.2 as well. ATM Pyblio only runs on GNOME, but that's going to change. > The first problem I've run into is that mysql or the MySQL > connector crashes when the size of one BLOB reaches a certain point: > in this case an .avi file of 7.2 mb . > > Here's the code: [...] > _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone > away') > >Exit code: 1 > > > > My Questions are: > > - Is my test code at fault? > > - Is this the wrong approach to begin with: i.e. is it a bad idea to > store the data itself in the database? Haven't read your code, but the error certainly strongly suggests a MySQL configuration problem. John From Florian.Lindner at xgm.de Thu Jan 22 08:15:50 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Thu, 22 Jan 2004 14:15:50 +0100 Subject: prog/lib to draw graphs References: Message-ID: netnews.upenn.edu wrote: > Florian Lindner wrote: >> Hello, >> I'm looking for a program or python library to draw graphs. >> They should look like the that: >> >> >> /--------\ /--------\ >> | Node A | ------ belongs to ----> | Node B | >> \--------/ \--------/ >> >> Which is a result of the function call like that: >> >> connectNodes(firstNode, secondNode, description, lineStyle) >> connectNodes("Node A", "Node B", "belongs to", dashed) >> >> It should have a open scalable vector format as output (DVI, SVG, PDF, >> ...) and should be able to make automatic optimal placement of the items. >> Do you know something like that? >> Thx, >> Florian > > Try graphviz: > > http://www.research.att.com/sw/tools/graphviz/ > > > I think there's a python interface to graphviz floating around (Google > it), but it's trivial to write a Python routine that spits out valid > Graphviz "dot" files. > > In the case of your example, the contents of the dot file would be > something like: > > digraph G{ > "Node A" -> "Node B" [label="belongs to"]; > } Thanks! (to all) Does GraphViz also support the automated optimal placement of nodes? I'll have many nodes... Thx, Florian From news at grauer-online.de Sun Jan 18 09:12:46 2004 From: news at grauer-online.de (Uwe Grauer) Date: Sun, 18 Jan 2004 15:12:46 +0100 Subject: Boa: printing source in the Editor In-Reply-To: <4jwOb.40507$DF4.24648@amsnews02.chello.com> References: <4jwOb.40507$DF4.24648@amsnews02.chello.com> Message-ID: F.A. Pinkse wrote: > Dear Group, > > > Does the Editor of BOA has a print function? > > If it has one, where is it placed in the menu hierarchy? > > Thanks for the answers. > > Frans. > > Using boa 0.2.8 i see Print under the Edit menu of the Editor. Uwe From necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com Fri Jan 23 22:29:42 2004 From: necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com (necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com) Date: Fri, 23 Jan 2004 22:29:42 -0500 Subject: get "yesterday's" date in iso format References: <877jzjb7o4.fsf@mrbun.watterson> Message-ID: On Fri, 23 Jan 2004 17:54:15 +0100, Gerrit Holl wrote: > Tim Heaney wrote: >> necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com writes: >> > >> > I am trying to find a simple way to get "yesterday's" date. >> >> Since time.time() gives the time in seconds since the epoch, you could >> just subtract a day from that to get yesterday. > > Even better: > >>>> from datetime import date, timedelta >>>> (date.today() - timedelta(1)).day > 22 Excellent. I guess I skipped the timedela section of the datetime module. Thanks a lot, David From pln at cosmic.stanford.edu Mon Jan 5 19:40:15 2004 From: pln at cosmic.stanford.edu (Patrick L. Nolan) Date: Tue, 6 Jan 2004 00:40:15 +0000 (UTC) Subject: Grab input&output of program on Windows Message-ID: I'm going nuts trying to port an application from Linux to Windows. We have a python/Tkinter script which runs a C++ application. It starts it with popen4 and communicates through the two pipes. It reads text output from stdout until a prompt appears, then sends commands through stdin. On Windows it seems to get all tangled up in the buffering of the two streams. When the script just reads stdout, it seems to be OK. As soon as the first command is sent to stdin, stdout blocks forever. I tried borrowing an idea from the Python Cookbok, recipe 9.6. I made the streams nonblocking and put a call to select in a loop. The results were promising on Linux, but there was a mysterious error message on Windows. I think select works only for sockets, not pipes. This seems like the sort of thing that might be solved by expect. Will that work? Is there some other way? -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From miki.tebeka at zoran.com Wed Jan 28 02:46:16 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 27 Jan 2004 23:46:16 -0800 Subject: Best way to compare a list? References: <7b454334.0401271739.59267018@posting.google.com> Message-ID: <4f0a9fdb.0401272346.157e8960@posting.google.com> Hello Faizan, > What do you guys think? The best/fastest way of comparing lists. >>> l1 = range(10) >>> l2 = range(10) >>> l1 == l2 True HTH. Miki From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 16:42:00 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 13:42:00 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: "Serv? Lau" wrote in message news:100bbb6kj9m03a4 at corp.supernews.com... > "Paul Boddie" wrote in message > news:23891c90.0401140223.344b22af at posting.google.com... > > Erik Max Francis wrote in message > news:<4004EC9E.1E2E2893 at alcyone.com>... > > > > > > There are plenty of things you can get out of starting, getting involved > > > with, and approaching open source projects. A legion of personal > > > servants is not going to be one of them, and only a crass idiot would > > > think otherwise. > > > > As far as I've been able to discover, life is just one long cocktail > > party in Brandon's honour. So it isn't exactly surprising that > > everyone appears to him as just another waiter with a tray of drinks. Is there something fundamentally *wrong* with recognizing how useless people are to your purposes? > Well said, that's just how he sounds. > I think I'm gonna create a new sig > > "I won't stop denigrating OS people for being incapable of fulfillng the > kinds of projects I have in mind > Brandon J. Van Every" Except that I didn't say that, so it wouldn't be within your legal rights to quote me as having said such. If you want to quote me, you're going to have to *quote* me, not paraphrase me in your own idiom. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From ashleylloyd at hotmail.com Fri Jan 9 06:01:12 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Fri, 09 Jan 2004 11:01:12 +0000 Subject: Newbie: Getting Image From Disk into Buffer Message-ID: Thanks very much for your reply. I ended up getting this working by using: f=open(fileName','rb',-1) buf=f.read() I'd swear I tried this before with no success, but I can't have (or more than likely did it in the wrong way, somehow) - so sorry to everyone whose time I've wasted by asking such a stupid question! Anyway, thanks very much once again for your reply. Cheers Ashley >From: woodsplitter at rocketmail.com (David Rushby) >To: python-list at python.org >Subject: Re: Newbie: Getting Image From Disk into Buffer >Date: 8 Jan 2004 13:27:49 -0800 > >"Ashley Lloyd" wrote in message >news:... > > I have been trying to get an image into an interbase database (see >earlier > > post), and came across a post made on a list some time ago (I ignored it > > earlier as we use kinterbasDB not gvib, but I thought I'd try using it >in > > kinterbasDB anyway): > > ... > > it always seems to place > > into the database a string of either the name of the image on disk > > ('c:/image.bmp', say), or text such as the following: > > > >In the 'c:/image.bmp' case, you're inserting the file's name (string); >in the "" case, >you're inserting an open file object, which is repr()ed into a string >for storage. Instead, you need to insert the *contents* of the file >as a string, e.g., the return value of the file object's read() >method. > > > ... but if someone could tell me how I get the image into blob_data > > (which I assume is a buffer), I'd be very grateful. > >http://sourceforge.net/forum/forum.php?thread_id=889866&forum_id=30917 >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From kramb64 at hotmail.com Wed Jan 21 18:20:23 2004 From: kramb64 at hotmail.com (kramb64 at hotmail.com) Date: Thu, 22 Jan 2004 00:20:23 +0100 Subject: shelve slow in python 2.3.3 for windows References: Message-ID: <322u00ppo44l8g003dgtcu8lna432to411@4ax.com> On Wed, 21 Jan 2004 15:47:20 -0600, Skip Montanaro wrote: > whichdb.whichdb("a") >report under both versions? My wild-ass guess is that the underlying anydbm >module finds dumbdbm under 2.3.3 and something more industrial strength like >bsddb under 2.2. Skip, you are right! Under 2.3.3: 'dbhash' Under 2.2: 'bsddb185' Now the question is: is it possible to use bsddb185 with python 2.3.3? Thanks. Ciao. Marco. From rick_muller at yahoo.com Sat Jan 17 23:19:07 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 17 Jan 2004 20:19:07 -0800 Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: <5eb8fb88.0401172019.358535c4@posting.google.com> Tim Churches wrote in message news:... However, if > some dead wood is ever removed from the Python standard library, I would > love to see gmpy take its place. Thanks to the gmpy (and GMP) developer, Amen to that. GMP is a sweet library, and gmpy makes it so easy to play around with I can waste all sorts of time when I should be getting real work done. From newsgroups at jhrothjr.com Sat Jan 3 12:45:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 12:45:34 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: "Frank" wrote in message news:3987e01c.0401030832.114c6f2a at posting.google.com... > Hi, > > can anybody help with the following problem? > > In C++ > > i = 5 / 10 and > i = -5 / 10 both have the same result 0. > > In python > > i = 5 / 10 gives me 0 as expected, but > i = -5 / 10 gives -1 as result. > > Is this a feature or a bug? I remember Delphi gave me the same result as > C++. That's a feature. Integer division is explicitly defined in Python to do exactly that. The basic thing to remember is that the *correct* mathematical result of dividing one integer by another integer is a rational. Python does not have a rational data type, so it has to pick one of the multitude of possible ways of rounding a non-integral result to an integer. There is no universally right answer to this process: the "right" answer to any rounding problem is what the customer wants it to be. John Roth > > TIA, > Frank From bart_nessux at hotmail.com Tue Jan 13 09:23:59 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 13 Jan 2004 09:23:59 -0500 Subject: Make a function call itself after set amount of time Message-ID: How do I make a function call itself every 24 hours. Also, is there a way to start the program automatically w/o depending on the OS functions like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and xp. Below is an example of what I'm trying to do. TIA def ipconfig_email(): from email.MIMEText import MIMEText import smtplib import time import os u = "user name" #Change This to user's name. f = "my-email-addy" t = "my-email-addy" fp0 = os.popen("ipconfig /all", "r") fp1 = os.popen("psinfo -d -s", "rb") msg = MIMEText(fp0.read() + fp1.read()) fp0.close() fp1.close() msg["Subject"] = "%s's IPconfig Report" % u msg["From"] = f msg["To"] = t h = "my.smtp.server" s = smtplib.SMTP(h) s.sendmail(f, t, msg.as_string()) s.quit() time.sleep(86400) #24 hour sleep HOW_DO_I_CALL_THE_FUNCTION_AGAIN? ipconfig_email() From maketo at otaku.freeshell.org Sun Jan 25 22:29:39 2004 From: maketo at otaku.freeshell.org (Ognen Duzlevski) Date: Mon, 26 Jan 2004 03:29:39 +0000 (UTC) Subject: ReadDirectoryChangesW (windows) Message-ID: Hi all, I am new to win32 programming and was wondring if anyone can enlighten me on a question I have: there is a win32file function I would like to use - ReadDirectoryChangesW() and its parameters are, according to below: ---- ReadDirectoryChangesW(handle, size, bWatchSubtree, dwNotifyFilter, overlapped) retrieves information describing the changes occurring within a directory. Parameters: handle : int Handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right. size : int Size of the buffer to allocate for the results. bWatchSubtree : int Specifies whether the ReadDirectoryChangesW function will monitor the directory or the directory tree. If TRUE is specified, the function monitors the directory tree rooted at the specified directory. If FALSE is specified, the function monitors only the directory specified by the hDirectory parameter. dwNotifyFilter : int Specifies filter criteria the function checks to determine if the wait operation has completed. This parameter can be one or more of the FILE_NOTIFY_CHANGE_* values. overlapped=None : PyOVERLAPPED Must be None ------ I would like to use this function asynchronously to open a directory using the FILE_FLAG_OVERLAPPED flag so that I can later on wait for a change to be signalled and so that I can use this in a service waiting with e.g. WaitForSingleObject(). I don't have much experience using pywin32 and I am puzzled by the last line "Must be None". Does this mean asynchronous access is not supported? Or am I ready to actually RTFM if someone can politely point me to one? :) Thanks, Ognen From jcarlson at uci.edu Thu Jan 22 11:51:05 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 08:51:05 -0800 Subject: Assignment to slice References: <20040121130236.D8E3.JCARLSON@uci.edu> <20040121185145.C648.JCARLSON@uci.edu> Message-ID: <20040122084443.0264.JCARLSON@uci.edu> > >Hell, I think that Perl variables are f-ing weird. In the dozen > >languages I've learned over the years, Perl is the only one where you > >have to say hey, you this variable I'm accessing now, it is a scalar, > >not a string. What the hell is that? On the other hand, Perl users > >have gotten used to it, and don't think it is strange. > > This seems to have emerged from a Perl tendency to > implement values as strings wherever possible. You're > saying "Use the stringness of this variable, rather than, > say, its intness." Weak typing, but it's what lets Perl > automatically fill in missing array values with some > assurance that it won't all go kaboom in the next statement. Mel, There are many ways to assure "that it won't go all kaboom in the next statement". Perl's choice is just that, a choice. Every language designer gets to make more than a few (close to semi-infinite) choices in how their language is going to work. The rest of us get on with our lives and use the language. Please let us get on with just writing code in whatever language we feel we need to, and stop talking about the different individual choices that every language designer made in the last 10 years. - Josiah From vincent at visualtrans.de Sun Jan 4 10:06:10 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 4 Jan 2004 16:06:10 +0100 Subject: importing References: <231bc96c.0401031249.12cff6d7@posting.google.com> Message-ID: "Boomer" schrieb im Newsbeitrag news:231bc96c.0401031249.12cff6d7 at posting.google.com... | Hi all, | I'm new to python which explains my problems with this. I'm trying | to import a .csv file(from excel) into some fields on my company's | software system(which interfaces to an sql database. Each row in this | .csv file needs to be split into smaller strings and each respective | string applied to it's field in the software then it's saved and the | next row starts, here's the code I've come up with so far. | | f=open ("book1.csv", "r") | s=f.readline () | while s != "": | print s | l = s.split(s,",",(11)) | PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0]) | PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}") | PlayIt.SetFieldContent ("SY012ADM1", "001bez", l[1]) | PlayIt.SetFieldContent ("SY012ADM1", "005agr", l[2]) | PlayIt.SetFieldContent ("SY012ADM1", "006agr", l[3]) | PlayIt.SetFieldContent ("SY012ADM1", "009kst", l[4]) | PlayIt.SetFieldContent ("SY012EHM1", "005laeh", l[5]) | PlayIt.SetFieldContent ("SY012EHM1", "006lauf", l[6]) | PlayIt.SetFieldContent ("SY012EHM1", "011vkuf", l[7]) | PlayIt.SetFieldContent ("SY012SDM1", "012fest", l[8]) | PlayIt.SetFieldContent ("SY012PRM1", "001tpr", l[9]) | PlayIt.SetFieldContent ("SY012PRM1", "002wpr", l[10]) | PlayIt.SetFieldContent ("SY012PRM1", "003plpr", l[11]) | PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}") | s=f.readline () | f.close () | | here's the error | | Traceback (innermost last): | File "", line 5, in ? | AttributeError: 'string' object has no attribute 'split' | | the furthest I get is when I remove the s.split all together then I | can actually watch it import the first field correctly and switch | focus to the second field where it prints a comma and then hangs and | eventually gives the | argument 3: expected string list found | Someone told me I need to import the string module using "import | string" somewhere in my code, but when I do this I get an error | stating that no such module exists. I run this as script inside a | macro from another program and I believe the version of python this | program uses is 2.2.1. Hi "Boomer" if you are using version V3.91 or lower of your companies software, the embedded Python will still be at 1.52. If it is V4.20 it'll be Python 2.2.2. Since I know that the Python standard library is not shipped with the software you are referring to, you need to either install Python (in the version corresponding to your version) on your local machine, or an accessible share and set your environment properly. Looking at your example I am pretty confident that your are using V391 which embedds 1.52. As a quick fix: check if either "string.pyc" or "string.py" lives in your w32 directory or - if you are executing via a .pli file - in the directory "playit.exe" lives in. If that is not the case, get either module in the correct version and copy it to the directories just described. This will fix your problem (until you try to import another module ofcourse). HTH Vincent Wehren | | Does anyone have any ideas? Any help would be wonderful!!! From skip at pobox.com Thu Jan 15 15:14:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Jan 2004 14:14:27 -0600 Subject: [OT] AS/400 In-Reply-To: References: <4005cd03@news.mt.net.mk> Message-ID: <16390.62627.412838.31268@montanaro.dyndns.org> >>> (will not mention that it works on AS/400, the best minicomputer(!) >>> ever made). >> >> Why is it the best minicomputer ever made? I really want to know! Jarek> Since nobody ever produced any other. Only IBM produced machines Jarek> that can be called "midrange" (something between microcomputer Jarek> and "real computer", the famous S/390 mainframe). They still use Jarek> this terminology. You seem to be forgetting (at least) DEC's VAX line of computers. Data General and PR1ME had computers classed as "mini" computers also. I'm sure there were others. Skip From kramb64 at hotmail.com Wed Jan 21 16:11:00 2004 From: kramb64 at hotmail.com (kramb64 at hotmail.com) Date: Wed, 21 Jan 2004 22:11:00 +0100 Subject: shelve slow in python 2.3.3 for windows Message-ID: I already submitted a bug, but I'm curious to know if anybody ran into this. Try this program on Windows with python 2.3.3 and with python 2.2: import shelve a=shelve.open("a", "c") for x in xrange(10000): a[str(x)]=x print str(x) + "\r", a.close() After about 7000/8000 insertions, the program gets so slow... With python 2.2 it ends in a blink! Really strange, isn't it? Ciao. Marco. From hasan at slac.stanford.edu Wed Jan 28 13:03:09 2004 From: hasan at slac.stanford.edu (Adil Hasan) Date: Wed, 28 Jan 2004 10:03:09 -0800 Subject: Problem connecting to https using ZSI (openssl problem) - python2.3 In-Reply-To: References: Message-ID: Hello, As a follow up to this. I noticed that the port that I was contacting the server on was not correct. Now, I have moved forward to an access denied message (I'll post that error in another news group). Hope this is helpful, adil On Tue, 27 Jan 2004, Adil Hasan wrote: > > Hello, > I'm having problems trying to use ZSI to connect to a https url. > I give the command and I get prompted for my X509 cert pass-phrase, but > the program dies with an openssl error. > > Here's my code: > > from ZSI import * > u='' > n='https://shahzad.fnal.gov/edg-voms-admin/uscms/services/VOMSAdmin' > b = Binding(url=u,ns=n, ssl=1, \ > host='shahzad.fnal.gov',port=8080, \ > cert_file='/home/hasan/.globus/usercert.pem', \ > key_file='/home/hasan/.globus/userkey.pem') > b.listCAs() > > The traceback I get is: > Enter PEM pass phrase: > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 28, in __call__ > requesttypecode=TC.Any(self.name, aslist=1)) > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 131, in RPC > self.Send(url, opname, obj, **kw) > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 184, in Send > self.h.connect() > File "/usr/local/python2.3/lib/python2.3/httplib.py", line 961, in > connect > ssl = socket.ssl(sock, self.key_file, self.cert_file) > File "/usr/local/python2.3/lib/python2.3/socket.py", line 73, in ssl > return _realssl(sock, keyfile, certfile) > socket.sslerror: (1, 'error:140770FC:SSL > routines:SSL23_GET_SERVER_HELLO:unknown protocol') > > Any ideas about this? Does anyone know how to solve this problem? I have > seen one post here with a similar problem, but haven't seen any > resolution. > > Help! > > thanks, adil > From webmaster at beyond-thoughts.com Fri Jan 9 13:41:32 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 09 Jan 2004 19:41:32 +0100 Subject: PRE-PEP: new Path class; sorting and __cmp__ In-Reply-To: References: Message-ID: <3FFEF5DC.1080804@beyond-thoughts.com> As I pointed out path.__cmp__ should not be used for e.g. comparing filesizes. But features like sorting on filesizes are very useful. I'm not sure if Gerrit Holl already meant this in his conclusion on "Comparing files" in the PEP. I'll outline it a bit ... I propose a callable singleton class which only instance we assign to sort_on (defined in the path-module). It will have methods like: filesize, extension, filename, etc. They will all be defined like: def filesize(self, path1, path2): try: return path1._cmp_filesize(path2) except XXX: # catch Exceptions that are raised because path1 doesn't know how to compare with path2 (for different path-subclasses) XXX try: return (-1) * path2._cmp_filesize(path1) # is this the best way to do this? except XXX: XXX raise YYY # "path1 and path2 can't be compared on filesize; class1 and class2 are not compatible" And def __call__(self, *args): if len(args) == 0: return self.filesize # example! elif len(args) == 1: # allow comparing uncommon things for subclasses of path e.g. ServerName/IPs for FTPPath ... def cmp_x(path1, path2, what=str(args[0])): # like filesize but pathCmpFunc= getattr(path1, '_cmp_'+what) return pathCmpFunc(path2) # Catch exceptions ... return cmp_x elif len(args) == 2: # default comparison return self.filesize(path1, path2) # example! else: raise "Won't work ... FIXME" Then we can have things like: l= [path1, path2, path3] l.sort(path.sort_on.filesize) l.sort(path.sort_on.extension) .... I like this :-) What do You think? Christoph Becker-Freyseng From fuf at mageo.cz Wed Jan 28 10:41:19 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 16:41:19 +0100 Subject: isinstance() bug In-Reply-To: <16407.54576.283608.505067@montanaro.dyndns.org> References: <20040128132225.GA10842@foof.i3.cz> <16407.54576.283608.505067@montanaro.dyndns.org> Message-ID: <20040128154119.GA11485@foof.i3.cz> Skip Montanaro wrote: >You imported the module twice (look at sys.modules) so you have two >different A classes. I believe isinstance() uses the __class__ attribute >and the class's __bases__ attribute to work its way up the class chain >looking for a match. Even though they are defined identically, you have two >different A classes. An instance of one can't also be an instance of the >other. i think that if absolute path was somehow put into the classes internal information this inconsistency would be put away. it's my belief that if i'm instantiating a class from the same location no matter how i imported its definition, its instances are always of the same class. and as to the sys.modules thing: this could be considered as just two references to the same module (again its absolute path would be taken into account), not two different modules. does it make sense? -- fuf (fuf at mageo.cz) From arjen.dijkstraNoSpam at hccnet.nl Wed Jan 14 04:07:50 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Wed, 14 Jan 2004 10:07:50 +0100 Subject: Oracle to Mysql (dates) Help please References: <4003b6e7$0$142$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <40051543$0$137$e4fe514c@dreader11.news.xs4all.nl> Sorry, I can't find it. Can you quote it for me, please? "Dennis Lee Bieber" schreef in bericht news:p7mdd1-g74.ln1 at beastie.ix.netcom.com... > duikboot fed this fish to the penguins on Tuesday 13 January 2004 01:13 > am: > > > > > > > Could you please explain that? > > See the reply > (Pieter Claerhout) -- though according to my documents, the method is > executemany(), not execute_many(). > > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From exarkun at intarweb.us Fri Jan 16 10:36:06 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 16 Jan 2004 10:36:06 -0500 Subject: Bug or feature? In-Reply-To: <1ljkd1-053.ln1@beastie.ix.netcom.com> References: <3dtid1-594.ln1@beastie.ix.netcom.com> <1ljkd1-053.ln1@beastie.ix.netcom.com> Message-ID: <20040116153606.GA25928@intarweb.us> On Fri, Jan 16, 2004 at 08:31:32AM +0000, Dennis Lee Bieber wrote: > Terry Reedy fed this fish to the penguins on Thursday 15 January 2004 > 15:39 pm: > > > > > and returning a value. I see a little better Guido's reason for having > > list modification methods return None. While chaining is not too > > problematical, object returns would allow list expressions mixing > > implicit and overt effects with possible puzzles similar to the one > > presented in this thread. > > > Now that you mention it... Yeah... Can you imagine trying to figure > out what something like > > alist = ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] > res = alist[:5] + alist.sort() + alist[5:] > > was supposed to return? > > jihgfabcdefghijedcba > or > jihgfabcdefghijabcde > or > abcdeabcdefghijabcde > or > abcdeabcdefghijfghij > > The only "known" is that the middle is supposed to be abcdefghij, but > the left and right ends depend solely on order of evaluation... > http://python.org/doc/current/ref/evalorder.html Doesn't seem to be a problem, after all. Jp From guido at python.org Mon Jan 12 13:26:23 2004 From: guido at python.org (Guido van Rossum) Date: Mon, 12 Jan 2004 10:26:23 -0800 Subject: PyCon Reminder: Proposal deadline 1/15 (LAST WARNING) Message-ID: <200401121826.i0CIQNI03412@c-24-5-183-134.client.comcast.net> This is the *last* reminder that the deadline for sending proposals for presentations at PyCon DC 2004 is January 15, 2004. That's upcoming Thursday! I'm also reminding everybody, speakers and non-speakers, of the upcoming deadline for Early Bird Registration: January 31. Until then, the registration fee is $175 (student rate $125); after that date, the registration price goes up to $250 (student rate $150). Don't forget to register! (Sorry, there's no speakers discount.) If you're coming to the conference, consider coming a few days early and participate in a coding sprint. Sprints are free (courtesy of the PSF!), and are held from Saturday March 20 through Tuesday March 23 (i.e. the four days leading up to the conference). For more info on sprints, see http://pycon.org/dc2004 . Now back to proposal submissions: We are interested in any and all submissions about uses of Python and the development of the language. Since there is expected to be a strong educational community presence for the next PyCon, teaching materials of various kinds are also encouraged. You can submit your proposal at: http://submit.pycon.org/ For more information about proposals, see: http://www.pycon.org/dc2004/cfp/ If you have further questions about the submission web interface or the format of submissions, please write to: pycon-organizers at python.org We would like to publish all accepted papers on the web. If your paper is accepted and you prepare an electronic presentation (in PDF, PythonPoint or PowerPoint) we will also happily publish that on the web site once PyCon is over. If you don't want to make a formal presentation, there will be a significant amount of Open Space to allow for informal and spur-of-the-moment presentations for which no formal submission is required. There will also be several Lightning Talk sessions (five minutes or less). About PyCon: PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. PyCon DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. We're looking for volunteers to help run PyCon. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ Pictures from last year's PyCon: http://www.python.org/cgi-bin/moinmoin/PyConPhotos I'm looking forward to seeing you all in DC in March!!! --Guido van Rossum (home page: http://www.python.org/~guido/) _______________________________________________ Pycon-organizers mailing list Pycon-organizers at python.org http://mail.python.org/mailman/listinfo/pycon-organizers From cjw at sympatico.ca Thu Jan 1 15:47:55 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 01 Jan 2004 15:47:55 -0500 Subject: newbie question In-Reply-To: <4ebabbc5.0312311614.2446e31c@posting.google.com> References: <4ebabbc5.0312311614.2446e31c@posting.google.com> Message-ID: You might look at your indentation. The def __init__ line should have the same indentation as the preceding doc string. Colin W. Julia Osip wrote: > Hi, just started fiddling around with python, having some difficulty > getting the following small play program to execute. Furious > searching in the docs, manual, newsgroup did not avail me, does anyone > have any ideas what might be the problem? Some sort of whitespace > issue (im still unsure of whitespace rules)? I'm running Mac OS > 10.2.8, with MacPython 2.3. > > Thanks for any help you can give... > > the code > ...snip... > #!/usr/bin/env python > > class World: > > """contains everything""" > > def __init__(self): > self.name = "world" > self.locations = [] # list of all locations in > the world > self.dist_locations = [] # the amount of travel time required > between locations > self.actors = [] # list of all actors in the world > self.organizations = [] # list of all organizations in the world > self.time = 0 # current moment in the world > return > > ...snip... > > the error > ...snip... > File "", line 7 > def __init__(self): > ^ > SyntaxError: invalid syntax > ...snip... From gerrit at nl.linux.org Tue Jan 6 13:58:31 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 6 Jan 2004 19:58:31 +0100 Subject: PRE-PEP: new Path class In-Reply-To: <20040105214508.GA29923@nl.linux.org> References: <20040105214508.GA29923@nl.linux.org> Message-ID: <20040106185831.GA4581@nl.linux.org> Hi, I have updated the PEP, partly based on comments by other, partly on my own thoughts. Tinyurl seems down, the latest version is available at: http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html yours, Gerrit. -- 263. If he kill the cattle or sheep that were given to him, he shall compensate the owner with cattle for cattle and sheep for sheep. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From lbates at swamisoft.com Mon Jan 12 18:29:43 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 12 Jan 2004 17:29:43 -0600 Subject: Calling dlls with Calldll/WinDll or Ctypes or... References: <9b849915.0312172302.7999d44a@posting.google.com> Message-ID: Todd, I write this and have used it with many different .DLLs over the last 18 months. Good luck. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847 The trick it getting the arguments into/from the correct format for the .DLL. I've made extensive use of struct to accomplish that. If you want to give it a try, I'd be happy to assist you as much as I can. Larry "Todd Gardner" wrote in message news:9b849915.0312172302.7999d44a at posting.google.com... > Hello all, > > Pardon my ignorance here. I would like to talk to someone that has > had success in calling ddls in Windows NT/2000/XP. > > I am wondering where to dload any of these packages? Google searches > keep turning up articles similar to this. > > Any pointers would be greatly appreciated! > > Todd From max at alcyone.com Fri Jan 16 15:13:12 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 16 Jan 2004 12:13:12 -0800 Subject: Very strange unicode behaviour References: Message-ID: <400845D8.C91E0AEE@alcyone.com> Syver Enstad wrote: > I have seem to isolate the behaviour: > > >>> chr(127).find(u'') > 0 > >>> > >>> chr(128).find(u'') > -1 > >>> > UnicodeError: ASCII decoding error: ordinal not in range(128) > >>> > > Observe that the exception is first thrown on after execing a blank > line, after calling find on a non ASCII string. > > I'll test this on 2.3 when I get home from work. I can indeed reproduce this bizarre behavior on 2.2.3. The problem does not occur in 2.3.3: max at oxygen:~% python Python 2.3.3 (#1, Dec 22 2003, 23:44:26) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> chr(127).find(u'') 0 >>> chr(128).find(u'') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128) >>> max at oxygen:~% python2.2 Python 2.2.3 (#1, Jan 8 2004, 22:40:34) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> chr(127).find(u'') 0 >>> chr(128).find(u'') -1 >>> UnicodeError: ASCII decoding error: ordinal not in range(128) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From franco.tomaselli at st.com Wed Jan 28 03:48:57 2004 From: franco.tomaselli at st.com (franco.tomaselli at st.com) Date: Wed, 28 Jan 2004 09:48:57 +0100 Subject: HI Message-ID: <200401280849.JAA05873@agx002.agr.st.com> ------------------ Virus Warning Message (on zeta) Found virus WORM_MIMAIL.R in file message.pif (in message.zip) The uncleanable file is deleted. --------------------------------------------------------- -------------- next part -------------- Mail transaction failed. Partial message is available. -------------- next part -------------- ------------------ Virus Warning Message (on zeta) message.zip is removed from here because it contains a virus. --------------------------------------------------------- From jepler at unpythonic.net Thu Jan 8 22:57:47 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 8 Jan 2004 21:57:47 -0600 Subject: convert a list to a string In-Reply-To: <3FFE2084.7010700@hotmail.com> References: <3FFE1E29.20801@hotmail.com> <7xwu81dcr7.fsf@ruckus.brouhaha.com> <3FFE2084.7010700@hotmail.com> Message-ID: <20040109035747.GF24734@unpythonic.net> On Thu, Jan 08, 2004 at 10:31:16PM -0500, Bart Nessux wrote: > How does randint and sample differ? I was under the impression that > sample was more random. sample is useful when you want to choose several items from the population. The degenerate case random.sample(range(100), 1) is equivalent to [random.choice(range(100))] is equivalent to [random.randrange(100)] here's where sample is useful: Pick a TLA, but don't repeat any letters: >>> "".join(random.sample(string.uppercase, 3)) 'CLA' You can't sample more than your whole population: >>> "".join(random.sample(string.uppercase, 28)) ValueError: sample larger than population And here's another way to take a random permutation of the alphabet: >>> "".join(random.sample(string.uppercase, 26)) 'STFVCQHDLOUNERPYIMABGJXKZW' No letters are repeated, unlike with random.choice: >>> "".join([random.choice(string.uppercase) for i in >>> range(26)]) 'ZMXYCNLDCQAIYTAVPPTSGABNVU' (the odds of *not* having a duplicate letter here are quite small, though I don't know offhand just how small--maybe 26!/(26**25)?) Jeff From aathan-python-5923 at cloakmail.com Mon Jan 5 20:27:13 2004 From: aathan-python-5923 at cloakmail.com (Andrew Athan) Date: Mon, 5 Jan 2004 20:27:13 -0500 Subject: Repost: Can't sys.exit() from SIGTERM handler? In-Reply-To: Message-ID: I have a python program (snippet below) which does not want to seem to die when I issue a sys.exit() inside the SIGTERM handler. The output below is generated as the result of sending several SIGTERM signals to the process, as a result of seeing that it had not died. I don't think this is relevant, but the application has fork()ed a child process (cdparanoia). The only thing I can think of is that somehow, there is an exception occuring inside sys.exit(), otherwise why am I not seeing the "Did not sys.exit()!?" output? Could it be that exit() is returning but that the output fd's are already closed? Verrry strange...and therefore I'm sure I'm making a brain dead mistake. Thanks in advance, A. -------------------------------------------------------------------------- ****SIGTERM***** ****SIGTERM***** .. ****SIGCHILD***** Ripper output status code: (4314, 15) 4320 /root/postprocess /var/music/ripper/8707620b ****SIGCHILD***** Error JOB_NODISC in job <__main__.JobHandler instance at 0x8204b24> 4321 /bin/setserial /dev/ttyS0 spd_normal ****SIGCHILD***** Killing child processes... -------------------------------------------------------------------------- def sigterm(a,b): print '\n****SIGTERM*****\n' sys.exit() print '\nDid not sys.exit()??!!\n' killChildren() os._exit(1) print '\nDid not os._exit()??!!\n' def killChildren(): global childPIDs print '\n\nKilling child processes...' for pid in childPIDs: try: print 'Terminating %d'%pid os.kill(pid,signal.SIGTERM) os.waitpid(pid,0) except: pass def child_exit(a,b): #childpid, status = os.wait() print '\n****SIGCHILD*****\n' pass -- http://mail.python.org/mailman/listinfo/python-list From gerrit at nl.linux.org Wed Jan 28 15:10:30 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 28 Jan 2004 21:10:30 +0100 Subject: FRE: PEP 326 is D-E-A-D (was Re: How does compare work?) In-Reply-To: References: Message-ID: <20040128201030.GA6588@nl.linux.org> Batista, Facundo wrote: > Aahz wrote: > #- >Even then, what about PEP 326, which presumes to define highest and > #- >lowest objects that can be compared with anything? > #- > #- What about it? ;-) > #- > #- (Guido just posted a Pronouncement rejecting it.) > > Can't find it at http://www.python.org/doc/essays/pepparade.html > > I'm looking in the wrong place? Look in the Python-Dev Archives: Guido said: PEP 326 is REJECTED, because: - The usefulness of the feature is marginal; - it is easily implemented when you really need it; and - we can't agree on a good way to spell it. http://mail.python.org/pipermail/python-dev/2004-January/042306.html Gerrit. -- 138. If a man wishes to separate from his wife who has borne him no children, he shall give her the amount of her purchase money and the dowry which she brought from her father's house, and let her go. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From somebody at nowhere.com Wed Jan 28 15:37:51 2004 From: somebody at nowhere.com (Sean Richards) Date: Thu, 29 Jan 2004 09:37:51 +1300 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: <87vfmvu7vk.fsf@hugin.valhalla.net> runed at stud.cs.uit.no (Rune) writes: > Hey > > I'm trying to build a gui application and need to know if the user is > actually holding down the shift or ctrl key. That is, if the user > currently is holding down the shift key. In pseudo code this will boil > down to something like this: > > def test: > if user presses shift: > return SHIFT_IS_PRESSED > elif user presses ctrl: > return CTRL_IS_PRESSED > else > return false > > It's important to notice here that I'm not interested if the user has > already pressed shift or ctrl. I'm only interested in knowing if he is > currently holding down one of these keys. (I have looked into msvcrt > and the like but have found no answer..) The function should also work > in both windows and Linux. > > Any help is appriciated :) In wxPython you could do it like this ... 1. Bind the key press events to the two functions EVT_KEY_DOWN(self, self.OnKeyDown) EVT_KEY_UP(self, self.OnKeyUp) 2. Set or unset a flag on keydown and keyup def OnKeyDown(self, event): if (event.GetKeyCode() == WXK_SHIFT): self.Shift = True elif (event.GetKeyCode() == WXK_CONTROL): self.Control = True def OnKeyUp(self, event): if (event.GetKeyCode() == WXK_SHIFT): self.Shift = False elif (event.GetKeyCode() == WXK_CONTROL): self.Control = False Vennlig hilsen, Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From tlo2075 at yahoo.fr Tue Jan 6 17:12:42 2004 From: tlo2075 at yahoo.fr (Tlo) Date: 6 Jan 2004 14:12:42 -0800 Subject: multiplayer online quizz game - can python help me? Message-ID: <929eabc7.0401061412.44d51645@posting.google.com> hello, i would like to do the following, and as i had never used python in a network framework i would like to have opinions on this : i would like to provide some kind of network quizz game, each player logged in and can then join 'playing rooms', in each rooms they had to answers many quizz-like questions, after a game finished each players involved in it are ranked from their corrects answers and the time they spent to answer. results are saved in a shared database. graphical interface can be very simple. can python help me? do you know of similar tools/application i could use as starting point? (from a first idea i was thinking of something much more like java but maybe python can do? i discarded php because i suppose it's more on the client side) thanks From js.bach at web.de Wed Jan 14 03:27:55 2004 From: js.bach at web.de (tm) Date: Wed, 14 Jan 2004 09:27:55 +0100 Subject: Parsing c-code Message-ID: Hello, are there recommended modules for parsing c-code. I want to read in c-structs and display it in a tree graphic. -- Torsten From try_vanevery_at_mycompanyname at yahoo.com Tue Jan 13 17:29:09 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 14:29:09 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Peter Ashford" wrote in message news:K_YMb.10994$9k7.204413 at news.xtra.co.nz... > Brandon, don't be such an arsehole. OS developers do things their own > way and offer their labour for free. If you don't like it noone will > care - but don't denegrate people just because they don't do things your > way. I'll denigrate them all I want. With rare exceptions, they aren't a value add to what I want to get done. There's this huge cultural divide between hobbyists and commercialists. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "We live in a world of very bright people building crappy software with total shit for tools and process." - Ed Mckenzie From caseyd1 at stanford.edu Sun Jan 18 00:26:02 2004 From: caseyd1 at stanford.edu (Casey) Date: Sat, 17 Jan 2004 21:26:02 -0800 Subject: Webbrowser and Mozilla control on linux In-Reply-To: <1d17eeb7.0401171633.170e313a@posting.google.com> References: <1d17eeb7.0401171633.170e313a@posting.google.com> Message-ID: I'm not sure about the current state, but you will want to google around with xul python mozilla and you will find another dimension of wonder. I don't know really how much is working, however. Jay Davis wrote: > I can launch a browser on linux with the webbrowser module > and the .open() method. However, I want to be able also to > control the browser, specifically, I'd like to be able to > go to a URL and invoke the automatic form filler and post > the form, all from within a python script. > > I have google'd around and I see hints that there are remote > controller objects for some browsers, but so far I haven't > found any examples of code that controls the browser; most > examples just open the browser, which I could just as well > do from os.system(). > > If anyone can share some samples, or point me to a good > reference with browser control details, I'd much appreciate > it. Thanks! > > J.D. From jjl at pobox.com Sat Jan 31 15:27:41 2004 From: jjl at pobox.com (John J. Lee) Date: 31 Jan 2004 20:27:41 +0000 Subject: Simple web proxy - help needed References: Message-ID: <87ad43kgn6.fsf@pobox.com> forshtat at hotmail.com (Ziv Forshtat) writes: [...] > Problem is - I don't have to much background in writing proxies, nor > in writing plugins. > Any help and suggestions would be welcome. Back again... just remembered I posted a tiny MSIE plugin skeleton to the ctypes list a while back. That might actually be very close to what you need already. Use the latest version of ctypes. I originally meant not to post it actually, because of the obvious applications in malware, then forgot about my decision and posted it anyway. Oh well, the black hats have plenty of evil code already, I'm sure. John From grobinson at transpose.com Thu Jan 22 11:25:23 2004 From: grobinson at transpose.com (Gary Robinson) Date: Thu, 22 Jan 2004 11:25:23 -0500 Subject: I support PEP 326 Message-ID: I've recently had a couple of cases of needing exactly what it proposes, and having to kluge around the fact that it's not there. It's a great idea. If there anywhere else I should be expressing my opinion on this, let me know. --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 Company: http://www.transpose.com Blog: http://www.garyrobinson.net From jepler at unpythonic.net Sun Jan 18 13:31:17 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Jan 2004 12:31:17 -0600 Subject: newbie question about compression and ascii In-Reply-To: References: Message-ID: <20040118183117.GC24401@unpythonic.net> Let's get down to what the problem is: >>> f = zipfile.ZipFile("/tmp/blah.zip", "w") >>> f.write(u'\xe0') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/zipfile.py", line 374, in write st = os.stat(filename) UnicodeError: ASCII encoding error: ordinal not in range(128) Your filenames are Unicode strings, and must contain some characters that aren't ASCII. I don't know if ZipFile (or the zip "standard") defines an encoding for filenames, but it appears not: http://www.info-zip.org/pub/infozip/FAQ.html#limits This might be relevant: http://dbforums.com/arch/97/2003/5/773834 Jeff From maketo at gronland.freeshell.org Fri Jan 9 10:21:29 2004 From: maketo at gronland.freeshell.org (Ognen Duzlevski) Date: Fri, 9 Jan 2004 15:21:29 +0000 (UTC) Subject: how to speedup this code? Message-ID: Hi all, I have rewritten a C program to solve a bioinformatics problem. Portion where most of the time is spent is: def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): global ONEINDELPENALTY,OPENGAPPENALTY for ndx1 in range(1,tlen+1): for ndx2 in range(1,qlen+1): delmat[ndx1][ndx2] = Min(delmat[ndx1-1][ndx2]+ONEINDELPENALTY, \ Min(scoremat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY, \ insertmat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY)) insertmat[ndx1][ndx2] = Min(insertmat[ndx1][ndx2-1]+ONEINDELPENALTY, \ Min(scoremat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY, \ delmat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY)) scoremat[ndx1][ndx2] = Min(scoremat[ndx1-1][ndx2-1], \ Min(delmat[ndx1-1][ndx2-1], insertmat[ndx1-1][ndx2-1])) + \ GetFitnessScore(tseq,ndx1-1,qseq,ndx2-1) def Min(a,b): if a< b: return a else: return b In C this is not a big deal, delmat, scoremat and insertmat are int matrices dynamically allocated and the loop-inside-a-loop is pretty fast. However, on python (2.3) it is very slow. So for comparison, my C version takes 8 seconds to execute and the python version takes around 730 seconds. I have narrowed down through visual observation (print before and print after entry into the above nested loop) that most of the time is spent in there. I have also tried the Numeric package with their arrays. It speeded things up somewhat but not considerably. Any suggestions? Thank you, Ognen From newsgroups at jhrothjr.com Sun Jan 4 07:07:22 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Jan 2004 07:07:22 -0500 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Aahz" wrote in message news:bt82d7$ort$1 at panix3.panix.com... > In article , > John Roth wrote: > >"Aahz" wrote in message > >news:bt7lbp$ovg$1 at panix2.panix.com... > >> In article , > >> John Roth wrote: > >>> > >>>Restricted Python was withdrawn because of a number of holes, of which > >>>new style classes were the last straw. > >> > >> RestrictedPython was *not* withdrawn; rexec was withdrawn. This is a > >> difficult enough issue to discuss without confusing different modules. See > >> http://dev.zope.org/Wikis/DevSite/Projects/SupportPython21/RestrictedPython > > > >I'm not sure what you're trying to say. The Zope page you reference > >says that they were (prior to 2.1) doing things like modifying generated > >byte code and reworking the AST. That's fun stuff I'm sure, but it > >doesn't have anything to do with "Restricted Execution" as defined in the > >Python Library Reference, Chapter 17, which covers Restricted Execution, > >RExec and Bastion (which was also withdrawn.) > > > >If I confused you with a subtle nomenclature difference, sorry. I don't > >care what Zope is doing or not doing, except for the fact that it seems > >to come up in this discussion. I'm only concerned with what Python is > >(or is not) doing. The approach in the Wiki page you pointed to does, > >however, seem to be a substantially more bullet-proof approach than > >Python's Restricted Execution. > > Well, I don't care what you do or don't care about, but I do care that > if you're going to post in a thread that you actually read what you're > responding to and that you post accurate information. If you go back to > the post that started this thread, it's quite clear that the reference > was specifically to Zope's RestrictedPython. I beg to differ. That's what the OP said he started with, not what he's mostly interested in nor where he wants to end up. I'm including the first paragraph below: [extract from message at head of thread] I've been playing around with Zope's RestrictedPython, and I think I'm on the way to making the modifications necessary to create a capabilities-based restricted execution system. The idea is to strip out any part of RestrictedPython that's not necessary for doing capabilities and do all security using just capabilities. [end extract] To me, at least, it's clear that while he's *started* with a consideration of Zope's RestrictedPython, he's talking about what would be needed in regular Python. If he was focusing on Zope, this is the wrong forum for the thread. My fast scan of Zope yesterday showed that it was quite impressive, but some of the things they did seem to be quite specific to the Zope environment, and don't seem (at least to me) to be all that applicable to a general solution to having some form of restricted execution. Much of this thread has focused on "capabilities" and the use of proxies to implement capabilities. AFIAC, that's not only putting attention on mechanism before policy, but it's putting attention on mechanism in the wrong place. What I *haven't* seen in this thread is very much consideration of what people want from a security implementation. I've seen that in some other threads, which included some ways of taming exec and eval when all you want is a data structure that contains nothing but known kinds of objects. You don't, however, need exec and eval for that if you're willing to use the compiler tools (and, I presume, take a substantial performance hit.) One problem I've been playing around with is: how would you implement something functionally equivalent to the Unix/Linux chroot() facility? The boundaries are that it should not require coding changes to the application that is being restricted, and it should allow any and all Python extension (not C language extension) to operate as coded (at least as long as they don't try to escape the jail!) Oh, yes. It has to work on Windows, so it's not a legitimate response to say: "use chroot()." John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Weinberg's Second Law: If builders built buildings the way programmers wrote > programs, then the first woodpecker that came along would destroy civilization. Have to be a pretty non-aggressive woodpecker, if it allowed something that extensive and complicated to happen before attacking it. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jan 2 16:11:11 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 02 Jan 2004 22:11:11 +0100 Subject: ANN: Snakelets 1.20 (simple-to-use web app server with dynamic pages) Message-ID: <3ff5dee8$0$318$e4fe514c@news.xs4all.nl> Happy new year everyone! I'm happy to say that Snakelets 1.20 is available. (I skipped a bunch of release numbers because of a few large changes) Snakelets is a Python web application server, mainly for educational purposes (but it works fine, mind you). This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). It is possible to run Snakelets off a CD (read-only mode). Snakelet's focus is on understanding the way dynamic web sites are created (the code is very compact and easy to understand), and make this process as easy as possible, while still providing a rich and powerful server environment. It's released under the open-source MIT Software license. You can download from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). Most relevant changes since 1.9: * new feature: virtual hosts! (webapp config has changed!) * page templates can now be parameterized * uses sendfile(2) if available for high performance static file serving (see http://www.snakefarm.org/ for the extension module) * fixed rather nasty object leak (reference cycles) * added memory usage viewer to 'test' webapp. * various bug fixes, improvements and updated documentation. To start, edit the vhost config file (see docs) and then run serv.py script, or the monitor.py script if you want to start it as a daemon (on Unix). Enjoy! Enjoy, --Irmen de Jong. From jcarlson at nospam.uci.edu Fri Jan 30 22:13:12 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 19:13:12 -0800 Subject: Python vs. Io In-Reply-To: <711c7390.0401301710.4353274@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> Message-ID: > IMHO, this makes more sense than iterating over a list created just > for a specific loop. On my computer, Io's loops are faster than > Python's (probably because they are lazy). Haven't you heard of xrange? It's like range, only without the list instantiation (and a few other things). > But the community will grow larger in time. The Io community is bigger > than the Python community two years after Python was released > (although that's probably because it wasn't publicly released for two > years). I would also be willing to bet that is due to the ease of distribution that the modern internet allows, coupled with the current geek-chic of learning new-better-than-ever languages. Heck, brainfuck probably has more users than Python did 2 years after its introduction, but that doesn't mean that you will be able to write programs that are better, more efficient, easier to update, easier to debug, etc., with BF than with some other newer language. > Also, Python has statements (as opposed to just expressions) even for > the simplest things like writing things to the command line. In Io, > flow control is in functions, which can be overwritten if you want to > change them. The Python philosophy is that if you allow this and other > flexible things to happen, you will have inconsistent code. If someone > asks on the Tutor mailing list how to change that, everybody responds > "Why would you want to do that?". While that's a valid viewpoint, it's > not the most flexible. Perhaps it isn't more flexible. On the other hand, it does allow anyone to read your code and know that there isn't any magical syntax that is usable on one Python x.y installation, that isn't on another. - Josiah From jtdubs at eos.ncsu.edu Sat Jan 24 12:12:23 2004 From: jtdubs at eos.ncsu.edu (Justin Dubs) Date: 24 Jan 2004 09:12:23 -0800 Subject: pty difficulties References: <2e262238.0401232202.5b21eba8@posting.google.com> Message-ID: <2e262238.0401240912.1ca6bb74@posting.google.com> Josiah Carlson wrote in message news:... > > while True: > > readable = select(connections.keys(), [], [])[0] > > for f in readable: > > data = read(f.fileno(), 1024) > > connections[f].write(data) > > connections[f].flush() > > I believe your problem exists in the write and flush. All you seem to > be doing is checking to see if your reading file handles are capable of > reading, you never check to see if you can write to anything. Your lisp > interpreter showcases the fact that it is not ready to get a write while > it is interpreting, by failing. I believe the following should fix you up: > > while True: > readable = select(connections.keys(), [], [])[0] > for f in readable: > if select([], [connections[f]], [], 0)[1]: > data = read(f.fileno(), 1024) > connections[f].write(data) > connections[f].flush() Thanks for the suggestions, but this didn't help. I should have mentioned that I had tried this before. Here's the code I had used: while True: readable, writeable, ignore = select(connections.keys(), connections.values(), []) for f in readable: if connections[f] in writeable: data = read(f.fileno(), 1024) connections[f].write(data) connections[f].flush() I don't think checking for writeable status /should/ help because the write call I am using blocks. So, if the stream isn't writeable, it should just block until it is. I think. Justin Dubs From newz at rekon.org.NOSPAM Sun Jan 18 06:13:11 2004 From: newz at rekon.org.NOSPAM (Wil Schultz) Date: Sun, 18 Jan 2004 03:13:11 -0800 Subject: Best way to do this? In-Reply-To: References: <100jg9er3qak890@corp.supernews.com> Message-ID: <100kqbt2spltf3b@corp.supernews.com> Okay, maybe I should have said the program should ask for the password up to 3 times, exiting on a) the correct password b) the third incorrect password. Wil my 2? "When everything seems to be going well, you have obviously overlooked something." William Park wrote: > Wil Schultz wrote: > >>One of the exercises asks for a program to ask for a password three >>times. Surprisingly this took me much longer that it probably should >>have so I am curious if the following is the easiest way this is done. >>Thanks much! >> >>************************************************* >>#!/usr/local/bin/python >> >>count = 0 >>password = "null" >> >>while count < 3: >> count = count + 1 >> password = raw_input("what's the pass: ") >> if password == "mypass": >> print "Access Granted" >> count = 3 >> else: >> if count < 3: >> print "Try Again" >> else: >> print "Too Bad" >>************************************************* > > > For crying out loud, here's 3 times for you... > password = raw_input("what's the pass: ") > password = raw_input("what's the pass: ") > password = raw_input("what's the pass: ") From john at doe.com Fri Jan 23 14:21:24 2004 From: john at doe.com (Brian Donovan) Date: Fri, 23 Jan 2004 19:21:24 GMT Subject: libxml2 w/ xpath python bindings References: Message-ID: Turns out the issue was with the XML namespaces. The document had a defualt namespace which had to be declared: xmlDoc = libxml2.parseFile(base + '/' + curfile) ctxt = xmlDoc.xpathNewContext() ctxt.xpathRegisterNs('rng',"http://relaxng.org/ns/structure/1.0") elements = ctxt.xpathEval('//rng:element/@name') for e in elements: rnc.elements.append(e.content) On Fri, 23 Jan 2004 18:58:34 +0000, Brian Donovan wrote: > Hi All, > > I'm trying to get xpath to work with the libxml2 python bindings. > I'm using the following > > doc = libxml2.parseFile(filename) > result = doc.xpathEval('//*') > > My test XML file has 10 nodes in it and I'm trying to get an element named > 'element' (from an relaxng schema). > > If I use the xpath expression '//*' I'll get a list with 10 nodes > including the element element as expected. If I try '//element' I'm > getting an empty list with no errors. Any idea where I could be going > wrong? > > Brian From chris.lyon at spritenote.co.uk Tue Jan 13 11:23:46 2004 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 13 Jan 2004 08:23:46 -0800 Subject: Does anyone else not find the fun in programming...? Message-ID: I find python very effective as a language and can generally project most of my hazy thoughts into it. But FUN !!! This is work dammit, I have now ground my teeth down from the number of times I read that programming is fun. Football (association) is fun, walking along canals is fun, Arguing about quite how useless the British Government is fun but programming ? Do I need help ? (Actually typing this was quite fun, so perhaps) From nsm38 at student.cpit.ac.nz Thu Jan 29 18:20:08 2004 From: nsm38 at student.cpit.ac.nz (nadia) Date: 29 Jan 2004 15:20:08 -0800 Subject: Job Wanted - New Zealand Message-ID: <9caa8908.0401291520.187c557a@posting.google.com> Hi, I am a recent IT graduate, who has some experince using Python. I would like the opportunity to expand my experince with python. I am currently based in christchurch, though I will be willing to move. I also have experince using PHP, XML, Java, JavaSCript, mySQL, VB, C, SQL. My home page (which has a copy of my CV and work I have done) is: http://home.clear.net.nz/pages/eamonreyn/ Thanks Nadia. From astrand at lysator.liu.se Sun Jan 4 08:38:53 2004 From: astrand at lysator.liu.se (=?iso-8859-1?Q?Peter_=C5strand?=) Date: Sun, 4 Jan 2004 14:38:53 +0100 (CET) Subject: Is Python Mac Centric??? Message-ID: [About including win32 into the Python core distribution] martin at v.loewis.de: >Mark is unlikely to request it because he doesn't want to wait a year for >the next Python release just to release the next version of PythonWin. I don't understand why this is necessary. win32 is just a bunch of additional modules. Let's say that these were included in, say, Python 2.4. Wouldn't it be possible for Mark to release an updated package that just replaces the modules included in 2.4? You could call it a "win32 servicepack X for Python Y.Z". Tim Peters (tim.one at comcast.net): >Mark likes having a release schedule independent of Python's, and Guido >hates Mark's coding style. Both act against folding the Windows >extensions into the core. So, theoretically, if another person stepped forward that re-indented the source code and was happy about following the Python release schedule, then the extensions could be added? I think it's a shame that such minor issues as coding style and release schedules should block an important thing like this. -- /Peter ?strand From jcarlson at nospam.uci.edu Sun Jan 25 01:04:36 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 24 Jan 2004 22:04:36 -0800 Subject: Text Animation In-Reply-To: <7b454334.0401242038.11404dac@posting.google.com> References: <7b454334.0401242038.11404dac@posting.google.com> Message-ID: Fazer wrote: > Hello, > > I was wondering if anyone has done any simple text-based animation? > > I mean things such as text-based pre-loaders. One example would be > when you use the *nix utility called `wget.` You get that fancy " > ====> " type of animation as you download a large file. Or maybe even > a rotating " | " that I have seen before in some installation > programs. > > Any ideas how these effects can be achieved? > > Thanks a lot! > > Faizan Yeah, don't print linefeed ('\n') characters, only print carriage returns ('\r'). import time for i in xrange(75): print '*'*i, '\r', time.sleep(.1) - Josiah From max at alcyone.com Thu Jan 22 20:44:16 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Jan 2004 17:44:16 -0800 Subject: Mixing protocols in pickles? Message-ID: <40107C70.13CA8495@alcyone.com> Is there any prohibition against mixing different protocols within the same pickle? I don't see anything about this in the Python Library Reference and, after all, the pickle.dump function takes a protocol argument for each time it's called. (This is in Python 2.3.3.) I have a pickle containing two objects: a tag string and a (large) object containing many children. The identifying string is there so that you can unpickle it and decide whether you really want to unpickle the whole data object. So I thought it would be clever to write the tag string with protocol 0 so it would show up in a file viewer as plain text and then write the rest of the data with protocol 1 (or 2; it doesn't use new-style classes, though). I open the file in binary mode and then dump the tag string in protocol 0, then the (big) instance data in protocol 1. When loading time comes around, they're just both loaded in the same order: def load(filename=DEFAULT_FILENAME): try: inputFile = gzip.GzipFile(filename + COMPRESSED_EXTENSION, 'rb') except IOError: inputFile = file(filename, 'rb') tag = pickle.load(inputFile) if DEBUG: print >> sys.stderr, "Tag: %s" % tag system = pickle.load(inputFile) inputFile.close() return system def save(system, tag, filename=DEFAULT_FILENAME, protocol=1, compressed=False): if compressed: outputFile = gzip.GzipFile(filename + COMPRESSED_EXTENSION, 'wb') else: outputFile = file(filename, 'wb') pickle.dump(tag, outputFile, 0) # write the tag in text pickle.dump(system, outputFile, protocol) outputFile.close() This works fine on Unix, but on Windows it generates the (utterly puzzling) error: C:\My Documents\botec-0.1x1>python -i ./botex.py Tag: default.botec:20040110:11175:ebec37a7632cc7176ff359a3754750ec:0.1x1 Traceback (most recent call last): File "./botex.py", line 70, in ? SYSTEM = init() File "./botex.py", line 15, in init return load() File "C:\My Documents\botec-0.1x1\botec.py", line 1666, in load system = pickle.load(inputFile) ImportError: No Module named copy_reg >>> ... made extra puzzling because you can type `import copy_reg' on that prompt and it will import fine. Googling for this error comes up with a few scattered complaints but nothing coherent about the cause. When I modify the dumping routine to use the same protocol (1) for both dumps, the problem goes away and everything works fine. So I guess there are a few questions: Why is the error being generated so obscure and seemingly incorrect? Is it really the case that mixing multiple protocols within the same pickle isn't allowed, or is this truly a bug (or, say, a Windows-specific problem because protocol 0 requires that the pickle file be in text mode?)? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Love is the most subtle form of self-interest. -- Holbrook Jackson From crescent_au at yahoo.com Fri Jan 2 06:56:13 2004 From: crescent_au at yahoo.com (Ben) Date: 2 Jan 2004 03:56:13 -0800 Subject: cgi using what? Message-ID: Hi all, I wanna use Python for creating a questionnaire. Is it a good choice using python on the basis of its availability? I wanna know if most servers support python or not... I don't know about the server yet.. so which language will be a good choice? Ben From me at privacy.net Tue Jan 13 17:33:03 2004 From: me at privacy.net (James Keasley) Date: 13 Jan 2004 22:33:03 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 In article , Brandon J. Van Every wrote: > > "Peter Ashford" wrote in message > news:K_YMb.10994$9k7.204413 at news.xtra.co.nz... >> Brandon, don't be such an arsehole. OS developers do things their own >> way and offer their labour for free. If you don't like it noone will >> care - but don't denegrate people just because they don't do things your >> way. > > I'll denigrate them all I want. With rare exceptions, they aren't a value > add to what I want to get done. There's this huge cultural divide between > hobbyists and commercialists. Yeah, one lot write software that works, the others write software that'll make them money for fixing their own mistakes after the fact ;) - -- James jamesk[at]homeric[dot]co[dot]uk 'Honesty is the best policy, but insanity is a better defense' -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFABHIfqfSmHkD6LvoRAu4JAJ404it8nTW7VF1EkEHlDY+9Nf/ZvACfW+g8 AP8YbKAdFCrPDtF3lN9Lg98= =i/F+ -----END PGP SIGNATURE----- From carroll at tjc.com Sat Jan 24 19:24:45 2004 From: carroll at tjc.com (Terry Carroll) Date: Sun, 25 Jan 2004 00:24:45 GMT Subject: time.time() References: <7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com> Message-ID: On Sat, 24 Jan 2004 16:25:01 -0500, Bart Nessux wrote: >Terry Carroll wrote: > >> It sounds like you're thinking time.time() does something else, which >> you're trying to do. What is that? There might be another function for >> you. > >I should have been more clear... here's the code: > >x = time.time() >fp = os.popen("some_process", "r") >fp.read() >fp.close() >print (time.time()-x/60)/60 Ah. You have a precedence problem. Try: print ((time.time()-x)/60)/60 From google at klaff.org Tue Jan 6 16:52:32 2004 From: google at klaff.org (David Klaffenbach) Date: 6 Jan 2004 13:52:32 -0800 Subject: Starting a script interactively? References: <37d5fe8f.0401021305.349a440@posting.google.com> <3FFAB968.3B8DDDC1@engcorp.com> Message-ID: <37d5fe8f.0401061352.371cd9ac@posting.google.com> Peter Hansen wrote in message news:<3FFAB968.3B8DDDC1 at engcorp.com>... > import os > os.environ['PYTHONINSPECT'] = '1' > > (untested) Tested now! Just what I was looking for! Thanks, Dave replies to google at klaff.org will bounce; replace 'google' with the name of your favorite programming language to get a good address. From claird at lairds.com Wed Jan 14 13:30:13 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 14 Jan 2004 18:30:13 -0000 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> Message-ID: <100b2llg67r546f@corp.supernews.com> In article , Derek wrote: . . . >Yes, I prefer compile-time checks to run-time checks. I don't know >which method is "better" by any objective measure, but I prefer to >know if there is a problem as early as possible. It's not hard to >make a change in Python that will go unnoticed until much later, and >in the real world test suites often don't have enough coverage to >catch every runtime error up front. > > Got it; thanks. There's been extensive discussion here and elsewhere on just this point. One of us might follow-up in a bit with a refer- ence to highlights ... While I spend most of my time in the Trotskyite fringe of those who proclaim that Testing Is The Answer, and that compile-time checks count for little, I'm deeply sympathetic with the anguish of letting the latter go. 'Fact, I just spent the morning do- ing "-Wall" to yet another corpus of unsanitized code, and *I* feel a lot better for it. -- Cameron Laird Business: http://www.Phaseit.net From paul at boddie.net Tue Jan 6 05:31:09 2004 From: paul at boddie.net (Paul Boddie) Date: 6 Jan 2004 02:31:09 -0800 Subject: PEP 324: popen5 - New POSIX process module References: Message-ID: <23891c90.0401060231.1b7a26b5@posting.google.com> Paul Moore wrote in message news:... > > The whole interface feels very Unix-specific. Well, the subject of the original message did mention POSIX explicitly. ;-) Seriously, it would be very nice to have something equivalent on Windows that works as well as the POSIX-like implementations without the user of the module needing to use various arcane tricks to prevent deadlock between parent and child processes. Of course, as people often mention, Windows operating systems do have some POSIX API support, although their compliance to the POSIX standard seems to be best described as being at the "version 0.1a1" level. Paul From jjl at pobox.com Mon Jan 12 13:56:51 2004 From: jjl at pobox.com (John J Lee) Date: Mon, 12 Jan 2004 18:56:51 +0000 (GMT) Subject: Databases: Which one's right for me? In-Reply-To: <1073925556.6341.403.camel@localhost.localdomain> References: <4378fa6f.0401091717.1ae63541@posting.google.com> <878ykf71g6.fsf@pobox.com> <1073925556.6341.403.camel@localhost.localdomain> Message-ID: On Mon, 12 Jan 2004, Jeremy Hylton wrote: > On Sat, 2004-01-10 at 19:50, John J. Lee wrote: [...about ZODB...] > > Which doesn't have a built-in query system, so isn't a database in the > > same way as a relational DB like Postgres or Oracle. It's more like > > BSDDB + pickle. > > A database is a lot more than a query system, although for some > applications query support is very important. Zope has a custom query > system, called the catalog, that is built on top of ZODB. I thought ZCatalog was dependent on Zope? There is IndexedCatalog, of course. > Whether ZODB > sans a builtin query system is suitable really depends on the > application. Of course. John From nospam-deets at web.de Mon Jan 12 10:28:55 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Mon, 12 Jan 2004 16:28:55 +0100 Subject: Using switches with exec? References: Message-ID: > I need to run a Python program dynamically within > another program. I am using exec for the purpose. Is > there a way to pass parameter switches to exec? You can pass a globals-dictionary to exec, which can hold the switches values. Diez From ras at holmes.nl Tue Jan 27 11:29:11 2004 From: ras at holmes.nl (Martijn Ras) Date: Tue, 27 Jan 2004 17:29:11 +0100 Subject: os.path.split: processing paths from one OS on another Message-ID: <401691D7.8050607@holmes.nl> Heya folks, I ran into the following problem: When i run this on Windows everything is as expected: C:\>python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> file='/TEST/FILE.EXT' >>> print os.path.split(file) ('/TEST', 'FILE.EXT') >>> file='C:\\TEST\\FILE.EXT' >>> print os.path.split(file) ('C:\\TEST', 'FILE.EXT') However, when i run this on Linux the results are unexpected: $ python Python 2.2.3 (#1, Nov 12 2003, 15:53:11) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> file='/TEST/FILE.EXT' >>> print os.path.split(file) ('/TEST', 'FILE.EXT') >>> file='C:\\TEST\\FILE.EXT' >>> print os.path.split(file) ('', 'C:\\TEST\\FILE') All i can find is some comments on POSIX-ness (or not) of the OS, in regard to os.path.split(), but i fail to see why that explains the different outcome of the last command in the two examples above. My server needs to be run on either Linux or Windows, it receives requests from clients that may run either OS. To process those requests i need to split the path and filename. I hoped to solves this using os.path.split (), any suggestions as to how to fix this? Mazzel, Martijn. From ashleylloyd at hotmail.com Fri Jan 9 08:53:30 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Fri, 09 Jan 2004 13:53:30 +0000 Subject: Debugging Python Message-ID: What do people generally use to debug their Python programs? I haven't seen anything out there that walks through the code, but perhaps I'm looking in the wrong places? TIA Ashley _________________________________________________________________ Tired of 56k? Get a FREE BT Broadband connection http://www.msn.co.uk/specials/btbroadband From cwilcox at etcconnect.com Fri Jan 23 13:59:38 2004 From: cwilcox at etcconnect.com (Christian Wilcox) Date: Fri, 23 Jan 2004 12:59:38 -0600 Subject: [OPINION] - does language really matter if they all do the samething? Message-ID: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> > Programming languages affect the way people > think about problem solving in different ways. The capacity to > solve problems is one of the most important capacities a > programmer can expect to have. In addition, it is the > responsibility of the programmer to see that some languages are, > by virtue of their design, made to solve certain problems in > certain ways, under various definitions of program flow, data > storage, etc. To suppose that all programming languages are, > as you might put it, fundamentally equivalent is to suppose > that english and arabic are, in the same sense, just two sides > of the same coin, which is a gross oversimplification of the > matter and a disrespect to the qualities of the languages > that make them distinct. On a more conjectural note, spoken > languages are more than just ways of expressing ideas; by > virtue of being evolving systems of communication, they serve > as an insight into the culture and people that developed > them. Programming languages are the same in that respect. You might find this http://www.artima.com/intv/craft.html artima.com interview (especially the section "Learning Languages") with Yukihiro Matsumoto, creator of Ruby, interesting. He discusses how certain programming languages focus on specific paradigms, which could allow a programmer to think in ways they may not otherwise. Python doesn't necessarily force any specific paradigm, which is one of it's selling points, IMO. Christian Wilcox From sross at connectmail.carleton.ca Sun Jan 25 11:08:26 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 25 Jan 2004 11:08:26 -0500 Subject: xrange not hashable - why not? References: Message-ID: "Gerrit Holl" wrote in message news:mailman.764.1075042048.12720.python-list at python.org... > Hi, > > why is an xrange object not hashable? I don't know the answer for this. > I was trying to do something like: > > comments = { > xrange(0, 4): "Few", > xrange(4, 10): "Several", > xrange(10, 100): "A lot", > xrange(100, sys.maxint): "Can't count them"} > for (k, v) in comments.items(): > if n in k: > commentaar = v > break There's a bit of an efficiency issue with using 'n in k' for something like xrange(100, sys.maxint), since you have to walk through the items in that range to see if n is in there, and that's a large range. Perhaps this would help: class bounds: def __init__(self, start, stop, step=1): self.start = start self.stop = stop self.step = step def is_step(self, other): q, r = divmod(other-self.start, self.step) return r == 0 def __contains__(self, other): return self.start <= other < self.stop and self.is_step(other) def __hash__(self): return id(self) def __repr__(self): return "bounds(start=%s, stop=%s, step=%s)"%\ (self.start, self.stop, self.step) import sys import random comments = { bounds(0, 4): "Few", bounds(4, 10): "Several", bounds(10, 100): "A lot", bounds(100, sys.maxint): "Can't count them"} n = random.randint(0, sys.maxint) print n for k, v in comments.iteritems(): print k if n in k: print v break else: print n, "out of bounds" HTH, Sean From jacek.generowicz at cern.ch Wed Jan 14 04:38:04 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 14 Jan 2004 10:38:04 +0100 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <95aa1afa.0401130424.49749912@posting.google.com> <95aa1afa.0401132224.1a8230c@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > Jacek Generowicz wrote in message news:... > > Go on, raise your hand if you thought that "Lisp" is a slow, > > interperted functional langugage. > > Never thought so. Michele, My post was not aimed at you specifically. It was aimed a lurkers who might infer that Lisp is only used in AI (or whatever), or who might have some unfounded assumptions about Lisp which would be re-inforced by your post. I was quite sure that my post would not be telling _you_ much you didn't already know. From maarten at remove_this_ws.tn.tudelft.nl Tue Jan 20 05:46:59 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Tue, 20 Jan 2004 11:46:59 +0100 Subject: Looking for very simple general purpose tokenizer References: Message-ID: Thank you all for your very useful comments. Below I have included my source. Could you comment if there's a more elegant way of implementing the continuation character &? With the RE implementation I have noticed that the position of the '*' in spclist is very delicate. This order works, but other orders throw exceptions. Is this correct or is it a bug? Lastly, is there more documentation and examples for the shlex module? Ideally I would like to see a full scale example of how this module should be used to parse. Maarten import re import shlex import StringIO def splitf90(source): buf = StringIO.StringIO(source) toker = shlex.shlex(buf) toker.commenters = "!" toker.whitespace = " \t\r" return processTokens(toker) def splitf90_re(source): spclist = ['\*', '\+', '-', '/', '=','\[', '\]', '\(', '\)' \ '>', '<', '&', ';', ',', ':', '!', ' ', '\n'] pat = '|'.join(spclist) + '|[^' + ''.join(spclist) + ']+' rawtokens = re.findall(pat, source) return processTokens(rawtokens) def processTokens(rawtokens): # substitute characters subst1 = [] prevtoken = None for token in rawtokens: if token == ';': token = '\n' if token == ' ': token = '' if token == '\n' and prevtoken == '&': token = '' if not token == '': subst1.append(token) prevtoken = token # remove continuation chars subst2 = [] for token in subst1: if token == '&': token = '' if not token == '': subst2.append(token) # split into lines final = [] curline = [] for token in subst2: if not token == '\n': curline.append(token) else: if not curline == []: final.append(curline) curline = [] return final # Example session src = """ MODULE modsize implicit none integer, parameter:: & Nx = 256, & Ny = 256, & Nz = 256, & nt = 1, & ! nr of (passive) scalars Np = 16 ! nr of processors, should match mpirun -np .. command END MODULE """ print splitf90(src) print splitf90_re(src) Output: [['MODULE', 'modsize'], ['implicit', 'none'], ['integer', ',', 'parameter', ':', ':', 'Nx', '=', '256', ',', 'Ny', '=', '256', ',', 'Nz', '=', '256', ',', 'nt', '=', '1', ',', 'Np', '=', '16'], ['END', 'MODULE']] [['MODULE', 'modsize'], ['implicit', 'none'], ['integer', ',', 'parameter', ':', ':', 'Nx', '=', '256', ',', 'Ny', '=', '256', ',', 'Nz', '=', '256', ',', 'nt', '=', '1', ',', '!', 'nr', 'of', '(', 'passive', 'scalars'], ['Np', '=', '16', '!', 'nr', 'of', 'processors', ',', 'should', 'match', 'mpirun', '-', 'np', 'command'], ['END', 'MODULE']] -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From jcarlson at nospam.uci.edu Fri Jan 23 00:49:10 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 21:49:10 -0800 Subject: I support PEP 326 In-Reply-To: References: <401081A1.E4C34F00@alcyone.com> Message-ID: > I suppose you could special-case min() and max() to return the > appropriate singletons if called with no arguments. > > There's something very nice about that. There's also something very > ugly about it. I'm having a hard time deciding which is stronger :-) That behavior was called very bad names by Guido. We shall not speak of it any longer. Heh. - Josiah From wsanchez at wsanchez.net Mon Jan 12 19:39:34 2004 From: wsanchez at wsanchez.net (=?ISO-8859-1?Q?Wilfredo_S=E1nchez?=) Date: Mon, 12 Jan 2004 16:39:34 -0800 Subject: setproctile()? Message-ID: Is there a way to set the kernel's notion of a python process' name on Unix such that, for example, ps shows what I specify? -wsv From r.s at ZZmindspring.com Tue Jan 6 14:57:11 2004 From: r.s at ZZmindspring.com (r.e.s.) Date: Tue, 06 Jan 2004 19:57:11 GMT Subject: looping to define a sequence of functions? References: Message-ID: "Rainer Deyke" wrote ... > r.e.s. wrote: > > Suppose we want to define ten functions such that the > > nth function of x simply returns x**n. Is there a way > > to avoid explicitly writing ten function def's? (They > > have to be ten distinct functions, not just a single > > one like def f(n,x): return x**n.) > > functions = [lambda x, n=n: x**n for n in range(10)] > > -or- > > class X(object): > def __init__(self, n): > self.n = n > def __call__(self, x): > return x ** self.n > functions = [X(n) for n in range(10)] > > -or- > > functions = [] > for n in range(10): > def f(x, n=n): > return x**n > functions.append(f) > > -or- > > def create_function(n): > def f(x): > return x**n > return f > functions = [create_function(n) for n in range(10)] > > > -- > Rainer Deyke - rainerd at eldwood.com - http://eldwood.com It's going to take me a bit to digest these, and it looks like I'm sure to learn from them, so I want to say 'thank you' now for the quick reply. From r.s at ZZmindspring.com Tue Jan 6 14:39:31 2004 From: r.s at ZZmindspring.com (r.e.s.) Date: Tue, 06 Jan 2004 19:39:31 GMT Subject: looping to define a sequence of functions? Message-ID: Suppose we want to define ten functions such that the nth function of x simply returns x**n. Is there a way to avoid explicitly writing ten function def's? (They have to be ten distinct functions, not just a single one like def f(n,x): return x**n.) E.g., the following doesn't work: f = {} for n in range(10): def f[n](x): return x**n Thanks. -- r.e.s. From peter at engcorp.com Tue Jan 20 17:45:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jan 2004 17:45:03 -0500 Subject: an example of a singleton design pattern in python? References: Message-ID: <400DAF6F.6EF66415@engcorp.com> Ville Vainio wrote: > > >>>>> "Daniel" == Daniel Ortmann writes: > > Daniel> Hello, Does anyone have an example of a singleton design > Daniel> pattern in python? > > This trivial snippet might be enough for your needs: > > class Foo(): > pass > > _inst = None > > def fooinstance(): > if not _inst: > _inst = Foo() > return _inst Looks like at least two errors, one being the parentheses on the class name, and the other being a failure to flag _inst as being global... -Peter From grahamd at dscpl.com.au Sat Jan 31 04:50:18 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 31 Jan 2004 01:50:18 -0800 Subject: Automatic access serialization References: <946d2ebc.0401301753.5bbe87c5@posting.google.com> Message-ID: gagenellina at softlab.com.ar (Gabriel Genellina) wrote in message news:<946d2ebc.0401301753.5bbe87c5 at posting.google.com>... > Hello! > > I have a number of objects that are not thread-safe - no locking > mechanism was originally provided. > But I want to use them in a thread-safe way. I don't want to analyze > each class details, looking for where and when I must protect the > code. So I wrote this sort-of-brute-force locking mechanism using > threading.RLock() around __getattr__ / __setattr__ / __delattr__. > The idea is that *any* attribute and method access is protected by the > lock. The calling thread may acquire the lock multiple times, but > other threads must wait until it is released. > This may be too much restrictive, and a bottleneck in performance, > since *all* accesses are effectively serialized - but it's the best I > could imagine without deeply analyzing the actual code. > I *think* this works well, but since I'm not an expert in these > things, any comments are welcome. Specially what could go wrong, if > someone could anticipate it. > Note: As written, this only works for old-style classes. I think that > just by adding a similar __getattribute__ would suffice for new-style > classes too - is that true? A few problems that I can see. First is that this only protects access to the reference to the data in question. Imagine that the data value is a dictionary. If I understand it correctly, two different threads could still get a reference to the same dictionary and then independently start modifying the dictionary at the same time. This is because you are then dealing with the dictionary directly and your locks aren't involved at all. Second is that it isn't always sufficient to lock at the level of individual attributes, instead it sometimes necessary to lock on a group of attributes or even the whole object. This may be because a thread has to be able to update two attributes at one time and know that another thread will not change one of them while it is modifying the other. One hack I have used is always ensuring that access to an object is through its functional interface and then locking at the level of function calls. That is provide additional member functions called lockObject and unlockObject which operate the thread mutex. When using the class then have: object.lockObject() object.someFunc1() object.someFunc2() object.etc() object.unlockObject() This can sort of be automated a bit by having: class _SynchronisedMethod: def __init__(self,object,name): self._object = object self._name = name def __getattr__(self,name): return _SynchronisedMethod(self._object,"%s.%s"%(self._name,name)) def __call__(self,*args): try: self._object.lockObject() method = getattr(self._object,self._name) result = apply(method,args) self._object.unlockObject() except: self._object.unlockObject() raise return result class _SynchronisedObject: def __init__(self,object): self._object = object def __getattr__(self,name): return _SynchronisedMethod(self._object,name) You can then say: sync_object = _SynchronisedObject(object) sync_object.someFunc1() sync_object.someFunc2() sync_object.etc() Although this avoids the explicit calls to lock the object, it still isn't the same thing. This is because in the first example, the lock was held across multiple function calls whereas in the second case it is only held for a single call. Thus something like the following could fail: if sync_object.dataExists(): sync_object.getData() This is because something could have taken the data between the time the check for data was made and when it was obtained. Thus automating it like this isn't foolproof either. The closest you will probably get to a quick solution is to have the lock/unlock functions for the object and change any code to use them around any sections of code which you don't want another thread operating on the class at the same time. You may even have to hold locks on multiple objects at the same time to ensure that things don't get stuffed up. Thus it isn't necessarily a simple task to add threading support after the fact. You probably will have no choice but to analyse the use of everything and work out to correctly implement locking or even change the functional interface a bit so functions can be atomic in themselves. Ie., rather than having to check if data exists before first getting it, you just try and get it and either rely on an exception or have the thread wait until data is there. From exarkun at intarweb.us Wed Jan 7 20:04:23 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 7 Jan 2004 20:04:23 -0500 Subject: PRE-PEP: new Path class In-Reply-To: <3FFC9209.7060703@beyond-thoughts.com> References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <20040108010423.GA13398@intarweb.us> On Thu, Jan 08, 2004 at 12:11:05AM +0100, Christoph Becker-Freyseng wrote: > [snip] > > openwith would be a nice add-on. I see two problems with it: > 1.) it's long. I mean > f(str(path), *args) > is shorter than > path.openwith(f, *args) > I got an idea of shortening this and making it look a bit like shell > (I'm not convinced of it very much, but I didn't want to keep it secret > --- maybe others like it ...) > > path > (f, arg1, arg2, ...) > > (this works by overwriting path.__gt__) You shoulda kept it secret. That's horrible. If you're going to override a piece of syntax for this, I think nothing makes as much sense as __call__ (but I don't think that makes much sense either). Jp From ods at strana.ru Tue Jan 27 10:46:02 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 27 Jan 2004 18:46:02 +0300 (MSK) Subject: [ANN] ip2cc-0.3: now it works with Python 2.3 Message-ID: ip2cc: Lookup country country by IP address =========================================== WHAT IS IT If you want to gather web statistics by countries (not by top-level domains) or implement targeting, here is solution: ip2cc. This module allows to resolve country from IP address. USAGE update.py - build/update database ip2cc.py
- print country name for which
is registered For example: $ ./ip2cc.py python.org python.org (194.109.137.226) is located in NETHERLANDS $ ./ip2cc.py google.com.ru google.com.ru (216.239.33.100) is located in UNITED STATES Module can be used as CGI. WHERE TO GET Homepage: http://ppa.sf.net/#ip2cc Download: http://prdownloads.sf.net/ppa/ip2cc-0.3.tar.gz?download LICENSE Python-style ACKNOWLEDGEMENTS Jason R. Mastaler Fredrik Lundh CHANGES 0.3 - Due to bug in bsddb module (http://python.org/sf/788421) it's rewriten to use very simple own database. 0.2 - Adopted to new format of registrars. - Added LACNIC to sources. - Fixed contry code map and added -check option to simplify maintainance. 0.1 Initial release -- Denis S. Otkidach http://www.python.ru/ [ru] From neanthumain at yahoo.com Sat Jan 10 19:44:02 2004 From: neanthumain at yahoo.com (N?ant Humain) Date: 10 Jan 2004 16:44:02 -0800 Subject: Providing Default Value for User Input Message-ID: I have just begun learning Python so that I can write a simple script to make modification of a file used by another Python script easier. This file is basically a list of regular expressions. What I want to do is allow the user to select one of these regular expressions to modify, but I've realized I know of no way to provide a default value for user input. I could choose to show the regular expression the user has chosen and simply allow the user to retype it and modify it from there, but that is time consuming and error prone. Does Python support a way to do this? If worse comes to worst, is there a way I could write such code on my own without having to write a C-based module (I'd like to stick to Python code only since some users will be running this script on Windows without a C compiler)? From bwglitch at hotpop.com Thu Jan 22 16:27:49 2004 From: bwglitch at hotpop.com (BW Glitch) Date: Thu, 22 Jan 2004 16:27:49 -0500 Subject: Ordered dictionary? In-Reply-To: References: Message-ID: Leif K-Brooks wrote: > I need to associate a string (key) with an integer (value). A dictionary > would do the job, except for the fact that it must be ordered. I also > need to look up the value for a specific key easily, so a list of tuples > wouldn't work. A dictionary could be used. When you need to managed the items in order, what you would do is called dict.keys(), followed by a sort. I don't know if this helps at all... -- Glitch http://andres980.tripod.com/ "That is the law of the jungle. The hunters and the hunted. Scrap or be scrapped!" "Animals hunt to SURVIVE!" "And what do you think war is about?!" -- Dinobot and Tigatron, "The Law of the Jungle" From theller at python.net Tue Jan 20 14:32:08 2004 From: theller at python.net (Thomas Heller) Date: Tue, 20 Jan 2004 20:32:08 +0100 Subject: ctypes 0.6.3 released References: Message-ID: <3caamn5z.fsf@python.net> Ganesan R writes: >>>>>> "Thomas" == Thomas Heller writes: > >> It works on Windows, Linux and MacOS X (the latter require that >> your machine is supported by libffi). > > Hi, > > I maintain the ctypes Debian package. The following patch allows ctypes to > be built on 64-bit archs. > > --- ctypes-0.6.3.orig/source/callproc.c > +++ ctypes-0.6.3/source/callproc.c > @@ -549,11 +549,11 @@ > #if (SIZEOF_LONG_LONG == 8 && SIZEOF_LONG == 4) > #undef ffi_type_ulong > #define ffi_type_ulong ffi_type_uint32 > -#define ffi_type_ulonglong ffi_type_uint64 > #undef ffi_type_slong > #define ffi_type_slong ffi_type_sint32 > -#define ffi_type_slonglong ffi_type_sint64 > #endif > +#define ffi_type_ulonglong ffi_type_uint64 > +#define ffi_type_slonglong ffi_type_sint64 > > Ganesan Cool, thanks. I've applied this in cvs. Thomas PS: Can you post (or send by private email, if it is large, the output of the test suite: 'python setup.py test' ? From theller at python.net Wed Jan 7 05:45:35 2004 From: theller at python.net (Thomas Heller) Date: Wed, 07 Jan 2004 11:45:35 +0100 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> Message-ID: Jacek Generowicz writes: > sdd writes: > >> Jp Calderone wrote: >> >> > On Tue, Jan 06, 2004 at 03:27:06PM +0100, Jacek Generowicz wrote: >> > >> >> >>Where can I find concise, clear documentation[*] describing what one has >> >>to do in order to enable Python's internal help to be able to provide >> >>descriptions of Python keywords ? >> > "Quote them" >> >> > help('if') >> >> > Jp >> >> Or simply use help() >> and interactively enter lines. > > > Yes, but this actually does not work out of the box (on any of the > GNU/Linux, Mac OS X, and even Windoze installaitions I have tried). You > get an error message complaining about the absence of HTML > documentation and setting PYTHONDOCS. So, to rephrase my question ... > > > Where can I find clear instructions on how to install and configure > the Python documentation which is necessary to make the following > work: > > >>> help('and') > > ? Download the HTML archive from , and unpack this in a temporary directory. Leave the directory structure intact - in Winzip, make sure the 'Use Folder Names' checkbox is checked. This creates a Python-Docs-2.3.3 subdirectory. Copy everything in this directory (including subdirectories) into your c:\python23\Doc folder (normally there is a single Python23.chm file in it), and you're done. Thomas From jsbenson at bensonsystems.com Thu Jan 15 17:43:14 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 15 Jan 2004 14:43:14 -0800 Subject: off-topic, but I can't resist the flamebait: best minicomputer? Message-ID: <0cd901c3dbb8$f61e4470$8d09500a@jsbwxp3> Like I said, I can't resist the temptation... Tandem practically invented the commercially useful, networked minicomputer. Up to 16 loosely-coupled processors with distributed microkernel OS architecture per system connected via a SAN (System Area Network), RAID 1 (mirrored disk volumes), SSI (Single System Image, with single logon, of course), multiple-system database commits, shared-nothing fault-tolerance: you had all this back in the late 70's. You could also add another network level to harness up to 255 16-processor systems together. This gave Tandems the linear expandability that allowed their "minicomputer" systems to scale up to and overtake the IBM big iron. As a matter of fact, it was the Tandem expandability (since you could have multiple channels per processor, 16 processors per system, 255 systems per Expand network) that provided the I/O bandwidth to enable the ATM explosion. Stock exchanges used to melt down automatically when their legacy systems choked on excessive trading volume. For years, NASDAQ has used Tandems, and needs to proactively decide when to suspend trading because the Tandems handle pretty much whatever is thrown at them. They're fault-tolerant, too. That's why a some of your 911 systems use them, because some people feel that 911 has to work all the time, like stock exchanges and ATM networks. The problem is, Tandems are the unsung heroes of data processing because they're embedded so deeply in the infrastructure. You place your trade with a discount broker, not a Tandem. You see a Diebold or perhaps an NCR ATM, not a Tandem. Go back to the top and look at the lineup of late 70's Tandem features. Chances are, you didn't read about them in Byte or wherever until the eighties or nineties. Fact is, pretty much everybody has been following Tandem's lead for decades, however much they posture as "industry leaders." When I started working on Tandems in the late 70's and they were expected to run weeks, months and years without stopping, I remember reading an article in which a Unix guy bragged that his system had actually run two or three weeks without crashing. Even now, in the 2000's, people still periodically reboot their Unix and NT servers to scare away the memory leak bogeymen, even if everything appears to be working fine. Anyone advocating that for a Tandem system even 20 years ago would have been dispatched to the nearest psychotherapist. Unix boxes: carried the Multics banner forward, and pioneered lots of software technology. Macs and PCs: added GUIs to the mix. Tandem: you never heard about it, because it never broke. From olivier.marechal at laposte.net Sat Jan 31 17:01:07 2004 From: olivier.marechal at laposte.net (Olivier) Date: Sat, 31 Jan 2004 23:01:07 +0100 Subject: wxPython documentation Message-ID: <401c25a3$0$11357$636a55ce@news.free.fr> Where could I find a good documentation about wxPython (a documentation which is not for C++ !!!) Olivier From jcarlson at nospam.uci.edu Fri Jan 23 03:40:59 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 00:40:59 -0800 Subject: Accessing Microsoft Word from Python In-Reply-To: References: Message-ID: Mickel Gr?nroos wrote: > Hi! > > I'm fiddling with Python for Windows (normally using Linux) and as a part > of that I want to try to make a simple word frequency list generator to be > used in conjunction with Microsoft Word. Does anybody have any good > pointers on where I can find information about accessing Word-documents > (or other Microsoft Office applications) from Python? To be more specific, > I want to be able to: > > - get the text content of the full Word document > - define a callback in Python that is called every time a user enters a > character into the text of a Word document > - get the last two graphical word tokens before the current position of > the insertion cursor in the text of the Word document. > > Cheers! > > /Mickel Mickel, Sounds like something that could be done with VB. VB will let you script anything in Word or Office, but then it requires you to learn the horror that is VB. Perhaps a limited interface is available through COM, but I wouldn't bet the farm on it. - Josiah From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 21 21:39:35 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 13:29:35 +1050 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: Message-ID: On Wed, 21 Jan 2004 17:53:19 -0300, - wrote: > Why 5 does not appear ? (this was the source of a deep bug in a 4000+ > lines networked program...) Curious: >>> a = range(8) >>> for b in a: ... if ( b == 4 ): ... a.remove(b) ... print ( b, a ) ... (0, [0, 1, 2, 3, 4, 5, 6, 7]) (1, [0, 1, 2, 3, 4, 5, 6, 7]) (2, [0, 1, 2, 3, 4, 5, 6, 7]) (3, [0, 1, 2, 3, 4, 5, 6, 7]) (4, [0, 1, 2, 3, 5, 6, 7]) (6, [0, 1, 2, 3, 5, 6, 7]) (7, [0, 1, 2, 3, 5, 6, 7]) It seems that, having removed the current item in the list, the index of the "for" loop hasn't changed. The next iteration increments that index, even though the list itself has become shorter. -- \ "You know I could rent you out as a decoy for duck hunters?" | `\ -- Groucho Marx | _o__) | Ben Finney From computer.problemen at skynet.be Sat Jan 10 10:30:51 2004 From: computer.problemen at skynet.be (broebel) Date: Sat, 10 Jan 2004 16:30:51 +0100 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> <3fff1245@usenet01.boi.hp.com> Message-ID: <400018e8$0$294$ba620e4c@news.skynet.be> Just like you don't speak dutch, I don't write python (that's a good reason to learn, isn't it) so I'm not trying out your proposal to see wheather it works or not. I kept it aside to check as soon as I understand more of the language. So thanks any way. btw is there a special reason why someone should speak dutch to programm in python.? "djw" schreef in bericht news:3fff1245 at usenet01.boi.hp.com... > Joe Francia wrote: > > > d wrote: > >> Worked fine for me on Linux... made two suggested changes: 1) use > >> raw_input(), not input(), 2) check user input for errors. Sorry, I don't > >> know how to say "Enter a number between 0 and 500" in whatever language > >> this is in (German?) > >> > > > > You're a Python user and you don't recognize Dutch?!?! For shame... ;>) > > Well, I was only off by one country - not too bad for someone who took 4 > years of high school Spanish and can hardly speak a word of it. > > I was looking at the code that I proposed to the OP, and wondered if this > wasn't better: > > #!/usr/bin/env python > while 1: > bedrag = raw_input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) > try: > bedrag = int( bedrag ) > if bedrag < 0 or bedrag > 500: > raise ValueError > except ValueError: > print "Enter a number between 0 and 500" # In DUTCH, of course! > else: > break > > # ... etc. > > > Is this good style, that is, to put multiple items inside a single try: > except: else: block? Seems more compact and tidy than my first try. > > -d > > > From poyol at hotmail.com Fri Jan 9 03:36:48 2004 From: poyol at hotmail.com (OPQ) Date: 9 Jan 2004 00:36:48 -0800 Subject: asynchronous rpc? References: Message-ID: "Maxim Khesin" wrote in message news:... > Hi, > is there a python framework that supports async RPC calls? > thanks! try twisted python. You may find what your're looking for. hth, ---OPQ From and-google at doxdesk.com Sat Jan 24 18:01:03 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 24 Jan 2004 15:01:03 -0800 Subject: utf8 encoding problem References: <20040122103549.GA5620@wiggy.net> Message-ID: <2c60a528.0401241501.11cab334@posting.google.com> Martin v. Loewis wrote: > As Denis explains, it is true. See 17.13.4 Indeed. [Skip: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 ] > To have non-ASCII input, use multipart/form-data: Quite so, in theory. Of course in reality, no browser today includes a Content-Type header in the subparts of a multipart/form-data submission, so there's nowhere to specify an charset here either! argh. multipart/form-data as implemented in current UAs is just as encoding-unaware as application/x-www-form-urlencoded, sadly. In practical terms it does not really matter much which is used. [...waiting for the glorious day when UTF-8 and UCS-4 are the only acceptable encodings; and on that day, Shift-JIS will be the first against the wall oh let me blummin' well tell you my brother...] -- Andrew Clover mailro:and at doxdesk.com http://www.doxdesk.com/ From eric.brunel at N0SP4M.com Mon Jan 12 05:22:39 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 12 Jan 2004 11:22:39 +0100 Subject: Communicating with MSVC++ via COM: how? References: Message-ID: Mark Hammond wrote: > Eric Brunel wrote: > >> This script doesn't work: the call to docs.CloseAll fails with the error: >> >> Traceback (most recent call last): >> File "test.py", line 13, in ? >> docs.CloseAll() >> TypeError: object of type 'int' is not callable > > > This is because docs.CloseAll is making the call, and returning an int. > This, docs.CloseAll() is attempting to call that int. Hi Mark, Thanks for your answer. We finally figured out this one, but the problem lies a bit farther in the script: bkpts.AddBreakpointAtLine(86) The method AddBreakpointAtLine takes an *optional* parameter which is the line number on which to put the breakpoint. But bkpts.AddBreakpointAtLine actually calls the method AddBreakpointAtLine with no parameter, so I just can't figure out how to call the method *with* a parameter... > It looks very much like you have no makepy support for MSVC built. > > Just after the line: > app = win32com.client.Dispatch('MSDev.Application') > Try adding: > app = win32com.client.gencache.EnsureDispatch(app) > > That should force makepy, and everything should start working. I tried what you suggest, but it didn't work: I get the following error: >>> app = win32com.client.gencache.EnsureDispatch(app) Traceback (most recent call last): File "", line 1, in ? File "H:\Tools\Python\bin\Windows\Python21\win32com\client\gencache.py", line 423, in EnsureDispatch disp = win32com.client.Dispatch(prog_id) File "H:\Tools\Python\bin\Windows\Python21\win32com\client\__init__.py", line 95, in Dispatch return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, UnicodeToString, clsctx) File "H:\Tools\Python\bin\Windows\Python21\win32com\client\__init__.py", line 26, in __WrapDispatch typeinfo = dispatch.GetTypeInfo() File "H:\Tools\Python\bin\Windows\Python21\win32com\client\dynamic.py", line 438, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: MSDev.Application.GetTypeInfo Trying to force the generation of the support files via an explicit makepy.py didn't work either: doing a Dispatch('MsDev.Application') still doesn't get the right type. Forcing the type by doing Dispatch('MsDev.Application', resultCLSID="{the-class-id}") seems to work, but apparently, the generated class knows nothing about the types of its members and simple things as: app.Visible = 1 fail with a traceback (something like "incorrect type for variable" - sorry for the imprecision: we have a French Windows, so the message I get is in French...). Getting an attribute like app.Debugger seems to work, but printing it says: so the object is a dynamic one, and also knows nothing about its type. Is there any solution to our problems? TIA -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From root at mail.artnet.com.pl Tue Jan 27 10:20:55 2004 From: root at mail.artnet.com.pl (root at mail.artnet.com.pl) Date: Tue, 27 Jan 2004 16:20:55 +0100 Subject: Uwaga probowales wyslac wiadomosc ktora zawierala virusa Message-ID: <200401271520.i0RFKt0S000511@mail.artnet.com.pl> Probowales wyslac wiadomosc do biuro at faxpol.gda.pl ktora zawierala virusa. ====================================== body.zip archive: ZIP body.zip/body.pif packed: UPX body.zip/body.pif infected: I-Worm.Novarg ====================================== Dzial Techniczny ArtNet Sp. z o.o. 80-855 Gdansk ul.Waly Piastowskie 1 tel.(058)307-45-37 admin at artnet.com.pl From ep at epoz.org Mon Jan 12 16:21:21 2004 From: ep at epoz.org (Etienne Posthumus) Date: Mon, 12 Jan 2004 22:21:21 +0100 Subject: Anyone else using Python OpenSSL Wrappers? (http://sourceforge.net/projects/pow/) Message-ID: <44E8A0EE-4545-11D8-BA82-0003935458F6@epoz.org> I have been considering the various SSL/crypto libraries for Python, and they all have their plus and minus points. The main sticking point has been to have BOTH X509 file support and access to some crypto operations for signing/hashing. The only one which does both (please correct me if this is a misconception on my part) is http://sourceforge.net/projects/pow/ but I can find very few references to it, or projects that use it via Google. Does anyone use it in their projects, or have any experiences to share? So far have tested reading some basic certificates and signing some small bits of data, and it looks pretty good. All comments welcome. Etienne Posthumus Amsterdam, Nederland From exarkun at intarweb.us Mon Jan 19 14:05:08 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 19 Jan 2004 14:05:08 -0500 Subject: A lazy-committing database object with curry? In-Reply-To: References: Message-ID: <20040119190508.GA3993@intarweb.us> On Mon, Jan 19, 2004 at 08:45:45AM -0800, Tim Lesher wrote: > I'm writing a database helper class that represents records in a SQL > database as objects. I want to be able to instantiate the objects > (from the database), play with their values locally, then lazily > commit the changes all at once (via an explicit commit call). Other > than the call to Commit(), I don't want clients of this class to have > to think about the fact that there's a database behind it all--there are > some interesting and non-obvious dependencies on the particular values > that are committed together, and I want to hide that in the Commit() call. Sounds familiar... > > I'm going to have a number of these, so I wanted to come up with a > solution that's short on glue code and can easily be aggregated into > all the classes that represent record types. This is what I've come > up with: > > # Simple currying class, no kwargs > class curry: > def __init__(self, fun, *args): > self.fun = fun > self.pending = args[:] > def __call__(self, *args): > return self.fun(*(self.pending + args)) > You don't need to copy args, Python has done that for you already. > > # Simple table: two columns, "title" and "description" > class SomeRecordType(object): > def __init__(self, title, description): > self.__modifications = {} > > # Avoid triggering propset on init > self.__dict__['title'] = title > self.__dict__['description'] = description > Are you sure? How will the initial values be committed to the database, if you don't catch them in the modifications dict? I guess you might be handling initial values somewhere else, in code you didn't post... > def __getValue(name, self): > try: > return self.__modifications[name] > except KeyError: > return self.__dict__[name] > > def __setValue(name, self, newValue): > self.modifications[name] = newValue > > name = property(curry(__getValue, 'title'), > curry(__setValue, 'title')) > description = property(curry(__getValue, 'description'), > curry(__setValue, 'description')) Nift. You surely don't use the full capabilities of currying here, but you are incurring a double function call overhead on every setattr now. Here's another way to do it: def makeModificationFunctions(name): def modget(self, value): try: return self.__modifications[name] except KeyError: return self.__dict__[name] def modset(self, value): self.__modifications[name] = value return modget, modset title = property(*makeModificationFunctions('title')) description = property(*makeModificationFunctions('description')) Of course, you can go one step better and use a metaclass: class MetaRecordType(type): def __new__(metaclass, name, bases, ns): for k, v in ns.items(): if v is makeModificationFunctions ns[k] = property(*v(k)) return type.__new__(metaclass, name, bases, ns) and now in the class definition simply say: __metaclass__ = MetaRecordType title = makeModificationFunctions description = makeModificationFunctions > > def Commit(self): > if self.modifications != {}: This can be just "if self.__modifications:" > # - snip - Do database commit and clear modifications > self.__dict__.update(self.modifications) > self.modifications = {} > > So I can do this: > > foo = myDb.LookupTitleRecord('some title') > print foo.description # 'foo' > foo.description = 'bar' # not updated in the DB yet > print foo.description # 'bar' > foo.Commit() # now updated in the DB > > > Are there any pitfalls to doing this? Am I being dazzled by the shiny > new toy that is currying? Is there another simple solution, or a > refinement of this one, that I'm not seeing? > One possible problem is failed commits. If you're doing commits transactionally, and the transaction fails, your in memory objects will retain their now-inconsistent values while the database remains unupdated. If you're not using transactions.. well that's a whole other problem :) You may want to look at xsdb and atop. Neither uses SQL, but both have developed pretty heavily on some of the ideas you're tinkering around with. Jp From jjl at pobox.com Wed Jan 14 18:35:17 2004 From: jjl at pobox.com (John J. Lee) Date: 14 Jan 2004 23:35:17 +0000 Subject: Does anyone else not find the fun in programming...? References: Message-ID: <871xq2t87e.fsf@pobox.com> Arthur writes: [...] > >Do I need help ? > > Since, for me, it's most particularly fun when I *should* be doing > something else: > > it would seem, I do. :-)) it's-only-work-when-they-make-you-do-it-ly y'rs, John From cookedm+news at physics.mcmaster.ca Thu Jan 29 17:21:19 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 29 Jan 2004 17:21:19 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: At some point, LittleDanEhren at yahoo.com (Daniel Ehrenberg) wrote: > Io (www.iolanguage.com) is a new programming language that's purely > object-oriented (but with prototypes), has a powerful concurrency > mechanism via actors, and uses an extremely flexible syntax because > all code is a modifiable message tree. Like Python, it is dynamically > typed, has a very clean syntax, produces short code, and is > excruciatingly slow (on the same level as eachother). Io has a unique > syntax combining Lisp's idea of functions for flow control with > traditional function syntax and smalltalk-like syntax to get slots of > objects. Io has no keywords and everything, even multiple lines of > code, can be used as an expression. Even as a beginner to Io, I was > able to write something in just 43 lines to let you do something like > this (and more) in Io: > > each((key, value) in map(x=1, y=2, z=3), > write(key, ": ", value, "\n") > ) > > Neither the each function nor the map function were built in (Io has > other mechanisms for that kind of thing, but they are less efficient). > Can anyone show me how to so much as alias "for" to "each" in Python > or allow block syntax at all without hacking the C source code? Hey, if I wanted to to, I could add functions and all that that would make Python look like Lisp, or IO, or whatever. But, why? If I wanted to write Lisp or Io, I'd use those. Your example I'd write in Python as for key, value in dict(x=1, y=2, z=3): print '%s: %s\n" % (key, value) I didn't have to write 43 lines of support code, and it's also two lines. I don't think "this isn't builtin" is a selling point -- you need a critical mass of builtins to make a language useful. > Io doesn't use __methods_with_this_annoying_syntax__ because nothing > is supposed to be for internal use only and there are only about three > functions that would cause a problem if overridden. > For embedding, Io doesn't have to use Py_ALL_CAPS, instead it just > uses IoCamelCase, which looks much better. Interfaces to C are much > more object oriented. Ok, these two points are window-dressing: minor spelling and punctuation issues (which seems to be what most language wars are about). Heck, use boost::python for C++ interfaces; those function names are even shorter. Or use pyrex to generate wrappers, writing them in a Pythonesque language. > Many users of Io (myself included) have switched over from Python for > these reasons. > > I guess there are still the obvious advantages of Python over Io, > including > *large community > *more bindings to stuff Yep. That's a *big* difference, I'd say. > *strict coding conventions > *inflexible so everything is the same Can you elaborate a bit on why Python is inflexible? I find Python to be extremely flexible. > *no need to close blocks > But unless there are other problems, the first two go away soon > (considering that Io was first created just two years ago). The last > three are somewhat trivial and may even be to Io's advantage. Python is 14 years old, and it's still working on global domination; Io's got some catching up to do :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From shalabh at cafepy.com Tue Jan 13 01:39:13 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Mon, 12 Jan 2004 22:39:13 -0800 Subject: Operator overloading and __getattr__ In-Reply-To: References: Message-ID: Alex Martelli wrote: > > It's true that (with newtype classes) special methods > can't be usefully "installed in the instance", but it's > not true that they can't usefully be "installed after > the class is defined" (as long as they ARE installed in > the _class_, not in the _instance_). > > For example: > > >>>>class X(object): pass > > ... > >>>>x = X() >>>>print x > > <__main__.X object at 0x402dea8c> > >>>>x.__str__ = lambda: "I am an X" >>>> >>>>print x > > <__main__.X object at 0x402dea8c> > >>>>X.__str__ = lambda self: "I am an X" >>>>print x > > I am an X > > > Here we see that the first attempt, "installing in > the instance" in your terminology, was inoperative; but > the second one, "installing in the class" even though > well after the class was defined was perfectly operative > (on existing instances of the class, too -- of course it > also works just fine on any further new instance you may > create thereafter). > > If you want to add what amounts to a "per-instance > special method" you have, in practice, to make the > instance's class unique. There are several ways to > do that, including on-the-fly and (better if you do > know all instances of a certain class will need such > treatment) in a __new__ method on the common baseclass. Another option might be to use a descriptor on the class that looks up an instance attribute. A simplified example: >>> class X(object): pass ... >>> x = X() >>> >>> class iprop(object): ... def __init__(self, ipropname): ... self.ipropname = ipropname ... def __get__(self, ob, cls): ... if ob is not None and ob.__dict__.has_key(self.ipropname): ... return ob.__dict__[self.ipropname] ... >>> X.__str__ = iprop('__istr__') >>> >>> x.__istr__ = lambda: 'this is the instance x' >>> >>> print x this is the instance x >>> Any downside to this one? -- Shalabh From gerrit at nl.linux.org Tue Jan 6 14:52:40 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 6 Jan 2004 20:52:40 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <20040106195240.GE4581@nl.linux.org> [PEP] > > >7) Should the various gettime methods return Datetime > > >objects. [John Roth] > > >Of course. I was hasitating, because of the backwards-compability, but this should not be a reason not to make things better, of course (TV isn't backward compatible with radio either ;) [Mike C. Fletcher] > > What are we doing for Python 2.2 then? I agree with the principle, but > > we should likely have a fallback when datetime isn't available. [John Roth] > Do we care? If this is going into Python, it will be in 2.4 at the > earliest, with a possible addon to a late 2.3 release. I don't see > it going into 2.2 at all, although a backwards version would > be nice. If the PEP will be finished and may be accepted, I think that the roadmap of introducing the feature will be like sets: In 2.4, it's a library, and if it's succesful/popular, it may become a builtin in 2.5. > > Path commonprefix are different operations from str commonprefix. Paths > > should only accept entire path-segments (names) as being equal, while > > strings should accept any set of characters: > > > > '/this/that/those/them' > > '/this/thatly/those/them' > > > > should see '/this/' as the commonprefix for the paths, not '/this/that'. In should... it doesn't seem to do so currently. > Good point if you're thinking of heterogenous collections. If you're > thinking (as I am) that an object can represent a directory, then it > seems like a singularly useless method. The only place where I can think of a use is a tarfile/zipfile. For a path, it means nothing. It can be useful but since it needs multiple paths, it can't be a method. The only thing I can think of is a classmethod, a constructor, but I don't really like the idea much. > > >13) chdir, chmod, etc? > > > > > >No. This has nothing to do with pathname. Is p.chdir() better or worse than chdir(p)? The latter reads better, but that may be because we're used to it. But on the other hand, that may be a convincing argument just as well :) > > chdir should accept a path, otherwise doesn't seem like it > > should be a method. > > If the path object describes a directory, then I'd see > a .chdir() method as useful. Otherwise, it belongs > somewhere else, although I don't have a clue where > at the moment. I think there should be no distinction between files and directories, and that p.chdir() for a non-directory should raise the same exception as currently (OSError Errno 20). yours, Gerrit. -- 27. If a chieftain or man be caught in the misfortune of the king (captured in battle), and if his fields and garden be given to another and he take possession, if he return and reaches his place, his field and garden shall be returned to him, he shall take it over again. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From slzatz at hotmail.com Mon Jan 19 08:47:35 2004 From: slzatz at hotmail.com (Steve Zatz) Date: 19 Jan 2004 05:47:35 -0800 Subject: Simple (?) Regular Expression Question References: Message-ID: <6747bc9d.0401190547.1d3b6b@posting.google.com> Thanks to both of you for your help. From r.s at ZZmindspring.com Thu Jan 1 18:22:45 2004 From: r.s at ZZmindspring.com (r.e.s.) Date: Thu, 01 Jan 2004 23:22:45 GMT Subject: PythonWin problems References: Message-ID: <9Z1Jb.15438$lo3.12939@newsread2.news.pas.earthlink.net> "Colin J. Williams" wrote ... > PythonWin has been my favourite IDE for quite a while. > > When one right clicks on a .py file in the Windows Explorer, among the > options are Open and Edit. The former is the default and executes > Python, with the selected script. The latter activates the PythonWin > editor, with the selected script. > > Since, most frequently, I wish to edit the script, or execute it with > the debugger, I tried changing the default to Edit, using the Edit File > Type menu. FWIW ... I'm not sure what you mean by "Edit File Type menu". Using WinXP Pro, in Windows Explorer I went to Tools/Folder Options/File Types selected PY, clicked Advanced, and set the default to Edit. Now double-clicking a .py file brings it up in PythonWin, and I've experienced neither of the problems that you report below. > > Unfortunately, this leads to a couple of problems: > > 1. Any activity becomes horrendously slow, and > 2. The following message appears: > LoadBarState failed - LoadBarState failed (with win32 exception!) > [Dbg]>>> From bart_nessux at hotmail.com Thu Jan 8 18:57:27 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 08 Jan 2004 18:57:27 -0500 Subject: count objects in a list and random numb gen References: <7xekuaxbj1.fsf@ruckus.brouhaha.com> Message-ID: <3FFDEE67.4070309@hotmail.com> Paul Rubin wrote: > Bart Nessux writes: > >>New to Python... trying to figure out how to count the objects in a >>list and then map the count to the objects or convert the list to a >>dict... I think the latter would be better as I need a number >>associated with each entry. Any pointers? > > > I'm sorry but I just can't understand the above description I want to count the objects in a list. len works well for this. Once I have a count, I want to map that count to the items in the list like this: entry one is 1 entry two is 2 entry three is 3 ... This is why I thought a dictionary may be better suited for this. > > >>Also, does this bit of code look to be truely random? >> >>def random_number_gen(): >> winner = [] >> winner.append(random.sample(xrange(100000), 1)) >> print winner > > > If you want to choose one random winner out of a list, you can say > print random.randint(100000). > > Note that Python's random function doesn't try to be really seriously > random, but only to have reasonable statistical properties. If you > need random numbers that can stand up to an adversary (e.g. you're > using it in an online game where the winners get substantial prizes), > you shouldn't generate them with the random module. I think random.sample is better than you think: sample( population, k) Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be *valid random samples*. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). From usenet_spam at janc.invalid Thu Jan 8 18:56:09 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 08 Jan 2004 23:56:09 GMT Subject: FYI: Python in Pricelessware 2004 list Message-ID: Python was voted into the Pricelessware 2004 list in the "Programming" category. This list reflects what the participants of alt.comp.freeware consider their favourite freeware programs. The new Pricelessware 2004 list is online since yesterday: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From simonb at NOTTHISBIT.webone.com.au Tue Jan 20 20:33:06 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Wed, 21 Jan 2004 12:33:06 +1100 Subject: Pyrex without Python (was Re: calling Pyrex results from C) References: Message-ID: On Tue, 20 Jan 2004 18:57:49 -0600, Jeff Epler wrote: > Perhaps I should take the advice given elsewhere to ask on a pyrex mailing > list, but I thought I'd try here first. > > As I mentioned in another thread a few weeks ago, a current hobby is > writing code for small embedded processors, where "small" means 1k-4k > instructions and 128-1k bytes data. C is a fine language for this as long > as you don't use FP arithmetic or much of the standard library. > > I wish I could write my code in Pyrex, of course keeping to 'int8_t' and > 'int16_t' as only basic data types, but it inevitably makes Python API > calls. Really? Can you post an example of what code you would write? I also use pyrex/python etc. and write code for Atmel AVRs, and fail to see how pyrex code (without the python API) would be easier than just c. Simon. -- Simon Burton, B.Sc. Licensed PO Box 8066 ANU Canberra 2601 Australia Ph. 61 02 6249 6940 http://arrowtheory.com From candiazoo at comcast.net Fri Jan 2 14:23:48 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 19:23:48 GMT Subject: Problem building on BeOS... References: Message-ID: <8zjJb.725764$Tr4.1845399@attbi_s03> Is there a way to strip'em? I see "cr nl". :/ Mike In message , Donn Cave wrote: > In article , > Zoo Keeper wrote: > > > Thanks for the reply! I checked in my editor (pe) and it indicates just a > > carriage return at the end of the line (visibles and tab stops on). > > I've never used pe. I would hope it doesn't do that, but to say > for sure I'd run the file through "od". Like, > $ fgrep '\' arrayobject.h | od -a > > If you see anything between "\" and "nl", that's your problem. > > Donn Cave, donn at u.washington.edu From peter at engcorp.com Fri Jan 9 09:09:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:09:17 -0500 Subject: What psyco is goot at [Was: Rookie Speaks] References: Message-ID: <3FFEB60D.A57578E@engcorp.com> Samuel Walters wrote: > > I've heard of a tool, I believe it's called HotSpot, that will help you > figure out which lines of code, not functions, are the most expensive for > you. You could then see if wrapping those lines in a function and binding > it with psyco would give you a gain in performance. You might look into > it. I haven't researched it, know nothing about it, and it's pretty low > on my to-do list ATM, but it might help you with your needs. Actually, "Hotshot" is the new profiler that was added in 2.2:: HotShot, a new profiler implemented using a C-based callback, has been added. This substantially reduces the overhead of profiling, but it is still quite preliminary. Support modules and documentation will be added in upcoming releases (before 2.2 final). See also http://www.python.org/doc/current/lib/module-hotshot.html . -Peter From no at spam.invalid Sat Jan 24 14:27:55 2004 From: no at spam.invalid (Russell E. Owen) Date: Sat, 24 Jan 2004 11:27:55 -0800 Subject: Tkinter Base Window References: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Message-ID: In article <401257c4$0$26116$afc38c87 at news.optusnet.com.au>, Peter Moscatt wrote: >Ok.... I am pretty new to Python (as you may have gathered from previous >posts). So now it time for another one of my ridiculous questions.... :-) > >When using 'Tkinter', what is used as the base window to work from, meaning >what widget do I use to place all other widgets onto to create a custom >dialog ? You'll want to create a new Toplevel (the term Tkinter uses for the thing many of us think of as a window). If you want the window to be modal you'll have to do a few extra things. Tkinter already includes a lot of modules for creating dialogs. Find the file Tkinter.py (in lib-tk in with your other python libraries) and look at some of its fellows such as tkFileDialog.py, tkSimpleDialog.py and a host of others with dialog in their names. Read the source code to see how to use it (or import each package and type help(package_name)). You may find exactly what you want, and if not, at least you'll see some examples. -- Russell From surffirst at yahoo.com Fri Jan 30 05:45:22 2004 From: surffirst at yahoo.com (Leo Yee) Date: Fri, 30 Jan 2004 18:45:22 +0800 Subject: pyc file problem Message-ID: Hi, I am programming a online game program. I use python as my game's script language. To avoid hacking and cheating I don't want anyone to read the python script file and find useful information for hacking the game. I know I can compile the '.py' file to '.pyc' file but I found that a normal text editor can read a lot of information from the '.pyc' file even those comments I wrote. My question is if there is a methond to compile the '.py' file into a state that there are no human readable strings. Thanks in advance. Leo Yee From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Wed Jan 28 02:15:44 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Wed, 28 Jan 2004 08:15:44 +0100 Subject: python in dreamweaver References: Message-ID: Hi ! Yes ! I do. @+ -- Michel Claveau From r_olson at sandiego.edu Thu Jan 8 22:05:04 2004 From: r_olson at sandiego.edu (Rick Olson) Date: 8 Jan 2004 19:05:04 -0800 Subject: Newbie has problem changing C char strings with Python/SWIG Message-ID: I've tried posting this on the SWIG listserve, but traffic has been slow there and I haven't had a reply. If this isn't the correct forum, please suggest another. Thanks. I'm trying to use python as the interface for an existing program written in C. I've gotten many things to work including using cvar to assign values to long and double variables in the C module from python. I'm having trouble using it to assign strings. I've reduced the problem to the following .c and .i files, and a sample idlefork session: -------------------- example.c char *eval_name; void define_globals() { eval_name = "Bob"; } -------------------- example.i %module example %{ %} extern void define_globals(); extern char *eval_name; --------------------- IDLEfork 0.9b1 >>> import example >>> example.define_globals() >>> example.cvar.eval_name 'Bob' >>> example.cvar.eval_name='Tony' >>> ==== RESTART ================================ I seem to be able to use Python invoke the C function that assigns "Bob" to the variable eval_name, but when I try to assign a new name ('Tony') the idlefork shell restarts. I've combed the docs and the archives at swig.org, but I didn't see this ddressed anywhere. I strongly suspect that I looked right at it, but didn't recognize it at the time. This leads to 2 questions: 1) How do I perofrm the desired assignment? 2) Where was the answer in the docs so I can look at it and try to understand how I overlooked it. Thanks in advance-- Rick Olson From drconrad at metaplay.com.au Fri Jan 30 00:39:02 2004 From: drconrad at metaplay.com.au (SimonW) Date: Fri, 30 Jan 2004 13:39:02 +0800 Subject: RESTful Python In-Reply-To: <20040130044446.GA30604@mail.theserver.ath.cx> Message-ID: <001501c3e6f3$5e619240$0000fea9@simonxp> I am building a application using XUL, and am looking at using the REST approach rather than XML-RPC for the back end. I've setup a mod-python handler which can handle PUT, DELETE, POST and GET requests, but after that I seem to get lost. I guess this is more a REST question than a python question, however I ultimately would like to implement the entire backend in Python. I want to be able to address sections of an XML document using an URI, but I am not sure how to implement this. I've seen this done in Python before, however I cannot find the site again, and cannot recall the correct google incantations to re-discover it. Can anyone point me to some REST style implementations in Python? Regards, Simon R. Wittber http://www.metaplay.com.au Perth, Western Australia. From elainejackson7355 at home.com Fri Jan 30 00:48:15 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 30 Jan 2004 05:48:15 GMT Subject: conditional expression sought References: <866j101bbuuhtpan29eop9o4mk1mt7nckn@4ax.com> Message-ID: This is a good idea. Thanks for pointing it out. "Dave K" wrote in message news:866j101bbuuhtpan29eop9o4mk1mt7nckn at 4ax.com... | On Thu, 29 Jan 2004 17:58:45 GMT in comp.lang.python, "Elaine Jackson" | wrote: | | >If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, | >then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without | >evaluating any other B_i. This is such a useful mode of expression that I would | >like to be able to use something similar even when there is an i with | >bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) | >or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious | >reasons. Does anybody know a good way to express this? Any help will be mucho | >appreciado. | > | >Peace | > | | I'm not sure if this is what you're looking for, but for i > a very | small number, the zip function seems more appropriate: | | >>> def get_B_i(A, B): | for a, b in zip(A, B): | if a: return b | return A[-1] | >>> print get_B_i([False, False, True, False], [0, 1, 2, 3]) | 2 | >>> print get_B_i([False, False, False, False], [0, 1, 2, 3]) | False | | This has exactly the same effect provided that A and B are the same | length, otherwise the return value by failure should be adjusted to | whatever suits your purpose. | | If you really want to write a conditional expression out in full, I | can't think of anything non-clumsy that would work for all possible | values of B_i, so unfortunately can't help you there. | | Dave | | From aaron at reportlab.com Fri Jan 9 12:03:42 2004 From: aaron at reportlab.com (Aaron Watters) Date: 9 Jan 2004 09:03:42 -0800 Subject: twisted request References: <9a6d7d9d.0312230829.29b014fa@posting.google.com> Message-ID: <9a6d7d9d.0401090903.72a0c42d@posting.google.com> Jp Calderone wrote in message news:... > On Tue, Dec 23, 2003 at 08:29:39AM -0800, Aaron Watters wrote: > > I have a "chat" protocol module called "Hollerith" which > > is appropriate for use with threads or stackless, but is not > > ready for "event loop" style programming. Can someone show > > me how to implement it (and use it) using Twisted? > > > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/xsdb/xsdb/xsdb/Hollerith.py?content-type=text%2Fplain&rev=1.1 > > > > Of course the twisted version should never block, please. > > > > Thanks in advance, -- Aaron Watters > > > > Twisted includes a netstring implementation and an int32 string > implementation, both of which are conceptually very similar to the > underlying function of Hollerith. Adapting either should be a simple task. Yes. It should be. Is it? That was my question. :) -- Aaron Watters === THANK YOU FOR NOT SMIRKING From usenet at -OBFUSCATION-joefrancia.com Wed Jan 14 15:03:09 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Wed, 14 Jan 2004 20:03:09 GMT Subject: wxPython worries In-Reply-To: References: Message-ID: <1ghNb.5638242$Of.891164@news.easynews.com> James Goldwater wrote: > I'm starting a new hopfully-commercial project soon, and I face a > dilemma about whether Python with wxPython would be appropriate. > > The project has 3 main areas: > > a) manipulation of lists and trees, using.. > b) a hopefully dead-sexy gui, all in order to... > c) eventually pump out certain bits of the datastructure over the > network in semi-realtime (< 10ms accuracy or so). > > The target is Win32 for now (98 - XP). Now, if it were up to me, I'd use > Delphi - it's what I know best. But I'm working with a less experienced > developer with whom I have no languages in common. He's keen to get > started on C#, I've toyed with C# and though it looks easy, I don't see > any major gains over what I already know. > > I've read a lot about python and done some mini-stuff in it, and been > impressed with it's ease and conciseness. What worries me is wxPython: > looking at the demo code, it's quite verbose and 'bitty'. I'm also > unclear as to how easy custom controls are to build. > > Am I just being confused by my newbie-ness, or are my initial concerns > justified? What's anybody else's experiences with gui programming in > wxPython like vs a RAD like Delphi or .NET? > > Thanks, > > James. > I share your concerns with wxPython - it's a good, powerful toolkit, but it lacks consistent and clear documentation, and a decent screen painter (wxGlade probably is the most complete). If you have the budget (USD 399 per developer), you may want look at BlackAdder from The Kompany. It uses the PyQt bindings for the Qt toolkit, which I find to be a bit better than wxPython/wxWindows, a bit more polished and consistent. The package includes the BlackAdder editor, the QtDesigner, PyQt docs and a license to redistribute the PyQt libraries for win32 (which is really what you're paying for - most of this is available for free on GPL'ed systems). Another option is to extend/embed Python with Delphi; specifically, use Delphi for the GUI, and Python for the logic. There's some Delphi bindings and documentation here: http://membres.lycos.fr/marat/delphi/python.htm http://www.atug.com/andypatterns/pythonDelphiTalk.htm From jsbenson at bensonsystems.com Tue Jan 13 17:21:46 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 13 Jan 2004 14:21:46 -0800 Subject: I come not to bury C++, but to praise it... Message-ID: <006a01c3da23$a1f69c30$890a500a@jsbwxp3> I got into Python because I took one look at C++ and saw all the handwaving in the introductory O'Reilly book to the effect that "everything looks sweet now, but wait until these snazzy little features interact..." and then started casting around for another road to OOP. I happened upon Python, and continue to use Python. I think that the already-posted comments seeking to appreciate the historical origin and motivations of C++ are essential to understanding it's applicability in the present. C++ started as a quintessentially Unix-like exercise in software engineering: add functionality by leveraging existing software components to the max. Another level of preprocessor (Cfront) was added to the compiler tool chain and Bingo! you had a new language. The advantage was quick time-to-implement. A big disadvantage was that you had to grok C to debug C++. Later compilers took C++ direct to object, but the C, non-OOP heritage persisted in the new language: you had to master pointers and references to really do C++. Later languages simplified the situation by dumping pointers. I think that C++ was a great exercise, but software engineering has advanced. Why not take advantage of the latest packaging of OOP and enjoy the smoother ride? Pick Java, or Python or whatever pleases you. I'm happy using C for projects that fit it, and Python for more ambitions OOP stuff. C++ was a great way to move OOP forward, but now it looks more like a transitional form than a best-of-breed. Sic transit gloria mundi, which is Latin for "when you're hot, your hot; when you're not, you're not" or something like that. If you have a big investment in C++ and can crank out beautiful code in your sleep, that's fine too. I just don't expect it to be as easy to find people to maintain it as if it were written in C, or Python, or Java, or whatever. From swalters_usenet at yahoo.com Fri Jan 9 04:00:41 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 09:00:41 GMT Subject: Looking for help with regular expressions- not Python Specific References: <8d3e714e.0401072114.5bf3fba7@posting.google.com> Message-ID: |Thus Spake Tony C On the now historical date of Wed, 07 Jan 2004 21:14:52 -0800| > I'm writing a python program which uses regular expressions, but I'm > totally new to regexps. > > I've got Kuchling's "Regexp HOWTO", "Mastering Regular Expresions" by > Oreilly, and have access to online stuff too. It may be more than you're looking for, but regular expressions are a nice compact encoding of finite state machines. If you really, really, really want to grok regexp's and are willing to make an investment of time in it, then you are best to understand fsm's. Searching for understandable material could be tough going. You'll come across a lot of cryptic mathematical papers. My tip is that you'll start turning up papers that include references to push down automata and turing machines. These are more powerful versions of finite state machines, but not directly related to regexps. Skip over them. Really, anyone with a solid understanding of programming fundamentals should be able to understand fsm's. I would point you to some resources, but I haven't got any handy. Happy Hunting. Sam Walters. P.S. If you look deeper into finite state machines, push down automata, turing machines and the lambda calculus, your soul will merge with the deeper zen of computer programming. Deep understanding of these four concepts (whether that understanding is conscious or unconscious) is what separates good programmers from truly great ones. I suggest "Godel, Escher, Bach" by Douglas Hofstadter as a good, but dizzying, introduction to this territory. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From tjreedy at udel.edu Thu Jan 29 21:58:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Jan 2004 21:58:46 -0500 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: "Robert Dodier" wrote in message news:6714766d.0401291559.45413e0d at posting.google.com... > Hello, > > I'm interested in introducing new variables into the environment > of a Python interpreter or program. This is a bit vague and not obviously connected to your question. Let's ignore this. Globals() returns the module-specific 'global' namespace, as opposed to the function-local namespace. > In reading through old posts to this newsgroup, I see there is > an often-repeating warning against modifying the contents of locals(). Outside of functions, locals() == globals(). Inside of functions, where locals() != globals() and is therefore not redundant and potentially useful, the result is only guaranteed to be a read-only *copy* of the current state of the local namespace. Even if it is writable, the changes may only change the *copy* and not the local namespace itself. This makes for subtle bugs when the programmer expects (if falsely) that changes are propagated. > Fair enough. However, is there anything wrong with modifying globals() No. "globals()['a'] = 3" is exactly the same as "a=3" executed at module scope, outside of functions. The purpose is to allow you to set a variable whose name you do not know until runtime. An example, as in your application, is when the name comes from user input. Having said that, you do need to ask yourself whether you really want to put user variables in the global namespace that your are using yourself for your code, which will wreck havoc when there is a name collision. Or whether you should put them is a separate namespace dict such as uservars. And then exec user code with uservars as the globals. Or something like that. Terry J. Reedy From trentm at activestate.com Wed Jan 28 19:49:27 2004 From: trentm at activestate.com (Trent Mick) Date: Wed, 28 Jan 2004 16:49:27 -0800 Subject: executing an external app In-Reply-To: <20040128210948.GZ18498@unpythonic.net>; from jepler@unpythonic.net on Wed, Jan 28, 2004 at 03:09:48PM -0600 References: <20040128210948.GZ18498@unpythonic.net> Message-ID: <20040128164927.A3849@ActiveState.com> [Jeff Epler wrote] > Try one or more of these: > > os.system, os.spawn*, popen2.*, os.fork + os.exec* (where os.fork is > supported, at least), popen5 (third-party module, posix/unix only), > win32??? (not sure of name, included in win32all, for Windows only) You could try process.py. Windows and Unix. http://starship.python.net/crew/tmick/#process Cheers, Trent -- Trent Mick TrentM at ActiveState.com From nomail at nospam.net Mon Jan 12 10:12:13 2004 From: nomail at nospam.net (Olaf Meyer) Date: Mon, 12 Jan 2004 15:12:13 GMT Subject: building strings with variable input In-Reply-To: <400273B8.E991F41D@alcyone.com> References: <400273B8.E991F41D@alcyone.com> Message-ID: Erik Max Francis wrote: > Olaf Meyer wrote: > > >>Especially if you have a lot of variable input it makes it hard to >>match >>the variables to the proper fields. From other scripting languanges >>I'm >>used to something like: >> >> $cmd = "$executable -start $startTime -end $endTime -dir $directory" >> >>This makes it very easy to see how the string is actually built. You >>dont't have to worry where which variables go. >> >>Is there a similar way to do this in python? > > > Sure: > > cmd = "%(executable)s -start %(startTime)s -end %(endTime)s -dir > %(directory)s" % locals() > > There are also more expansive solutions such as YAPTU or EmPy. > > Note, however, that what you are trying to do (presuming you're passing > this to os.system or something similar) is potentially a serious > security risk. If the values of the strings you are constructing the > command line are not fully trustworthy, they can be easily manipulated > to make your program execute arbitrary shell commands. > Erik, thanks for your solution suggestion and pointing out the security risks. However security is not an issue in my case ;-) Olaf From http Thu Jan 1 15:36:34 2004 From: http (Paul Rubin) Date: 01 Jan 2004 12:36:34 -0800 Subject: Rekall Binary References: <8a27e309.0312310529.3c1f43a8@posting.google.com> <8a27e309.0401010633.20271486@posting.google.com> Message-ID: <7xpte3o17x.fsf@ruckus.brouhaha.com> ny_r_marquez at yahoo.com (R.Marquez) writes: > How strong a buisness model is GPL software is a relative issue. If > you mean making the kind of money that software developer houses used > to make in the BOS (Before Open Source) days then it isn't. But you > just may be able to support your family on it and pay the rent (and > maybe even buy a modest house if you are really successful). I see > nothing wrong with that. This are hard times you know. An acquaintance of mine started a GPL-centric company, Cygnus Solutions, that at first mainly supported GCC. One of the first things he did as sufficient profits appeared was bought himself a Maserati with the license plate "GNU CC". He did that specifically to show off how one could make money doing free software. The company was later sold to Red Hat, another GPL-centric company, for an amount in excess of $100 million. From http Sat Jan 31 23:37:53 2004 From: http (Paul Rubin) Date: 31 Jan 2004 20:37:53 -0800 Subject: OT: why do web BBS's and blogs get so slow? References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xznc3xvmm.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > * Some of that slowness may be latency on the client side, not the server. A > heavily table-based layout may require that the client get most or all of > the HTML before rendering it. Slashdot's HTML is a nightmare of tables; > some weblogs have CSS-based designs that are much lighter-weight. Yeah, I'm specifically concerned about how severs get overloaded. > * To build the top page, Slashdot requires a lot of SQL queries. > There's the list of stories itself, but there are also lists of > subsections (Apache, Apple, ...), lists of stories in some > subsections (YRO, Book reviews, older stories), icons for the > recent stories, etc. All of these may need an SQL query, or at > least a lookup in some kind of cache. That's what I'm saying--in a decently designed system, a common operation like a front page load should take at most one SQL query, to get the user preferences. The rest should be in memory. The user's preferences can also be cached in memory so they'd be available with no SQL queries if the user has connected recently. On Slashdot, an LRU cache of preferences for 10,000 or so users would probably eliminate at least half those lookups, since those are the ones who keep hitting reload. > It also displays counts of posts to each story (206 of 319 comments), > but I don't think it's doing queries for these numbers; instead there > are extra columns in various SQL tables that cache this information > and get updated somewhere else. That stuff would just be in memory. > * I suspect the complicated moderation features chew up a lot of time. You > take +1 or -1 votes from people, and then have to look up information > about the person, and then look at how people assess this person's > moderation... It's not doing this on every hit, though, but this feature > probably has *some* cost. Nah, that's insignificant. Of 10k messages a day, maybe 1/3 get moderated at all, but some get moderated more than once, so maybe there's 5k moderations a day. Each is just an update to the metadata for the article, cost close to zero. > * There are lots of anti-abuse features, because Slashdot takes a lot > of punishment from bozos. Perhaps the daily traffic is 10,000 > that get displayed plus another 10,000 messages that need to be filtered > out but consume database space nonetheless. I think 10,000 total is on the high side, just adding up the number of comments on a typical day. > * Slashcode actually implements a pretty generic web application system that > runs various templates and stitches together the output. Yeah, I think it's doing way too much abstraction, too much SQL, etc. > > 3) The message store would be two files, one for metadata and one for > > message text. Both of these would be mmap'd into memory. There would > > be a fixed length of metadata for each message, so getting the > > metadata for message #N would be a single array lookup. The metadata > > I like this approach, though I think you'd need more files of metadata, e.g. > the discussion of story #X starts with message #Y. Basically, a story would just be a special type of message, indicated by some field in its metadata. Another field for each message would say where the next message in that story was (or a special marker if it's the last message). So the messages would be in a linked list. You'd remember in memory where the last message of each story is, so you could append easily. You'd also make an SQL record for each story so you can find the stories again on server restart. > (Note that this is basically how Metakit works: it mmaps a region of > memory and copies data around, provided a table-like API and letting > you add and remove columns easily. It might be easier to use > Metakit than to reinvent a similar system from scratch. Anyone know > if this is also how SQLite works?) Wow cool, I should look at Metakit. > Maybe threading would be a problem with fixed-length metadata records. It > would be fixed-length if you store a pointer in each message to its parent, > but to display a message thread you really want to chase pointers in the > opposite directory, from message to children. But a message can have an > arbitrary number of children, so you can't store such pointers and have > fixed-length records any more. Each metadata record would have a pointer to its parent, and another pointer to the chronologically next record in that story. So you'd read in a story by scanning down the linear chronological list, using the parent pointers to build tree structure in memory as you go. If you cache a few dozen of these trees, you shouldn't have to do those scans very often (you'd do one if a user visits a very old story whose tree is not in cache). From ahmed.mohamed.edigram at wanadoo.fr Tue Jan 20 04:54:38 2004 From: ahmed.mohamed.edigram at wanadoo.fr (Ahmed MOHAMED ALI) Date: Tue, 20 Jan 2004 10:54:38 +0100 Subject: Offre d'emploi Message-ID: Editeur de logiciel sp?cialis? dans le domaine des syst?mes d'information pour les m?dias,cherche un d?veloppeur pour int?grer un projet de portail internet sous zope/python.Le candidat doit avoir au moins un an d'exp?rience dans le d?veloppement d'applications.La connaissance de python serait fortement appr?cici?e et celle de zope,c/c++ et vb6 serait un plus.En outre,le candidat doit conna?tre les syst?mes d'exploitation Windows 2000 et Linux.Il doit ?tre rigoureux,curieux,autonome et disposer d'un tr?s bon sens relationnel pour int?grer notre ?quipe de d?veloppement. Lieu de travail : Paris, France. Envoyer cv,lettre de motivation et pr?tentions ? max.herve.edigram at wanadoo.fr From merkosh at hadiko.de Sun Jan 25 17:25:39 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 25 Jan 2004 23:25:39 +0100 Subject: find function Message-ID: Hi, is there for python a find() function, like the perl module Find or the command line tool find? All I found was os.listdir(), but that does return all files in a folder. I'd like to have i.e. regex or shell-like file selections, as in: $ find -name \*.pyc -maxdepth 1 Thanks Ciao Uwe -- From jepler at unpythonic.net Thu Jan 15 14:43:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 15 Jan 2004 13:43:46 -0600 Subject: python & mathematical methods of picking numbers at random In-Reply-To: References: Message-ID: <20040115194328.GA7659@unpythonic.net> It sounds like your co-worker has re-written sample. random.sample(l, 1) is the same as random.choice(l), so that's another source of inefficiency. But why are *you* using random.sample(range(len(x)), 25) instead of random.sample(x, 25) ? Jeff From claird at lairds.com Wed Jan 28 08:13:58 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Jan 2004 13:13:58 -0000 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> <40177f07$0$1730$5a62ac22@freenews.iinet.net.au> Message-ID: <101fdcm8b5b8sda@corp.supernews.com> In article <40177f07$0$1730$5a62ac22 at freenews.iinet.net.au>, Derek Fountain wrote: >> What do you need this for? If you can be more specific, we might be able >> to help you a little better. > >I have a Tcl/Tk script which uses a canvas to graphically represent the data >stored in the program. Whenever the data store is updated, a Tcl trace >automatically triggers to ensure the graphical display is kept consistent >with the data. I was after a simple way to convert the script to Python >Tkinter. Without the eqivalent of Tcl traces I'm probably going to have to >think about it... ;o) Newsgroups: comp.lang.python Subject: Re: Tcl style traces Summary: Expires: References: <40171be5$0$1742$5a62ac22 at freenews.iinet.net.au> <40177f07$0$1730$5a62ac22 at freenews.iinet.net.au> Sender: Followup-To: Reply-To: claird at phaseit.net Distribution: Organization: The Lairds Keywords: Cc: In article <40177f07$0$1730$5a62ac22 at freenews.iinet.net.au>, Derek Fountain wrote: >> What do you need this for? If you can be more specific, we might be able >> to help you a little better. > >I have a Tcl/Tk script which uses a canvas to graphically represent the data >stored in the program. Whenever the data store is updated, a Tcl trace >automatically triggers to ensure the graphical display is kept consistent >with the data. I was after a simple way to convert the script to Python >Tkinter. Without the eqivalent of Tcl traces I'm probably going to have to >think about it... ;o) The Pythonic thing to do is to intercept the data store's set or __setattr__ or ... method. -- Cameron Laird Business: http://www.Phaseit.net From lvrk at yahoo.com Fri Jan 2 19:40:15 2004 From: lvrk at yahoo.com (Raghav Lagisetty) Date: 2 Jan 2004 16:40:15 -0800 Subject: cgi using what? References: Message-ID: crescent_au at yahoo.com (Ben) wrote in message news:... > Hi all, > > I wanna use Python for creating a questionnaire. Is it a good choice > using python on the basis of its availability? I wanna know if most > servers support python or not... I don't know about the server yet.. > so which language will be a good choice? Recently, I was in the same boat as you deciding on which server side scripting language to use. I had to design a web based application which takes inputs from users using HTML forms. The user details and inputs are stored in a databse and are retrieved on demand. I had worked with Perl before but decided to go for Python this time for several reasons: 1) I wanted to try out something new. 2) Readability and manageability of perl scripts is pretty bad 3) A quick look at Python's tutorials told me that the learning curve was not very steep. (Goto www.python.org) 4) Found some cool python modules to generate HTML page layouts which helped me to jump into my problem right away instead of concentrating on the page designs. (http://ht2html.sourceforge.net/) Regarding your question about the server side support, Apache web servers definitely support python. You might have to dig a little bit to find out what server you have and whether it supports Python. Hope that helps, Raghav. From km at mrna.tn.nic.in Fri Jan 16 05:08:19 2004 From: km at mrna.tn.nic.in (km) Date: Fri, 16 Jan 2004 15:38:19 +0530 Subject: python mode vi Message-ID: <20040116100819.GA19095@mrna.tn.nic.in> hi all, how to invoke python mode in vi editor ? kindly enlighten, regards, KM From zm23 at seznam.cz Fri Jan 2 02:10:19 2004 From: zm23 at seznam.cz (Zdenda) Date: 1 Jan 2004 23:10:19 -0800 Subject: Python 2.3.3 compilation problem Message-ID: Hi, i have RH9 and i need python 2.3. I executed tgz file and typed ./configue. Then i type make. It is without problem. When I type make install ... ... ... Compiling /usr/local/lib/python2.3/xml/sax/handler.py ... Compiling /usr/local/lib/python2.3/xml/sax/saxutils.py ... Compiling /usr/local/lib/python2.3/xml/sax/xmlreader.py ... Compiling /usr/local/lib/python2.3/xmllib.py ... Compiling /usr/local/lib/python2.3/xmlrpclib.py ... Compiling /usr/local/lib/python2.3/zipfile.py ... make: *** [libinstall] Error 1 Have somebody any idea where is error? Thanks From mike at triplepc.com Mon Jan 5 15:16:16 2004 From: mike at triplepc.com (Michael T. Babcock) Date: Mon, 05 Jan 2004 15:16:16 -0500 Subject: Pre-PEP: new Path class In-Reply-To: References: Message-ID: <3FF9C610.1090300@triplepc.com> > > >I see what you're saying. I'd argue (softly) that iterating over >> the directory entries is the natural interpretation, though. > > > >It's far too implicit to my taste; for one since it's a folder-only >operation (and I don't see much merit in having separate classes for >folder and file paths). Would you also be in favor of interating over > > >file-paths meaning iterating over the lines in the file? > I was thinking about how I'd expect to use such a class and think perhaps neither iterator type should exist. If an iterator exists for a path, it should probably be for the elements of the path, not what the path points to. These are different objects, in my mind. > Path path > path.parse("/usr/share/doc") > for item in path: > print str(item) usr share doc > print str(path[0]) # get top-level path element /usr > print str(path[:-1]) # get parent to path /usr/share > for item in os.pathwalk(path): > # Do stuff > pass > f = file(path + "mydoc.txt", "r') > f.close() ... any thoughts? I see a Path object as being very useful, in that it can hide the concepts of parsing and using paths from the user, but it shouldn't "understand" what its pointing to, whether a pipe or a file or a directory or a special device. Those are features for their own specific objects which can use the data stored in a Path object. -- Michael T. Babcock http://www.fibrespeed.net/~mbabcock/ From Mike at DeleteThis.Geary.com Mon Jan 5 11:49:58 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 5 Jan 2004 08:49:58 -0800 Subject: Embedding Python with Dynamic Loading (win) References: <5e571368.0401050603.265d469d@posting.google.com> Message-ID: Simon Steele wrote: > I'm trying to embed python into my application, and have > everything working fine using the static import lib. > However, I don't want my application to be dependant on > python being installed (it's an optional script interpreter). > Therefore I want to be able to dynamically load python > instead (which I believe is possible, but I can't find any > examples for). It seems, however, that the import lib is > imported in python.h using a pragma statement. > > 1. Is there any suggested way to prevent this import > without modifying python.h? Assuming you're using Visual C++, you could use delay loading, which essentially converts any imported DLL to use LoadLibrary/GetProcAddress without requiring any code changes. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/vcconLinkerSupportForDelayedLoadingOfDLLs.asp or http://tinyurl.com/2bmzr -Mike From drconrad at metaplay.com.au Fri Jan 23 03:50:02 2004 From: drconrad at metaplay.com.au (SimonW) Date: Fri, 23 Jan 2004 16:50:02 +0800 Subject: Modem beeping In-Reply-To: <001c01c3e18d$260b02c0$b10d10ac@metasalio> Message-ID: <004301c3e18d$e46a35b0$0000fea9@simonxp> This question is completely un-related to python, however, I do believe ATAH0 should do the trick. regards, SimonW. From jl at windsmith.net Sat Jan 10 11:44:09 2004 From: jl at windsmith.net (John Lull) Date: 10 Jan 2004 10:44:09 -0600 Subject: Multithreaded COM server problem... Message-ID: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> I'm writing a multithreaded COM server to manage a pool of hardware resources. All objects are designed to be thread-safe, and I've set sys.coinit_flags to COINIT_MULTITHREADED before importing pythoncom. The problem is that all requests to the server seem to be serialized by COM. To demonstrate the problem, I'm including a simple test server that exposes one interface object, PyComThreads.Application, with a single method sleep(delay). I'm also including 2 test programs -- test20.py uses the server to delay 20 seconds, and test1.py delays only one second. The server prints status messages to the trace collector debugging tool when creating the Application object, and at the beginning and end of the specified delay. When I run the 20-second test program, then a couple seconds later run the 1-second test program, I had expected to see something like this: Object 8087872 in thread 8160416 created Object 8087872 in thread 8160416 delays 20 seconds Object 8086008 in thread 8156272 created Object 8086008 in thread 8156272 delays 1 seconds Object 8086008 delay ends Object 8087872 delay ends Instead, I see: Object 8087872 in thread 8160416 created Object 8087872 in thread 8160416 delays 20 seconds Object 8087872 delay ends Object 8086008 in thread 8160416 created Object 8086008 in thread 8160416 delays 1 seconds Object 8086008 delay ends Apparently the requests from both client applications are being serialized by the COM interface. I need each request (or at least each interface object) to run in its own thread, or in a pool of threads, and haven't been able to figure out how to accomplish this. Any suggestions would be appreciated. Regards, John ---------- PyComThreads.py: import sys import threading from time import sleep import win32traceutil sys.coinit_flags = 0 # 0 == pythoncom.COINIT_MULTITHREADED # !!!!! import pythoncom class Application: """ Test version of a Multi-threaded local server """ _reg_progid_ = 'PyComThreads.Application' _reg_verprogid_ = 'PyComThreads.Application.100' _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _reg_clsid_ = '{56BEC27D-EDC4-43A0-AEB7-77E4A1381C0F}' _public_methods_ = ['sleep'] _public_attrs_ = [] _readonly_attrs_ = [] def __init__(self): print 'Object %s in thread %s created' % \ (id(self), id(threading.currentThread())) def sleep(self, delay): print 'Object %s in thread %s delays %s seconds' % \ (id(self), id(threading.currentThread()), delay) sleep(delay) print 'Object %s delay ends' % id(self) # COM server registration, etc. if __name__ == '__main__': if hasattr(sys, 'argv'): # If *no* command-line arguments, we were not invoked as a server. # Assume the user wants us to self-register. if len(sys.argv) == 1: sys.argv.append('--register') import win32com.server.register win32com.server.register.UseCommandLine(Application, debug=0) ---------- test20.py: from win32com.client import Dispatch app=Dispatch('PyComThreads.Application') app.sleep(20) ---------- test1.py: from win32com.client import Dispatch app=Dispatch('PyComThreads.Application') app.sleep(1) From python at hitmedia.com Sat Jan 24 18:41:26 2004 From: python at hitmedia.com (Python Baby) Date: Sat, 24 Jan 2004 15:41:26 -0800 Subject: [OPINION] - does language really matter if they all do the same thing? In-Reply-To: <4012FEB1.5000106@prescod.net> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> <4012FEB1.5000106@prescod.net> Message-ID: <20040124234126.GB42028@mail.hitmedia.com> > Of course there are (rare) circumstances where the other languages' > advantages are so extreme that it justifies the cost of integration, > distribution, training, etc. This would be a good statement to bring this thread back to my original question on: """ Since my old website needed an overhaul anyway, I thought it'd be a good time to learn [OOP]... Wondering if, since I'm about to re-write my entire website anyway, if I should use Ruby or Python instead of PHP. As I've fretted over this for way too many hours, I started wondering: Can Ruby do something (important) that Python can't? Can Python do something (important) that PHP can't? Can PHP do something (important) that Ruby or Python can't?""" Has anyone here ever looked at different languages for making an interactive website, and felt that Python was the best choice of language to use? It would definitely be a learning curve for me, since I know PHP so well, but if it had some great benefits, I'd go for it. (Half just for fun, to learn something new.) From max at cNvOiSsiPoAnMtech.com Wed Jan 14 11:15:17 2004 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Wed, 14 Jan 2004 16:15:17 GMT Subject: FRPythoneers Meeting -- January 19, 2004 In-Reply-To: References: Message-ID: Jeffery D. Collins wrote: > January 19, 2004, 7:00PM at Level 3 Communications in Broomfield, CO. > > Title: Jython, the best of both worlds or the lowest common denominator > Author: Demian L. Neidetcher > > Abstract: > Python is a language that this choir knows has many great features. > Admittedly, Java has some benefits that Python doesn't; it has great > momentum behind it and it has a good install base. > Jython allows us to take advantage of the usability and rapid > development of Python as well as being able to use popular Java class > libraries and take advantage of the popularity of the Java Virtual Machine. This sounds cool. Could you posta link to the presentation for the rest of us not in Broomfield, CO, if it's not too much work? thanks, max From bart_nessux at hotmail.com Sun Jan 18 21:38:10 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Sun, 18 Jan 2004 21:38:10 -0500 Subject: How to hide user's input Message-ID: locale = input("Where is the property located?\n 1. Town\n 2. City\n 3. County\n") How do I hide the input that the user types? The program runs in the bash shell. TIA!!! From newsgroups at jhrothjr.com Mon Jan 5 18:36:52 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 5 Jan 2004 18:36:52 -0500 Subject: Pre-PEP: new Path class References: Message-ID: "Michael T. Babcock" wrote in message news:mailman.114.1073333780.12720.python-list at python.org... > > > > > >I see what you're saying. I'd argue (softly) that iterating over > >> the directory entries is the natural interpretation, though. > > > > > > > >It's far too implicit to my taste; for one since it's a folder-only > >operation (and I don't see much merit in having separate classes for > >folder and file paths). Would you also be in favor of interating over > > > > > >file-paths meaning iterating over the lines in the file? > > > > I was thinking about how I'd expect to use such a class and think > perhaps neither iterator type should exist. If an iterator exists for a > path, it should probably be for the elements of the path, not what the > path points to. These are different objects, in my mind. > > > Path path > > path.parse("/usr/share/doc") > > for item in path: > > print str(item) > usr > share > doc > > print str(path[0]) # get top-level path element > /usr > > print str(path[:-1]) # get parent to path > /usr/share > > for item in os.pathwalk(path): > > # Do stuff > > pass > > f = file(path + "mydoc.txt", "r') > > f.close() > > ... any thoughts? I see a Path object as being very useful, in that it > can hide the concepts of parsing and using paths from the user, but it > shouldn't "understand" what its pointing to, whether a pipe or a file or > a directory or a special device. Those are features for their own > specific objects which can use the data stored in a Path object. So you're saying that a file object or a directory object "has-a" path object? Sounds right to me. John Roth > -- > Michael T. Babcock > http://www.fibrespeed.net/~mbabcock/ > From gerrit at nl.linux.org Tue Jan 6 14:04:39 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 6 Jan 2004 20:04:39 +0100 Subject: PRE-PEP: new Path class In-Reply-To: <3FF9D91E.2090302@rogers.com> References: <3FF9D91E.2090302@rogers.com> Message-ID: <20040106190439.GB4581@nl.linux.org> Mike C. Fletcher wrote: > >9) Current OS constants? > > > >What are they? Are we talking about the four > >constants in the access() function, or about something > >else? > > > > > Don't know myself. I meant os.path constants: curdir, pathsep, defpath, etc. They should be included. > >use the visitor pattern directly, with different method > >names for files, directories and whatever else a > >particular file system has in it's warped little mind. > > > > > Reworking walk is probably a good idea. I'll let others worry about it, > as I've re-implemented the functionality so many times for my own code > that I'm just sick of it :) . I think os.walk is good as it is. yours, Gerrit. -- 34. If a ... or a ... harm the property of a captain, injure the captain, or take away from the captain a gift presented to him by the king, then the ... or ... shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From bcd at pvv.ntnu.no Wed Jan 14 09:22:30 2004 From: bcd at pvv.ntnu.no (Bent C Dalager) Date: Wed, 14 Jan 2004 14:22:30 +0000 (UTC) Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: In article , Dan Olson wrote: > Cygwin is a horrible horrible >way to run things on Windows, and I'd like to take this time to insult the >mothers of everyone who has ever made their Linux application run on >Windows using only Cygwin. I've always thought of Cygwin as 1) an excellent way to run the Unix-like tools that I know and love and 2) a useful intermediate step while porting an app to Windows. Now, except as a quick first step to achieving (2) I don't really know why anyone would put much effort into "porting to CygWin". Isn't part of the point that most things will just automatically work under CygWin so that you get (1) pretty much for free? Cheers Bent D -- Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd powered by emacs From computer.problemen at skynet.be Fri Jan 9 08:05:41 2004 From: computer.problemen at skynet.be (broebel) Date: Fri, 9 Jan 2004 14:05:41 +0100 Subject: debugging makes a person a better programmer Message-ID: <3ffea564$0$296$ba620e4c@news.skynet.be> I'm just wondering, people tell me that helping to debug someone elses program is a really good way to learn to understand the language it's programmed in. My question is: from wich point of can someone start to try to help a programmer by debugging or testing a program. If indeed you already need a profound knowledge of the language than how can you learn something about it? except for the fact that you see other possibilities of way to programm. Are there pages that can be found with programs to help understand the language or the way to use the language. thanks in advance ik From deets_noospaam at web.de Wed Jan 14 13:25:38 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 14 Jan 2004 19:25:38 +0100 Subject: passing callback function to c-extension References: Message-ID: > Diez> I'm now looking for a way to ensure that the passed object is > Diez> actually a callable one > > Try it and see. If an exception is raised, just return NULL. The > appropriate exception stuff will have been set. Thanks - I already found out about that. Its incredible - a few hours of work (mostly because I've actually have to _learn_ something new, not because of the api makes things complicated) and I've got my wrapper. If I can keep up that pace, I'll release my wrapper this night, or tomorrow :) Regards, Diez From eddie at holyrood.ed.ac.uk Tue Jan 27 12:23:24 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 27 Jan 2004 17:23:24 +0000 (UTC) Subject: os.path.split: processing paths from one OS on another References: Message-ID: Martijn Ras writes: >Heya folks, >I ran into the following problem: >When i run this on Windows everything is as expected: >C:\>python >Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> file='/TEST/FILE.EXT' > >>> print os.path.split(file) >('/TEST', 'FILE.EXT') > >>> file='C:\\TEST\\FILE.EXT' > >>> print os.path.split(file) >('C:\\TEST', 'FILE.EXT') >However, when i run this on Linux the results are unexpected: >$ python >Python 2.2.3 (#1, Nov 12 2003, 15:53:11) >[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> file='/TEST/FILE.EXT' > >>> print os.path.split(file) >('/TEST', 'FILE.EXT') > >>> file='C:\\TEST\\FILE.EXT' > >>> print os.path.split(file) >('', 'C:\\TEST\\FILE') Well, that is correct behaviour for any unix type machine because \ and C: are just part of a filename, the only special character in a unix file name is / (the directory separator). So if the user is trying to specify a file on the unix system either they will need to use unix conventions or you will need to do your own mapping from windowsland names to unixland names. Since Python already does the mapping in the opposite direction (ie making everything look like a unix name) it might make more sense to adopt this convention. Of course, if your actual purpose is simply to manipulate filenames rather than use the name to reference a file then you need to use the library functions specific to the OS (in this case windows) which someone else has already mentioned. Eddie From jepler at unpythonic.net Sun Jan 4 16:51:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 4 Jan 2004 15:51:06 -0600 Subject: Problems compiling python In-Reply-To: References: <3FF88279.33BF192A@alcyone.com> Message-ID: <20040104215106.GA1075@unpythonic.net> see Misc/setuid-prog.c in the Python source distribution. Jeff From gagenellina at softlab.com.ar Mon Jan 5 19:26:16 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Mon, 05 Jan 2004 21:26:16 -0300 Subject: problem with async chat client in windows In-Reply-To: Message-ID: <5.2.1.1.0.20040105212550.0270b150@192.168.0.115> At 5/1/2004 03:02, you wrote: >I'm writing a small chat client to learn some python and networking. No >problem with the network stuff tho, the problem is when the user should be >able to interact and type messages to send. Since I work with windows I >can't use the select function >(http://www.python.org/doc/current/lib/module-select.html). Maybe it could >work if I use two threads? One thread reading keyboard and the other >handling network stuff, but I would prefer to leave threads out from this. >Any suggestions? You could try asyncore Gabriel Genellina Softlab SRL From me at here.there.com Tue Jan 13 21:44:23 2004 From: me at here.there.com (Peter Ashford) Date: Wed, 14 Jan 2004 15:44:23 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: Brandon J. Van Every wrote: > "Peter Ashford" wrote in message > news:K_YMb.10994$9k7.204413 at news.xtra.co.nz... > >>Brandon, don't be such an arsehole. OS developers do things their own >>way and offer their labour for free. If you don't like it noone will >>care - but don't denegrate people just because they don't do things your >>way. > > > I'll denigrate them all I want. With rare exceptions, they aren't a value > add to what I want to get done. There's this huge cultural divide between > hobbyists and commercialists. > Why do you think OS developers owe you any kind of value at all? From list-python at ccraig.org Thu Jan 15 10:02:34 2004 From: list-python at ccraig.org (Christopher A. Craig) Date: 15 Jan 2004 10:02:34 -0500 Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: miki.tebeka at zoran.com (Miki Tebeka) writes: > Which made me think why Python don't use gmp as it's primary math > package - we'll get fast results, a lot of number types and much more. > > Can't think of any reason why Python is implementing its own long > numbers... Can you enlighten me? > Originally I'm sure licensing was a concern, but portability is still a huge concern. I haven't tried to port gmp, but from what I've heard it's an absolute nightmare. Python's long type, on the other hand, was (before kmul) essentially a textbook (a Knuth text book, to be specific) implementation of multiprecision integers. kmul takes a couple shortcuts, especially in cases where the two numbers are of wildly differing sizes, but is still pretty close to textbook. As such longobject.c should compile pretty much anywhere with anything resembling ANSI C with no problems. -- Christopher A. Craig Perl is worse than Python because people wanted it worse -- Larry Wall From jcarlson at uci.edu Wed Jan 21 16:12:04 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Jan 2004 13:12:04 -0800 Subject: Need help with Python class idioms References: Message-ID: <20040121131049.D8E6.JCARLSON@uci.edu> On 21 Jan 2004 12:43:28 -0800 tad at tadland.net (Tad Marko) wrote: > Howdy! > > I'm trying to get my head around Python and I've come to realize that > there are a lot of idioms in Python that are a bit different than in > other languages. I have a class similar to what I've included below. > The only difference is that in the real class, I have even more > mandatory attributes. Too many to specify at once on a constructor and > they don't always exist at construction time anyway, so the accessor > idiom must remain. > > Can anyone suggest a more Pythony way to do the following? > > Thanks, > Tad > > #!/bin/env python > > class A: > def __init__(self): > self.mandatoryVar1 = None > self.mandatoryVar2 = None > > def setMV1(self, mv1): > self.mandatoryVar1 = mv1 > > def setMV2(self, mv2): > self.mandatoryVar2 = mv2 > > def saveToDB(self, db): > if self.mandatoryVar1 == None: > raise Exception, "Mandatory Var 1 not set." > if self.mandatoryVar2 == None: > raise Exception, "Mandatory Var 2 not set." > > # Using db, do whatever saving stuff is needed. mandatoryvariables = dict(mandatoryvar1=mv1, mandatoryvar2=mv2...) inst = A() inst.__dict__.update(mandatoryvariables) That should work for you. - Josiah From peter at engcorp.com Fri Jan 16 09:28:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Jan 2004 09:28:31 -0500 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> <265368cb.0401151529.50c36679@posting.google.com> Message-ID: <4007F50F.E2AF33AD@engcorp.com> Laurent Therond wrote: > > I used the interpreter on my system: > >>> c = StringIO() > >>> c.write('%d:%s' % (len('string?'), 'string?')) > >>> print c.getvalue() > 7:string? > > OK > > Did StringIO just recognize Extended ASCII? > Did StringIO just recognize ISO 8859-1? > > ? belongs to Extended ASCII AND ISO 8859-1. No, StringIO didn't "recognize" anything but a simple string. There is no issue of codecs and encoding and such going on here, because you are sending in a string (as it happens, one that's not 8-bit clean, but that's irrelevant though it may be the cause of your confusion) and getting out a string. StringIO does not make any attempt to "encode" something that is already a string. > >>> print c.getvalue().decode('US-ASCII') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 8: ordinal > not in range(128) > > >>> print c.getvalue().decode('ISO-8859-1') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\encodings\cp437.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\x82' in position 8 > : character maps to > >>> > > OK > > It must have been Extended ASCII, then. Hmm... note that when you are trying to decode that string, you are attempting to print a unicode rather than a string. When you try to print that on your console, the console must decode it using the default encoding again. I think you know this, but in case you didn't: it explains why you got a DecodeError in the first place, but an EncodeError in the second. The second example worked, treating the string as having been encoded using ISO-8859-1, and returns a unicode. If you had assigned it instead of printing it, you should have seen now errors. -Peter From jmdeschamps at cvm.qc.ca Mon Jan 19 15:09:43 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 19 Jan 2004 12:09:43 -0800 Subject: Analysing Word documents (slow) What's wrong with this code please! References: <3d06fae9.0401161351.75e7f5a@posting.google.com> Message-ID: <3d06fae9.0401191209.7169532@posting.google.com> "Daniel Dittmar" wrote in message news:... > jmdeschamps wrote: > > Anyone has a hint how else to get faster results? > > (This is to find out what was bold in the document, in order to grab > > documents ptoduced in word and generate html (web pages) and xml > > (straight data) versions) > [...] ... > Perhaps you can search for bold text. The Word search dialog allows this. > And when you use the keybord macro recording feature of Word, you can > probably figure out how to use that search feature from Python. > > Daniel Thanks Paul Prescod suggested this also, works great! Jean-Marc From erwin+usenet at andreasen.org Fri Jan 30 18:10:53 2004 From: erwin+usenet at andreasen.org (Erwin S. Andreasen) Date: Sat, 31 Jan 2004 00:10:53 +0100 Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Message-ID: <87k739xcaq.fsf@andreasen.org> llothar at web.de (Lothar Scholz) writes: > is there something like "JpGraph" for python ? > For those who don't know this PHP library: It is a high level > drawing library that generates gif files with all kind of charts. I've used gdchart previously but these days I use ChartDirector which, although being a commercial program ($99), was well-worth the money for me. It produces high-quality charts, is very flexible (e.g. you can overlay different chart types, add custom symbols, produce HTML image maps) and has excellent bindings for Python and many languages. Also, I've found the support to be unusually friendly, accurate and fast. The documentation is good enough so you won't need it much (and customised to each language too, with something like 100 examples). Some samples: http://www.advsofteng.com/gallery.html -- =============================================================== Herlev, Denmark <*> =============================================================== From plucker-dev-admin at rubberchicken.org Sat Jan 31 21:18:11 2004 From: plucker-dev-admin at rubberchicken.org (plucker-dev-admin at rubberchicken.org) Date: Sun, 01 Feb 2004 13:18:11 +1100 Subject: Your message to plucker-dev awaits moderator approval Message-ID: <20040201021811.14585.99614.Mailman@ike.inomial.com> Your mail to 'plucker-dev' with the subject hi Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From jamwt at jamwt.com Fri Jan 9 15:21:00 2004 From: jamwt at jamwt.com (J Turner) Date: Fri, 9 Jan 2004 12:21:00 -0800 Subject: Enumerating Fonts with the win32 extensions Message-ID: <20040109202100.GA35247@stan.jamwt.com> Hi All, I've googled and googled, but I can't seem to track this down anywhere... Point me to a thread if I've missed it. How would one retrieve a list of all available system fonts on a win32 box using Mark Hammond's win32all extensions? Thanks, - Jamie From aahz at pythoncraft.com Fri Jan 30 16:03:31 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2004 16:03:31 -0500 Subject: Building a Course Management System References: Message-ID: In article , Graham Fawcett wrote: > >-- Are there other Python-based CMS (Course management systems) that >I've overlooked? (Zope4Edu came to mind, but it's commerical, I think; >at least, there's no public CVS that I can find.) IIRC, there's at least one *conference* management system; I'd expect there to be a lot of overlap between the domains. Don't remember enough off-hand to help you find it, though I think EuroPython uses it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From exarkun at intarweb.us Mon Jan 5 08:11:35 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 5 Jan 2004 08:11:35 -0500 Subject: Scoped Lock In-Reply-To: References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: <20040105131135.GA4988@intarweb.us> On Mon, Jan 05, 2004 at 01:40:01PM +0100, Daniel Dittmar wrote: > Marco Bubke wrote: > > This does not look nice to me. There should be something me easily. > > Maybe that: > > > > def do_something() lock(mutex): > > #this stuff is locked by the mutex > > > > So you don't forget to release the lock. > > You could create a class that locks the mutex in the constructor and unlocks > it in the __del__ method. > > class ScopedLock: > def __init__ (self, mutex): > self.mutex = mutex > mutex.acquire() > > def __del__ (self): > self.mutex.release () > > use as > def do_something(): > lock = ScopedLock (mutex) > # do something > # lock will be automatically released when returning > > > This works only in the current implementation of CPython where local > variables are usually (*) deleted when they fall out of scope. Notably, this fails if an exception is raised, since the lock remains in the locals dictionary of one of the frame objects in the traceback. Definitely not desirable. Jp From fsc at fuentez.com Tue Jan 27 01:23:05 2004 From: fsc at fuentez.com (fsc at fuentez.com) Date: Tue, 27 Jan 2004 01:23:05 -0500 Subject: Delivery failure notification Message-ID: <200401270623.i0R6M3j1022784@wmsc.fuentez.com> Your message with Subject: test could not be delivered to the following recipients: hildjj at fuentez.com Please do not resend your original message. Delivery attempts will continue to be made for 1 day(s). From antonmuhin at rambler.ru Mon Jan 26 11:45:35 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Mon, 26 Jan 2004 19:45:35 +0300 Subject: Single and double asterisks preceding variables in function arguments In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I've run across code like "myfunction(x, *someargs, **someotherargs)", > but haven't seen documentation for this. > > Can someone fill me in on what the leading * and ** do? Thanks. > > Stephen See item 7.5 in Language Reference. In short: * declaries list of additional parameters, while ** declares map of additional parameters. Try somehting like: def foo(*params): print params and def bar(**params): print params to find out details. regards, anton. From phil_nospam_schmidt at yahoo.com Sun Jan 4 18:37:46 2004 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 4 Jan 2004 15:37:46 -0800 Subject: Python for Embedded Devices? References: Message-ID: <221e7b06.0401041537.2896b22d@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:... > The one point I'd emphasize when thinking about this > is that "embedded devices" covers a wide range, as I > believe you already know. Some developers commonly > work with hardware that's far, far more constrained > than are cellular telephones; others, who also program > embedded devices, can't be distinguished from vanilla > Linux coders. I am one such developer who works with very small systems: 8-bit micros with under 128K flash and 4K RAM. I am keenly interested in Python or some other similar langauge that would run on such hardware. 'C' is the usual language for such environments, but I believe that, in many cases, using a dynamic and 'object-able' language would reduce development time and improve product quality significantly. I've looked at Io, Lua, PyMite and Pippy, to name a few, and none are quite appropriate. Io is perhaps the closest match, if it were stripped down a lot. I have been tinkering around with some ideas to make a new language to fit the environment I deal with. This is slow work, as I haven't a lot of time to spend on it, and I am not a language design expert, but I'm having fun with it! From max at alcyone.com Wed Jan 21 22:30:59 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 21 Jan 2004 19:30:59 -0800 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: <400F3D90.2176087B@alcyone.com> Message-ID: <400F43F3.51FE9BC8@alcyone.com> Ben Finney wrote: > Got a pointer to somewhere that says so? Or at least describes the > expected behaviour for iteration over mutable types? Tutorial, section 4.2: http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000 "It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy." This is actually not specific to Python; in C++'s Standard Library, for instance, there are complicated ramifications of modifying a container's contents while you're actively maintaining and using an iterator over it. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Isn't the best defense always a good attack? -- Ovid From zensunni at rochester.rr.com Sat Jan 24 21:45:02 2004 From: zensunni at rochester.rr.com (Brian Samek) Date: Sun, 25 Jan 2004 02:45:02 GMT Subject: Newbie Nested Function Problem Message-ID: I began learning python a few days ago and just wrote the following program. I have nested three functions together. For some reason, the leave function works fine when 'y' or 'n' are inputted, but it does not restart itself when other things are inputted. Why is this? Thanks, Brian Samek # Brian Samek # Created 01/24/2004 # This program counts down from a user-defined integer less than or equal # to 500. print "This program counts down from any number less than or equal to 500" print # ask_number gets the number from the user and then puts it into countdown def ask_number(): number = input("Please enter a number.\n") if number > 500 or number - int(number) != 0 or number < 1: print "Input positive integers less then 501 only, please." ask_number() else: # countdown does the actual counting down until 0 def countdown (number): if number != 0: print number number = number - 1 countdown (number) else: # leave asks the user if he wishes to exit def leave(): leave = raw_input ("Type 'y' to start over - type 'n' to exit. ") if leave == "y": ask_number() elif leave == "n": return else: print "Type either 'y' or 'n' please." leave() leave() countdown (number) ask_number() From just at xs4all.nl Tue Jan 6 03:36:17 2004 From: just at xs4all.nl (Just) Date: Tue, 06 Jan 2004 09:36:17 +0100 Subject: PRE-PEP: new Path class References: Message-ID: [Mike C. Fletcher] > > That said, I don't mind making path it's own base-class, I just *really* > > want to be able to pass them to path-unaware code without extra coercian > > (otherwise switching a module to *producing* paths instead of raw > > strings will cause the *clients* of that module to break, which is a > > serious problem for rapid adoption). [John Roth] > That's an excellent point, but it begs the question of which > string class it should subclass. Unless it's got some way of > changing its base class depending on the system it's running > on. That, in turn, probably violates the Principle of Least > Astonishment. That's in fact exactly what Jason Orendorff's path module does. But it's buggy due to os.path.supports_unicode_filenames being buggy. It would be interesting to figure out to what extent non-string (and non-unicode) path objects can or can't be made to work for existing string-accepting code. I would very much prefer a path _not_ to inherit from str or unicode, but Mike's point is an important one. What is missing in Python to allow non-string objects to act like (unicode) strings? Just From frithiof.jensen at removethis.ted.ericsson.dk Mon Jan 12 05:59:18 2004 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Mon, 12 Jan 2004 11:59:18 +0100 Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> Message-ID: "Alan Gauld" wrote in message news:3fffbe99.486050433 at news.blueyonder.co.uk... > On Fri, 9 Jan 2004 10:29:46 GMT, Harry George > Interesting comments. How do people generally perform these tests > then? I use the unittest module. It is *tedious* as hell to get the test cases up and running in unittest but I find that it always takes less time and effort in total to take the pain up front instead of debugging "later". Often difficulties with the test code inspires one to rethink an interface or a design, something one would not like to do on a larger collection of code that "almost" runs. From mwh at python.net Mon Jan 5 11:56:41 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 5 Jan 2004 16:56:41 GMT Subject: Optimized quoting (was Re: Speed?) References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: Grr... aahz at pythoncraft.com (Aahz) writes: > In article , > John Hunter wrote: > > > >Donald Knuth, God of Computer Science, said "Premature optimization is > >the root of all evil". > > If Knuth is God, then Hoare is God's father: > > "Premature optimization is the root of all evil in programming." > --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) Cite? > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil." --Knuth restates Hoare This is from "Structured Programming with goto Statements", and he's not quoting Hoare at this point. Really! Cheers, mwh -- Or here's an even simpler indicator of how much C++ sucks: Print out the C++ Public Review Document. Have someone hold it about three feet above your head and then drop it. Thus you will be enlightened. -- Thant Tessman From Florian.Lindner at xgm.de Sun Jan 4 10:00:19 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 04 Jan 2004 16:00:19 +0100 Subject: Find out username and UID/GID Message-ID: Hello, how can I find out the username and it's UID and GID on a linux system, using the most recent python version? If possible, without the use of extra libraries. Thanks, Florian From okyoon at stanford.edu Tue Jan 27 04:01:45 2004 From: okyoon at stanford.edu (Ohkyu Yoon) Date: Tue, 27 Jan 2004 01:01:45 -0800 Subject: Newbie : innerproduct function from Numarray References: Message-ID: Wow! Thank you all. My program runs super fast now. The biggest problem was changing lists into arrays. By starting with arrays, the program runs almost infinitely faster. Ohkyu "Ohkyu Yoon" wrote in message news:bv40rm$ra$1 at news.Stanford.EDU... > I have two vectors that have about 2000 elements. > I need to calculate the innerproducts of those vectors 2000 times where > one of them cycles left(ie 1234, then 2341, then 3412, etc) > Basically, I want to calculate A*x, where A is a left-circulant cyclic > matrix, > and x is a vector. > > I tried it two ways. > vector1 & vector2 are lists. > > 1) > from Numarray import innerproduct > output = [] > temp = vector1 + vector1 # temp is twice the length of vector1 > for i in range(2000): > output.append(innerproduct(temp[i:(i+2000)],vector2) > 2) > output = [] > temp = vector1 + vector1 > for i in range(2000): > sum = 0 > for j in range(2000): > sum += temp[i+j] * vector2[j] > output.append(sum) > > I thought the first method using Numarray should be faster. > But it looks like the second method is faster. > Am I doing anything wrong? > Do you guys know any faster way to do this? > > Thank you. > > From michael at foord.net Wed Jan 28 04:25:30 2004 From: michael at foord.net (Fuzzyman) Date: 28 Jan 2004 01:25:30 -0800 Subject: Displaying HTML Files from Python (Using Tkinter) Message-ID: <8089854e.0401280125.57480392@posting.google.com> Does anyone know of an 'easy' way of displaying HTML from python - preferably using standard Tkinter widgets. I've heard that the 'Text' widget can be used to do this - but I don't fancy hand building an HTML parser when it's quite likely someone else has already done it..... I don't *need* eternal links to work, or even stylesheets or tables, but I'd like the other basic tags to work. I'm sure someone has built a library to do this - but I can't find it. Anyone any clues ? Fuzzy -- 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.voidspace.org.uk/atlantibots/pythonutils.html Python functions - home of dateutils, ConfigObj, StandOut, CGI-News and more.... -- 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 nobody at nowhere.near.org Tue Jan 13 09:57:51 2004 From: nobody at nowhere.near.org (nobody) Date: Tue, 13 Jan 2004 14:57:51 -0000 Subject: Generate PDF or LaTeX ? References: Message-ID: <40040775$0$11171$cc9e4d1f@news.dial.pipex.com> reportlab ? "Sinclair" wrote in message news:bu0r5k$q7f$1 at news-reader4.wanadoo.fr... > Hi all, > > I am looking for a way to generateLaTeX or PDF code from python/zope > objects. The goal is to produce print documents. > Does any python module exist to do that ? > > Thanks for your help. > > From rick_muller at yahoo.com Thu Jan 22 12:07:23 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 22 Jan 2004 09:07:23 -0800 Subject: distutils uninstall References: <5eb8fb88.0401210822.55b60ef7@posting.google.com> Message-ID: <5eb8fb88.0401220907.7cd965cc@posting.google.com> Skip Montanaro wrote in message news:... > Rick> I've been trying to figure out whether there are any plans to add > Rick> an "uninstall" feature to the Python distutils. Googling has found > Rick> several people posting the same question, but, to the best of my > Rick> knowledge, no answers. > > This has been proposed before. It's not a trivial problem though. > Distutils would need to record all the files and directories it creates > during installation and carefully remove stuff during the uninstall process > (do things "backwards", not remove directories which still contain files, > etc). That wouldn't be foolproof though, because unlike packaging systems > such as Red Hat's RPM, you don't have a full system picture. What if your > distutils-installed package provides a new version of /etc/magic? If you > uninstall it, /etc/magic would be deleted, since distutils couldn't tell > that /etc/magic was actually used by many other parts of the system. > > Skip Thanks for the reply, Skip. I actually had a simpler case in mind, that you go to the directory from which you installed the software, and typed 'setup.py uninstall', since the setup.py script should be able to determine which files it originally installed, and remove them. Certainly not foolproof, but it may be useful all the same. From usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org Sat Jan 3 17:07:16 2004 From: usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org (Sami Juvonen) Date: Sat, 03 Jan 2004 22:07:16 GMT Subject: Starting a script interactively? References: <37d5fe8f.0401021305.349a440@posting.google.com> Message-ID: On 2 Jan 2004 13:05:14 -0800, David Klaffenbach blurted: > Is there a way from within a python script to cause the interpreter to > be in interactive mode after the script finishes? > > so that if I run: > > myscript.py > > it will always execute as if I had run: > > python23.exe -i myscript.py In Windows, create another extension mapping for python, like .pyi and set the program to open them to something like c:\python23\python.exe -i "%1" %* (see .pyw and py for guidance). Then rename your script to myscript.pyi -- "...you want a .sig with that?" From jjl at pobox.com Tue Jan 13 13:47:44 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 18:47:44 +0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> Message-ID: <87oet7it2n.fsf@pobox.com> Forgot to add: what happened to all those Python interface proposals? At least one was PEPed, wasn't it? I suppose it's waiting for Guido-bandwidth. John From t_therkelsen at hotmail.com Sat Jan 3 18:03:58 2004 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 03 Jan 2004 23:03:58 GMT Subject: Lists are weird when they are instance members References: Message-ID: In article , python newbie wrote: > hey, > okay, I'm trying to figure out why my books: Quick Python, Python in a > Nutshell, Python Cookbook and Learning Python don't say anything about the > weird behavior of a list when you have one as an object instance member. > > for instance (my first pun of 2004), if I have, > > test.py > ---------------- > > global_filegroup_array = [] # array of filegroup objects > > class FileGroup: > a = 0 > mylist = [] # here it is mylist in this case is a class variable; what this means is that it is shared amongst all *instances* of the class. Only if an instance of the class rebinds mylist is it local to the particular class instance doing this. > > def put_stuff_in_my_list(self, anyfile): > self.mylist.append( get just a single string from file) # > pls excuse the psuedo Because lists are mutable, when you use mylist.append(...) you don't rebind mylist, but change its contents. Since mylist is a class variable, this change is available to the class as well as all instances of the class. > > def __init__(self): > put_stuff_in_my_list(anyfile) > > def main(): # do ten times: instantiate the > above object, and add to the global array > for i in xrange(10): > filegroup = FileGroup() > global_filegroup_array.append(filegroup) > > > # print the list contents > print global_filegroup_array[0].mylist > > ------------ end of file > > Output is: [u'.string1', u'.string2', u'.string3' ] # only > u'string1' should show up > > No matter which index I use into the global array, I always get ALL of > the strings > showing up. I should only get u'string1' showing up, and u'string2' > if > I used "[1].mylist" > > > How I resolved it, is by slipping in > > self.mylist = [] > > before > > put_stuff_in_my_list(anyfile) > > in __init__(self) > > Why should I have to empty out the list when it's a member of a newly > instantiated object? Because __init__() is called when a class is about to be instantiated. You are masking the *class variable* mylist with a local *instance variable* of the same name. The latter is not shared amongst all instances of the class, but remains unique to the particular instance. Hope this helps, /Troels Therkelsen From Pieter.Claerhout at Creo.com Tue Jan 6 05:38:16 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 6 Jan 2004 11:38:16 +0100 Subject: How to I get the classname of object ? Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D48@cseexch01.cse.creoscitex.com> Try MyClassInstance.__class__.__name__ cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: fowlertrainer at anonym.hu [mailto:fowlertrainer at anonym.hu] Sent: 06 January 2004 11:31 To: python-list at python.org Subject: How to I get the classname of object ? Hello python-list, Please help me !!! like Delphi's obj.ClassName Thanx -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu -- http://mail.python.org/mailman/listinfo/python-list From swalters_usenet at yahoo.com Fri Jan 9 16:36:58 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 21:36:58 GMT Subject: Python is far from a top performer according to benchmark test... References: Message-ID: |Thus Spake Krzysztof Stachlewski On the now historical date of Fri, 09 Jan 2004 22:13:58 +0100| > "Carl" wrote in message > news:ryELb.238$tK2.228 at amstwist00... > >> I have been experimenting with numerical algorithms in Python with a >> heavy use of the Numeric module. My experience is that Python is quite >> fast in comparison with (and sometimes as fast as) traditional languages >> such as C or C++. > > With "heavy use of Numeric module" you were calling functions written in > C. So how can you say that Python is fast, when C code is doing all the > work. Because python works best as a glue layer coordinating outside libraries and functionality. I think the true strength of python comes from a one-two punch of "Fast and pretty implementation with easy interface to lower level tools." When python is not the right tool, we code our solution with the right tool and then use python to glue all the right tools together. For numerical processing, C is the right tool, but python is not. Therefore, noone tried to use the wrong tool, they just used the right tool and gave it python bindings so that python could act as a coordinator. I read the benchmark and I think it doesn't measure python in it's target area. That's like taking a world-class marathon runner and wondering why he doesn't compete well in a figure-skating event. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From graham__fawcett at hotmail.com Wed Jan 28 09:42:09 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 28 Jan 2004 06:42:09 -0800 Subject: little client + server app : has this been done? References: <7x1xpkk6j9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7x1xpkk6j9.fsf at ruckus.brouhaha.com>... > Python Baby writes: > > Should I do it from scratch or is this just some well-known library I > > don't know about? (I searched around, of course, but couldn't find one.) > > > > Thanks! > > Use a web server. Good, terse advice. ;-) Mr. Baby, note that Python has both HTTP server (BaseHTTPServer, SimpleHTTPServer) and HTTP client (httplib, urllib) functionality built into the standard library. It will definitely pay off in the long run if you stick to open standards like HTTP instead of rolling your own protocols. -- Graham From dck at gazeta.pl Tue Jan 27 06:11:22 2004 From: dck at gazeta.pl (DCK) Date: Tue, 27 Jan 2004 11:11:22 +0000 (UTC) Subject: TELNET instead PING References: <5f505344.0401260332.184d4225@posting.google.com> <401571B9.F9DF99D0@engcorp.com> Message-ID: Peter Hansen wrote: > Interesting, but why would you use TELNET for that? Telnet is > simply one of many possible protocols, whereas you need only > open a socket to the port to see if the host is responding. I was on some kind of Network course, where teacher said, that telnet is better then PING. In my work i found this usefull for pinging network. When i meet with Python, i foud TELNETLIB module and write simply scheduled script which probe network. > from socket import * > s = socket(AF_INET, SOCK_STREAM) > try: > s.connect((host, port)) > print 'host connected' > s.close() > except error: > print 'host not responding' THX for this advice. In future i will read manual carefully :) Greetz Michal DCK Kaczor From martin at v.loewis.de Wed Jan 21 12:07:00 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 21 Jan 2004 18:07:00 +0100 Subject: distutils uninstall In-Reply-To: <5eb8fb88.0401210822.55b60ef7@posting.google.com> References: <5eb8fb88.0401210822.55b60ef7@posting.google.com> Message-ID: <400EB1B4.3040901@v.loewis.de> Rick Muller wrote: > I've been trying to figure out whether there are any plans to add an > "uninstall" feature to the Python distutils. Googling has found > several people posting the same question, but, to the best of my > knowledge, no answers. As Skip explains: no. Instead, use a bdist_ command, then use the uninstall mechanism of the binary packaging technology (e.g. wininst, rpm). There are some complaints that bdist-generated packages don't properly uninstall either (e.g. may not remove directories properly); contributions are welcome. Regards, Martin From tjreedy at udel.edu Wed Jan 21 16:21:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Jan 2004 16:21:00 -0500 Subject: Assignment to slice References: Message-ID: "Rich Krauter" wrote in message news:mailman.604.1074712550.12720.python-list at python.org... Guido very intentionally made index access of items strict and slice access of subsequences permissive. This partly due to the difference between items, which must exist, and subsequences, which can be empty. It also gives programmers a choice in some situations. For instance, seq[0] only works on non-empty seqs while seq[0:1] gives you a sequence with 0 or 1 items without raising an error to catch when there are 0. > Oh well. Maybe my problem is that I'm using perl as my > model of consistency. How amusing ;-) > I just need to be aware of it, and not try to write > perl code in python. I need to learn to write python > code in python. Definitely. Good insight. Terry J. Reedy From ferrell at diablotech.com Thu Jan 15 13:58:13 2004 From: ferrell at diablotech.com (Robert Ferrell) Date: 15 Jan 2004 10:58:13 -0800 Subject: Can MayaVi visualize 3D functions in an unstructured grid ? References: <11d4728b.0401150613.1bfb4ca3@posting.google.com> Message-ID: <73b00f0c.0401151058.526211b9@posting.google.com> I can't answer about MayaVi. However, I use Paraview (paraview.org). I use it on windows, but it's available for Linux. It is open source. Works great for me. I use it on unstructured FE meshes, among other things. -robert arian.novruzi at mathstat.uottawa.ca (A. Novruzi) wrote in message news:<11d4728b.0401150613.1bfb4ca3 at posting.google.com>... > Hi, > > I am looking for a free 3D visualization software, running in Linux, > and able to visualize 3D functions in nonstructured mesh (basically, > my mesh is a set of thetraheders used for some 3D FE computations). > > Can anyone confirm that indeed MayaVi can visualize 3D functions in > nonstructured mesh? I went through the manuals but I didn't find that > MayVi can do so. > > Thank you, > Arian Novruzi From elainejackson7355 at home.com Sun Jan 11 23:42:42 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 12 Jan 2004 04:42:42 GMT Subject: exceptions Message-ID: <6BpMb.66656$JQ1.17722@pd7tw1no> Could someone give me a hint regarding exceptions? Specifically, how you handle different exceptions with different blocks of code? All I know how to do now is to follow "raise" with a string (and even that is now deprecated, apparently). Muchas gracias. Peace From aahz at pythoncraft.com Wed Jan 21 19:53:03 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jan 2004 19:53:03 -0500 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <7934d084.0401181805.71029c2f@posting.google.com> <400EE6B5.27C6B694@hotmail.com> <20040121131300.D8E9.JCARLSON@uci.edu> Message-ID: In article <20040121131300.D8E9.JCARLSON at uci.edu>, Josiah Carlson wrote: > >Of course you could just as easily use a single lock and a class: > >class lockedgen: > def __init__(self, gen): > self.g = gen > self.l = threading.Lock() > def get(self): > self.l.acquire() > a = self.g.next() > self.l.release() > return a This is one case where you *DEFINITELY* want to use try/finally: class lockedgen: def __init__(self, gen): self.g = gen self.l = threading.Lock() def get(self): self.l.acquire() try: a = self.g.next() finally: self.l.release() return a -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From timr at probo.com Thu Jan 15 23:36:46 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 15 Jan 2004 20:36:46 -0800 Subject: dde References: <8EFMb.102403$_P.3808599@news4.tin.it> Message-ID: "Alessandro Crugnola *sephiroth*" wrote: > >"Tim Roberts" wrote: >> >> What DDE app are you trying to control? > >macromedia Flash That's not an app, that's a file format. What app are you trying to control? I would have guessed that a fancy app like Dreamweaver, for example, would probably be controllable by COM, which is easy in Python. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From remi at cherrypy.org Mon Jan 12 16:50:26 2004 From: remi at cherrypy.org (Remi Delon) Date: 12 Jan 2004 13:50:26 -0800 Subject: what is best for web development?? References: Message-ID: <585c0de9.0401121350.10ced5a4@posting.google.com> > i am developing an issue tracking system > the primary requirements are > 1)it should be platform independent which i think python will take > care of > 2)it should have customizeable gui .I am thinking of using templates > for this like Cheetah. Is there any other better solution to Cheetah? > The problem i am facing here is i dont know what to use for > development of the application. I came across many ways to develop > web application in python which I already specified like > i)the cgi module in python > ii)Python Server Pages > iii)Quixote > iv)WebWare > v)Zope etc. > I want to choose such an environment so that i dont have to install > other softwares to run my application.For eg. I think if I develop > using zope then the client also has to install zope to run my > software and i dont want this. If you want something that meets your requirement and is very easy to deploy, you can try CherryPy ... It will generate a single executable containing everything that's needed to run the site (including its own HTTP server). Then all you need to install on the deployment machine is Python. Actually, you can also freeze the script generated by CherryPy (with py2exe for instance) and then Python isn't even required anymore ... Remi. remi at remove-me.python-hosting.com ---------------------- Specialized python hosting: http://www.python-hosting.com CherryPy: http://www.cherrypy.org Free CherryPy hosting: http://www.freecherrypy.org ---------------------- From gerrit at nl.linux.org Sun Jan 4 12:47:19 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 18:47:19 +0100 Subject: Proposal: new peps always in clpa Message-ID: <20040104174719.GA16475@nl.linux.org> Hi, would it be a good idea to automatically sumbit all new peps to comp.lang.python.announce? After all, each PEP is an announcement and may be important to the entire Python community. Another possibility would be to python-dev, but since c.l.py.announce has a broader public, I'd prefer the first one. What do you think? Gerrit. -- 201. If he knock out the teeth of a freed man, he shall pay one-third of a gold mina. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From giles_brown at hotmail.com Sun Jan 4 05:02:57 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 4 Jan 2004 02:02:57 -0800 Subject: Cheetah best for templating? References: Message-ID: <57de9986.0401040202.65b1882f@posting.google.com> "Roger Jack" wrote in message news:... > I have just finished reading Code Generation In Action which uses Ruby for > code generation. I would like to use Python instead. Is Cheetah the best > tool to use for templating source code files and then generating code? Is > there something more mature or better? I had a project where I wanted to generate some pro*c + C++ database code. I found that the Python Template Language that comes with Quixote was very convenient for this purpose, because it avoids needing to learn another syntax. Quixote: http://www.mems-exchange.org/software/quixote/ PTL: http://www.mems-exchange.org/software/quixote/doc/PTL.html Regards, Giles From deets_noospaam at web.de Sun Jan 4 11:34:41 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 04 Jan 2004 17:34:41 +0100 Subject: how to make a code object a function References: Message-ID: > You could provide a separate namespace and then extract only the > callables: > >>>> d = {} >>>> exec "factor=2\ndef alpha(s, t): print factor*t" in d >>>> d.keys() > ['__builtins__', 'alpha', 'factor'] >>>> funcs = dict([(n,f) for n, f in d.iteritems() if callable(f)]) >>>> funcs > {'alpha': } >>>> funcs["alpha"](None, 2) > 4 And again I learned something completely new - cool. Thanks, Diez From missive at frontiernet.net Fri Jan 23 22:23:04 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 24 Jan 2004 03:23:04 GMT Subject: sort profile stats by percall Message-ID: Is there an easy way to sort the stats returned from the hotshot.Profile() by the percall column? From newsgroups at jhrothjr.com Sun Jan 4 17:53:33 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Jan 2004 17:53:33 -0500 Subject: Let users execute but not view References: Message-ID: "Florian Lindner" wrote in message news:bt9o11$7rq$05$1 at news.t-online.com... > Hi! > I have a python script which should be executed my normal users but they > should not be able to view the sourcecode. Setting permissions to x only > does not help, the python interpreter can not read the file. > How can I do that? > Thanks, > Florian You've already got the standard answers, hopefully that will do what you need to do. The other way is to dig into the import mechanics, paying particular attention to how it unfreezes frozen modules, and then arrange to decrypt your encrypted pre-compiled modules when they have to be imported. That's a *lot* of hassle, and I don't know of anyone who's actually done it. Whether the work is worth the benefit is, of course, your decision. John Roth From jcarlson at uci.edu Tue Jan 20 21:14:20 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 18:14:20 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> Message-ID: <20040120181009.060C.JCARLSON@uci.edu> > A question for gui application programmers. . . > I 've got some GUI programs, written in Python/wxPython, and I've got > a help button and a help menu item. Also, I've got a compiled file > made with the microsoft HTML workshop utility, lets call it > c:\path\help.chm. My question is how do you launch it from the GUI? > What logic do I put behind the "help" button, in other words. > > I thought it would be > > os.spawnv(os.P_DETACH, "c:\\path\\help.chm", []) needs to be: os.spawnv(os.P_DETACH, "c:\\path\\help.chm", ["c:\\path\\help.chm"]) > so I guess help.chm isn't executable itself, but is associated with > some unknown executable. I tried explorer.exe- at the dos cmd line it > basically works to type > os.spawnv(os.P_DETACH, 'explorer.exe', ["c:\\path\\help.chm"]) os.spawnv(os.P_DETACH, 'explorer.exe', ['explorer.exe', "c:\\path\\help.chm"]) > would be equivalent but it fails. I have to believe someone out there > in python community likes to include help.chm with their applications, > nad there is a right way to do this. > > On another note, are there pure python based help viewers that people > use instead? The reason I ask is that would be more portable then the > *.chm files are. If there is such a beast I can't find it. Personally, I would suggest: os.startfile("c:\\path\\help.chm") It is documented to do exactly what you want it to do, open up the help file with the microsoft help file viewer. - Josiah From cpl.19.ghum at spamgourmet.com Mon Jan 26 18:40:06 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 27 Jan 2004 00:40:06 +0100 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: malcolmny_1 at lycos.com (malcolm) wrote in news:64cff82f.0401251143.328388bd at posting.google.com: > Why you can't get something for nothing > Jack Schofield Jan 22 2004 is that the "Al Jazira runs IIS 5 on Linux" Jack Schofield? From Vincent.Raaijmakers at ge.com Tue Jan 20 16:02:52 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Tue, 20 Jan 2004 15:02:52 -0600 Subject: adodbapi, exception/error handling question Message-ID: <971323274247EB44B9A01D0A3B424C850558E2E3@FTWMLVEM02.e2k.ad.ge.com> Hopefully posted on the correct newsgroup. The adodbapi group seems so quit.... I want to distinguish between 1) an error in the sql statement to create a table, and 2) when the sql is correct but the table exists in the database (and thus the create sql failed.) Is there an error that I can catch and figure out which of the above 2 scenarios occurred. Thanks Vincent From craspe at mvtools.net Thu Jan 22 12:38:59 2004 From: craspe at mvtools.net (Chris Raspe) Date: Thu, 22 Jan 2004 12:38:59 -0500 Subject: Program Python in VIM In-Reply-To: <871xpsc5zf.fsf@tulip.whu.ca> References: <871xpsc5zf.fsf@tulip.whu.ca> Message-ID: <20040122173859.M70110@mvtools.net> from the VIM FAQ... 30.1. Can I run a shell inside a Vim window? Currently Vim doesn't have support for running shell and other external commands inside a Vim window. For more information, read :help shell-window Alternatively, you can try using the Unix "screen" utility or the 'splitvt' program. You can also use the vimsh plugin by Brian Sturk to run a shell in a Vim window. To use this you need to have Vim built with python support. For more information visit the following URL: http://vim.sourceforge.net/scripts/script.php?script_id=165 On Thu, 22 Jan 2004 11:17:56 -0500, Peter Wu wrote > I'm giving vim a try to program Python. The following are the steps I > follow to code/test a python program. > > vi test.py > [key in some python code] > :wq > :!python test.py > > Is there any other way? I don't want to type 'python test.py' every time > I've made any modifications. In Emacs, I can simply fire C-c C-c to fire > the python interpreter. Thanks! > > -- > ,,, > (o o) Peter Wu > ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 > -- > http://mail.python.org/mailman/listinfo/python-list From cygnus at cprogrammer.org Thu Jan 22 15:36:01 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Thu, 22 Jan 2004 15:36:01 -0500 Subject: Ordered dictionary? In-Reply-To: References: Message-ID: <20040122203601.GA3404@mail.theserver.ath.cx> # I need to associate a string (key) with an integer (value). A dictionary # would do the job, except for the fact that it must be ordered. I also # need to look up the value for a specific key easily, so a list of tuples # wouldn't work. As the other posts on this thread suggest, dictionaries -- by virtue of their structure -- have no inherently meaningful ordering. You'll have to either sort the keys (the easy way) or design a wrapper for the dictionary that maintains a sorted list of the dictionary's keys and updates it as necessary (the hard way). -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From xx758 at cam.ac.uk Tue Jan 20 11:52:49 2004 From: xx758 at cam.ac.uk (Xiao-Qin) Date: Tue, 20 Jan 2004 16:52:49 +0000 Subject: Problem with TCL Message-ID: Hello, Verybody, After I swith my Redhat 9.0 to Chinese interface, I cannot run python codes based on Tkinter any more, the error message is list following: """ [xqxia at sunflower bin]$ wish #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?usr/lib/tcl8#?#?#?#?lib/tcl8#?#?#?#?usr/librar#?#?#?librar#? #?#?tcl8#?3/librar#?#?#?usr/share/tcl8#?#?#?#?#?P`#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?[xqxia at sunflower bin]$ """ and """ >>> from Tkinter import * Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: libtk.so.0: cannot open shared object file: No such file or directory >>> """ Anybody know how to solve it? Many thanks from, Xiao-Qin From mir4uu at yahoo.com Tue Jan 20 11:44:10 2004 From: mir4uu at yahoo.com (mir nazim) Date: 20 Jan 2004 08:44:10 -0800 Subject: Please Help Me (Re: needed PyXPCOM tutorial.) References: <425cc8d1.0401150908.287de0d8@posting.google.com> <425cc8d1.0401170903.3c331ab9@posting.google.com> Message-ID: <425cc8d1.0401200844.f6dcf9c@posting.google.com> mir4uu at yahoo.com (mir nazim) wrote in message news:<425cc8d1.0401170903.3c331ab9 at posting.google.com>... > Christoph Becker-Freyseng wrote in message news:... > > mir nazim wrote: > > > > >hi > > >i m in need of a PyXPCOM tutorial. it should explain using python > > >(instead of JavaScript) for creating apps. if any body can point me to > > >some web resources or a printed book . > > >thankz > > > > > > > > Maybe those will help (check 3! They've some more links) > > > > http://lxr.mozilla.org/seamonkey/source/extensions/python/xpcom/ > > http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/ > > http://pygecko.sourceforge.net/ > > http://xul.sourceforge.net/ > > http://luxor-xul.sourceforge.net/ > > http://www.thomas-schilz.de/MozPython/ (the downloads-dirctory > > contains installers for upgrading Mozilla to Python-Interpretability) > > > > > > > > Christoph Becker-Freyseng > > yeah i know about them all > but what i acutally need is an indepth tutorial/guide/refrence. Please help me find some tutorials on pyxpcom. my project is at hold due to it. From hans at zephyrfalcon.org Fri Jan 23 14:10:38 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 23 Jan 2004 14:10:38 -0500 Subject: [OPINION] - does language really matter if they all do the same thing? In-Reply-To: <20040123183127.GA35281@mail.hitmedia.com> References: <20040123183127.GA35281@mail.hitmedia.com> Message-ID: <401171AE.7000806@zephyrfalcon.org> Python Baby wrote: > Are programming languages like spoken languages, in the sense > that they all say the same things, just using different words? Some people think so. I do not agree. It depends where you're coming from, I guess. E.g. if all you do is build business applications, and you spend most of you time in a GUI builder and calling methods on pre-made objects, then it may seem that the language doesn't matter. After all, all this functionality is available in Java, VB, Delphi, VC++, etc. Also, "problem X" can probably be solved in most languages, whether it be C, Python, Ruby, Perl, COBOL, PHP, you name it. However, there are important differences in *how* these problems are solved. Creating a dictionary with a few names and phone numbers, for example, can be a one-liner in Python (and other high level languages), but it won't be in C. The "level" of languages is just one aspect, though. Programming languages are designed with different philosophies in mind. For example, Python was designed to be very readable. Not all languages share this design goal. :) Other languages were designed to do system programming, text processing, web programming, to enforce "good" programming behavior, to offer programmers endless choices, etc. In other words, there are many reasons to choose language X over Y, depending on your preferences, and on the situation at hand. (Although there are also more or less objective criteria... some languages are demonstrably more concise and/or readable than others, others have better performance or are better suited to a certain task, etc.) Personally, I've come to believe that the choice of language is *very* important, and not something trivial. (I am also convinced that management should not impose a language on programmers, aside...) > As I've fretted over this for way too many hours, I started wondering: > > Can Ruby do something (important) that Python can't? > Can Python do something (important) that PHP can't? > Can PHP do something (important) that Ruby or Python can't? > > Are they all just the same, and it's just a matter of taste? I don't know enough about Ruby or PHP to make an informed statement about what they can do that the others cannot, but it's definitely not just a matter of taste. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From mhammond at skippinet.com.au Wed Jan 21 18:17:36 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 22 Jan 2004 10:17:36 +1100 Subject: Multithreaded COM server problem... In-Reply-To: <9uvs00568u2tb2qp0lndh649d0ajdginkl@4ax.com> References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com> <9uvs00568u2tb2qp0lndh649d0ajdginkl@4ax.com> Message-ID: John Lull wrote: > 1. Dig into exactly how apartment-threaded servers are supposed to be > written in C or C++ & see how much of that is transferrable to Python. > I'm not confident this would give me a solution, though. ... > 3. Dig into why setting sys.coinit_flags=0 in localserver.py doesn't > work. This is probably the right thing to do, both because I know it > will yield a solution, and because it would solve the same issue for > anyone else with similar needs. Unfortunately it means I have to dig > into Python threading internals, pythoncom internals, and the whole > COM mechanism rather more heavily than I'd hoped to. I think these are pretty-much the same option. The win32com extensions make no attempt to insulate you from these threading issues - it will blindly do what you ask. In that regard, Python already acts very much like a C/C++ application - under the covers, we have a C++ pointer to a COM object, and when Python code tries to make a call, from whatever thread, we just make the call. The same thing is true in reverse - we hand out a C++ pointer, and when an incoming call is made on that, we blindly call Python on that thread. The Python GIL is in the picture, but I see no evidence it has any bearing in this case. Certainly, in the simple example we started with, no threads were blocked waiting for this lock. Re sys.soinit_flags - I am fairly confident that this will cause CoInitEx to be called with the specified flag as pythoncom is imported. However, note that any exceptions raised by this function are masked when called implicitly during that import. Try explicitly calling pythoncom.CoInitializeEx(0) near the top of localserver.py - any exceptions you see would also have happened for the implicit call made at import time. I'd welcome any evidence that a C++ app would behave differently, and am keen to help you resolve (or at least explain) this for everyone's future benefit. Mark. From seanl at chaosring.org Sun Jan 4 23:54:30 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sun, 04 Jan 2004 20:54:30 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: <-PmcnYBHI_Sac2WiXTWc-w@speakeasy.net> Serge Orlov wrote: > "Sean R. Lynch" wrote in message news:mvScnSDrma66AWWiXTWc-g at speakeasy.net... >> >>Global *mutable* state shouldn't be shared, AFAICT. > > > Right, I missed this simple rule. My mind is still confined by my recent > attempt to add security by only translating bytecode without any changes > to the interpreter. You were translating bytecode rather than working with ASTs? That would be hard to maintain, considering that Zope found it too difficult to maintain even manipulating concrete syntax trees. Also, I don't really consider that I'm modifying the interpreter, I'm just giving the interpreter a different globals dict. >>I believing making >>sure no mutable state is reachable through __builtins__ > > > Are you going to create multiple __builtins__ or you're just going > to get rid of any global objects in __builtins__? The first lets you > handle str.encode the right way. I'm not sure what you mean by this. I'm creating a dict for __builtins__, but AFAIK it's not possible for code to modify the __builtins__ dict other than through the name __builtins__, which starts with an underscore and so is invalid. All of the objects I have in __builtins__ right now are immutable within the restricted environment because they're either functions or classes. Python modules that are imported in the restricted environment will be read-only and each domain will get its own copy. This should prevent leaks caused by two domains importing the same module and then performing operations that affect the state of the module. Modules will need to explicitly specify what names they want to export the same way classes do in order to prevent inadvertent leaks. >>and having a new >>globals dict for each security domain should be enough. Any modules that >>are imported would need to be imported separately for each domain, > > > Can C modules be imported more than once in CPython? Not that I'm aware of, which is why they will need to be audited for mutable state and other sources of leaks and excess privilege. C modules that we need that have problems will get proxies the same way E has proxies for Swing. From fapinkse at hotmail.com Sun Jan 18 08:59:28 2004 From: fapinkse at hotmail.com (F.A. Pinkse) Date: Sun, 18 Jan 2004 13:59:28 GMT Subject: Boa: printing source in the Editor Message-ID: <4jwOb.40507$DF4.24648@amsnews02.chello.com> Dear Group, Does the Editor of BOA has a print function? If it has one, where is it placed in the menu hierarchy? Thanks for the answers. Frans. From ark at acm.org Wed Jan 14 01:35:02 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 14 Jan 2004 06:35:02 GMT Subject: I come not to bury C++, but to praise it... References: Message-ID: "John Benson" wrote in message news:mailman.337.1074032524.12720.python-list at python.org... > I got into Python because I took one look at C++ and saw all the handwaving > in the introductory O'Reilly book to the effect that "everything looks sweet > now, but wait until these snazzy little features interact..." and then > started casting around for another road to OOP. Perhaps you should cast around for a different C++ book while you're at it, too -- maybe the one you found isn't well suited to your particular learning style. From nohmad at sub-port.net Sun Jan 11 01:57:26 2004 From: nohmad at sub-port.net (Gyoung-Yoon Noh) Date: 10 Jan 2004 22:57:26 -0800 Subject: Problem in directory working Message-ID: <92ed2954.0401102257.565dd6f4@posting.google.com> I've written Unix's find-like function using recursive os.listdir() call and generator expression. It seems that error happens in generator expression. Below codes do not work. walk.next() generates StopIteration. When I replace 'yield' with 'print', it works fine. Why this does not work? I've had successively implemented unix-find using os.path.walk(). But I want to combine recursive call and generator expressions. Any comments are welcome. [snip] import os def find(path): if not os.path.exists(path): raise StopIteration if os.path.isdir(path): for l in os.listdir(path): fullpath = os.sep.join((path, l)) find(fullpath) else: yield path if __name__=='__main__': #find('/home/myhome'); raise SystemExit() walk = find('/home/myhome') for i in walk: print i.next() From ir4u4 at yahoo.com Sat Jan 24 17:48:21 2004 From: ir4u4 at yahoo.com (Equis Uno) Date: 24 Jan 2004 14:48:21 -0800 Subject: My Python cannot find wxPython References: <692feddd.0401221457.18d40480@posting.google.com> Message-ID: <692feddd.0401241448.447817e2@posting.google.com> I got Boa Constructor working. I'm not sure what the problem was so I 'wiped the slate clean'. I downloaded Python-2.3.3.tgz I unpacked and installed it with this script: #! /bin/bash set -x export DESTDIR=/python/ /bin/rm -rf /python mkdir /python make clean make distclean ./configure --enable-unicode=ucs4 --prefix /python --exec-prefix /python make make test make install cd /bin/ mv python pythonWhichIUsedToUse ln -s /python/bin/python . Next, I added these tokens to my LD_LIBRARY_PATH /python/lib/python2.3/lib-dynload Next, I downloaded wxPythonSrc-2.4.2.4.tar.gz I unpacked and installed it with this script: #! /bin/bash set -x export WXPREF=/python/wxPython cd /CD/python/wxPythonSrc-2.4.2.4/ mkdir build cd build ../configure --with-gtk \ --prefix=$WXPREF \ --enable-rpath=$WXPREF/lib \ --with-opengl \ --enable-geometry \ --enable-optimise \ --enable-debug_flag \ --with-libjpeg=builtin \ --with-libpng=builtin \ --with-libtiff=builtin \ --with-zlib=builtin make make install cd ../wxPython /bin/python setup.py WX_CONFIG=/python/wxPython/bin/wx-config build install cd demo /bin/python demo.py Next, I added these tokens to my LD_LIBRARY_PATH /python/wxPython/lib Next, I downloaded boa-constructor-0.2.3.src.zip I unzipped it. I ran this and it worked great: /bin/python Boa.py -moi From mcfletch at rogers.com Fri Jan 9 15:08:22 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 15:08:22 -0500 Subject: Database interfacing In-Reply-To: References: Message-ID: <3FFF0A36.80806@rogers.com> Harry George wrote: >"Michael T. Babcock" writes: > > > >>I'm working with databases (MySQL primarily) more and more with >>Python, and having used PERL in the past for similar work, I'm >>wondering if there are good tools for doing 'intelligent' >>selects/inserts to/from dictionaries, etc. For example: >> >>data = {'FirstName': 'Michael', 'LastName': 'Babcock', 'Age': 99} >>lastid = db.insert('Users', data) >> >> userSchema = schema.lookupName( 'users' ) data = userSchema.itemClass( FirstName = 'Michael', LastName= 'Babcock' Age= 99, ) data.insertQuery( APPLICATION.getDBConnection() ) >>... which would execute "INSERT INTO Users (FirstName, LastName, Age) >>VALUES ('Michael', 'Babcock', 99)" >> >>And also helpful would be: >> >>data = db.query("dbname", "SELECT * FROM Users WHERE Age >= 99)") >> >> users = userSchema.query( """SELECT * FROM Users WHERE Age >= 99)""", APPLICATION.getDBConnection()) >>... which would return me an array of dictionary items like: >> >>[ {'ID': 143, 'FirstName': 'Michael' ... }, {'ID': 242, ... }, ... ] >> >> In this case, a row of wrappers around dictionaries (objects). You can change what class those objects are by declaring it in the userSchema object. The default ones are fairly heavy wrappers with properties for each field in the table, coercian of field-values to specified classes/types, insert/refresh/update/delete query methods, etceteras. >You can write tools like this yourself or use existing tools. For >starters take a look at: http://skunkweb.sourceforge.net/PyDO/ > > Or, for the code above, PyTable RDBMS Manager. http://pytable.sourceforge.net/ I mostly use it with PostgreSQL, but it does have MySQL-compatible plumbing as well. >If you roll your own, here are some considerations: > >You need to synchronize the table definitions in the DBMS with the >class definitions in python. Some approaches start with the DBMS and >extract the table definitions (attributes, keys, etc) for use in >generating the needed python code. Some start with python and define >a list of attributes and their meta data as a class-level var for a >class. (I've tried both ways.) > > PyTable normally goes Python-definition -> database, but does have some support for reading the definition out of the database. There are, as Harry points out, a number of such wrapper mechanisms available. The biggest problem with all of them is that it's almost as much effort to learn and adapt them as it is to write your own. The impedence mismatch between OO programming (Python) and RDBMS just doesn't seem to allow for a "perfect" solution to the problem, so instead you see a number of different approaches with different strengths and weaknesses. Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From gandalf at geochemsource.com Mon Jan 26 15:31:41 2004 From: gandalf at geochemsource.com (Gandalf) Date: Mon, 26 Jan 2004 21:31:41 +0100 Subject: TELNET instead PING References: <5f505344.0401260332.184d4225@posting.google.com> <401571B9.F9DF99D0@engcorp.com> Message-ID: <4015792D.8030407@geochemsource.com> Peter Hansen wrote: >DCK wrote: > > >>Into group-archive i found most e-mails, which touches PINGing. >>In my work i've used TELNET for testing if host is operational. >>Sometimes, for unknown reasons, workstation doesn't respond >>for PINGing. But in WinNT network, all hosts has a nbsession >>listening on port 139. I always use this script instead PING >>command (hope, will be usefull for someone :) ): >> >> > >Interesting, but why would you use TELNET for that? Telnet is >simply one of many possible protocols, whereas you need only >open a socket to the port to see if the host is responding. > > Exactly. All you need is an open port you can check. Note: that reason you talked about is most likely a packet filtering firewall. A good firewall can block PING, Telnet, Nbsession and many others. In most cases, the best policy is to lock everything by default and permit only the ones you really want. Firewall rules can include source addresses too. It is possible that a computer do not respond on PING and TELNET ports for you but it does for a similar request from another computer. I think there is no universal way to determine if a remote host is alive or not. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bwglitch at hotpop.com Wed Jan 21 23:32:51 2004 From: bwglitch at hotpop.com (BW Glitch) Date: Wed, 21 Jan 2004 23:32:51 -0500 Subject: How to disable dos shell window popup for os.system call In-Reply-To: References: Message-ID: Peter Gordon wrote: > When I try to execute another program, the dos command shell window > pops up with the application. For example: > os.system("notepad") brings up the notepad but I also get the command > shell window. How do I prevent command shell window to open? You can use the Win32 extensions by Mark Hammond, as well as one of the os.popen (iirc, it's os.popen2). os.system is doing what it is expected, btw. -- Glitch http://andres980.tripod.com/ Nobody wins a war -- somebody loses. -- Grears (G1) From ANTIGEN_DATA at sewelld.com Thu Jan 29 11:49:34 2004 From: ANTIGEN_DATA at sewelld.com (ANTIGEN_DATA) Date: Thu, 29 Jan 2004 09:49:34 -0700 Subject: Antigen found VIRUS= Win32.Mydoom.A (CA(Vet)) worm Message-ID: <266583517F575241B30C945BF3741F1038A5FF@data> Antigen for Exchange found myqfg.zip->myqfg.txt .scr infected with VIRUS= Win32.Mydoom.A (CA(Vet)) worm. The message is currently Purged. The message, "Test", was sent from python-list at python.org and was discovered in IMC Queues\Inbound located at sewelld/provo/DATA. From gerrit at nl.linux.org Mon Jan 5 16:45:08 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 5 Jan 2004 22:45:08 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <20040105214508.GA29923@nl.linux.org> John Roth wrote: > Subject: PRE-PEP: new Path class > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q I will update the Pre-PEP tomorrow based on the comments I already have seen in this PEP. Note that it is very 'pre' and opinions expressed in the PEP are not guaranteed to be consistent in any way ;) I will comment on the comments later. yours, Gerrit. -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From wxyisok at hotmail.com Sun Jan 4 11:18:23 2004 From: wxyisok at hotmail.com (wang xiaoyu) Date: 4 Jan 2004 08:18:23 -0800 Subject: how to use activex in wxpython with event support References: Message-ID: i have solve the problem.my solution is :since this activex(DICOM) works fine in vb,and i know activex controls developed by vb works fine in python,so why cant i develop an activex control which wrap this activex(DICOM)?so i build a vb's activex project insert this activex(DICOM) in it and delegate this control(DICOM) events into vb control's event. this activex developed by vb works fine in wxpython,MakeActiveXClass works fine. but i really dont understand why this method works,can you give me some explanation? best regards. wangxiaoyu wxyisok at hotmail.com (wang xiaoyu) wrote in message news:... > Hello: > i want use activex in wxpython program,but when i use MakeActiveXClass > an exception occurs. > > this is my source code dealing the DICOM ocx.I must note that in this > program "hwtxcontrol" is a ocx developed my me use vc6,this ocx works > fine in wxpython. > > but you can see i only change this ocx with a new DICOM ocx and set up > eventClass, > > but the exception occure: > > File ".\site-packages\wxPython\lib\activexwrapper.py", line 105, in > axw__init__ > File "D:\Py22\lib\site-packages\win32com\gen_py\3A75EE8D-8E68-43FF-A90A-E4835B9A3DBDx0x1x0.py", > line 187, in __init__ > cookie=cp.Advise(win32com.server.util.wrap(self, > usePolicy=EventHandlerPolicy)) > com_error: (-2147220990, 'CONNECT_E_CANNOTCONNECT', None, None) > > the ocx and the source code (in delphi) you can down at: > > http://www.psychology.nottingham.ac.uk/staff/cr1/dicomcom.html > > from wxPython.wx import * > from wxPython.lib.rcsizer import RowColSizer > import pywin.mfc.activex > import activexwrapper,win32ui > > if wxPlatform == '__WXMSW__': > from wxPython.lib.activexwrapper import MakeActiveXClass > import win32com.client.gencache > import win32com.client > try: > import hwtxcontrol > hwtxocx=hwtxcontrol > #import ezdicom > #dicomocx=ezdicom > #dicomocx=win32com.client.gencache.EnsureModule("{3A75EE8D-8E68-43FF-A90A-E4835B9A3DBD}",0,1,0) > #dicomocx=win32com.client.Dispatch("ezDICOMax.ezDICOMX") > dicomocx=win32com.client.gencache.EnsureModule('{3A75EE8D-8E68-43FF-A90A-E4835B9A3DBD}', > 0, 1, 0) > except: > raise ImportError("IE4 or greater does not appear to be > installed.") > > class DicomControl(pywin.mfc.activex.Control, dicomocx.ezDICOMX): > def __init__(self): > pywin.mfc.activex.Control.__init__(self) > dicomocx.ezDICOMX.__init__(self) > def OnDCMmouseDown(self, X ,Y ,Button ,Shift): > print "DICOM ocx Click!" > > class HwtxControl(pywin.mfc.activex.Control, hwtxocx.Hwtx): > def __init__(self): > pywin.mfc.activex.Control.__init__(self) > hwtxocx.Hwtx.__init__(self) > def OnClick(self): > print "hwtx click!" > class TestPanel(wxWindow): > def __init__(self, parent, log, frame=None): > wxWindow.__init__(self, parent, -1, > > style=wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) > sizer = wxBoxSizer(wxVERTICAL) > hwtxCtls=RowColSizer() > theClass2 = MakeActiveXClass(dicomocx.ezDICOMX,eventClass=DicomControl) > #theClass2 = > MakeActiveXClass(hwtxocx.Hwtx,eventClass=HwtxControl) > self.ie4=theClass2(self,-1) > self.ie4.SetSize(wxSize(300,300)) > #self.ie4.filename="e:\\d02.img" > #self.ie4.palnumber=12 > #self.ie4.state=1 > hwtxCtls.Add(self.ie4, row=2, col=2) > sizer.Add(hwtxCtls, 0, wxEXPAND) > self.SetSizer(sizer) > self.SetAutoLayout(True) > EVT_WINDOW_DESTROY(self, self.OnDestroy) > def OnDestroy(self, evt): > if self.ie4: > self.ie4.Cleanup() > self.ie4 = None > > def runTest(frame, nb, log): > if wxPlatform == '__WXMSW__': > win = TestPanel(nb, log, frame) > return win > else: > dlg = wxMessageDialog(frame, 'This demo only works on MSW.', > 'Sorry', wxOK | wxICON_INFORMATION) > dlg.ShowModal() > dlg.Destroy() > > overview = __doc__ > > if __name__ == '__main__': > class TestFrame(wxFrame): > def __init__(self): > wxFrame.__init__(self, None, -1, "ActiveX test -- Internet > Explorer", > size=(640, 480), > > style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) > self.CreateStatusBar() > self.tp = TestPanel(self, sys.stdout, self) > EVT_CLOSE(self, self.OnCloseWindow) > > def OnCloseWindow(self, evt): > self.tp.Destroy() > self.Destroy() > > app = wxPySimpleApp() > frame = TestFrame() > frame.Show(True) > app.MainLoop() > > i am a new python programer but i was really attracted by it elegant > code.i really want use wxpython as my framework,but if i cant use > activeX,i will have to change to vb:( > > can you help me.Best regards. > > sincerely > > wangxiaoyu From stephendotboulet at motorola_._com Mon Jan 26 11:24:57 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Mon, 26 Jan 2004 10:24:57 -0600 Subject: Zope In-Reply-To: References: Message-ID: Just wondering, it's not in /etc/init.d/zope* ? Stephen lenk wrote: > Hi > I installed zope in suse 9.0(own package).but i can t find start to > start the server . > /opt/zope/ ... is it a right path ? > > second problem > Can you give an web example for python (forum,gueastbook ...) > links pls:) > > thanks for all > From tim at lesher.ws Tue Jan 20 13:27:27 2004 From: tim at lesher.ws (Tim Lesher) Date: 20 Jan 2004 10:27:27 -0800 Subject: A lazy-committing database object with curry? References: Message-ID: Jp Calderone wrote in message news:... > On Mon, Jan 19, 2004 at 08:45:45AM -0800, Tim Lesher wrote: > Are you sure? How will the initial values be committed to the database, > if you don't catch them in the modifications dict? I guess you might be > handling initial values somewhere else, in code you didn't post... Yes... this class will only be working on rows that already exist in the database--in other words, it only has to cope with updates and deletes, not inserts. > Nift. You surely don't use the full capabilities of currying here, but > you are incurring a double function call overhead on every setattr now. > Here's another way to do it: > > def makeModificationFunctions(name): > def modget(self, value): > try: > return self.__modifications[name] > except KeyError: > return self.__dict__[name] > def modset(self, value): > self.__modifications[name] = value > return modget, modset > title = property(*makeModificationFunctions('title')) > description = property(*makeModificationFunctions('description')) Aha. This is what I was really looking for. I tried it with lambdas at first and got bitten by the expressions-only limitation. Coming from a C++ background, I keep forgetting about local functions... > Of course, you can go one step better and use a metaclass: Wow. That's even shinier than the currying. > This can be just "if self.__modifications:" I know... explicit better than implicit and all. > One possible problem is failed commits. If you're doing commits > transactionally, and the transaction fails, your in memory objects will > retain their now-inconsistent values while the database remains unupdated. > If you're not using transactions.. well that's a whole other problem :) Yep, failed commits are handled in the 'snipped' piece of code when they're handled at all--initially this is running against a transactionless database, but the place is there to handle transactions--that's why I don't clear the modifications until after the update is made. > You may want to look at xsdb and atop. Neither uses SQL, but both have > developed pretty heavily on some of the ideas you're tinkering around with. Thanks; I will. -- Tim Lesher From dlee at rightnow.com Fri Jan 23 11:38:32 2004 From: dlee at rightnow.com (dustin lee) Date: 23 Jan 2004 08:38:32 -0800 Subject: closing database connections Message-ID: <71fd0ae5.0401230838.309e9b02@posting.google.com> Over the years I've gotten out of the habit of explicitly closing file objects (whether for reading or writing) since the right thing always seems to happen auto-magically (e.g. files get written to disk with no missing data). I've recently started do the same thing with database connections. I'm wondering if anyone has had trouble with this sort of "lazy" programming style. My assumption is the the database connection will get closed auto-magically when the interpreter closes. I'd be interested to hear if any one has been bitten by not explicitly closing database connections and under what cirumstances. My main fear is that I will "run out of" database connections or in some other way adversely affect server performance. I'm using recent versions of both mysql and oracle. Thoughts? dustin ps. If someone wants to try to talk me into explicitly closing files I'd be interested to hear wisdom on that as well. From tr at jotsite.com Thu Jan 15 17:17:19 2004 From: tr at jotsite.com (Hoang) Date: Thu, 15 Jan 2004 22:17:19 GMT Subject: the thread that refused to die: I come not to bury C++, but to praise it... References: Message-ID: Unfortunately there are too many C++ programmers working in the real-world. Getting them to change their minds about their favorite language is no small hurdle. Additionally, there is the perception that Python is slow. Again, it's mindshare that is important in converting to Python. Hoang Do http://jotsite.com From aa at bb.cc Fri Jan 30 09:49:40 2004 From: aa at bb.cc (Ladvánszky Károly) Date: Fri, 30 Jan 2004 14:49:40 GMT Subject: Adding/removing instance members Message-ID: I understand instance members can be added to an object in a dynamic manner: class Cc: pass oCc=Cc() oCc.x=10 # oCc now has a new member What is the way to remove these instance members? Is it possible to add a new member whose name is given by a string? Thanks on any help, K?roly From jcarlson at nospam.uci.edu Tue Jan 27 18:03:32 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 27 Jan 2004 15:03:32 -0800 Subject: Portable /dev/null? In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Hi everyone, > Is there an object in some standard library that would be the > portable equivalent of "file('/dev/null','w')" or do I have to create my > own class and object to do it? If it doesn't exist, do you think it > would be a good idea to have such an object in a standard library? > > Thx and Regards, > > Nicolas > In Windows you can open the file 'NUL' and it will work the same as '/dev/null' in *nix. - Josiah From astrand at lysator.liu.se Sat Jan 3 08:47:41 2004 From: astrand at lysator.liu.se (=?iso-8859-1?Q?Peter_=C5strand?=) Date: Sat, 3 Jan 2004 14:47:41 +0100 (CET) Subject: PEP 324: popen5 - New POSIX process module Message-ID: There's a new PEP available: PEP 324: popen5 - New POSIX process module A copy is included below. Comments are appreciated. ---- PEP: 324 Title: popen5 - New POSIX process module Version: $Revision: 1.4 $ Last-Modified: $Date: 2004/01/03 10:32:53 $ Author: Peter Astrand Status: Draft Type: Standards Track (library) Created: 19-Nov-2003 Content-Type: text/plain Python-Version: 2.4 Abstract This PEP describes a new module for starting and communicating with processes on POSIX systems. Motivation Starting new processes is a common task in any programming language, and very common in a high-level language like Python. Good support for this task is needed, because: - Inappropriate functions for starting processes could mean a security risk: If the program is started through the shell, and the arguments contain shell meta characters, the result can be disastrous. [1] - It makes Python an even better replacement language for over-complicated shell scripts. Currently, Python has a large number of different functions for process creation. This makes it hard for developers to choose. The popen5 modules provides the following enhancements over previous functions: - One "unified" module provides all functionality from previous functions. - Cross-process exceptions: Exceptions happening in the child before the new process has started to execute are re-raised in the parent. This means that it's easy to handle exec() failures, for example. With popen2, for example, it's impossible to detect if the execution failed. - A hook for executing custom code between fork and exec. This can be used for, for example, changing uid. - No implicit call of /bin/sh. This means that there is no need for escaping dangerous shell meta characters. - All combinations of file descriptor redirection is possible. For example, the "python-dialog" [2] needs to spawn a process and redirect stderr, but not stdout. This is not possible with current functions, without using temporary files. - With popen5, it's possible to control if all open file descriptors should be closed before the new program is executed. - Support for connecting several subprocesses (shell "pipe"). - Universal newline support. - A communicate() method, which makes it easy to send stdin data and read stdout and stderr data, without risking deadlocks. Most people are aware of the flow control issues involved with child process communication, but not all have the patience or skills to write a fully correct and deadlock-free select loop. This means that many Python applications contain race conditions. A communicate() method in the standard library solves this problem. Rationale The following points summarizes the design: - popen5 was based on popen2, which is tried-and-tested. - The factory functions in popen2 have been removed, because I consider the class constructor equally easy to work with. - popen2 contains several factory functions and classes for different combinations of redirection. popen5, however, contains one single class. Since popen5 supports 12 different combinations of redirection, providing a class or function for each of them would be cumbersome and not very intuitive. Even with popen2, this is a readability problem. For example, many people cannot tell the difference between popen2.popen2 and popen2.popen4 without using the documentation. - One small utility function is provided: popen5.run(). It aims to be an enhancement over os.system(), while still very easy to use: - It does not use the Standard C function system(), which has limitations. - It does not call the shell implicitly. - No need for quoting; using a variable argument list. - The return value is easier to work with. - The "preexec" functionality makes it possible to run arbitrary code between fork and exec. One might ask why there are special arguments for setting the environment and current directory, but not for, for example, setting the uid. The answer is: - Changing environment and working directory is considered fairly common. - Old functions like spawn() has support for an "env"-argument. - env and cwd are considered quite cross-platform: They make sense even on Windows. - No MS Windows support is available, currently. To be able to provide more functionality than what is already available from the popen2 module, help from C modules is required. Specification This module defines one class called Popen: class Popen(args, bufsize=0, argv0=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, preexec_args=(), close_fds=0, cwd=None, env=None, universal_newlines=0) Arguments are: - args should be a sequence of program arguments. The program to execute is normally the first item in the args sequence, but can be explicitly set by using the argv0 argument. The Popen class uses os.execvp() to execute the child program. - bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). - stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. - If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed, with arguments preexec_args. - If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. - If cwd is not None, the current directory will be changed to cwd before the child is executed. - If env is not None, it defines the environment variables for the new process. - If universal_newlines is true, the file objects fromchild and childerr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects fromchild, tochild and childerr are not updated by the communicate() method. The module also defines one shortcut function: run(*args): Run command with arguments. Wait for command to complete, then return the returncode attribute. Example: retcode = popen5.run("stty", "sane") Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the child's point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A PopenException will also be raised if Popen is called with invalid arguments. Security -------- popen5 will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ------------- Instances of the Popen class have the following methods: poll() Returns -1 if child process hasn't completed yet, or its exit status otherwise. See below for a description of how the exit status is encoded. wait() Waits for and returns the exit status of the child process. The exit status encodes both the return code of the process and information about whether it exited using the exit() system call or died due to a signal. Functions to help interpret the status code are defined in the os module (the W*() family of functions). communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional stdin argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: fromchild A file object that provides output from the child process. tochild A file object that provides input to the child process. childerr A file object that provides error output from the child process. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value means that the process was terminated by a signal with number -returncode. Open Issues Perhaps the module should be called something like "process", instead of "popen5". Reference Implementation A reference implementation is available from http://www.lysator.liu.se/~astrand/popen5/. References [1] Secure Programming for Linux and Unix HOWTO, section 8.3. http://www.dwheeler.com/secure-programs/ [2] Python Dialog http://pythondialog.sourceforge.net/ Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: -- /Peter ?strand From pgmoscatt at optushome.com.au Sat Jan 24 18:46:51 2004 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Sun, 25 Jan 2004 09:46:51 +1000 Subject: Tkinter Base Window References: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Message-ID: <401303eb$0$14483$afc38c87@news.optusnet.com.au> Thanks Salvatore for the link. Pete Salvatore wrote: > Peter Moscatt wrote: >> Ok.... I am pretty new to Python (as you may have gathered from previous >> posts). So now it time for another one of my ridiculous questions.... >> :-) >> >> When using 'Tkinter', what is used as the base window to work from, >> meaning what widget do I use to place all other widgets onto to create a >> custom dialog ? >> >> Pete >> > Here you can find what you search and more ;-) > http://www.pythonware.com/library/tkinter/introduction/ > > Regards > > Salvatore From mcfletch at rogers.com Sat Jan 3 23:17:09 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 03 Jan 2004 23:17:09 -0500 Subject: Parametrized inheritance In-Reply-To: <2AJJb.725692$HS4.5422608@attbi_s01> References: <2AJJb.725692$HS4.5422608@attbi_s01> Message-ID: <3FF793C5.5070507@rogers.com> Dan Bullok wrote: ... >The inheritance looks like this: > Base->MyBase > ->Sub->MySub > >But I'd really like it to look like this: > Base->MyBase->Sub->MySub > >i.e. define Sub as "class Sub(X)", where I can change X at the time of >instantiation. Then I could define MySub as "class MySub(Sub(MyBase))". >(I hope that it's obvious that I'm looking for this effect, not this syntax) > > Works quite nicely in Python 2.2 with only one minor change. In particular use of object as base for Base: >>> class Base(object): ... pass ... >>> class Sub( object ): ... pass ... >>> class MyBase( Base ): ... pass ... >>> class MySub( Sub, MyBase ): ... pass ... >>> MySub.mro() [, , , , ] >>> You can use the super( ... ) built-in to provide really elegant support for mix-in classes overriding base-class operations cooperatively. BTW, you could have made Sub a sub-class of Base in the example above and *still* had it give you the desired method-resolution-order, (a nice feature of Python's multiple-inheritance mechanism, IMO). (I made Sub's parent object to make it clear how the inheritance works.) You can find more information about these kinds of patterns by searching for "Mix-In Class" and/or "Multiple Inheritance". Python 2.2 changed how multiple inheritance graphs are constructed in Python, BTW. If you used old-style classes the mro would have been [MySub, Sub, Base, MyBase, Base] IIRC. HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From http Sun Jan 11 14:37:46 2004 From: http (Paul Rubin) Date: 11 Jan 2004 11:37:46 -0800 Subject: Help with if statement References: Message-ID: <7xk73y8eet.fsf@ruckus.brouhaha.com> "Jikosan" writes: > for N in range(0, 100000, 25): For such a large list, you should xrange instead of range. That will use less memory. > c = math.sqrt(math.pow(x,2.0) + math.pow(y,2.0)) You should use "c = math.sqrt(x*x + y*y)" which is both faster and more flexible: math.pow(x,2.0) happens to work ok here, but can throw an error in some implementations if x is negative. > pi = 4.0*(onecheck*math.pow(N,-1)) You can say "pi = (4.0 * onecheck) / N" here. That's faster and more straightforward. > #Convert pi and N to log10 and write to a file to graph on Excel. Why are you going to graph log(N) vs log(pi)? Do you expect them to have an exponential relationship? If not, log(N) vs pi, instead of log(pi), may make more sense. From andre.bernemann at gmx.de Thu Jan 15 17:08:04 2004 From: andre.bernemann at gmx.de (Andre Bernemann) Date: 15 Jan 2004 14:08:04 -0800 Subject: Python COM Server with C++ Message-ID: Hi, I have written a Python COM Server with the help of Mark Hammond's Book Programming Python on Win32. I used the CreateObjects method in VB to access the COM Methods and all worked fine. Unfortunately, that is not what i really want. First I'd like to make the COM Server accessible from C++ and as a beside product I want to use early binding within VB with the NEW operator. I've googled around alot, but I still have not the complete picture of what to do. So far I think I have to create an IDL file to describe the interface and compile it with the MIDL Compiler. There ist my first question. What do I have to create first, the IDL file or the Python COM Server? I'm a little bit confused about dispid's, the GUID's and naming conventions. Do i need to make use of the makepy Utility in any way? Do I have to modify the Python COM Server Source Code in any way or can I use it as it is? (I can post the code here on request) It would be great if anybody can give me information about the things i have to do in order to make this work. Documentation links and sample code would also be fantastic. (I'm programming on Python 2.2 with the appropriate Windows Extensions and Visual C++ 6.0) Thx in advance Andre From warlock at eskimo.com Fri Jan 23 23:06:41 2004 From: warlock at eskimo.com (Jim Richardson) Date: Fri, 23 Jan 2004 20:06:41 -0800 Subject: Perl vs. Python for text manipulation (was: [OPINION] - does language really matter if they all do the samething?) References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sat, 24 Jan 2004 03:02:31 -0000, Cameron Laird wrote: > In article , > Paul Prescod wrote: >>Dietrich Epp wrote: >>> >>>... >>I would appreciate an example of something you would do by capturing a >>message that cannot be done in Python. >> >>I rather wonder if you've illustrated the downside of flitting from >>language to langauge. You may think you're using a language to capacity >>without actually doing so. I could be wrong but perhaps even the tasks >>you turn to Lisp or Perl for may have easy equivalents in Python. >> >> Paul Prescod >> >> > > The comparison with Perl in particular interests me. I > often encounter characterizations of Perl (or Ruby--I > regard them as equivalent in this dimension) as the par- > agon of text manipulation. It's not, of course, as Icon > conclusively demonstrates, at least for me; but I don't > even see Perl as distinctly superior to Python in text > mangling. I recognize that Python REs can feel a bit > cumbersome, in comparison to Perl, because they essenti- > ally demand the extra step of explicit compilation. Is > that all that people mean, though, when they talk about > Perl's superiority for text mangling? Is there more to > it? Not sure about superiority. But I find perl useful for those one liners sed/awk/grep replacements. It's nothing I'd want to use to write anything more involved, but it's a great replacement/supplement to tr/cut/grep/awk/sed/etc. On the otherhand, where I used to write bash scripts, using all or some of the above, I tend to use python now, and am much happier for it :) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAEe9Rd90bcYOAWPYRAh78AKDmi4QnsEcMLfN5HqPHwUJa8ZFGNQCePZ75 Jcu7eTJUh/xAdrtt73s+UaM= =KZM9 -----END PGP SIGNATURE----- -- Jim Richardson http://www.eskimo.com/~warlock Microsoft gives you Windows... Linux gives you the whole house From christianjauvin at videotron.ca Wed Jan 21 10:33:49 2004 From: christianjauvin at videotron.ca (Christian Jauvin) Date: Wed, 21 Jan 2004 10:33:49 -0500 Subject: newbie: prefix operator "**" Message-ID: Hello, I am playing with some classes in the Tkinter module to learn some GUI basics. One problem is that I can't figure what is the meaning of the prefix operator "**". I'm guessing that it has something to do with dictionnaries, but I can't find any explanation of it in the Python doc, nor on Google. Here is a code snipped which I would like to understand: class AnyWidget: def __init__(self, master=None, cnf=None, **kw): if cnf is None: cnf = {} if kw: cnf = _cnfmerge((cnf, kw)) fcnf = {} Thanks! From exarkun at intarweb.us Fri Jan 30 22:43:38 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 30 Jan 2004 22:43:38 -0500 Subject: Tcp/ip programs in python In-Reply-To: References: Message-ID: <20040131034338.GA32302@intarweb.us> On Fri, Jan 30, 2004 at 12:46:25PM -0800, Josiah Carlson wrote: > Jp Calderone wrote: > > >On Fri, Jan 30, 2004 at 06:27:45PM -0000, M.Dikmen wrote: > > > >>Do you now a source about socket programming in python? or some source > >>codes, demo programs? i really need them > >> > > > > > > In order of increasing relevance: > > > > http://www.google.com/ > > > > http://www.vex.net/parnassus/ > > > > http://www.twistedmatrix.com/ > > > I always found http://www.python.org/doc/current/lib/module-socket.html > to be quite useful for the background and > http://www.python.org/doc/current/lib/module-asyncore.html for the > actual implementation. Those are decent sources as well, though neither provides much in the way of "source codes" or "demo programs". If I had to choose just one, it would be _UNIX Network Programming_, you know the one I mean. Fortunately, there is no such limitation. Jp From carroll at tjc.com Sat Jan 24 03:14:32 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat, 24 Jan 2004 08:14:32 GMT Subject: progress bar References: <59e5b87.0401231329.6e084d6f@posting.google.com> Message-ID: On 23 Jan 2004 13:29:38 -0800, mirandacascade at yahoo.com (Miranda Evans) wrote: >Seeking references to documentation that discuss how a python script >can handle displaying a progress bar. Also, if you are aware of any >sample code that illustrates this, I'm interested in looking at that >sample code. > >Are there ways to accomplish this that do not involve using a >full-featured GUI toolkit like Tkinter or wxPython or PythonCard? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 From daniels at dsl-only.net Fri Jan 2 14:20:00 2004 From: daniels at dsl-only.net (sdd) Date: Fri, 02 Jan 2004 11:20:00 -0800 Subject: Conditional except: blocks In-Reply-To: References: Message-ID: <3ff5d00c$1@nntp0.pdx.net> Robert Brewer wrote: > try: > return nextHandler(args) > except (None, Exception)[self.trapErrors], exc: > if page == u'-Error': > raise exc raise # re-raises the same error with the full traceback. > else: > return self.handle_error(exc, scriptWithPath) From noemail at noemail4u.com Fri Jan 30 10:05:29 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 30 Jan 2004 15:05:29 GMT Subject: Simple Database Package References: <8089854e.0401290034.4d57a45d@posting.google.com> Message-ID: <444c343a820dc6204c623ffbc24651c6@news.teranews.com> On 29 Jan 2004 00:34:37 -0800, michael at foord.net (Fuzzyman) wrote: >I don't know what it is - but I asked a couple of questions here >yesterday... and seem to have received a lot of help from peopel >called Peter..... sounds suspiciously like a conspiracy to me :-) I thought they were all named Bruce? --dang From JimJJewett at yahoo.com Thu Jan 22 11:00:25 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 22 Jan 2004 08:00:25 -0800 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <400AB936.BA1D9D73@hotmail.com> <7934d084.0401181805.71029c2f@posting.google.com> <400EE6B5.27C6B694@hotmail.com> Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > My point is that I haven't (yet) seen many good use cases for sharing a > generator between threads, and I'm guessing that many people will try > using generators inappropriately for problems that really are better > suited to Queue.Queue. A globally unique ID, such as: "What filename should I store this page under?" The standard library has (several versions of) similar functionality for temporary filenames. They aren't all threadsafe, they often enforce the "temporary" aspect, they run into hashing collision problems eventually, there is no good way to include even approximate ordering information, etc... The fact that these are in the standard library suggests that it is a common use case. The fact that there are several different versions each with their own problems suggests that the problem is hard enough to justify putting a good solution in the library. -- -jJ Take only memories. Leave not even footprints. From Z_kline at hotmail.com Sun Jan 18 20:44:00 2004 From: Z_kline at hotmail.com (Zachary) Date: Sun, 18 Jan 2004 17:44:00 -0800 Subject: Python Text Adventure Authoring System Message-ID: Hello, I've recently thought of how ideal Python is for the development of what used to be called text adventures. In case any of you don't know, these were basically sort of a computer game in which the player guided the story by typing in natural language commands, e.g. get ball. Some popular games of the 1980's include Zork, A Mind Forever Voyaging, among others. I was just wondering if anyone has any module that might help in the implementation of a text parser, something to read player commands. My idea is to have each room, item, creature, etc. Be represented as a Python instance. For example, the following code might setup a room class: class room: def __init__(self, rdesc, exit): self.desc = rdesc #Add Other code here If anyone has any idea how this might be done, I would love to hear from you. P.S: I have already seen another text adventure development system written in Python, called Paws. I thought this would be a sort of first project. From jcarlson at nospam.uci.edu Tue Jan 27 17:30:04 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 27 Jan 2004 14:30:04 -0800 Subject: How does compare work? In-Reply-To: <4016A368.9050806@skynet.be> References: <40158680$0$7044$ba620e4c@news.skynet.be> <4016A368.9050806@skynet.be> Message-ID: > But silently(!) comparing apples with pears is evil. E.g. the example I > came across this was > > thresh=raw_input('enter threshold') > ... > level=2 > ... > if level > thresh : > > which failed miserably. By the way, Perl does convert the string to an > integer silenty and, as most of the time, these Perl conversions are > just what one wants, so here. > Nevertheless, I'd prefer an exception in this case since automatic > conversions can never be right in all circumstances. > So this is a case where Python is a very dangerous language! The comparison doesn't fail, it succeeds, just not the way you like. If you want thresh to be an integer, perhaps you should say thresh = int(raw_input('enter threshold')) Perhaps one way to alleviate the problem is to have a special kind of input function: def special_input(prompt, typ): a = None while a is None: if typ is int: r = '-?[0-9]+' #special cases for each kind of input a = re.search(r, raw_input(prompt)) if a is not None: return typ(a.group(0)) Maybe a more fully featured set of input functions would be useful to include in the standard library. Perhaps someone should write an example module and submit it. - Josiah From nospam-deets at web.de Fri Jan 23 07:25:36 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Fri, 23 Jan 2004 13:25:36 +0100 Subject: debugging References: <88bc63c6.0401230416.7acf904c@posting.google.com> Message-ID: Hi, > Can someone help me out a little with Python? What do people use to > debug Python code? I don't understand how to use the built in debugger > and I haven't had any luck getting ddd to debug my Python programs. I > end up falling back on inserting print statements in my code to figure > out what's going on. This works but isn't always the fastest route to > a solution. So, I'm just wondering what other people do. I use print..... But if you want to have a graphical debugger, look into eric. Actually, its much more, and if I were not so tied to xemacs key bindings, I'd switch yesterday. Diez From skip at pobox.com Thu Jan 15 10:08:12 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Jan 2004 09:08:12 -0600 Subject: MySQLdb In-Reply-To: References: Message-ID: <16390.44252.184363.369912@montanaro.dyndns.org> Lukas> I want add the new record to Mysql database. When I use my script Lukas> I got an exception "UnicodeEncodeError: 'ascii' codec can't Lukas> encode character u'\xe4' in position 12: ordinal not in Lukas> range(128). Lukas, You will need to encode your Unicode objects before stuffing the resulting strings into MySQL. For example: utf8foo = foo.encode("utf-8") c.execute("insert into blah blah blah", (..., utf8foo, ...)) instead of c.execute("insert into blah blah blah", (..., foo, ...)) Skip From gerrit at nl.linux.org Sat Jan 24 05:07:25 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 24 Jan 2004 11:07:25 +0100 Subject: efficient matching of elements a list In-Reply-To: References: Message-ID: <20040124100725.GA21063@nl.linux.org> > What is the fastest way in python to get out all the tuples from the > list whose first element is equal to i? Use a list comprehension: >>> L = [(1,2,3), (2,3,1), (3,2,1), (1,2,5), (5,1,3)] >>> [t for t in L if t[0] == 1] [(1, 2, 3), (1, 2, 5)] yours, Gerrit. From tim.golden at viacom-outdoor.co.uk Tue Jan 13 06:30:41 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 13 Jan 2004 11:30:41 -0000 Subject: How to intercept a keypress using python? Message-ID: >-----Original Message----- >From: teengo at yahoo.com [mailto:teengo at yahoo.com] >Sent: 12 January 2004 17:51 >To: python-list at python.org >Subject: How to intercept a keypress using python? > > >Hello all, > >Does anyone know how to intercept user's keypress or >mouseclick in Python? >I'd like to write a small tool (Python-based preferrably) running on >Windows to capture the user's keypresses and mouseclicks and write >them to a file. > >Thanks for your help. >-- Check out: http://mail.python.org/pipermail/python-list/2003-November/195739.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 frithiof.jensen at removethis.ted.ericsson.dk Tue Jan 13 04:48:13 2004 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 13 Jan 2004 10:48:13 +0100 Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> <4002AE9B.C51448FB@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:4002AE9B.C51448FB at engcorp.com... > ...., as it takes me only about twenty seconds to start a > new test file and that's *without* using a template. ....in twenty seconds you can just about write "import unittest" ;-) I find that a simple module will need about three to five tests for each method in each class and probably some test data as well often yielding in total *more* lines of test code than the module I want to test. It is simple, stupid & boring code but still lines that have to be typed and debugged. *That* is tedious work. Always will be. The benefit comes later - when improving and extending the module one can immediately see if it breaks and also I find that if one cannot think of an obvious way of testing some class/method/unit it is usually because the interface is stupid and needs a redesign. The real fun with unittest starts when using "other peoples code": I wrote an accounts database module based on pySqlite for a horse racing program I am (still!) writing for fun. That was not at all easy to get to run in such a way as one could test the database functions properly with unittest. There is a lot of massaging of data to test that the queries work as intended and manual work to design SQL data that will yield simple tests. OTOH I am pretty confident the implementation actually works and I even think I understand the kinks in pySqlite's implementation of the python database API too ;-). From __peter__ at web.de Sat Jan 24 17:11:17 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 24 Jan 2004 23:11:17 +0100 Subject: nested class problem References: <4012d34f$0$17124$626a54ce@news.free.fr> Message-ID: Stephane Ninin wrote: > I am trying to play with nested class in a script I am making, > and I am not sure I really understand how they work. [..] > > class _PTest(ITest): > > class _PHandler(object): > > def __init__(self): > super(_PHandler,self).__init__() Make that super(_PTest._PHandler, self).__init__() or, even better, omit it entirely. Python class hierarchies tend to remain flat, because inheritance is only necessary for code reuse, not to indicate a particular interface. > #self.__map={} > > def test(self): > pass > > def __init__(self): > super(_PTest,self).__init__() > > > def read(self,filename): > super(_PTest,self).read(filename) > print "HERE" > print dir() > print dir(self) > print self.__class__ > print dir(self.__class__) > dh = self._PHandler() > #dh.test() > > if __name__=='__main__': > > a=ITest.make_reader() > print dir(a) > b=a.read("") > print b > > > > > I want to put class _PHandler in _Ptest, > and use _PHandler in _Ptest methods, > but anything I try doesnot work... I think that's you fighting against the language and - a rare case - python fighting back :-) > > On this configuration, I have: > Traceback (most recent call last): > File "./test.py", line 58, in ? > b=a.read("") > File "./test.py", line 51, in read > dh = self._PHandler() > File "./test.py", line 34, in __init__ > super(_PHandler,self).__init__() > NameError: global name '_PHandler' is not defined > > and I have similar problems if I try to access _PHandler > in different ways... > Is this possible somehow ? Or what is the problem with my approach ? > I know I could just dont use nested classes.., but I'd like to try. I fail to see the benefit of nested classes. If you want to bring some structure into your python application, try packages instead. Peter From michael at foord.net Wed Jan 21 09:04:30 2004 From: michael at foord.net (Fuzzyman) Date: 21 Jan 2004 06:04:30 -0800 Subject: Python Email Packages Message-ID: <8089854e.0401210604.4d041ea3@posting.google.com> I've started to learn CGI programming with Python.... and despite a few problems with 'internal server errors' (one hour to debug a 1k file - but now I understand thigns a bit better !!) I'm enjoying it ! We have quite a restrictive firewall and internet policy here at work - as you can tell by the fact that I'm posting from google :-) I'm trying to build a CGI newsreader using python (assisted by the fact that www.xennos.com offers free hosting with Python 2.2 woohay :-) and actually having some success ! I'll build a python client for my desktop as well.... nice. ( www.voidspace.xennos.com for the curios - but there isn't a lot there yet). What I would also like is a package that will interface with my CGI scripts via email - and respond by email... is there a nice python e-mail management package that anyone can reccomend me ?? Sorry if the question is dumb... I haven't done a lot of research into this yet....... Fuzzy -- 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.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. Building with Python - programming language that rules the world. --- 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 jcollins_boulder at earthlink.net Wed Jan 14 10:53:51 2004 From: jcollins_boulder at earthlink.net (Jeffery D. Collins) Date: Wed, 14 Jan 2004 08:53:51 -0700 Subject: FRPythoneers Meeting -- January 19, 2004 Message-ID: <4005660F.2010004@earthlink.net> January 19, 2004, 7:00PM at Level 3 Communications in Broomfield, CO. Title: Jython, the best of both worlds or the lowest common denominator Author: Demian L. Neidetcher Abstract: Python is a language that this choir knows has many great features. Admittedly, Java has some benefits that Python doesn't; it has great momentum behind it and it has a good install base. Jython allows us to take advantage of the usability and rapid development of Python as well as being able to use popular Java class libraries and take advantage of the popularity of the Java Virtual Machine. I'd like to talk at a high level about where using Jython makes sense and also discuss some caveats that Jython introduces. I'll show how to build Jython code with Ant (the Java build tool), some freebies that Jython gives you when dealing with the Java APIs. I'll also show a few comparisons of functionally equivalent Java and Jython code. =================================================================== Meeting Information - http://fr.co.us.pythoneers.org/meetings.html Driving Directions - From US36, exit at the 96th Street exchange (also marked Interlocken Blvd) and head south (towards the new Flatirons Mall.) Alternatively, if you are coming from the south and want to avoid the construction on Hwy 36... come up Hwy 93, Indiana, or Wadsworth. Turn onto Hwy 128 (east from 93 or Indiana, west from Wadsworth just before 36). Then turn north on 96th (not Interlocken) and continue below. From 96th Street turn west (or right - away from the Sun campus) onto Eldorado Blvd. The entrance to the conference room is in Building 2000. These doors will be locked, so arrive shortly before 7pm to ensure entry. Proceed upstairs to the second conference room on your right. -- Jeffery Collins From http Fri Jan 9 21:03:24 2004 From: http (Paul Rubin) Date: 09 Jan 2004 18:03:24 -0800 Subject: Databases: Which one's right for me? References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: <7xad4wef0z.fsf@ruckus.brouhaha.com> What do you need to do with the database? For a lot of standalone applications, one of the standard Python dbm modules is good enough. From bmgx_no_sp at mgleesonprop.co.za Tue Jan 6 14:35:03 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Tue, 06 Jan 2004 21:35:03 +0200 Subject: using cgi form via http and extracting results In-Reply-To: <3ffaf37b.0@news1.mweb.co.za> References: <3ff84844.0@news1.mweb.co.za> <3ffaf37b.0@news1.mweb.co.za> Message-ID: <3ffb0dde.0@news1.mweb.co.za> Ok it's done right.. import urllib a = urllib.urlopen("http://www.suckerservice.com/convert.cgi", "Amount=1&From=EUR&To=USD") b = a.readlines() c = open("tempresult.html","w") i = 0 d = "********* local copy ******\n\n" while i < len(b): d = d + b[i] i = i + 1 c.write(d) c.close() a.close() bmgx wrote: > How would one "create" post data so that I can skip the html form and > access the submission script (in
) > directly. This is simple if the script uses GET as mentioned, but > unfortunately this is not the case which is the very reason for my > dilemma.. > > Ben Finney wrote: > >> On Mon, 05 Jan 2004 17:39:30 -0800, Tim Roberts wrote: >> >>> bmgx wrote: >>> >>>> 1) Make an http connection to the remote script >>>> (http://server/script.cgi) >>>> 2) Fill out the html form (1x TEXT and 2x SELECT input fields) >>>> 3) Submit the form >>>> 4) extract the actual returned result. (using regex or something..) >>> >>> >>> You don't actually need steps 1 and 2 at all. >> >> >> >> True. >> >> >>> HTTP transactions are all completely separate. >> >> >> >> True (ignoring cookies for now). >> >> >>> The results of a form submission are just a URL. >> >> >> >> Usually false. >> >> The result of most form submissions is an HTTP POST request, which >> contains the URL and form content as separate data. >> >> >>> If the form has fields "FromCurrency", "ToCurrency", and "Amount", all >>> you have to do is this: >>> >>> http://www.currencyservice.com?FromCurrency=dollars&ToCurrency=pounds&Amount=15 >>> >> >> >> >> This is only true if the form action is an HTTP GET request, which is a >> rather insecure and ugly way to submit form data, and makes it >> impossible to submit many kinds of data. HTTP POST is the recommended >> method for submitting data to a CGI script. >> >> >>> You don't have to HAVE the form source in order to submit a request. >> >> >> >> True. You just need to construct the HTTP POST request correctly. >> > From wolfoxbr at hotmail.com Thu Jan 15 07:37:01 2004 From: wolfoxbr at hotmail.com (Roberto Amorim) Date: Thu, 15 Jan 2004 10:37:01 -0200 Subject: Python used in Freedom Force References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> Message-ID: Not only Freedom Force, but also Severance: Blade of Darkness (3rd-person action medieval game) and Bridge Commander (Star Trek TNG simulator). > I don't know if it's been discussed since the game came out a while > ago, but I was looking through some temp files that were installed with > the game Freedom Force (a very fun game) and the scenarios are > programmed in Python! (This is on the Mac, but I assume it also used > Python on the PC.) From jcarlson at nospam.uci.edu Sun Jan 25 19:59:39 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 16:59:39 -0800 Subject: any news client in Python? In-Reply-To: <1075055910.305663@yasure> References: <2b4c49e0.0401230915.3438810f@posting.google.com> <4de76ee2.0401241125.45e77f9e@posting.google.com> <1075055910.305663@yasure> Message-ID: > That's my story too, but the way I deal with it is to present my > BeOS newsreader and IMAP email reader as a demo application for the > widget set, hence a built-in excuse for its lameness. I never even > got around to the "add group" interface you show there. A really good > newsreader is a lot of work (and of course its users are by definition > the USENET crowd, not people you want to have to deal with!) But it > wasn't much of an issue, because each BeOS user tended to write his > own newsreader for some reason - much easier to tolerate the defects > of your own software, I suppose. Heh. I had been using a plugin that allowed my email software to do news...except the plugin was buggy and crashed every 2-3 posts to newsgroups. I was contemplating writing my own (wxPython's treectrl would have been perfect for threading, as would a dict for properly looking up 'in reply to' posts, but I digress), until I decided to give Mozilla Thunderbird a shot. Damn. Thunderbird is the best news reader I've had the opportunity to use. I'm even contemplating tossing my old email client, even though I have around 100 filters for filtering email from certain people. My only complaint is that it can be a little laggy on a PII-400. I can deal. - Josiah From kyo at netease.com Mon Jan 5 02:49:35 2004 From: kyo at netease.com (kyo) Date: 4 Jan 2004 23:49:35 -0800 Subject: Why exception is not newstyle class? Message-ID: <2f9c31f.0401042349.3eea0e9b@posting.google.com> class A(Exception): def __init__(self, n): self.test = n (1) : class B(A): def __init__(self, n): #A.__init__(self, n) super(B, self).__init__(n) self.testb = n try: raise B, B(1) except A, a: print dir(a) ============================= (2): class B(object): pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" ================================ I want to use new style class, how to do that? If I can't, Why? From jepler at unpythonic.net Mon Jan 12 11:49:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 12 Jan 2004 10:49:41 -0600 Subject: Moving widgets in Tkinter In-Reply-To: References: Message-ID: <20040112164941.GG2810@unpythonic.net> I've embellished your program a little bit ... from Tkinter import * def clamp(lo, hi, x): return min(max(x, lo), hi) class blah: all = [] def MoveWindowStart(self, event): self.move_lastx = event.x_root self.move_lasty = event.y_root self.focus() def MoveWindow(self, event): self.root.update_idletasks() dx = event.x_root - self.move_lastx dy = event.y_root - self.move_lasty self.move_lastx = event.x_root self.move_lasty = event.y_root self.x = clamp(0, 640-200, self.x + dx) # should depend on self.y = clamp(0, 480-200, self.y + dy) # actual size here self.f.place_configure(x=self.x, y=self.y) def __init__(self, root, title, x, y): self.root = root self.x = x; self.y = y self.f = Frame(self.root, bd=1, relief=RAISED) self.f.place(x=x, y=y, width=200, height=200) self.l = Label(self.f, bd=1, bg="#08246b", fg="white",text=title) self.l.pack(fill=X) self.l.bind('<1>', self.MoveWindowStart) self.f.bind('<1>', self.focus) self.l.bind('', self.MoveWindow) # self.f.bind('', self.MoveWindow) self.all.append(self) self.focus() def focus(self, event=None): self.f.tkraise() for w in self.all: if w is self: w.l.configure(bg="#08246b", fg="white") else: w.l.configure(bg="#d9d9d9", fg="black") root = Tk() root.title("...") root.resizable(0,0) root.geometry("%dx%d%+d%+d"%(640, 480, 0, 0)) x = blah(root, "Window 1", 10, 10) y = blah(root, "Window 2", 220, 10) y = blah(root, "Window 3", 10, 220) root.mainloop() From james at logicalprogression.net Wed Jan 28 09:44:34 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 28 Jan 2004 14:44:34 +0000 Subject: r prefix bug ... or my lack of understanding? In-Reply-To: References: Message-ID: <200401281444.34472.james@logicalprogression.net> On Wednesday 28 January 2004 2:27 pm, Bill Sneddon wrote: > Below is from python 2.3.3 on windows. > I have tryed on Pythonwin and Idle and on > a Solaris unix build 2.2.2. > > I know there are work arounds but the behavior > seems a bit strange to me. > > >>> path = r'c:\data' #this is fine > >>> print path > > c:\data > > >>> path = r'c:\data\' > > Traceback ( File "", line 1 > path = r'c:\data\' > ^ > SyntaxError: EOL while scanning single-quoted string > > >>> path = r'c:\data\\' > >>> print path > > c:\data\\ Fuether to my last post the full details are at: http://www.python.org/doc/current/ref/strings.html >From which I quote: r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character) J. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From newsgroups at jhrothjr.com Tue Jan 6 19:54:59 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 6 Jan 2004 19:54:59 -0500 Subject: Pre-PEP: Dynamically evaluating default function arguments References: <711c7390.0401061452.3ee3789f@posting.google.com> Message-ID: "Daniel Ehrenberg" wrote in message news:711c7390.0401061452.3ee3789f at posting.google.com... > One of the most common bugs that people have on the Python Tutor list > are caused by the fact the default arguments for functions are > evaluated only once, not when the function is called. The solution to > this is usually to use the following idiom: [snip] It's an interesting proposal, but outside of the possible breakage, there is one really major problem: Where is the variable going to come from on the function call? If it comes from the original context, it's static so why bother, and if it comes from the caller's context, you're causing a *huge* amount of coupling, as well as a substantial slowdown to do a search of the calling chain and the global context. You can't even make it optional: use the original value if it's not defined in the caller's context. If you do that, you're still exposing the names to the caller as names he has to avoid when writing the calling routine. To put a somewhat positive spin on it though, it is a significant novice problem. Given that you don't want to change the language semantics, what's the next possible way to fix it? Compare PEP's 215 and 292. Both of these do dynamic variable fills, but they have one critical difference: the template is visible, and not off in a function or method definition somewhere. Even so, there are significant issues that have to be resolved. John Roth > > Daniel Ehrenberg From paul at boddie.net Fri Jan 16 06:10:26 2004 From: paul at boddie.net (Paul Boddie) Date: 16 Jan 2004 03:10:26 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <878yka2sze.fsf@pobox.com> <100bbekd61fbl53@corp.supernews.com> <100d4ljnic3l465@corp.supernews.com> Message-ID: <23891c90.0401160310.754b10eb@posting.google.com> "Andrew Dalke" wrote in message news:... > JanC: > > But Netscape was largely based on Mosaic anyway; being developed by the > > same developers. The beta I was talking about above still has a Mosaic > > logo. ;-) > > While it had many of the same developers, as I recall, none of the code was > shared. They were planning to call it Netscape Mosaic but that was > changed before the final release. It was actually called Mosaic Netscape for a time since the company was originally called Mosaic Communications Corporation. Visit http://www.mcom.com and see where it takes you! (Completely work safe, I might add.) Now that's what I call long term domain name asset management! There seemed to be some fairly major differences between later releases of Mosaic before NCSA pulled it (after licensing it to various corporations) and Netscape Navigator - Navigator was threaded even on Windows 3.1, and was clearly better supported on UNIX, Windows and Mac. Still, it's amusing to consider Netscape 4.x and earlier as having some common heritage with Internet Explorer. As for Grail, it was certainly a "hot product" in the Python community in 1995 because of the restricted execution environment which I evaluated for a project involving mobile software agents. How priorities and trends have changed since then! Who would have thought that Microsoft Outlook would be the premier platform for mobile code? ;-) Paul From __peter__ at web.de Thu Jan 8 05:39:12 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Jan 2004 11:39:12 +0100 Subject: Read from, then write to a file without closing first??? References: Message-ID: Amy G wrote: > I am looking to make this code a little "nicer"... any suggestions??? > I want to do a "read+" where I would be able to first read the contents of > the file... then either close the file out or write to the file without > appending. I want to overwrite the content. > > vacation_message = "blah blah blah" > > f_vm=open("/home/%s/.vacation.msg" %userid, 'r') > lines=f_vm.readlines() > f_vm.close() > > if (lines != vacation_message): > f_vm=open("/home/%s/.vacation.msg" %userid, 'w') > f_vm.writelines(vacation_message) > f_vm.close() You can open the file in "r+" mode and then f_vm.seek(0) before writing. However, from the above example I can not see why you even bother to check the old contents and don't just write the new data. Peter From bkelley at wi.mit.edu Mon Jan 12 12:00:31 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 12 Jan 2004 12:00:31 -0500 Subject: py2exe, Inno Setup, and tkinter In-Reply-To: References: Message-ID: <4002d24b$0$577$b45e6eb0@senator-bedfellow.mit.edu> Anthony Baxter wrote: > I'm trying to use py2exe and Inno Setup to build an installer for > shtoom, which uses tkinter. > > If I take the py2exe generated directory, and run the executable from > there, it works fine. > > If I add all the files in the directory to an installer (including > the tk-8.4 and tcl-8.4 directories), it builds an installer fine. I have a script for creating innosetup's [FILE] section. I have used this just fine so it fails for you it may indicate a problem with tcl/tk on your *normal* installation. Can you run your program outside of py2exe? Here is the script: import os # This script creates the [FILES] section for innosetup # I use it for creating the installer for py2exe # generated distributions. Mainly because adding the # tcl/tk stuff is a royal pain. # Point FROM_DIRECTORY to py2exe's destination directory # This will include all tcl/tk and wxPython files and # everything else in the directory and subdirectories. FROM_DIRECTORY = r"C:\Users\kelley\Working\PlateReader\app\dist\Vista" os.chdir(FROM_DIRECTORY) def innoSourceLine(source, dest): return 'Source: "%s"; DestDir: "{app}\%s"; CopyMode: alwaysoverwrite'%(source, dest) for root, dirs, files in os.walk("."): sourcedir = os.path.abspath(root) for f in files: # get the destination directory source = os.path.join(sourcedir, f) dest = root print innoSourceLine(source, dest) # Brian From brian at sweetapp.com Thu Jan 8 22:14:33 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 08 Jan 2004 19:14:33 -0800 Subject: Pesky reverse() In-Reply-To: <_noLb.81639$BA6.1706329@news20.bellglobal.com> Message-ID: <02f001c3d65e$b4871f50$0000fea9@dell8200> >>> # Method described by Sean Ross >>> forward = range(10) >>> reverse = forward[:] # copy >>> reverse.reverse() >>> print forward [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print reverse [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> This will work too: >>> forward = range(10) >>> reverse = forward[-1::-1] >>> print forward [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print reverse [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> From jjl at pobox.com Sun Jan 11 09:16:10 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jan 2004 14:16:10 +0000 Subject: help with Python Environment For Blind User References: Message-ID: <87d69qlget.fsf@pobox.com> Forgot to include the tinyURL for that URL I posted: http://tinyurl.com/28pod John From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jan 14 16:20:09 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 14 Jan 2004 22:20:09 +0100 Subject: CheckButton -- modify "check state" In-Reply-To: <104c369a.0401141314.5c64a727@posting.google.com> References: <104c369a.0401141314.5c64a727@posting.google.com> Message-ID: <4005b288$0$327$e4fe514c@news.xs4all.nl> Askari wrote: > How do for do a "select()" on a CheckButton in a menu (make with > add_checkbutton(....) )? > I can modify title, state, etc but not the "check state". :-( I have no clue what you're talking about: you have to at least tell us what GUI toolkit you're using, and preferrably, show a snippet of code. --Irmen From llothar at web.de Wed Jan 28 07:03:38 2004 From: llothar at web.de (Lothar Scholz) Date: 28 Jan 2004 04:03:38 -0800 Subject: Chart drawing library for Python Message-ID: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Hello, is there something like "JpGraph" for python ? For those who don't know this PHP library: It is a high level drawing library that generates gif files with all kind of charts. Or (maybe better) is there a C library doing this. I think i read about something like this a while ago. From ketulp_baroda at yahoo.com Wed Jan 14 01:09:20 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 13 Jan 2004 22:09:20 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: hi graham is right.I used the term "client" in the business sense, not the client/server sense; and i am trying to write a Web application that is easy to deploy on clients' (customers') servers.sorry for the confusion. From cphsu at zen.com.tw Fri Jan 9 06:37:53 2004 From: cphsu at zen.com.tw (Kent Hsu (Hsu, Chih-Peng)) Date: Fri, 9 Jan 2004 19:37:53 +0800 Subject: Looking for a Python interface to TAPI on Win32 References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200604.44d343f4@posting.google.com> Message-ID: Try "ctypes" or "calldll" to call the Win32 api directly. Best regards, Kent Hsu Ray Chu wrote in message news:fo7rvvoa9bh8m1jg2otndeildpl8gqur7i at 4ax.com... > > > I'd like to get familiar with the Win32 phone interface by using Python. Googling has just yielded Linux > apps. Would appreciate specific help or suggestions about where to look. > > - TIA > Ray From exarkun at intarweb.us Mon Jan 5 14:24:41 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 5 Jan 2004 14:24:41 -0500 Subject: problem with async chat client in windows In-Reply-To: References: Message-ID: <20040105192441.GA5816@intarweb.us> On Mon, Jan 05, 2004 at 04:49:56PM +0100, Jonas wrote: > Jp Calderone wrote: > >On Mon, Jan 05, 2004 at 03:02:29AM +0100, Jonas wrote: > > > >>Hi, > >>I'm writing a small chat client to learn some python and networking. No > >>problem with the network stuff tho, the problem is when the user should > >>be able to interact and type messages to send. Since I work with windows > >>I can't use the select function > > > > > > Why not? select works perfectly well on Windows. > > > > See http://www.twistedmatrix.com/ > > > > Jp > > > > Well the standard library select doesn't work for file descriptors like > stdin on windows and I didn't know about Twisted. Anyway there must be some > way to solve this without the need for extra depencencies?? Ahh! I did not jump from "type messages to send" to "select on stdin", just assumed you were popping up a window into which the user could type. Twisted won't help with reading from stdin, as it relies on select() working on that file descriptor. Not sure if one of the win32-specific modules has something useful here. I'd probably just use a GUI. Sorry, Jp From rudy.schockaert at pandoraSTOPSPAM.be Sat Jan 17 12:17:22 2004 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Sat, 17 Jan 2004 17:17:22 GMT Subject: Best Python IDE Code Completion! In-Reply-To: References: Message-ID: yshurik wrote: > John wrote: > > >>Hi, >> Could you give your opinions on the best code completion in Python >>IDEs. My only complaint with PythonWin has been that the code >>completion support is incomplete. The interactive mode has better >>behavior than the editor. Tried to fix it but could not. Boa is not >>too different. At least when I last checked (a few months ago) Komodo >>and Visual Python were not very different either. >> >> Wing IDE seems converse. The editor auto list members is great but >>has no calltips. The interactive window has no completion at all. >> >> I have not checked PythonWorks and Black Adder in a while but their >>web sites do not seem to brag much in this direction. > > > About BlackAdder: because it is oriented to GUI programming. > in version 1.1 it will have completion for Qt classes and functions. > and completion to all words which happens in edited text. > (it is Vi - like style of completion - Ctrl-N, Ctrl-P) > > >> Python has great introspective capabilities and we have a great open >>contributing community. What technical difficulties keep us from >>having REAL code completion like MS, Borland and several Java IDEs >>(All of which have been funded at one time or the other if not >>entirely - perhaps this is the reason?) >> >> For me, code completion is a very important part of the coding >>experience and I really miss it in Python in it's full effect. > > Have you checked out SPE (Stani's Python Editor): Spe is a python IDE with wxGlade GUI designer, auto-indentation, auto completion, call tips, syntax coloring, syntax highlighting, class explorer, source index, auto todo list, sticky notes, integrated pycrust shell, python file browser, recent file browser, drag&drop, context help, ... Special is its blender support with a blender 3d object browser and its ability to run interactively inside blender. Spe is extensible with boa. You can find it at http://spe.pycs.net/ From stephan.diehlNOSPAM at gmx.net Wed Jan 21 06:17:15 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Wed, 21 Jan 2004 12:17:15 +0100 Subject: personal document mgmt system idea References: Message-ID: Sandy Norton wrote: > Stephan Diehl wrote: > > [...] > [...] >> In addition, a real (text) search engine might be of help. I'm using >> swish-e (www.swish-e.org) and are very pleased with it. > > Just downloaded it... looks good. Now if it also had a python api (-; I'm just using the command line interface via os.system and the popenX calls. The only thing that (unfortunatelly) not possible, is to remove a document from the index :-( If you need any help, just drop me a line. > >> Maybe, before you invest to much time into such a project, you should >> check out the following: >> >> Chandler (http://www.osafoundation.org) >> if it's finished, it will do excactly what you are aiming for >> (and it's written in Python) > > Still early stages... I see they dropped the ZODB. Did they? If they succeed, Chandler will rock. My personal opinion is that they try doing too much at once. I guess that a better filesystem will make most of the document management type applications obsolete. The big problem, of course, is to define 'better' in a meaningfull way. > >> ReiseFS (see www.namesys.com -> Future Vision) >> Gnome Storage (http://www.gnome.org/~seth/storage) >> WinFS >> (http://msdn.microsoft.com/Longhorn/understanding/pillars/WinFS/default.aspx) > > > Wow! Very exciting stuff... I guess we'll just have to wait and see what > develops. Or go the other way: build a new filesystem prototype application in python and see, if it works out as intended and then build a proper file system. > > >> Hope that helps > > Yes. Very informative. Cheers for the help. > >> Stephan > > Sandy From q2n8byu02 at sneakemail.com Tue Jan 6 21:44:07 2004 From: q2n8byu02 at sneakemail.com (Ivan Nestlerode) Date: 6 Jan 2004 18:44:07 -0800 Subject: KeyboardInterrupt and threading References: Message-ID: Michael Hudson wrote in message news:... > On debian, the signal module certainly should be available, and the > KeyboardInterrupt exception should go to the main thread. Or at > least, that's what I thought. You're definitely seeing it being > delivered to an arbitrary thread? > > Cheers, > mwh After a closer look, I am not seeing KeyboardInterrupt being delivered to non-main threads. What I am seeing is that Ctrl-C does not work at all when non-main threads are CPU intensive. I had previously jumped to the conclusion that because Ctrl-C didn't work and because the non-main thread was sloppy ("except:"), that Ctrl-C wasn't working because KeyboardInterrupt was going to the sub-thread. That was an incorrect conclusion. So I guess the entire problem can be restated as: How do I make Ctrl-C work properly when the non-main thread is busier than the main thread? The short program at the end of this post demonstrates the problem with Ctrl-C and busy non-main threads. The idea behind this script is that the main thread launches a busy sub-thread. Ctrl-C is supposed to be caught in the main thread, stopping both threads, and ending the program (with some printouts). As written, the program does not respond to Ctrl-C even if I hold it down continuously. If you uncomment the print statement in the main thread, all of the sudden it starts to work. Why? I think it has something to do with the main thread needing some larger amount of CPU to detect the signal and the KeyboardInterrupt. I think this is a bug though (I shouldn't have to put hacks into the main thread to get this to work). Any thoughts? Thanks, -Ivan #!/usr/bin/python from threading import Event, Thread from time import sleep class CpuHogThread(Thread): def __init__(self): Thread.__init__(self) self.counter = 0 self.stopEvent = Event() def join(self): self.stopEvent.set() Thread.join(self) def run(self): try: while not self.stopEvent.isSet(): self.counter += 1 except KeyboardInterrupt: print 'CPU hog subthread caught KeyboardInterrupt' if __name__ == '__main__': t = CpuHogThread() t.start() print 'CPU hog subthread spawned' try: while True: sleep(2) # without the next print, Ctrl-C is completely ignored #print 'still sleeping' except KeyboardInterrupt: print 'main thread caught KeyboardInterrupt' t.join() print 'CPU hog subthread joined at counter %d' % t.counter From paul at prescod.net Wed Jan 21 10:34:05 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 21 Jan 2004 07:34:05 -0800 Subject: Installing SpamBayes In-Reply-To: <400d3f3f_2@newsfeed.slurp.net> References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> <20040120135921.1C3F.JCARLSON@uci.edu> <400c5790_1@newsfeed.slurp.net> <20040120150005.1C48.JCARLSON@uci.edu> <400c6146_1@newsfeed.slurp.net> <20040120171127.0606.JCARLSON@uci.edu> <400d3f3f_2@newsfeed.slurp.net> Message-ID: <400E9BED.7020700@prescod.net> Dog at will.hunt wrote: > Its my fault for not being clear on this. I know how to change the > directory on a command prompt in Windows. I was speaking of the Python > prompt (>>>). Once I got that, I tried running the file but got this: > > 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. > >>>>python setup.py install > > File "", line 1 > python setup.py install > ^ > SyntaxError: invalid syntax You do not run the setup command from within Python. You do it from your Windows/Unix/Mac/DOS command line. C:\>python setup.py install Paul Prescod From skip at pobox.com Wed Jan 14 09:48:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 08:48:31 -0600 Subject: pulling set of unique values from a list In-Reply-To: <400551c0$1@baen1673807.greenlnk.net> References: <400551c0$1@baen1673807.greenlnk.net> Message-ID: <16389.22207.524690.979989@montanaro.dyndns.org> Ben> I need to get [1,2,3] from [1,1,1,2,2,3,3] with as little effort Ben> possible for my CPU (and keyboard). You didn't say if order was important, but since one solution you posted was dict-based, I'll assume not. If you're running 2.3 or from CVS, this seems the most straightforward to me: >>> list(set([1,1,1,2,2,3,3])) [1, 2, 3] given the new set type. If you are running 2.3 you'll need to import from the sets module: >>> from sets import Set as set >>> list(set([1,1,1,2,2,3,3])) [1, 2, 3] Skip From EP at zomething.com Thu Jan 1 18:24:02 2004 From: EP at zomething.com (EP) Date: Thu, 01 Jan 2004 15:24:02 -0800 Subject: Test if IDLE is a mature program In-Reply-To: References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> <3ff30f2f.674586974@news.blueyonder.co.uk> Message-ID: <5.2.0.9.0.20040101151048.00b7c4b0@mail.zomething.com> >Anyway, there might be some use in thinking about the underlying issue... Any "complaint", if that's even really what the original post was, is a gift, an opportunity for epiphany and original thought. Defenses of IDLE seem to be based on existing paradigms broadly accepted - that doesn't mean there isn't a better, smarter way (and I am imagining inventive Pythonistas somewhere concocting strange and beautiful things in "the labs".) As an esteemed manager once told me: "Your job is to make your job obsolete." cheers and Happy New Year!, EP "who likes IDLE just a little too much" From nuffsaid at phreaker.net Wed Jan 21 05:42:52 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Wed, 21 Jan 2004 11:42:52 +0100 Subject: twistedmatrix.com - time out error Message-ID: I am trying to download Twisted form www.twistedmatrix.com since maybe 2 days, but I always get a time out error from the server. Is there a mirror resp. another 'official' download site for Twisted? (Or: does someone know what's going on with twistedmatrix.com?) Thanks in advance for any hint! Nuff From jzgoda at gazeta.usun.pl Tue Jan 13 14:01:58 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 13 Jan 2004 19:01:58 +0000 (UTC) Subject: id3v2 module References: Message-ID: Andy Todd pisze: >> I'd like to know if there is a third-party module for reading/writing >> id3v2 informations. >> Thanks > > http://www.nedbatchelder.com/code/modules/id3reader.html Good one, but only for reading. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From piedmontbiz at aol.com Thu Jan 15 17:59:53 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 15 Jan 2004 22:59:53 GMT Subject: Printing to console, no scroll References: <4006C2FB.B377BE82@engcorp.com> Message-ID: <20040115175953.26514.00000024@mb-m07.aol.com> >From: Peter Hansen peter at engcorp.com >Date: 1/15/04 11:42 AM Eastern Standard Time >Message-id: <4006C2FB.B377BE82 at engcorp.com> > >PiedmontBiz wrote: >> >> Sorry for my post with all the ansi.py code. >> >> I forgot the website I got it from. > >Google is your friend (along with five seconds of effort): > > http://www.demonseed.net/~jp/code/ansi.py > >-Peter > > > > > > Appreciate the rebuke. Also, the url was saved in the html by IExplorer. I could have looked there. Allen From skip at pobox.com Fri Jan 16 17:51:15 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 16 Jan 2004 16:51:15 -0600 Subject: Bug or feature? In-Reply-To: <200401162241.07500.james@logicalprogression.net> References: <200401161613.06481.james@logicalprogression.net> <20040116191853.GA27129@intarweb.us> <200401162241.07500.james@logicalprogression.net> Message-ID: <16392.27363.264594.821314@montanaro.dyndns.org> >> Of course, it should be noted that, in Python, "a += b" is only >> sometimes synonymous with "a = a + b". The rest of the time, it's >> hard to say what it is synonymous with :) James> What do you have in mind? J. For immutable objects, += works as you'd expect: return a new object, leaving the old object unchanged. That's not the case for mutable objects, to wit: >>> foo = [1] >>> bar = foo >>> foo += [2] The object referenced by foo is modified in-place... >>> bar [1, 2] >>> foo = foo + [2] Here foo is bound to a new object, leaving the old object (still referenced by bar) unchanged. >>> foo [1, 2, 2] >>> bar [1, 2] Skip From csgcsg39 at hotmail.com Fri Jan 9 11:07:08 2004 From: csgcsg39 at hotmail.com (CSG) Date: 9 Jan 2004 08:07:08 -0800 Subject: ZSI and faults Message-ID: <592ab9dd.0401090807.6c68e4a@posting.google.com> Dear All, I'm very new to python/ZSI and have a (simple) query to ask. I have a simple client: from ZSI.client import Binding fp=open('debug.out','w') b=Binding(url='somewhere',tracefile=fp) print b.connect('usename') fp.close() and a server of from ZSI import * import sys def connect(usename): try: except Exception,e: sys.exit(1) The trouble I'm having is with the . I've tried things like: FaultFromException(e,0).AsSOAP(sys.stdout) or f=Fault() f.code="some message" with no success. Any suggestions Many thanks Colin From NAIGIMSESRIMAIL at gims.com Tue Jan 27 05:20:37 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Tue, 27 Jan 2004 12:20:37 +0200 Subject: ALERT - GroupShield ticket number OA1434_1075198830_ESRIMAIL_3 w as 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: GroupShield for Exchange (ESRIMAIL) Sent: 183607680,29615295 Subject: ALERT - GroupShield ticket number OA1430_1075198765_ESRIMAIL_3 was generated Attachment Details:- Attachment Name: ATT09137.txt File: ATT09137.txt 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: 1959 bytes Desc: not available URL: From carroll at tjc.com Tue Jan 27 23:05:46 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed, 28 Jan 2004 04:05:46 GMT Subject: Confused about a list.sort() References: Message-ID: On Tue, 27 Jan 2004 18:28:09 -0800, "Amy G" wrote: >I have a list of numbers... actully I have two lists, List 1 is a list of >number strings and List2 is one of numbers. > >List 1 example: >List1 = [ '20040124123000', '20040124123001', '20040125012456'] > >List 2 example: >List2 = [ 20040124123000L, 20040124123001L, '20040125012456L] > >When I try either: >List1 = List1.sort ... or >List2 = List2.sirt > >and then... >print List1... or >print List2 > >I get None. > >Why is this? Yeah, most everyone who uses sort() for the first time gets bit by this. Sort() sorts the list in place, and returns None: >>> list1=[20, 40, 60, 80, 10, 30, 50] >>> list1 [20, 40, 60, 80, 10, 30, 50] >>> list1.sort() >>> list1 [10, 20, 30, 40, 50, 60, 80] So, to sort list1, you just use list1.sort(), not foo = list1.sort() From LittleDanEhren at yahoo.com Sat Jan 31 21:22:09 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 31 Jan 2004 18:22:09 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> Message-ID: <711c7390.0401311822.539c381a@posting.google.com> > >[snip] > Definitely. But "stuff" isn't always the same as "magical syntax". > > Jp By that logic, anything that can be implimented in the language isn't "magical syntax". In Io, there is no difference between flow control and functions, so it's not "magical syntax" and it's just "stuff". Daniel Ehrenberg From klapotec at chello.at Sat Jan 31 00:24:49 2004 From: klapotec at chello.at (Christopher Koppler) Date: Sat, 31 Jan 2004 05:24:49 GMT Subject: HowTo Search in nested lists References: Message-ID: On Fri, 30 Jan 2004 11:11:47 -0800, "Robert Brewer" wrote: >Florian Lindner wrote: >> >I've two nested lists which are representing a table or matrix. >> >Now I found to search for certain values in a certain column. >> >For example: column 1, search for 5, return 1, because 5 is >> >found in the first column of the second element of t > >Christopher Koppler replied: >> ...let's make a function of it that returns the list(s) >> (in case you have more than one list fitting your search >> criteria) containing the searched for value. > >Good answers, Christopher. You might consider combining the several >approaches into a single one by creating an iterator; Well, just what popped into my mind first. I still have some trouble getting iterators and generators to pop up before, though often they're just so much more elegant, as your solution shows. But for that I have to consciously think about the problem, whereas ordinary functions are quite entrenched in my brain. I blame my shady past of Pascal, Visual Basic, Modula 2, C, and Java. At least by now I instantly think of list comprehensions... -- Christopher From rodrigob at elo.utfsm.cl Mon Jan 19 10:06:28 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Mon, 19 Jan 2004 12:06:28 -0300 Subject: Munkware 0.3 References: Message-ID: <400beeb1$1_1@nova.entelchile.net> as common, using twistedmatrix.com will ease a lot to you to provide remote access methods rodrigob. "Jeremy Jones" escribi? en el mensaje news:mailman.498.1074509063.12720.python-list at python.org... > Munkware, a transactional and persistent queueing mechanism, is proud to > announce version 0.3 for public consumption. One bug fix in this release: > > - Now checks for proper index on all put_commit() and get_commit() calls. > > The Sourceforge Project page is located at > http://sourceforge.net/projects/munkware/ and the project home page is located > at http://munkware.sourceforge.net/ > > I'm currently working on a quasi-RESTish (web services/HTTP) interface for > Munkware rather than going the SOAP route that I had initially thought. I've > got a design about 3/4 of the way hammered out, but no code so far on that. I'm > planning on (at least as a first stab) using the standard library BaseHTTPServer > to run it from. Hopefully, I'll be able to get something present-able in the > next couple of weeks. > > If you have any suggestions, please feel free to email them to me. > > > Jeremy Jones > From jeff.holle at verizon.net Wed Jan 28 15:54:00 2004 From: jeff.holle at verizon.net (Jeffrey Holle) Date: Wed, 28 Jan 2004 12:54:00 -0800 Subject: linking problems with Python C API Message-ID: I am working on a Linux system using gcc v3.3 and python v2.3.2 I have a problem linking a cpp program to a shared library that uses the Python C API. With just referencing this shared library, I get unresolved references like: PySequence_DelSlice PyNumber_InPlaceXor PyInt_FromLong _PyObject_New This is just a sample, there are actually 130 of similarly named functions. The only other library that I have tried, /usr/local/lib/python2.3/config/libpython2.3.a, causes more trouble, to the point that makes me believe this is a misdirection. Can anybody tell me what library I should be linking to? From sheetalap79 at yahoo.com Sun Jan 25 12:42:07 2004 From: sheetalap79 at yahoo.com (SA) Date: 25 Jan 2004 09:42:07 -0800 Subject: Need Python script to search content in the web pages Message-ID: Hello I need a python script that can enable users of a site to search through the contents of the website. Can anyone help? --SA From newspost at lolmc.com Mon Jan 26 13:56:03 2004 From: newspost at lolmc.com (Lol McBride) Date: Mon, 26 Jan 2004 18:56:03 +0000 Subject: MySQL insert query problem References: Message-ID: On Sun, 25 Jan 2004 17:49:37 -0500, Mike C. Fletcher wrote: > Did you by any chance declare the field to be 19 characters wide when > creating the database? Truncating to the length of the field is, I > think, normal SQL practise. > > Just a thought, > Mike > > Lol McBride wrote: > ... > >>varchar field in a database I'm using. The query being sent to the MySQL >>server by my program is : INSERT INTO analysis (DrawNumber,pool1)VALUES >>(847, ' (4, 8, 21, 24, 39, 44) ' ) ; >> >>But the field pool1 actually contains (4, 8, 21, 24, 39, i.e it is >>missing the final digits ( 44 ) >> > ... > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ Oh yeah baby, obvious and therefore invisible to my gaze.Thank you for opening my eyes. Lol McBride From aahz at pythoncraft.com Fri Jan 30 15:59:50 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2004 15:59:50 -0500 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Aahz wrote: >> In article , >> Peter Otten <__peter__ at web.de> wrote: >>>Aahz wrote: >>>> >>>> import __main__ >>>> tmp = parse_funky_language("Hey, this is far out, man.") >>>> setattr(__main__, tmp.name, tmp.value) >>>> >>>> In the context of the interactive interpreter, it's a bit harder to do; >>>> I don't remember off-hand what the namespace of the interpreter is. >>> >>>You don't need to :-) >>> >>>Python 2.3.3 (#1, Jan 3 2004, 13:57:08) >>>[GCC 3.2] on linux2 >>>Type "help", "copyright", "credits" or "license" for more information. >>>>>> __name__ >>>'__main__' >> >> Yes, but how do you access that from a module? > > >import sys >import __main__ >setattr(sys.modules["__main__"], "name", "value") >__main__.anotherName = "another value" > > >Python 2.3.3 (#1, Jan 3 2004, 13:57:08) >[GCC 3.2] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import interp >>>> name >'value' >>>> anotherName >'another value' >>>> > >Or is this a misunderstanding continued? No, it's a brain fart; for some reason, I was thinking that "__main__" == "currently executing module". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From andreas at andreas-jung.com Sun Jan 18 08:18:47 2004 From: andreas at andreas-jung.com (Andreas Jung) Date: Sun, 18 Jan 2004 14:18:47 +0100 Subject: Fw: PDF library for reading PDF files In-Reply-To: <000c01c3ddc3$27312800$7800a8c0@mailer> References: <000c01c3ddc3$27312800$7800a8c0@mailer> Message-ID: <2147483647.1074435527@[192.168.0.102]> There is none. Use an external converter to convert the PDFs to text and then read the result using some common Python module (os.system(), commands module etc). -aj --On Sonntag, 18. Januar 2004 14:01 Uhr +0100 Peter Galfi wrote: > Hi! > > I am looking for a library in Python that would read PDF files and I > could extract information from the PDF with it. I have searched with > google, but only found libraries that can be used to write PDF files. > > Any ideas? > > Peter From exarkun at intarweb.us Fri Jan 9 14:00:53 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 9 Jan 2004 14:00:53 -0500 Subject: PRE-PEP: new Path class; sorting and __cmp__ In-Reply-To: <3FFEF5DC.1080804@beyond-thoughts.com> References: <3FFEF5DC.1080804@beyond-thoughts.com> Message-ID: <20040109190053.GA3677@intarweb.us> On Fri, Jan 09, 2004 at 07:41:32PM +0100, Christoph Becker-Freyseng wrote: > As I pointed out path.__cmp__ should not be used for e.g. comparing > filesizes. > > But features like sorting on filesizes are very useful. > I'm not sure if Gerrit Holl already meant this in his conclusion on > "Comparing files" in the PEP. > I'll outline it a bit ... This seems to be covered by the new builtin DSU support which will exist in 2.4. See the (many, many) posts on python-dev on the "groupby" iterator: http://mail.python.org/pipermail/python-dev/2003-December/thread.html In particular, the ones talking about `attrget'. Jp From anthony at interlink.com.au Thu Jan 22 10:08:49 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Fri, 23 Jan 2004 02:08:49 +1100 Subject: interest in an email package sprint at PyCon? Message-ID: <20040122150849.0B2DB25ADD5@bonanza.off.ekorp.com> How many people are going to PyCon and interested in a sprint focused on the email package? I'm trying to work out if there's enough people to make it worthwhile... followups to me or to the email-sig at python.org list. Thanks, Anthony -- Anthony Baxter It's never too late to have a happy childhood. From ray at rays-web.com Thu Jan 1 22:38:38 2004 From: ray at rays-web.com (Ray Smith) Date: 1 Jan 2004 19:38:38 -0800 Subject: Rekall Binary References: <8a27e309.0312310529.3c1f43a8@posting.google.com> <8a27e309.0401010633.20271486@posting.google.com> <6ee58e07.0401011433.5ce91221@posting.google.com> Message-ID: <5654fff9.0401011938.1dd4bd85@posting.google.com> llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0401011433.5ce91221 at posting.google.com>... [snip] > In fact i believe that a main stream desktop tool like "Rekall" has no > future when it must live on support contracts only. If you need > support then the product has an error, but i don't want to use > errounous software. This is the reason why GPL does not work for a lot > of software products. Every non trival product has errors. ( And most trival product ;) ) Support charges "seem to me" to be one of the most popular ways for Open Source devlopers to make an income. Coupled with the fact that most sane IT managers won't rely on unsupport software it seems to make alot of sense. Note: IT managers will rely on "officially unsupported" software if it has an excellent track record, i.e. Debian, in the same breath why do so many companies buy Linux supported distributions (i.e. Red Hat)? Regards, Ray Smith From deets_noospaam at web.de Thu Jan 8 07:51:05 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 08 Jan 2004 13:51:05 +0100 Subject: creating a daemon? References: <3ffd355c.0@news1.mweb.co.za> Message-ID: bmgx wrote: > This is what I am trying to find out, instruction on how to create a > simple daemon on unix systems(Linux), can't find any info on usual > sources.. google: daemonize python fork Works perfect for me. Diez From astoltz at nyx.net Fri Jan 30 09:10:20 2004 From: astoltz at nyx.net (Al Stoltz) Date: Fri, 30 Jan 2004 07:10:20 -0700 Subject: Python ODBC Driver Module In-Reply-To: References: Message-ID: On Fri, 30 Jan 2004, Mark Buch wrote: > Hi, > > where can i find a freeware python odbc module for windows? ActiveState's distribution of python (ActivePython) comes bundled with a bunch of windows only exensions - including an ODBC module. http://activestate.com/Products/ActivePython/ From jcarlson at nospam.uci.edu Fri Jan 30 03:43:07 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 00:43:07 -0800 Subject: Printing/updating output to the screen In-Reply-To: <40192945$1@nntphost.cis.strath.ac.uk> References: <40192945$1@nntphost.cis.strath.ac.uk> Message-ID: Daniel Pryde wrote: > Hi there. I hope this isn't a stupid question to ask, but does anyone > know how to print out a string without moving to a new line each time > and simply updating the first line. An example would be, if I wanted to > have a percentage progress counter that was constantly updating. I'm > unsure how to do this without printing to a brand new line. Any help > would be greatly appreciated. Thanks. > > Daniel > try this... import time for i in xrange(101): print i, '\r', time.sleep(.1) - Josiah From reidyre at yahoo.com Tue Jan 27 15:56:39 2004 From: reidyre at yahoo.com (Ron Reidy) Date: 27 Jan 2004 12:56:39 -0800 Subject: Compiling DCOracle2 on RH Linux 8.0 References: <8725c51c.0401241912.316a7cfc@posting.google.com> Message-ID: dripton at wizard.net (David Ripton) wrote in message news:<8725c51c.0401241912.316a7cfc at posting.google.com>... > reidyre at yahoo.com (Ron Reidy) wrote in message news:... > > > I am trying to compile DCOracle2 on RedHat 8.0 and make is giving me > > the following error: > > > > gcc -pthread -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes > > -I/usr/local/include/python2.3 -I/usr/local/include/python2.3 @DEFS@ > > -I/oracle/app/oracle/9i/rdbms/demo > > -I/oracle/app/oracle/9i/network/public > > -I/oracle/app/oracle/9i/plsql/public > > -I/oracle/app/oracle/9i/rdbms/public -DORACLE9i -c ././dco2.c -o > > ./dco2.o > > gcc: cannot specify -o with -c or -S and multiple compilations > > > > > > Did I do something wrong? > > No. The DCOracle2 build process isn't very robust. > > Look at src/Makefile. Find a line that says "DEFS=%DEFS" and change > it to "DEFS=-fno-strict-aliasing" David, Thanks. That worked well. Now, how do I install it? The only copies of dco2.so that exist are in the directory tree where I built the library. In searching for any kind of install directios, I found nothing like 'make install', etc. Thanks you your help. From deets_noospaam at web.de Sat Jan 24 20:55:23 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sun, 25 Jan 2004 02:55:23 +0100 Subject: [OPINION] - does language really matter if they all do the same thing? References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> <4012FEB1.5000106@prescod.net> Message-ID: Hi, > Has anyone here ever looked at different languages for making an > interactive website, and felt that Python was the best choice of > language to use? > > It would definitely be a learning curve for me, since I know PHP so well, > but if it had some great benefits, I'd go for it. > (Half just for fun, to learn something new.) As others have pointed out, PHP is _made_ for creating websites. Some people are using it for general purpose programming, but its not tailored to that. Thats a major difference to python: Its aim is programming in general. Its power for certain task comes from the ease of creating libs, tools and apps for these special cases: twisted for networking, ZOPE (and others) for webapps, COM access, GUI building and so on. For websites, I tried ZOPE - and quite love it. But I'm a programmer at first, not so much a website designer. And while there are great products for ZOPE, like PLONE or ZMS, that give you a fully featured CMS with a couple of clicks, I have to admit that DTML and even TAL/METAL as templating languages are a kludge. At least for someone with a "how do I get this particular task done ASAP"-attitude. PLONE and ZMS both encourage separation of data from presentation. This is very good from a purist POV, and has advantages in larger environments where some people provide app logic and others the layout. But for small projects, it bears unecessary complexity. So - if your goal is just to enhance your forum with a "new articles"-counter, you almost surely are better of with PHP. But if your projects get more elaborated with complex data models, or you want to explore programming beyond HTML-generation, I urge you to give Python a try. Regards, Diez From adalke at mindspring.com Fri Jan 16 02:58:39 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 16 Jan 2004 07:58:39 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: R. Alan Monroe > >You think "cross-platform" means "it runs out-of-the-box on all possible > >platforms that ever existed, now exist, and will ever exist"? > > > >Please go searching and come back when you find 1 (one) program which fits > >that definition... :-p My favorite program for this is /bin/true. On some machines it is 0 bytes long. It works on Unix and, with a ".bat" extension, on MS Windows. Andrew dalke at dalkescientific.com From engsolnom at ipns.com Fri Jan 2 00:23:00 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Thu, 01 Jan 2004 21:23:00 -0800 Subject: NEWBIE: map | zip | list comp Message-ID: Hello again...hope everyone had a great New Year...:) In the quest to learn more about Python, I decided to create an arbitrary sequence, then march each member through a 'field' of each of the members in turn, and just to complicate it a bit, make the length of the field user defined. Hard to explain...an example might serve: 10000 01000 00100 . . 00009 01111 10111 11011 . . 21111 12111 11211 and so forth. The only coding I could come up with is: base_seq = 'ABCD' length = 6 for char_1 in base_seq: # Loop thru the set char_1 at a time for char_2 in base_seq: # Loop thru the seq again for each char_1 if char_2 == char_1: continue # Don't march 'A' thru a field of 'A's for ix in range(length): # Now march char_2 thru a field of char_1's print (char_1 * length)[:ix] + char_2 + (char_1 * length)[ix:-1] which, as you can see, has three nested FOR loops. I played with map, zip and list comps a bit, but couldn't figure out how to compress the above code. Am I barking up the wrong Python tree? Thanks......Norm From jzgoda at gazeta.usun.pl Sat Jan 3 02:54:19 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 3 Jan 2004 07:54:19 +0000 (UTC) Subject: Text-to-HTML processing program References: Message-ID: phil hunt pisze: > Does anyone know of a text-to-HTML processing program, ideally > written in Python because I'll probably be wanting to make small > modifications to it, which is simple and straightforward to use > and which uses a simple markup language (something like Wikipedia > markup would be ideal)? Try PyTextile: http://www.diveintomark.org/projects/pytextile -- it's Python implementation of Dean Allen's original PHP Textile. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From alexander.dejanovski at laposte.net Tue Jan 13 12:43:01 2004 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Tue, 13 Jan 2004 18:43:01 +0100 Subject: JyRetic EAI Server 1.0RC1 released Message-ID: <5.1.0.14.2.20040113184248.03e9fc10@127.0.0.1> Retic goes Jython now, and is thus fully compatible with the Java platform. (I won't develop no more on the former Python version of Retic. ) This gives a better connectivity, particularly through JDBC and JMS. Jython 2.1 is included in the release. Download on the sourceforge project's site => http://sourceforge.net/projects/retic Available sources are : file, FTP, HTTP, JMS, SOAP, JDBC, XMLBlaster Available pipes are : Zip, Unzip, Flat-to-XML, XML-to-Flat, XPath, XSLT, FOP (to produce PDF or PS from XSL-FO input), Excel (to produce MS Excel files from Gnumeric-XML input) Available sinks are : file, FTP, HTTP, JMS, SOAP, JDBC, XMLBlaster, Jabber (open source instant messaging), shell, SMTP, Xindice (Apache's XML database) Two new kinds of components have appeared in this release : Preprocessors and Postprocessors : executed only once respectively before and after adaptor execution. Available preprocessors : SQL, Xindice (much more to come) Available postprocessors : SQL (much more to come) The logging system is now based on log4j (I've added a Jabber appender (IMAppender), thanks to orange-soft.com). Adaptors can be launched through command-line, XMLRPC calls (retic administrator uses it) or JMS queue (the server has to be listening your queue). Retic also has now a scheduler. I know docs aren't up-to-date but I'll fix that real soon. ============================================================= WHAT IS RETIC ? Retic is an EAI Server. The aim is to permit applications to communicate, even if they don't speak the same language (which means transport protocols as well as data structures). This is done by building adaptors. An adaptor is composed of : - One source - Several pipes (process data transformations) - Several sinks (destination of data) - Several loggers (using log4j) - Preprocessors (executed only once before adaptor execution - for example => drop/create a table through a SQL query) - Postprocessors (executed only once after adaptor execution - for example => creation of an index on a table through a SQL query) It is written in Jython and works 100% fine with only Java 1.3+ installed on your system (jython 2.1 is embedded in the releases). ============================================================= I've also released a reworked version of Retic Administrator (1.0) the GUI to create adaptors, and control the server. Yet another piece of software released is reticSOAP, a small tool that parses WSDL and permits to : - test SOAP services - See the messages exchanged Both Retic Admin and Retic SOAP come as a win32 release or a wxPython 2.4 source file release (Python 2.3+ needed). Enjoy !! From usenet_spam at janc.invalid Thu Jan 8 20:23:58 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 09 Jan 2004 01:23:58 GMT Subject: NNTP Server for this group References: Message-ID: jonas at jonasgalvez.com (Jonas Galvez) schreef: > Can anyone recommend a good NNTP server for accessing this group? For this and most other text groups: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From prof_888 at hotmail.com Thu Jan 8 17:36:39 2004 From: prof_888 at hotmail.com (ChrisD) Date: 8 Jan 2004 14:36:39 -0800 Subject: unable to register PythonService.exe Message-ID: I'm running Python 2.3.3 with Win32 extensions win32all-163. I'm working through Chapter 18 of Mark Hammond's excellent "Python Programming on Win32". On page 350 the simple NT service example requires that the PythonService.exe program be registered. However, when I attempt it I get this error: --------------------------------- C:\Python23\Lib\site-packages\win32>PythonService /register Registering the Python Service Manager... Fatal Python error: PyThreadState_Get: no current thread abnormal program termination --------------------------------- Any thoughts on how I can fix this problem? thank you! Chris From skip at pobox.com Thu Jan 29 14:47:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 29 Jan 2004 13:47:44 -0600 Subject: isinstance() bug In-Reply-To: <20040129170037.GF18498@unpythonic.net> References: <20040129170037.GF18498@unpythonic.net> Message-ID: <16409.25440.195276.497839@montanaro.dyndns.org> Skip> You need to compare inode numbers to see if you have the same or Skip> different files. ... Michs> really a good idea, Skip. Jeff> I'd have to come out on the -1 side. I wasn't necessarily proposing that the current behavior ought to be changed. I hadn't considered all the subtle possibilities of such a change, but in another msg suggested there would be some. Jeff> First, because it adds complications to the interpreter simply to Jeff> notify a programmer of an avoidable problem that should be caught Jeff> by testing. I suspect some people would disagree with you on this (that it's simply complicating the interpreter to get rid of an avoidable problem - I don't know what you meant about "notify a programmer"; I don't envision notification if such a change were implemented). Jeff> Second, I'm not convinced that you won't create some other kind of Jeff> problem through cleverness. Agreed. Jeff> Third, I'm not convinced that using inode numbers is guaranteed to Jeff> work. In Unix, it at least needs to be the tuple (inode, device), Jeff> because the same inode number can appear on multiple devices. Correct. My mistake. I agree with you about all the other nasty corner cases. Skip From jcarlson at nospam.uci.edu Mon Jan 26 15:24:33 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 12:24:33 -0800 Subject: I support PEP 326 In-Reply-To: References: <10105bn3bsi63c9@news.supernews.com> Message-ID: > +1 on the PEP. The names Max and Min seem fine to me, but I'm not > married to them. > > What would be the consequence of making Min and None compare equal? > Then the "None as second lowest" issue goes away. I can't think of an > example where that would cause problems, but there probably are > some... The issue is that when Min and None are in a sequence that gets sorted, you can end up with Minimums and Nones getting interspersed like so: [Min, None, Min...] In general, that behavior is frowned upon. - Josiah From dj00302003 at yahoo.com Sat Jan 17 19:33:55 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 17 Jan 2004 16:33:55 -0800 Subject: Webbrowser and Mozilla control on linux Message-ID: <1d17eeb7.0401171633.170e313a@posting.google.com> I can launch a browser on linux with the webbrowser module and the .open() method. However, I want to be able also to control the browser, specifically, I'd like to be able to go to a URL and invoke the automatic form filler and post the form, all from within a python script. I have google'd around and I see hints that there are remote controller objects for some browsers, but so far I haven't found any examples of code that controls the browser; most examples just open the browser, which I could just as well do from os.system(). If anyone can share some samples, or point me to a good reference with browser control details, I'd much appreciate it. Thanks! J.D. From francisgavila at yahoo.com Sun Jan 11 13:46:28 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 11 Jan 2004 13:46:28 -0500 Subject: Providing Default Value for User Input References: <1001kcqqk9ic2cc@corp.supernews.com> Message-ID: <10036i3a6m4nv47@corp.supernews.com> Francis Avila wrote in message <1001kcqqk9ic2cc at corp.supernews.com>... >This question is entirely too vague, because the answer depends entirely >upon your implementation and has nothing to do with Python per se. ... > >As a shot in the dark, why not just look at what the user types? If it's As Miki showed me, even is saying the question is too vague, I *already* assumed too much in my answer to you, namely, that you were using a CLI. I don't even know that. So you see the problem with your question? We're glad to help, but you need to give us more specific information. -- Francis Avila From woodsplitter at rocketmail.com Thu Jan 8 16:27:49 2004 From: woodsplitter at rocketmail.com (David Rushby) Date: 8 Jan 2004 13:27:49 -0800 Subject: Newbie: Getting Image From Disk into Buffer References: Message-ID: <7876a8ea.0401081327.6fff63fc@posting.google.com> "Ashley Lloyd" wrote in message news:... > I have been trying to get an image into an interbase database (see earlier > post), and came across a post made on a list some time ago (I ignored it > earlier as we use kinterbasDB not gvib, but I thought I'd try using it in > kinterbasDB anyway): > ... > it always seems to place > into the database a string of either the name of the image on disk > ('c:/image.bmp', say), or text such as the following: > In the 'c:/image.bmp' case, you're inserting the file's name (string); in the "" case, you're inserting an open file object, which is repr()ed into a string for storage. Instead, you need to insert the *contents* of the file as a string, e.g., the return value of the file object's read() method. > ... but if someone could tell me how I get the image into blob_data > (which I assume is a buffer), I'd be very grateful. http://sourceforge.net/forum/forum.php?thread_id=889866&forum_id=30917 From tjreedy at udel.edu Thu Jan 15 18:39:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Jan 2004 18:39:40 -0500 Subject: Bug or feature? References: <3dtid1-594.ln1@beastie.ix.netcom.com> Message-ID: "Dennis Lee Bieber" wrote in message news:3dtid1-594.ln1 at beastie.ix.netcom.com... > Alexey Nezhdanov fed this fish to the penguins on Wednesday 14 January > 2004 21:40 pm: > > > Case 1 and case 2 prints out different calues (1 and 2 respectively). > > Do not know - if this is a bug or feature of python. > > > It's a problem with using what I would consider a side effect... And > not understanding that "variables" are not memory addresses. In particular, the problem with both modifying in place (the side effect) and returning a value. I see a little better Guido's reason for having list modification methods return None. While chaining is not too problematical, object returns would allow list expressions mixing implicit and overt effects with possible puzzles similar to the one presented in this thread. Terry J. Reedy From kbk at shore.net Sat Jan 31 18:16:53 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 31 Jan 2004 23:16:53 GMT Subject: pythonwin woes References: Message-ID: <878yjnzp22.fsf@hydra.localdomain> Mark Hammond writes: > IDLE runs all programs in a new, external Python process, so never > sees this issue. In lots of ways, I like the way Pythonwin does it - > keeping that state around can be very useful - eg, after the program > has terminated, you can still see the objects etc. The IDLE in Python 2.3 does use an external process, which, as you say, completely avoids the reload/import dance. It also substantially separates the user's code from the IDLE code. However, I should make it clear that IDLE's Python shell (which also serves as the output window) looks at the subprocess and continues to reflect the state of the most recent run of the program. That is indeed useful for inspecting the entrails and testing, and was a key requirement during IDLE's re-design. Run/Run Module (F5) will create a fresh subprocess, connect the Shell window to it, and restart the program from scratch. There is an autosave feature, so re-running a program following modification is one keystroke. This is now the preferred way to use IDLE, rather than initiating a re-run from the Shell window with reload() etc, though that is still possible. The shell's state will persist until it's restarted or F5 is keyed. That is indicated with a ====== RESTART ===== in the Shell window, followed by any output from the new run. It is still possible to copy lines and blocks of code forward in the shell, even if they belong to a previous run. That capability is very useful for testing during development. -- KBK From somebody at nowhere.com Fri Jan 9 16:45:52 2004 From: somebody at nowhere.com (Sean Richards) Date: Sat, 10 Jan 2004 10:45:52 +1300 Subject: Problem with OpenGL.GLUT References: <7447dd2a.0401071402.2c0737e6@posting.google.com> Message-ID: <87oetchk33.fsf@hugin.valhalla.net> "Cousin Stanley" writes: > Steven .... > > I'm also having import problems > with a Win98 installation of PyOpenGL for Python 2.3 > from .... > > http://prdownloads.sourceforge.net/pyopengl > /PyOpenGL-2.0.1.07.py2.3-numpy23.exe?download > > Any of the test programs in the Demo folder > that attempt from OpenGL.GLUT fail > as does a direct import attempt > from the Python interpreter .... > > python > Enthought Edition build 1028 > Python 2.3 (#46, Aug 11 2003, 09:34:05) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> >>>> from OpenGL.GLUT import * > Traceback (most recent call last): > File "", line 1, in ? > ImportError: DLL load failed: One of the library files needed to run this applic > ation cannot be found. > > Using < dependency walker > to examine .... > > /site-packages/OpenGL/GLUT.pyd > > shows .... glut32.dll * Not Found * > > I've done a few searches on Google, > but as yet haven't turned up what > seems to be a compatible version > of this particular missing DLL file .... > > Hopefully, someone here might know > how to resolve this .... > > -- > Cousin Stanley > Human Being > Phoenix, Arizona I use the glut DLLs from here[1] with PyOpenGL on NT and I am pretty sure that the GLUT examples worked OK. I haven't got access to that machine at the moment so I can't check. But if you haven't already tried the DLLs from[1] perhaps they might work for you. [1] http://www.xmission.com/~nate/glut.html Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From timr at probo.com Fri Jan 16 01:03:13 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 15 Jan 2004 22:03:13 -0800 Subject: Printing to console, no scroll References: Message-ID: "Totte Karlsson" wrote: > >How can I print to the console without having it scrolling to a new line for >each print statement? >I want to print a count down in the console, but for each count it scrolls >the screen (of course). > > Is there another way? > >Here is the simple script for now > >print "Closing window in :" >for second in range(10): > time.sleep(1) > print `10-second` +" seconds" print "Closing window in : " for second in range(10,0,-1): print "%2d\x08\x08\x08" % second, time.sleep(1) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Mon Jan 26 18:26:56 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jan 2004 18:26:56 -0500 Subject: Deleting objects References: Message-ID: > > for t in db.tables: > > del t As Gerrit said, this is equivalent to 'pass'. db.tables = [] # or db.tables[:] = [] # or db.cleartables() is more likely to work. But a db.close() method should contain what will work. TJR From robert_dodier at yahoo.com Thu Jan 29 18:59:27 2004 From: robert_dodier at yahoo.com (Robert Dodier) Date: 29 Jan 2004 15:59:27 -0800 Subject: Safe to modify globals(), or not? Message-ID: <6714766d.0401291559.45413e0d@posting.google.com> Hello, I'm interested in introducing new variables into the environment of a Python interpreter or program. In reading through old posts to this newsgroup, I see there is an often-repeating warning against modifying the contents of locals(). Fair enough. However, is there anything wrong with modifying globals() ? In the list of built-in functions (http://www.python.org/doc/lib/built-in-funcs.html) locals() has an explicit warning, globals() doesn't. Does that mean it's safe to modify globals() ? By the way, is there another way to introduce a new variable into a scope (local or global) other than assigning directly to the dictionary returned by locals() or globals() ? Just some context -- I want to parse strings written in a "little language" and then have new variables show up in the Python environment so the user can manipulate them. E.g., >>> parse_funky_language("Hey, this is far out, man.") >>> Hey.part_of_speech Interjection Any light you can shed on this issue will be appreciated. Thanks for not getting distracted about whether this is useful. regards, Robert Dodier -- If I have not seen as far as others, it is because giants were standing on my shoulders. -- Hal Abelson From zapazap at yahoo.com Sun Jan 25 20:06:49 2004 From: zapazap at yahoo.com (zapazap) Date: 25 Jan 2004 17:06:49 -0800 Subject: -- Pythonic control of Windows GUI application: tabs and listviews Message-ID: <4b3b1124.0401251706.6cf67f27@posting.google.com> -- Pythonic control of Windows GUI application: tabs and listviews Dear Snake-charming Gurus, I have learned to manipulate some controls ("Button", "ComboBox", etc) through such means as: win32gui.SendMessage(hwnd, win32con.BM_GETCHECK, 0 ,0) win32gui.SendMessage(hwnd, win32con.CB_GETCOUNT, 0 ,0) provided by Python Win32 Extensions, and understand that such constants as: win32con.BM_GETCHECK win32con.CB_GETCOUNT corresponding to distinct messages (documented at [1] and [2]) that can be sent to such controls. For the "List-View" and "Tab" controls then, I expected to find the constants win32con.LVM_GETCHECK win32con.TCM_GETITEMCOUNT corresponding to the distinct messages documented at [3] and [4]. Unfortunately the module win32com module does not have any LVM_* or TCM_* attributes, and I have not found reference to such constants in the Extensions documentation. I want to control a windows app through the GUI, but I do *not* want to resort to 'mouseclick/keypress recorder' type tools. For now, I seem to be able to work the Button and Combobox controls for a target window while another window is running full screen mode, and I want to keep it that way. But some of the controls I need can be reached only by mamipulating Tab and Listview controls. Do you have any advice on how I might control these controls in a way similar to my controling Buttons and Comboboxes? Or, failing that, do you have an entirely different route for me controlling one app while a second is running maximized? Much thanks!! - Bryan Hann [1] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/buttons/buttonreference/buttonmessages/bm_getcheck.asp [2] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/comboboxes/comboboxreference/comboboxmessages/cb_getcount.asp [3] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/messages/lvm_getitemcount.asp [4] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/tab/messages/tcm_getitemcount.asp From philh at invalid.email.address Sat Jan 3 00:51:33 2004 From: philh at invalid.email.address (phil hunt) Date: Sat, 3 Jan 2004 05:51:33 +0000 Subject: Text-to-HTML processing program Message-ID: Does anyone know of a text-to-HTML processing program, ideally written in Python because I'll probably be wanting to make small modifications to it, which is simple and straightforward to use and which uses a simple markup language (something like Wikipedia markup would be ideal)? -- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From jcarlson at nospam.uci.edu Wed Jan 28 14:42:28 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 28 Jan 2004 11:42:28 -0800 Subject: PEP 326 is D-E-A-D (big frownie face) In-Reply-To: References: <40158680$0$7044$ba620e4c@news.skynet.be> <20040126235704.GD13453@siliconimage.com> Message-ID: Aahz wrote: > In article , > Mel Wilson wrote: > >>Even then, what about PEP 326, which presumes to define highest and >>lowest objects that can be compared with anything? > > > What about it? ;-) > > (Guido just posted a Pronouncement rejecting it.) When I get around to posting the final version with an example module, people can still use it if they want. - Josiah From wlpqasyj at vkoparwi.com Thu Jan 22 05:39:14 2004 From: wlpqasyj at vkoparwi.com (M.B (ml)) Date: Thu, 22 Jan 2004 10:39:14 GMT Subject: $$$ Im at a loss for words THIS WORKS $$$ Message-ID: MAKE MONEY!!!MAKE MONEY!!! MAKE THOUSANDS!!! I found this on a bulletin board and decided to try it: I don't care about the useless pre-fabricated crap this message usually says. All I say is, it works. Continue pre-fab crap. WELL GUESS WHAT!!! Within five days, I started getting money in the mail!! I was shocked!! I figured it would end soon, but the money just kept coming in. In my first week, I made about $63.00 By the end of the second week I had made a total of $1873.00!! In the third week I had made a total of $9,612.00 and more mail kept coming in!! This is now my fourth week and I have made a total of $35,165.00 and it's still coming rapidly. It's certainly worth $6.00 and six stamps, and I have spent more than that on the lottery without ever winning!!! My mailman asked me what was with all the mail , and when i showed him this system he was amazed and got going at it . Everyday he thanks me , it feels good to know your helping make other pepole have more time and money to do the things they care about most .(Dont let this pass you buy , it so easy and it realy does work) Let me tell you how this works and most important, why it works.......... also make sure you print this out NOW, so you can get the information off of it, as you will need it. I promise you that if you follow the directions exactly that you will start making more money than you thought possible by doing something so easy!! Suggestion: Read this entire message carefully!! (Print it out or download it) Follow the simple directions and watch the money come in!! It's easy. It's legal. And, your investment is only $6.00 (Plus postage) !!! IMPORTANT: This is not a rip-off, it is decent; it's legal; and it is virtually no risk - it really works!! If all the following instructions are adhered to, you will receive extraordinary dividends. PLEASE NOTE: Please follow the directions EXACTLY, and $50,000 or more can be yours in 20 to 60 days. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. You will now become apart of the Mail Order business. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to income which is made from people like you and me asking to be included in that list. Here are the four easy steps to success. STEP ONE: Get six separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 U.S. $1.00 bills and place ONE inside of EACH of the six pieces of paper so the bill will not be seen through the envelope (to prevent thievery). Next, place one paper in each of the six envelopes and seal them. You now should have six sealed envelopes, each with a piece of paper stating the above phrase, your name and address, and a $1.00 bill. What you are doing is creating a service. THIS IS ABSOLUTELY LEGAL!!!!! You are requesting a legitimate service and you are paying for it!! Like most of us I was a little skeptical and little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-238-5355) and they confirmed that it is indeed legal!! Mail the six envelopes to the following addresses: 1) A. L. Alexander 12 Briggate Elland Bridge Elland HX5 9DP England 2) G. Burrows 1/264 Tor St Toowoomba QLD 4350 Australia 3) J. Safian 6950 W. Forest Presrv. Dr., #115 Norridge, IL 60706-1324 4) R. Ansems Gen. Foulkesstraat 5 4641 BW Ossendrecht Netherlands 5)C. Milligan 6597 Herry Rd. Vernon BC Canada V1B3T6 6)M. Boisvert 357-B Presland Rd Ottawa ,Ont Canada K1K 2B4 STEP TWO:Now take the #1 name off the list that you see above, move the other names up (six becomes 5, 5 becomes 4, and etc.) and add YOUR NAME as number 6 on the list. STEP THREE: Change anything you need to but try to keep this article as close to original as possible. Now post your amended article to at least 200 news groups. : (I think there are close to 24,000 groups) All you need is 200, but remember, the more you post, the more money you make!! This is perfectly legal!! If you have any doubts, refer to Title 18 Sec. 1302 & 1341 of the Postal Lottery laws. Keep a copy of these steps for yourself and whenever you need money, you can use it again, and again. PLEASE REMEMBER that this program remains successful because of the honesty and integrity of the participants and by their carefully adhering to directions. Look at it this way. If you were of integrity, the program will continue and the money that so many others have received will come your way. NOTE: You may want to retain every name and address sent to you, either on a computer or hard copy and keep the notes people send you. This VERIFIES that you are truly providing a service. (Also, it might be a good idea to wrap the $1 bill in dark paper to reduce the risk of mail theft). So, as each post is downloaded and the directions carefully followed, all members will be reimbursed for their participation as a List Developer with one dollar each. Your name will move up the list geometrically so that when your name reaches the #1 position you will be receiving thousands of dollars in CASH!!! What an opportunity for only $6.00 ( $1.00 for each of the first six people listed above) Send it now, add your own name to the list and you're in business!!! *****DIRECTIONS FOR HOW TO POST TO NEWS GROUPS!!!***** STEP ONE: You do not need to re-type this entire letter to do your own posting. Simply put your cursor at the beginning of this letter and drag your cursor to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into the computer's memory. STEP TWO: Open a blank 'notepad' file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into the notepad so that you will add your name to the list. STEP THREE: Save your new notepad file as a text file. If you want to do your posting in different settings, you'll always have this file to go back to. STEP FOUR: You can use a program like "postXpert" to post to all the newsgroups at once. You can find this program at . Use Netscape or Internet Explorer and try searching for various new groups (on- line forums, message boards, chat sites, discussions.) STEP FIVE: Visit message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done. Congratulations!!!!!! THAT'S IT!! All you have to do, and It Really works!!! Best Wishes From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 23 06:30:50 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 23 Jan 2004 12:30:50 +0100 Subject: cgi concurrency approaches? References: <7x7jzjgso7.fsf@ruckus.brouhaha.com> <66s11056aptit3vd2inv3p3r07v95k52ha@4ax.com> Message-ID: Matt Goodall: >Rene Pijlman: >> Use mod_python and keep the counter in a Python variable > >That will only work if you use Apache 2 in threaded mode. Of course, good point. -- Ren? Pijlman From a9804814 at unet.univie.ac.at Thu Jan 8 15:40:08 2004 From: a9804814 at unet.univie.ac.at (Thomas Mang) Date: Thu, 08 Jan 2004 20:40:08 GMT Subject: books Message-ID: <3FFDC029.AB0A4097@unet.univie.ac.at> Hello, I have programmed mostly in C++ lately, and I want to start learning Python now. Which books would you recommend to buy? I am both looking for an introduction into the language, as well as complete guides. thanks for your responses, Thomas From tim.one at comcast.net Mon Jan 12 18:10:04 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 12 Jan 2004 18:10:04 -0500 Subject: Python is far from a top performer according to benchmarktest... In-Reply-To: Message-ID: [Lothar Scholz] >> Fortran does not have this problem so a lot of optimizations can be >> done and values can be hold in registers for a much longer time, >> resulting in much greater speed. [Robin Becker] > I'm not sure I agree with the above. Aliases could certainly occur in > fortran 77, I haven't used 90 so can't say for sure. That's the magic of Fortran: the F77 standard says (in part): If a subprogram reference causes a dummy argument in the referenced subprogram to become associated with another dummy argument in the referenced subprogram, neither dummy argument may become defined during execution of that subprogram. It bascially says you can alias all you want, so long as you only read the aliased entities and don't modify them. If effect, if you do anything with aliases that would inhibit optimizations that assume there isn't any aliasing, then it's your *program* that's not legitimate Fortran. The Fortran standard has lots of text "like that", imposing (often unenforcable) restrictions on conforming programs for the benefit of optimizing compilers. That was the right choice for Fortran's audience. From fwang2 at yahoo.com Fri Jan 30 16:09:16 2004 From: fwang2 at yahoo.com (oliver) Date: 30 Jan 2004 13:09:16 -0800 Subject: pythonwin woes Message-ID: Hi, I am trying my hands on the latest verion of pythonwin extension with python 2.3.3 , and run into *semi-fatal* problem: the run command ignores the modifications I made to the source code, and *always* show me results given by that outdated source: it feels like it just use that cached .pyc!!! I wonder if the other pythonwin users had experienced the same problem, or did I miss anything here. There is no such problem in IDLE though. Thanks oliver From exarkun at intarweb.us Wed Jan 14 10:35:16 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 14 Jan 2004 10:35:16 -0500 Subject: I come not to bury C++, but to praise it... In-Reply-To: References: Message-ID: <20040114153516.GA16224@intarweb.us> On Wed, Jan 14, 2004 at 09:42:52AM -0500, Derek wrote: > [snip] > > I also use C++ and Python as my main languages and I agree with your > comments. However, I don't agree that Python is inherently "safer" > than C++. At best I see it as a tie. For example, C++ let's you > corrupt memory among other "unsafe" things, most of which can be > avoided by using standard containers, smart pointers, etc. Python > lets you do "unsafe" things such as passing an object to a function > when it makes no sense to do so, which can lead to nasty runtime > surprises. > A traceback is *much* less nasty than memory corruption. One stops the program immediately and shows you exactly where the problem lies, the other may let the program run for quite a long time before simply causing the process to die, leaving few clues as to the source of the problem. Python may not be *completely* safe (indeed, memory corruption is still possible due to bugs in the interpreter and extension modules), but it is quite a bit safer than C++. Jp From rainerd at eldwood.com Thu Jan 29 17:17:39 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 29 Jan 2004 22:17:39 GMT Subject: Rookie question about data types (hashtables) References: Message-ID: <7EfSb.139694$sv6.756780@attbi_s52> Steve D. Perkins wrote: >> Sounds like a sorted list would work best. A binary search (see the >> bisect module) lets find all matches in O(log n) time. > > > Hmm... a double-linked-list with recursion, like back in Freshman > Programming 101? I was thinking about a standard Python list, which is actually implemented as an array, not a linked list. Binary searches don't work on linked lists. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From mensanator at aol.com Wed Jan 14 21:09:05 2004 From: mensanator at aol.com (mensanator) Date: 14 Jan 2004 18:09:05 -0800 Subject: Printing to console, no scroll References: Message-ID: Harry George wrote in message news:... > "Totte Karlsson" writes: > > > Hi, > > How can I print to the console without having it scrolling to a new line for > > each print statement? > > I want to print a count down in the console, but for each count it scrolls > > the screen (of course). > > > > Is there another way? > > > > Here is the simple script for now > > > > print "Closing window in :" > > for second in range(10): > > time.sleep(1) > > print `10-second` +" seconds" > > > > thanks > > /totte > > > > > > > > > > You need to flush after the print statements. If you have several > prints (not just 1 as in this example), it is easier to hide in a > separate function. > > def msg(txt): > sys.stdout.write(txt) > sys.stdout.flush() > > > for second in range(10): > > time.sleep(1) > > msg(`10-second` +" seconds ") #add a space at the end to delimit > > print #to finish off the line That produces 10 seconds 9 seconds 8 seconds 7 seconds 6 seconds 5 seconds 4 seconds 3 seconds 2 seconds 1 seconds This will produce a true countdown - the messages overwite each other: for sec in range(10): time.sleep(1) m = "%2d seconds" % (10-sec) msg(m + chr(13)) But this will only work on systems that properly handle control characters. It works from a Windows command prompt but doesn't from Idle which shows that silly undefined character box (which I'll show here as []). So the Idle output looks like 10 seconds[] 9 seconds[] 8 seconds[] 7 seconds[] 6 seconds[] 5 seconds[] 4 seconds[] 3 seconds[] 2 seconds[] 1 seconds[] which, when copied and pasted into Google, results in 10 seconds 9 seconds 8 seconds 7 seconds 6 seconds 5 seconds 4 seconds 3 seconds 2 seconds 1 seconds This is the reason why the PROPER way to end a new line is with a carriage_return + line_feed and not simply line_feed. It also worked properly from the shell in Cygwin, but I don't have a real unix or linux system to try it on. From python at hitmedia.com Tue Jan 27 23:19:57 2004 From: python at hitmedia.com (Python Baby) Date: Tue, 27 Jan 2004 20:19:57 -0800 Subject: little client + server app : has this been done? Message-ID: <20040128041957.GA92182@mail.hitmedia.com> I'm about to try a little test project in Python, but want to make sure I'm on the right foot. Any advice appreciated before I start this. MOST important : I want to make sure I'm not just re-inventing the wheel, if there's a library out there that does this exact thing already. SERVER: Has some protected files, not in a webroot, that I want to let the client download only if they pass me a verified key in the server's "OK" database. CLIENT: Knows which files it wants (by file id# not full path). Knows its key to get them. Passes some kind of message to the remote server saying, "Here is my key. Here is the file I want." Server replies by passing the file, and a little metadata about the file. Sound familiar? Should I do it from scratch or is this just some well-known library I don't know about? (I searched around, of course, but couldn't find one.) Thanks! From Chuck at spears.com Wed Jan 28 11:37:17 2004 From: Chuck at spears.com (Chuck Spears) Date: Wed, 28 Jan 2004 11:37:17 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: >The conclusion may seem obvious to _you_ but this is no guarantee that >everyone else also possesses this knowledge. OSS is being hailed as >the second coming, and it comes as no surprise therefore that some >people might be deluded into thinking they could harness this power to >cure cancer overnight or land a man on Mars by 2005. > If you can get by his trolling and unbearable arrogance, there are some kernels of truth in there. I come from a commercial background as well but instead of trying to exploit the OSS community, ive been lurking around looking for a project I feel I could contribute to. Most geeks by their nature, are very independent and abhor order. You have to have order to get anything done. Thats why most successful projects have one or at most a few people pulling the strings because if you don't, the project will flounder. I've personally based a few of my projects on some OSS projects and they failed miserably. Because of the bugs and the Authors unwilligness to address them or even accept them as bugs. You can say "well why didnt you just fix it yourslef" but I just didnt have the time. On the other side of the coin, i've used OSS projects like PHP and Postgres with great results. The other problem with hobbyist geek programmers is they are just in it for the fun of it. They get bored when the last 10% of the project which is mostly bug fixing and rengineering code coes about and generally abandon it. I've poked into literally over one hundred sourceforge projects that started out as good ideas and had lots of activity. i'd come back in 6 months and There would be almost no activity. With a developer with a commericial background, he might be more willing to see the project through. I too get annoyed when an OSS author pulls a massive library into his project just to get a few functions out of it he could have written himself. It's really problematic as Brandon has said when you are using CygWin or Ming because a lot of these libraries dont work on it. My bread and butter is palm and windows development so I cannot abandon the platform yet. What i've been trying to do is build up a nice linux dev environment using ming and python. The python side of things works great but the C++ side... well.. sucks. Thankfully, I finally decided to evaluate VMWare and being able to run linux and windows together has been a godsend so I can hopefully abandon the cygwin stuff. From db3l at fitlinxx.com Mon Jan 12 11:34:33 2004 From: db3l at fitlinxx.com (David Bolen) Date: 12 Jan 2004 11:34:33 -0500 Subject: How to insert into listbox using wxPython References: <3ffda907$0$572$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: "Andrew" writes: > I typed what you wrote > > for x in self.results: > self.listbox.Append(x[0]) > > and I got the same error as what I had tried earlier > > Traceback (most recent call last): > File "S:\GUI\MYSQL\mysqlgui.py", line 65, in OnB2Button > self.listbox.Append(x[0]) > File "F:\Python22\Lib\site-packages\wxPython\controls.py", line 78, in > Append > val = controlsc.wxControlWithItems_Append(self, *_args, **_kwargs) > TypeError: String or Unicode type required > > Any help is alway's appreciated Your database query is returning a list of tuples, where each element in the tuple is a column from your database that is part of the query (or all columns in the table with your query of *). The tuple is not a string, which is what the wxListBox understands how to display. I expect that if you change the code to: self.listbox.Append(str(x[0])) you'll get rid of the error, since that will provide a string representation of the tuple x[0], but I also expect it won't be exactly what you want depending on the database columns, and/or the way certain data types automatically turn themselves into strings. In the end you'll probably want to process each entry in 'results' according to your own desires for display purposes, formatting an appropriate string to be put into the ListBox. You may also find that using a wxListCtrl in wxLC_REPORT mode fits well since it will make it simpler to divide the columns of data (either that or a wxGrid, although wxGrid is probably overkill). -- David From exarkun at intarweb.us Thu Jan 1 01:16:33 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 1 Jan 2004 01:16:33 -0500 Subject: selecting a random item from a set In-Reply-To: References: <3FF20AA3.7080603@v.loewis.de> Message-ID: <20040101061633.GA26751@intarweb.us> On Wed, Dec 31, 2003 at 10:37:13PM +0000, Alexander Schmolck wrote: > Jp Calderone writes: > > > > Alexander Schmolck wrote: > > > Maybe not insensibly -- the fairly generic approach outlined above that will > > > work for any iterable with len is clearly not desirable as default (because of > > > its time complexity), and just using it as a fallback won't work either, > > > because AFACT there is no way for `choice` to find out whether its argument is > > > a sequence or not. > > > > > > def choice(self, seq): > > """Choose a random element from a non-empty sequence.""" > > try: > > return seq[int(self.random() * len(seq))] > > except TypeError: > > # Fallback algorithm > > choice(dict(1:"gets this", 2:"gets that", "three":"gets the key")) > This is as broken in the current choice implementation as in the one I proposed. I don't think it makes any difference to the question at hand. Jp From ih8spam at spamtrap.com Wed Jan 14 14:59:06 2004 From: ih8spam at spamtrap.com (WTH) Date: Wed, 14 Jan 2004 14:59:06 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <4004AC8E.46A3104F@alcyone.com> Message-ID: <100b8c5rm4bdke6@corp.supernews.com> > This reminds me of the old expression: "A winner never quits. A quitter > never wins. But if you never win and never quit, you're a fucking idiot." I've seen that anti-motivational poster :). LOL. WTH From brian at sweetapp.com Fri Jan 9 03:11:32 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 09 Jan 2004 00:11:32 -0800 Subject: Lua: further investigation and comparisons with Python and Forth In-Reply-To: Message-ID: <004501c3d688$3124fdb0$0000fea9@dell8200> > > Before reading about Open Firmware, I had assumed that Forth had > > completely dropped out of sight. Anyone else aware of > > counterexamples? > > I know that Sun systems have a forth based boot system. Which is Open Firmware, though Sun calls it something else. Cheers, Brian From snake at penza-gsm.ru Fri Jan 16 09:44:33 2004 From: snake at penza-gsm.ru (Alexey Nezhdanov) Date: Fri, 16 Jan 2004 17:44:33 +0300 Subject: Bug or feature? In-Reply-To: References: <3dtid1-594.ln1@beastie.ix.netcom.com> Message-ID: Terry Reedy wrote: > "Dennis Lee Bieber" wrote in message > news:3dtid1-594.ln1 at beastie.ix.netcom.com... > >>Alexey Nezhdanov fed this fish to the penguins on Wednesday 14 January >>2004 21:40 pm: >> >> >>>Case 1 and case 2 prints out different calues (1 and 2 respectively). >>>Do not know - if this is a bug or feature of python. >>> >> >> It's a problem with using what I would consider a side effect... > > And > >>not understanding that "variables" are not memory addresses. > > > In particular, the problem with both modifying in place (the side effect) > and returning a value. I see a little better Guido's reason for having > list modification methods return None. While chaining is not too > problematical, object returns would allow list expressions mixing implicit > and overt effects with possible puzzles similar to the one presented in > this thread. > > Terry J. Reedy So since the word "problem" is so popular in this tred I have an another question: Does anybody agree that this is a python problem and not a programmer problem? Let me explain. I DO know that this behaivoir of python is matches the DOCS and all declared official language laws. I DO know why it is happening and how to fix my program to solve the problem (in fact I already knowed it when written my first post here). I DO know that fixing on python level it will rise particular incompartibility with previous versions of python. BUT I know the case where such python behaivoir causes hard-to-catch problems. I do not know any case (anybody knows? please give example) where such "feature" may be useful. So I proposing to make a change into python and reverse the order of calculations. Just for sure: === Order used now === ## a+=a.Sub(b) 1. evaluate value of 'a' 2. evaluate value of 'a.Sub(b)' 3. evaluate the sum 4. store the result into 'a' === Proposed order === ## a+=a.Sub(b) 1. evaluate value of 'a.Sub(b)' 2. evaluate value of 'a' 3. evaluate the sum 4. store the result into 'a' (same about -=, *=,... of course) -- Respectfully Alexey Nezhdanov From carroll at tjc.com Sat Jan 24 13:41:16 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat, 24 Jan 2004 18:41:16 GMT Subject: there is no exitfunc in sys module References: Message-ID: On Sat, 24 Jan 2004 00:07:53 -0800 (PST), Hameed Khan wrote: > i was reading the manual for sys module. i found a > description for a function known as exitfunc. and it > says the function installed by > sys.exitfunc(cleanUpFunc) call will be called when the > interpreter exits. but when i try to call this > function on Python interactive prompt it says there is > no attribute named exitfunc in sys module. It doesn't exist by default. It's a function that you set up to be called at termination. Try this:: import sys def outtahere(): print "Okay, I quit" sys.exitfunc=outtahere print "program starting" # do something print "program done, now exiting" From dwall at fastmail.fm Thu Jan 8 15:55:30 2004 From: dwall at fastmail.fm (David K. Wall) Date: Thu, 08 Jan 2004 20:55:30 -0000 Subject: Looking for help with regular expressions- not Python Specific References: <8d3e714e.0401072114.5bf3fba7@posting.google.com> Message-ID: Roy Smith wrote: > I don't know of any regex-specific newsgroups or mailing lists, but most > old unix hands are pretty good at them, so asking in comp.unix.questions > might be worth trying. Perl makes extensive use of regex, so I'll bet > you'll find some regex gurus on comp.lang.perl too. Please use comp.lang.perl.misc instead. comp.lang.perl "officially" does not exist, as it was rmgrouped in August 1995. Some carelessly-administered news servers still carry it, unfortunately. alt.perl is another possibility, and is perhaps a bit looser about what is considered on-topic for the newsgroup, but clpm tends to have more knowledgeable people. (although some people frequent both c.l.p.m and a.p) -- David Wall From tim.golden at viacom-outdoor.co.uk Tue Jan 27 04:23:10 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 27 Jan 2004 09:23:10 -0000 Subject: winapi: mouseclick Message-ID: >From: Tim Golden [mailto:tim.golden at viacom-outdoor.co.uk] > >>From: KNS [mailto:netquest at sympatico.ca] >> >>> Can someone please suggest how to test for a mouse click using >>> the WinAPI? I have dispatched a windows application and would >>> like to detect any mouseclicks (and keyboard entry for that >>matter)... >>> >> > [... snip my original explanation via win32all / ctypes ...] Or, alternatively, you can use PyGame (http://pygame.org) to get lower-level control, obviously intended for games, but quite able to be used for gui-type operations. TJG BTW I apologise for the loss of threading on these posts: I'm using Outlook to reply to the mailing list, and it notoriously doesn't thread properly. If anyone has a fix, please let me know. Tim ________________________________________________________________________ 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 jjl at pobox.com Fri Jan 16 15:04:44 2004 From: jjl at pobox.com (John J. Lee) Date: 16 Jan 2004 20:04:44 +0000 Subject: Why gmp is not in the standard library? References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> <4006f74a$0$567$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <87smif64o3.fsf@pobox.com> Brian Kelley writes: > Skip Montanaro wrote: > > Bdb's license is not GPL: > > http://www.sleepycat.com/download/oslicense.html > > I stand corrected, it makes perfect sense that the Berkeley DB should > be released using the Berkeley license :) I don't know why I thought > otherwise. > > That being said, wasn't there some issue with making the Python > License GPL compatible for issues like these? Yes. "GPL-compatible" is very different from "GPL", of course. John From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 21 21:11:43 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 13:01:43 +1050 Subject: Identifing current function References: Message-ID: On Thu, 22 Jan 2004 02:21:54 GMT, Brian Donovan wrote: > Is there a way to identify the current function. For example: > > class A: > def B(self): > print current_function_name Functions, like all objects, have no inherent name. Names are bound to objects; each object can have zero, one or more names bound to it. None of the names has any particular status as "the" name of the object. -- \ "I moved into an all-electric house. I forgot and left the | `\ porch light on all day. When I got home the front door wouldn't | _o__) open." -- Steven Wright | Ben Finney From gerrit at nl.linux.org Thu Jan 29 10:31:02 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 29 Jan 2004 16:31:02 +0100 Subject: sending mail cc, bcc In-Reply-To: <000f01c3e67b$de344800$1603a8c0@pc22> References: <000f01c3e67b$de344800$1603a8c0@pc22> Message-ID: <20040129153102.GA24226@nl.linux.org> Alberto Vera wrote: > I have a library called smtplib that send email > I use these lines to use it: (from -->to) > ------------------------------------ > server = smtplib.SMTP(server) > server.sendmail(fromaddr, toaddrs, message) > ------------------------------------ > > But I'd like to include some mails CC ,BCC. > (from -->to) > ( |-->cc ) > ( |-->bcc) > > Does anyone have a library to make it? (mail: from, to, cc, bcc) The 'message' string contains the headers. The information in this string is not used to determine the recipients. So, you can do: message = "From: Knight who says Ni To: Sir Galahad Cc: Sir Robin Ni! """ ...while you send it to someone else in reality: server.sendmail("my at address.com", ["mother at isp.com", "father at isp.com"], message) See also the online documentation. Try it out! yours, Gerrit. -- 243. As rent of herd cattle he shall pay three gur of corn to the owner. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From xpythonist at yahoo.com.br Fri Jan 23 10:25:34 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Fri, 23 Jan 2004 12:25:34 -0300 (ART) Subject: file open problem In-Reply-To: <20040123143808.80139.qmail@web14702.mail.yahoo.com> Message-ID: <20040123152534.41615.qmail@web21508.mail.yahoo.com> Are you sure that the file c:\temp\pytest.txt exists in your laptop's hard disk? --- Neil MacGaffey escreveu: > Hi - I'm new to python and am stymied by something > that should be simple. The file open command below > works fine on my desktop machine, but I cant get it > to > work on my laptop. Since using Python on my laptop > is > realistically the only way I'm going to find the > time > to learn Python, this is a big problem for me. > Here's > what I'm up against: > > PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond > (mhammond at skippinet.com.au) - see > 'Help/About PythonWin' for further copyright > information. > >>> fobj = open(r'c:\temp\pytest.txt','r') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: > 'c:\\temp\\pytest.txt' > > The laptop is a Sony VIAO that's about 2 years old. > Its running Windows 2000, SP4. The desktop is an > older machine, but with the same Windows > environment. > I've obtained a fresh download of Python 2.3.3 and > the > Win32 extension and have re-installed both a couple > of > times with no apparent problems. I also tried > dropping back to Python 2.3.2, but had same result. > Any ideas as to what I should be looking at on this > laptop that might be causing the problem? > > Thank you > Neil > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. > Try it! > http://webhosting.yahoo.com/ps/sb/ > > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis! http://br.geocities.yahoo.com/ From glenfant at nospam-bigfoot.com Thu Jan 29 10:06:55 2004 From: glenfant at nospam-bigfoot.com (Gilles Lenfant) Date: Thu, 29 Jan 2004 16:06:55 +0100 Subject: regexp upward compatibility bug ? Message-ID: Hi, Porting a Zope app from (old) Zope 2.3.3 powered by Python 1.5.2 to a newer Zope powered by Python 2.1.3, I found a regexp problem : This does perfectly the job with Python 1.5.2 but raises an exception with Python 2.1.3. I can't see what's wrong when reading the "re" module doc. Any hint welcome File "txt2html.py", line 27, in txt2html pat = re.compile(r'((ftp|http)://[\w-]+(?:\.[\w-]+)*(?:/[\w-\.?=]*)*)') File "/usr/local/lib/python2.1/sre.py", line 90, in compile return _compile(pattern, flags) File "/usr/local/lib/python2.1/sre.py", line 136, in _compile raise error, v # invalid expression sre_constants.error: bad character range Many thanks by advance -- Gilles From mwh at python.net Wed Jan 7 07:52:09 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 7 Jan 2004 12:52:09 GMT Subject: PEP 310 suggestions References: <3ffbd106$0$15344$afc38c87@news.easynet.co.uk> Message-ID: Ben writes: > I hope its not too late to make these comments as I know the PEP has been > around for a while! No, no hurry at present. Posting to comp.lang.python isn't necessarily the best way of making comments if you want me to read them, but, hey, it's worked this time... > While I was reading the PEP a few ideas popped into my head and I wondered > if something like them had already been considered. They are probably > rubbish, but I thought I would throw them into the mix! > > 1) If Python had code blocks, If Python had code blocks it would be a different language (as you say below). PEP 310 arose out of a vast (at least 1000 posts) discussion on python-dev, and is deliberately conservative. Perhaps I should mention this in the PEP... > something like this would be possible > > def open_file(file, code_block): > try: > code_block() > finally: > file.close() > > then, > > f = file("foo") > with open_file(f): #Note only passing one argument > # do stuff with f > > This would only work if the code_block could be executed in the scope in > which it was written, and not in the one in which it was called. > > This seems to be more general than the current PEP, but introduces quite > massive changes into the language. The idea is that: > > with func(args): > suite > > goes to > > func(args, suite) "That's my PEP, you go get your own!" (with apologies to Shrek). I don't want to get into a huge discussion of this sort of feature, but I don't want to stop you getting into one either. But I think it belongs in a different PEP (you seem to have a decent start here!). > 2) Exit handler blocks. These are kind to backwards try-finally blocks that > allow the "close" function to be written close to the "open" one. They also > have the advantage that no extra special functions are needed. > > e.g > > l = lock.aquire() > onexit l.release(): > # do stuff while locked > > is eqivalent to > > l = lock.aquire() > try: > # do stuff while locked > finally: > l.release() > > The obvious disadvantage is that it may be non-obvious that the release call > is delayed to the end of the block Hmm, that's an idea I hadn't had. Limiting the "on exit" code to just one expression and the disadvantage you mention mean I'm not sure I like it that much, though... > Any comments? The main reason I like these methods is that they are > both more explicit than the PEP, and don't require the addition of > any more special functions. However I can see the disadantages as > well! Well, thanks for your comments, but I'm not sure I want to incorporate your ideas... I'll add the "onexit" idea as an alternative. Cheers, mwh -- Gullible editorial staff continues to post links to any and all articles that vaguely criticize Linux in any way. -- Reason #4 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From martin at v.loewis.de Fri Jan 2 17:01:22 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 02 Jan 2004 23:01:22 +0100 Subject: version-independence between Python & BerkDB in Solaris packages? In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Is it possible to compile and package Python and the external libraries it > uses to minimize coupling between package versions like this? There are several alternatives: 1. Link _bsddb.so statically with a libdb.a. Then you don't need any additional shared libraries on the target system. You may find that _bsddb.so can't open databases of the "system's" libdb-x.y.so, though. 2. Be prepared to have multiple versions of libdb installed on a system. BerkeleyDB is deliberately packaged in a way to make this possible: You can have /usr/local/BerkeleyDB-4.0, and, at on the same system, /usr/local/BerkeleyDB-4.2. Still the same problem as in 1) with opening newer databases. 3. Package _bsddb.so separately from Python. This is the typical Linux answer. Then provide multiple copies of _bsddb.so, each packaged for its own libdb-x.y. The different packages should conflict with each other. Can be combined with either 1 or 2. > I note that > other modules which link to specific external libraries don't have such > problems: > > % ldd zlib.so > libz.so => /usr/lib/libz.so > libc.so.1 => /usr/lib/libc.so.1 > libdl.so.1 => /usr/lib/libdl.so.1 > /usr/platform/SUNW,Ultra-80/lib/libc_psr.so.1 That's because libz.so is part of the operating system. Even if newer libz releases are available, nobody would install them on Solaris (anymore), since it is so convenient to use the system library. If Sun ever decides to bundle Sleepycat with the system, the same thing may happen: Solaris 11 comes with BerkeleyDB 4.7.178, and nobody installs 4.9.26 even though this has been available for three months already. Instead, people upgrade to Solaris 12 when it comes out. Regards, Martin From a.schmolck at gmx.net Fri Jan 23 08:10:50 2004 From: a.schmolck at gmx.net (A.Schmolck) Date: 23 Jan 2004 13:10:50 +0000 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> <4010E442.8D13AEF3@alcyone.com> Message-ID: Erik Max Francis writes: > Since min(S) and min(*S) behave identically, I submit to you that they > _should_ be. They don't. (See bottom for example). 'as >>> min([[1]]) [1] >>> min(*[[1]]) 1 From james at logicalprogression.net Thu Jan 22 13:43:40 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 22 Jan 2004 18:43:40 +0000 Subject: Need help with Python class idioms In-Reply-To: <0DBEAls/KrhZ089yn@the-wire.com> References: <0DBEAls/KrhZ089yn@the-wire.com> Message-ID: <200401221843.41030.james@logicalprogression.net> On Thursday 22 January 2004 6:05 pm, Mel Wilson wrote: > In article , > > James Henderson wrote: > >On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote: > >> # P.S. Since you're asking about idiom, it would be more Pythonic to > >> write: # > >> # if self.mandatoryVar1 is None: > >> # > >> # using the identity test "is" rather than equality test "==", since > >> there is # only one None. > >> > >> I'd write > >> > >> if not self.mandatoryVar1: > >> > >> but the first method works, too. > > > >Are you sure an empty sequence or zero aren't valid values? J. > > It can get weird if you have to allow your caller to > optionally specify the value None: > > > class _MissingParam: > "An object that no-one else will have a valid use for." > ... > def a_func (opt1=_MissingParam): > if opt1 is _MissingParam: > opt1 = default_calculation () # for instance > ... > > > Regards. Mel. In the original example (not by me) it was None that was being used as the marker that the value had not been set - that's all. The topic was Python idiom and None is the most often used marker that a value has not been passed explicitly and the default value should be used. (Of course, if the default value is immutable it can be used directly.) See: http://www.python.org/doc/current/ref/function.html You're talking about the case where None may be passed explicitly and should not trigger the default. An even terser solution to this than yours is to use an empty list, though any mutable type will do. You see this all over the Zope code: _marker = [] J. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From max at cNvOiSsiPoAnMtech.com Fri Jan 16 09:36:38 2004 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Fri, 16 Jan 2004 14:36:38 GMT Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: whitekid wrote: > SimpleXMLRPCServer.py is Just Simple! > > A few days age. I considered XMLRPC framework for our service. > But finally I choose WebWare. > > Read paper below: http://webware.sourceforge.net/Papers/IntroToWebware.html Ok, but I am interested in the XML-RPC protocotl, so how is webware supposed to help me? From theller at python.net Tue Jan 27 03:16:05 2004 From: theller at python.net (Thomas Heller) Date: Tue, 27 Jan 2004 09:16:05 +0100 Subject: Py2exe and WMI module References: Message-ID: Tim Golden writes: >>From: nekiv at start.no [mailto:nekiv at start.no] >> >>I'm having a problem when I try to make a standalone installation of a >>Python program using Tim Goldens WMI-module. The py2exe produce the >>exe-file as expected, but it fails to execute. > > Well, I've tried to play with wmi-py2exe myself for the first > time, with mixed results. If I understand the idea, what you > do is this: > > Use the makepy generator to generate gen_py support for the > Microsoft WMI 1.1 Scripting Library. This will result in a > proxy module in %TEMP%\gen_py\2.3 (for recent win32all releases) > called something like: > > 565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1.py > > Note the x0x1x1 at the end. > > You then need a setup script such as this one: > > > from distutils.core import setup > import py2exe > > setup ( > console=["wmi_test.py"], > options = { > "py2exe": { > "typelibs": [('{565783C6-CB41-11D1-8B02-00600806D9B6}', 0, 1, 1)] > } > } > ) > > > That "typelibs" line is made up from the proxy string > effectively split like this: > > "565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1".split ("x") > > It's not exactly that, but you can work it out for yourself. In > fact, the first bit is the CLSID, and the others are the LCID, > major and minor numbers from within > 565783C6-CB41-11D1-8B02-00600806D9B6x0x1x1.py > > <... snipped from Python proxy module ...> > > CLSID = IID('{565783C6-CB41-11D1-8B02-00600806D9B6}') > MajorVersion = 1 > MinorVersion = 1 > LibraryFlags = 8 > LCID = 0x0 > > I think the 'official' way is to run makepy with the '-i' flag, then it prints out this: c:\>\python23\lib\site-packages\win32com\client\makepy.py -i Microsoft WMI Scripting V1.2 Library {565783C6-CB41-11D1-8B02-00600806D9B6}, lcid=0, major=1, minor=2 >>> # Use these commands in Python code to auto generate .py support >>> from win32com.client import gencache >>> gencache.EnsureModule('{565783C6-CB41-11D1-8B02-00600806D9B6}', 0, 1, 2) Thomas From mwh at python.net Mon Jan 12 07:11:38 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 12 Jan 2004 12:11:38 GMT Subject: script to translate from compiler AST References: Message-ID: Andrey Khavryuchenko writes: > Hi! > > I'm looking for a script to translate from 'compiler' AST to py source google('decompyle') > and executable code. Um, not sure what you're asking for here. You might be asking for Python2C, but it's probably not what you want... Cheers, mwh -- Enlightenment is probably antithetical to impatience. -- Erik Naggum, comp.lang.lisp From sross at connectmail.carleton.ca Tue Jan 6 10:59:36 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 6 Jan 2004 10:59:36 -0500 Subject: help needed with class and method confusion References: <20040106102232.19889.00002028@mb-m01.aol.com> Message-ID: "Cndistin" wrote in message news:20040106102232.19889.00002028 at mb-m01.aol.com... > The problem part of my code is > class Application: > class Moon: > def __init__(self, name): > self.name = name > def __init__(self): > self.moons = [] > names = ["Io", "Europa", "Ganymeade"] > for name in names: > setattr(self, name, Moon(name)) > I would like to somehow get self.moons to equal > [self.Io, self.Europa, self.Ganymeade]. I had hoped on using > self.moons as an iterant in "for" loops to be able to alter each > in turn. > > Thanks in advance for any possible help. class Application: class Moon: def __init__(self, name): self.name = name def __repr__(self): "added this to pretty up the printing of a.moons" return "Moon(%s)"%self.name def __init__(self): self.moons = [] names = ["Io", "Europa", "Ganymeade"] for name in names: # took Moon(name) out of the setattr() because we'll be # using it again in moons.append. Also used self.Moon # because Moon alone raises a NameError moon = self.Moon(name) setattr(self, name, moon) self.moons.append(moon) a = Application() print a.moons # output [Moon(Io), Moon(Europa), Moon(Ganymeade)] HTH Sean From jepler at unpythonic.net Sat Jan 24 16:33:55 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 24 Jan 2004 15:33:55 -0600 Subject: time.time() In-Reply-To: References: <7cf510d1k3ug79am8s709ebhar2sspjlm2@4ax.com> Message-ID: <20040124213355.GG32445@unpythonic.net> bart, a-b/c evaluates as a-(b/c) Jeff From bignose-hates-spam at and-benfinney-does-too.id.au Mon Jan 26 20:49:25 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jan 2004 12:39:25 +1050 Subject: efficient updating of nested dictionaries References: Message-ID: On Mon, 26 Jan 2004 20:11:39 -0500, Rich Krauter wrote: > What a nice way to simplify this common task. That's great. Thanks for > the advice. > > [HTML garbage repeating the same content] What a hideous way to complicate this simple medium. That sucks. Thanks for turning it off in future. -- \ "My roommate got a pet elephant. Then it got lost. It's in the | `\ apartment somewhere." -- Steven Wright | _o__) | Ben Finney From nuffsaid at phreaker.net Sun Jan 18 15:16:27 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sun, 18 Jan 2004 21:16:27 +0100 Subject: Printing variable names References: Message-ID: On Sun, 18 Jan 2004 11:22:08 -0800, Mike wrote: > mylist = [a, b, c] > > I want to print out the names of the variables in mylist (not the > values of a, b, and c). How do I go about doing this. Thanks. The following example shows that this does not really make sense: a = 1; b = 2; c = 3; mylist = [a, b, c] a = 4; b = 5; c = 6; print mylist print a, b, c Result: [1, 2, 3] 4 5 6 and *not*: [4, 5, 6] 4 5 6 You might want to google for 'Python object reference' etc. Moreover, having a look (e.g. in the tutorial) at how Python passes arguments to functions (mutable and immutable objects) might help to get a better understanding of what is going on behind the scenes. HTH / Nuff From candiazoo at comcast.net Sun Jan 25 01:44:26 2004 From: candiazoo at comcast.net (Michael S. Jessop) Date: Sun, 25 Jan 2004 06:44:26 GMT Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> <1074926701.236022@yasure> Message-ID: Rebuilt with Net_Server. Works fine now. Mike Donn Cave wrote: > Quoth Zoo Keeper : > | No takers, eh? :/ > | > | I can't be the only python user on BeOS... > | > | The only thing I can think of is that I am running "bone". > > Well, at least now we know one thing about your setup. > > In later versions, a Python class can definitely inherit > from BWindow. If you have the 0.5.1 distribution, the > programs in "test" do it that way, and they work. Earlier > versions, before 0.5.0, can't do this (and neither can > older versions of Python.) It is certainly possible to > mess up the BeOS libraries while trying to improve them, > though, as demonstrated by the 3rd party "Developer Edition". > That certainly could be your problem. > > You're not the only Python user on BeOS, but they are few. > Given the level of general interest, I think you'd have > better odds posting to comp.sys.be.programmer. > > As for what I read as your implicit question, will you be > sorry you chose to develop your application in Python with > a Bethon UI - it depends on the details. The functions > available here are numerous but not nearly the whole Be API, > and there are whole areas of functionality that it will > probably never get into. It's pretty useful for casual > stuff, but probably not for real hard core polished > applications. Distribution will be a harder, too, than > a straight C++ program. > > Donn Cave, donn at drizzle.com From latex-bugs at latex-project.org Thu Jan 29 21:41:15 2004 From: latex-bugs at latex-project.org (latex-bugs at latex-project.org) Date: Fri, 30 Jan 2004 03:41:15 +0100 (CET) Subject: hi In-Reply-To: <200401300241.i0U2f6IA014897@rzdspc1.informatik.uni-hamburg.de> References: <200401300241.i0U2f6IA014897@rzdspc1.informatik.uni-hamburg.de> Message-ID: <200401300241.i0U2fFwb016361@sun.dante.de> Thank you for your message to latex-bugs at latex-project.org. Sorry, but to prevent SPAM, the latex-bugs email processor will accept only messages produced with the help of latexbug.tex. Please resend your problem report with the contents of latexbug.msg as the body of your message. -- From jcarlson at uci.edu Tue Jan 20 18:04:31 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 15:04:31 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> <20040120135921.1C3F.JCARLSON@uci.edu> <400c5790_1@newsfeed.slurp.net> Message-ID: <20040120150005.1C48.JCARLSON@uci.edu> > That didnt work either and the file assoc. are correct. > > > If you are in windows and your associations are correct, try: > > setup.py install Steps for you to help us help you: 1. Open up a console. 2. Change to the proper path. 3. Run (without the single quotes) 'python setup.py install' if that doesn't work, try 'setup.py install' 4. Copy and paste the output in a message here. - Josiah From pythonguy at Hotpop.com Fri Jan 23 07:56:41 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 23 Jan 2004 04:56:41 -0800 Subject: Python Consultants? References: <8e198b65.0401221315.6d5cb3fe@posting.google.com> Message-ID: <84fc4588.0401230456.3085796f@posting.google.com> I do some python consultancy in India. Your problem looks interesting, so I will take a look at it after the week-end break. If you dont mind off-shore consultancy, you can contact me at pythonguy at hotpop.com . Regards -Anand arsanalytica at yahoo.com (Dan) wrote in message news:<8e198b65.0401221315.6d5cb3fe at posting.google.com>... > I am working on a python/zope web application and could really use > some *expert* help on a short term basis. > > Is there an appropriate forum for trolling for Python Consultants? > > Here are a pair XML problems that are available: > > #1) Setup to convert these xml files > http://www.gothamanalytics.com/PairTools/geturl?url=http://app.quotemedia.com/data/getHistory.xml&symbol=SUNW > http://www.gothamanalytics.com/PairTools/geturl/?url=http://app.quotemedia.com/data/getQuotes.xml?symbols=SUNW > into a vector of open,close,volume information suitable for use with a > numerical Python module. Doing this quickly is a plus. > Here are the dtds of interest: > http://app.quotemedia.com/data/dtds/history.dtd > http://app.quotemedia.com/data/dtds/quotes.dtd > > #2) Expose the Salesforce.com SOAP functionality from salesforce.com > generated WSDL files, here is an example WSDL > http://gothamanalytics.com/Ex/enterprise.wsdl > See sforce.com for more info on the salesforce.com API. A Python > solution is preferred but a work around which uses Java and the > Salesform.com Apache Axis library and an appropriate gateway from > python might also be acceptable. Results from an attempt at using ZSI > to process the WSDL file is appended to this message. From netquest at sympatico.ca Tue Jan 27 22:31:27 2004 From: netquest at sympatico.ca (KNS) Date: Tue, 27 Jan 2004 19:31:27 -0800 Subject: winapi: mouseclick In-Reply-To: References: Message-ID: This snippet launches the application...It's not strictly meant for IE. w=DispatchEx("InternetExplorer.Application") w.Navigate(startpage) w.Left=225 w.Top=25 w.Width=900 w.Height=960 w.Resizable=0 w.Visible=1 handle=w.HWND lasturl = w.LocationURL cururl = w.LocationURL while w.Visible: if cururl != lasturl: #bunch of stuff here to check ReadyState #would also like to see if mouse click/keypress here... This is an attempt to explore simple possibilities first. If such a solution doesn't exist, then 'yes' the use of pyHook will have to be considered or even mandated. Not knowing before hand can't be avoided. Tim Golden wrote: > > > Could you *please* post some code, or at least pseudo-code, to > show us what you're doing. What is sounds like to me, is that > you're doing this, say: > > import win32api > win32api.ShellExecute (0, "open", "iexplore.exe", None, None, 1) > > and then you want to know what the user's doing within that > application so that you can, eg, keep track of URLs accessed etc. > > Am I close? > > If I am, this isn't easy. If it is, strictly, Internet Explorer that > you're trying to use, then it does have an Events mechanism (about > which I know nothing) which I believe can be accessed from Python. > > If it is any application in general which you're trying to keep track > of, that's more difficult. Windows (and by that I mean any modern GUI > system) apps don't work like your old-fashioned batch / terminal > apps. You don't "wait" for a user to press something; rather, you set > up an event loop and handle or ignore any event which comes in. Each > application does this on its own behalf. To do the same on behalf of > another application requires either subclassing (messy) or system > key / mouse hooks (cf > http://cvs.sourceforge.net/viewcvs.py/uncpythontools/pyHook/) > or some other arcane mechanism. > > 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 mwh at python.net Mon Jan 5 11:39:24 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 5 Jan 2004 16:39:24 GMT Subject: KeyboardInterrupt and threading References: Message-ID: q2n8byu02 at sneakemail.com (Ivan Nestlerode) writes: > Hello comp.lang.python, > > I am attempting to write a threaded program right now in Python > (version 2.3 on Debian unstable) and the current behavior of > KeyboardInterrupt is causing me grief. From the documentation of the > thread module in Python 2.3.3: > > "Threads interact strangely with interrupts: the KeyboardInterrupt > exception will be received by an arbitrary thread. (When the signal > module is available, interrupts always go to the main thread.)" On debian, the signal module certainly should be available, and the KeyboardInterrupt exception should go to the main thread. Or at least, that's what I thought. You're definitely seeing it being delivered to an arbitrary thread? Cheers, mwh -- The Programmer's Quick Guide To Python (Time Machine version): You try to shoot yourself in the foot, only to realize that there's no need, since Guido thoughtfully shot you in the foot years ago. -- Nick Mathewson, comp.lang.python From donn at drizzle.com Sun Jan 25 13:04:51 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 25 Jan 2004 18:04:51 -0000 Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> <1074926701.236022@yasure> Message-ID: <1075053883.217392@yasure> Quoth Michael S. Jessop : | Rebuilt with Net_Server. Works fine now. Thanks, that's interesting. I would not have guessed that the host network implementation could be a factor in the Python type/class internals that seemed to be failing for you, so I'm guessing that when you choose between the two, there are some other things that come along that have nothing to do with the network. I'm actually running a BONE system right now, as I type this, and the Python inheritance works fine - Zeta RC1. Python+Bethon comes on the CD, but looks like it's the standard issue software built on 5.03 (and has a problem with the Zeta internationalization software, crashes on exit after I suppose it freed something it wasn't supposed to.) Donn Cave, donn at drizzle.com From nick889 at mail.com Sat Jan 3 13:28:02 2004 From: nick889 at mail.com (Nick) Date: 3 Jan 2004 10:28:02 -0800 Subject: Py2exe?? Error: Nothing to do? Message-ID: <86df8ed4.0401031028.6edf2381@posting.google.com> I am trying to turn one of my .py files into an exe and I created a setup script and everything, but when i do the follwing "python myscript.py py2exe" I get an error saying "Error: Nothing to do" I am using Python 2.3 (not alpha) with the latest binary of py2exe on windows 98. What did i do wrong and how do i fix it, thanks. From deets_noospaam at web.de Wed Jan 14 11:45:08 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 14 Jan 2004 17:45:08 +0100 Subject: passing callback function to c-extension References: Message-ID: Hi, > A Python function is just a regular Python object, so it is represented at > C level by a PyObject*. To call it from C, just use one of the > PyObject_Call functions - see > http://www.python.org/doc/current/api/object.html#l2h-189 Thanks - works like a charm. I'm now looking for a way to ensure that the passed object is actually a callable one - and how to throw exceptions. But I just started looking for that, so I'll be back if I really need help. Diez From rainerd at eldwood.com Tue Jan 13 17:32:52 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Tue, 13 Jan 2004 22:32:52 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt><100655fo84c2211@corp.supernews.com><87d69og2jl.fsf@pobox.com><873cajafr8.fsf@pobox.com> Message-ID: Jp Calderone wrote: > On Tue, Jan 13, 2004 at 02:28:38PM -0500, Derek wrote: >> "John J. Lee" wrote: >> Python and C++ can also be a bigger mess than sum of either part. >> Take your pick. >> > > Look at how many modules in the stdlib are not implemented in > Python. Look at all the builtin types. It *can* and *does* work, and > with very little mess, if you know what you're doing. They're also not implemented in C++. They're implemented in C, a very different language. And they *are* a mess compared to C code that doesn't have to interface with Python. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From kirk at strauser.com Tue Jan 27 10:15:10 2004 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 27 Jan 2004 15:15:10 GMT Subject: TELNET instead PING References: <5f505344.0401260332.184d4225@posting.google.com> <401571B9.F9DF99D0@engcorp.com> Message-ID: <87y8rt2zow.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-01-27T11:11:22Z, "DCK" writes: > I was on some kind of Network course, where teacher said, that telnet is > better then PING. Your teacher was on crack. That's like saying that "table lamps are better than pencil cups". :-) - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAFn/T5sRg+Y0CpvERAq0UAJ9WhPxMY1Um93QwcOLqGHy+0KlcQgCeJbdW 4o7kvcO5ryEZ8HrSwDy7o9c= =kPeN -----END PGP SIGNATURE----- From bart_nessux at hotmail.com Fri Jan 23 16:58:38 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 23 Jan 2004 16:58:38 -0500 Subject: when x process isn't running... do something In-Reply-To: References: Message-ID: Josiah Carlson wrote: > Bart Nessux wrote: > >> Bart Nessux wrote: >> >>> Howdy, >>> >>> I'm trying to time how long it takes dd to run on a G5, versus how >>> long it takes to run on a G4 (PATA vs. SATA). Both sytems have Mac OS >>> X 10.3.2 and Python 2.3. Could someone demonstrate how I might use >>> Python to monitor for the presense of a process and to do something >>> (in this case send an email which I know how to do) as soon as that >>> process is no longer present? Any suggestions on how to monitor? Call >>> top every 5 secs and read it's output searching for 'dd'??? >>> >>> TIA, >>> Bart >>> >> >> I forgot to mention the fact that I already know when the process >> began. All I need to know is when it ends and then I can calculate the >> part in between those two points. >> > > Why not just: > > import time > import os > start = time.time() > s = os.system('dd ') > print time.time()-start > > > - Josiah That works great... i didn't think of using time (the module)... had to rewrite my function to contain sub-functions so that I could time each piece of it seperately. Thanks for the tip!!! Bart From mwh at python.net Tue Jan 20 06:32:29 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 20 Jan 2004 11:32:29 GMT Subject: secure unpickle? References: <8765f8xe8p.fsf@pobox.com> <7xsmiby92z.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: > > marshal > > > > The docs have similar warnings, though. > > Marshal has an additional problem, which is that the format can change > incompatibly between one Python version and another. Oh, and this: >>> marshal.loads('x') Segmentation fault There's a patch from Armin that I'm supposed to be reviewing about that... I really wouldn't unmarshal input that could come from some random source on the internet. Cheers, mwh -- If design space weren't so vast, and the good solutions so small a portion of it, programming would be a lot easier. -- maney, comp.lang.python From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 14 20:23:50 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 15 Jan 2004 12:13:50 +1050 Subject: confusion about Exception Mechanism References: Message-ID: On Wed, 14 Jan 2004 17:31:41 -0800, Zachary wrote: > I'm relatively new at Python Welcome! Please work your way through the tutorial, to get a good grounding in the language. > slightly confused about how the try...except mechanism is supposed to > work. Chapter 8 of the tutorial deals with errors and exceptions. > I am just not sure how it would > be used, as it just seems that it is another sort of loop. Goodness, that *is* confused :-) > Is their any sort of example I could look at, that has an example of > how it is applied? Work your way through the tutorial, start to finish, and see if it doesn't also answer a whole lot of other questions -- including ones you haven't thought of yet. -- \ "Faith may be defined briefly as an illogical belief in the | `\ occurrence of the improbable." -- Henry L. Mencken | _o__) | Ben Finney From ods at strana.ru Thu Jan 22 08:47:00 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 22 Jan 2004 16:47:00 +0300 (MSK) Subject: utf8 encoding problem In-Reply-To: <20040122103549.GA5620@wiggy.net> Message-ID: On Thu, 22 Jan 2004, Wichert Akkerman wrote: WA> I'm struggling with what should be a trivial problem but I WA> can't seem to WA> come up with a proper solution: I am working on a CGI that WA> takes utf-8 WA> input from a browser. The input is nicely encoded so you get WA> something WA> like this: WA> WA> firstname=t%C3%A9s WA> WA> where %C3CA9 is a single character in utf-8 encoding. WA> Passing this WA> through urllib.unquote does not help: WA> WA> >>> urllib.unquote(u't%C3%A9st') WA> u't%C3%A9st' You have to pass 8-bit string, but not unicode. The following code works as expected: >>> urllib.unquote('t%C3%A9st').decode('utf-8') u't\xe9st' P.S. According to HTML standard, with application/x-www-form-urlencoded content type form data are resricted to ASCII codes: http://www.w3.org/TR/html4/interact/forms.html#form-data-set http://www.w3.org/TR/html4/interact/forms.html#submit-format -- Denis S. Otkidach http://www.python.ru/ [ru] From stephan.diehlNOSPAM at gmx.net Fri Jan 16 10:24:30 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Fri, 16 Jan 2004 16:24:30 +0100 Subject: SimpleXMLRPCServer References: Message-ID: Maxim Khesin wrote: > whitekid wrote: > >> SimpleXMLRPCServer.py is Just Simple! >> >> A few days age. I considered XMLRPC framework for our service. >> But finally I choose WebWare. >> >> Read paper below: >> http://webware.sourceforge.net/Papers/IntroToWebware.html > > Ok, but I am interested in the XML-RPC protocotl, so how is webware > supposed to help me? Actually, Webware contains a WebKit.XMLRPCServlet class that lets you define your xml services. From sidharthk at hotmail.com Wed Jan 28 10:42:13 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Wed, 28 Jan 2004 21:12:13 +0530 Subject: isinstance() bug References: Message-ID: "Michal Vitecek" wrote in message news:mailman.907.1075296157.12720.python-list at python.org... > hello, > > please consider the following situation: > > under the current directory there's a subdirectory 'package' with two > files: __init__.py and module.py > > ./package: > __init__.py > module.py > > module.py contains: > > class A(object): > pass > > aModule = A() > > > now, let's do: > > current directory: > > >>> import package.module > >>> type(package.module.aModule) > > >>> isinstance(package.module.aModule, package.module.A) # so far good > 1 > >>> a = package.module.A() > >>> isinstance(a, package.module.A) # so far good > >>> import sys > >>> sys.path.append('package') > >>> import module > >>> a = module.A() > >>> isinstance(a, package.module.A) # will return 0 !!! > 0 > >>> isinstance(package.module.aModule, module.A) # will return 0 !!! > 0 > >>> > > how is it possible that it IS important how you imported a class > definition for isinstance() to work? it's insane! > > -- > fuf (fuf at mageo.cz) > its got to do with how python imports modules. both imports are treated as seperate modules because the relative paths are diferent. python is a dynamic language it figures out where modules are located at run time, it would be expensive to check all paths to see if they ended up at the same file. From seefeld at sympatico.ca Sun Jan 18 15:03:48 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 18 Jan 2004 15:03:48 -0500 Subject: circular dependency between class and its metaclass Message-ID: <400AE6A4.4090409@sympatico.ca> hi there, I'v run into a little problem for which I only found an ugly workaround, so I'd like to know whether people are aware of better ways to achieve this... I'm defining a class 'Class' for which I want to set up a __metaclass__ 'Type' which does some work on class variables. In particular, it should apply a function on all base classes that are themself derived from 'Class'. My first try was: ==== class Class(object): class Type(type): def __init__(cls, name, bases, dict): hierarchy = list(filter(lambda i:issubclass(i, Class), bases)) # do something with the hierarchy here __metaclass__ = Type ==== However, this fails because at the point where I want to create the 'hierarchy' variable 'Class' isn't known yet. (At what point is it actually injected into the local dict ?) Then I tried to define 'Type' after 'Class' (instead of inside it): ==== class Class(object): pass #supress details for clarity class Type(type): ... Class.__metaclass__ = Type ==== But this didn't work at all (even though I don't quite understand why). Then I tried a workaround using an auxiliary base class: ==== class Base(object): pass #supress details for clarity class Type(type): def __init__(cls, name, bases, dict): # now base the filter on 'Base' hierarchy = list(filter(lambda i:issubclass(i, Base), bases)) # do something with the hierarchy here class Class(Base): __metaclass__ = Type ... ==== though this is quite ugly, as 'Class' is the class that provides the stuff the 'Type' constructor should act on, not 'Base' (so to make the filter above work I have to do some more ugly tricks). I'd very much appreciate if anybody could shed some light on why python behaves the way it does in the two first cases, and whether there are better ways to achieve what I want. Thanks a lot ! Stefan From Kyler at news.Lairds.org Tue Jan 20 19:12:17 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Wed, 21 Jan 2004 00:12:17 GMT Subject: calling Pyrex results from C References: Message-ID: Paul Prescod graciously responded to my plea for help by gently asking if I had initialized Python. Doh! I had gotten lazy and assumed that Pyrex would take care of such details. (How could it?!) Initializing the interpreter seems to have the simple test case I made working smoothly. Now it's on to bigger and better things... Pyrex is *so* cool. Thank you, Paul! --kyler From peter at engcorp.com Thu Jan 15 11:32:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Jan 2004 11:32:28 -0500 Subject: Lua versus C++ for embedded processor References: Message-ID: <4006C09C.66B714BC@engcorp.com> (Sorry for off-topic posts...) John Benson wrote: > > Maybe Lua has a place in your embedded application, if there isn't > enough infrastructure for Python. That's something I should seriously investigate. I did consider FORTH but encountered the usual emotional block which always shows up: the language is just too "weird" for most people, and I can't saddle the company with a maintenance issue like that. It just doesn't seem feasible to expect all the developers to have to learn FORTH just to write for our embedded products. Lua, on the other hand, as I understand it, is much more traditional in flavour and (therefore?) easier to read, so it feels more likely to find a place. Thanks for the suggestion. > As for C++ on microcontrollers, I have absolutely no idea what the pros and > cons are. Any ideas out there on whether C++ is a good fit there? I believe the same pros and cons apply there as they do anywhere. Easier to handle complexity (e.g. encapsulating hardware with clean driver objects) etc, but possible impact on performance. -Peter From jcarlson at nospam.uci.edu Sat Jan 24 00:31:15 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 21:31:15 -0800 Subject: Batch commands on Windows In-Reply-To: References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: > It is a small subset, but an important subset. Shell scripting started > probably when people got sick of typing the same commands into the prompt. > For a language to really support shell scripting, it should provide a way of > automating the process of typing in the commands. As in, there should be no > difference whether you're actually typing, or you're running the script. Python is not a shell, nor scripting language. It does contain an interactive interpreter for executing Python code, and it does have support for executing programs through calling a shell, but that does not necessitate (or warrant) it having every feature for shell scripting that everyone wants. JanC makes a great point about the fact that commands are run in a subshell, and any environment changes are lost when the subshell terminates. I believe this is by design. Perhaps you should look into os.popen2 and friends. You can execute a command shell (cmd.exe or command.com), send it commands, and read its output. On Windows it is a little awkward right now, but os.popen5 is supposed to make it easy to deal with such things. Hopefully it will make it into Python 2.4. - Josiah From jcarlson at uci.edu Thu Jan 22 14:39:02 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 11:39:02 -0800 Subject: I support PEP 326 References: Message-ID: <20040122113148.BF3E.JCARLSON@uci.edu> > I've recently had a couple of cases of needing exactly what it proposes, and > having to kluge around the fact that it's not there. It's a great idea. > > If there anywhere else I should be expressing my opinion on this, let me > know. Gary, I'm glad you like my PEP. In general, many other people have found the objects to be a useful addition. Seemingly the only stalling point is where the Max/Min values are going to be placed, and what they should be called. If you feel like looking at a listing of the possible locations and names, check the previous version in cvs: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/peps/pep-0326.txt?content-type=text%2Fplain&rev=1.2 The listing was removed in the latest version because it detracted from the specific functionality, which is more important than location. If you feel like posting your exact use for the Max/Min value, that would be great. - Josiah From news at badblocks.de Sat Jan 31 08:52:45 2004 From: news at badblocks.de (Walter Haslbeck) Date: Sat, 31 Jan 2004 14:52:45 +0100 Subject: problem with weakref.proxy Message-ID: Hello, I'm a completly Python newbie. As a first learning project I want to port an game-engine I have writte some time ago in pure C to Python using OO methods. So I created a base-class 'GOb' (GameObject). This class should have a sorted list of all instances stored as as class-attribte __olist[]. When I add a reference of the new created object in the constructor (with GOb.__olist.append(self)) I have 2 references to each created instance and if I 'del' the instance the destructor is not called, because __olist[] holds another reference to that object. Now I got to tip to use the weakref module. Well I thought this should be exactly what I need and changed the program to add not a reference to the instances but a weakref.proxy. So now my instances are deleted really deleted when I use 'del', but: How do get corresponding weakref.proxy object out of __olist[]? I tried to use the callback parameter from weakref.proxy, but at the time when the callback takes place, the proxy object is allready 'dead', I get an Exception when I try to remove the proxy-instance from __olist[]: Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in ignored And if I iterate throu all objects in __olist[] I get an 'ReferenceError: weakly-referenced object no longer exists' please look at the following source: ################################################################################ import weakref class GOb: __olist=[] def c_show_all(): print "all GObs, sorted by priority:" for i in GOb.__olist: i.show() def proxy_callback(x): print "weakref.proxy callback" GOb.__olist.remove(x) proxy_callback=staticmethod(proxy_callback) c_show_all=staticmethod(c_show_all) def __init__(self, name="GOB", priority=0): self.priority=priority self.name=name ref=weakref.proxy(self, GOb.proxy_callback) GOb.__olist.append(ref) GOb.__olist.sort() def __del__(self): print "Destruktor called for GOB " + self.name def show(self): print self.name + " " + str(self.priority) def __cmp__(self, other): if self.priority < other.priority: return -1 elif self.priority == other.priority: return 0 else: return 1 if __name__ == '__main__': a=GOb("T1", 0) b=GOb("T2", 2) c=GOb("T3", 1) GOb.c_show_all() print "delete T1:" del a GOb.c_show_all() ################################################################################ any hints? Walter From Majordomo-owner at cert.org Thu Jan 29 04:56:09 2004 From: Majordomo-owner at cert.org (Majordomo-owner at cert.org) Date: Thu, 29 Jan 2004 04:56:09 -0500 Subject: Majordomo results: test Message-ID: <200401290956.i0T9uDc6015793@ioannes.indigo.cert.org> An embedded and charset-unspecified text was scrubbed... Name: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tepihlaj at NOpaju.SPAMoulu.fi Mon Jan 5 07:59:36 2004 From: tepihlaj at NOpaju.SPAMoulu.fi (Tero Pihlajakoski) Date: 5 Jan 2004 12:59:36 GMT Subject: Python/C and PYTHONPATH Message-ID: Hi, I've been experimenting on embedding Python to a C software, and ran into a little problem with PYTHONPATH (I'm running on linux). Here's the deal: When trying to call PyImport_Import("xyz"), Python returns an error "No module named xyz". The problem _seems_ to be that I had no PYTHONPATH variable defined (though python-shell works ok regardless), since the following in bash helps: PYTHONPATH= export PYTHONPATH I'm not defining anything as the PATH, and now it works. Why doesn't it look from "." without a dummy PYTHONPATH? Or is this actually a bug fixed in a newer release (running 2.3.?)? What is the "official" way to solve this? PySetProgramName()? Shell script? Thanks, - Tero -- From ketulp_baroda at yahoo.com Mon Jan 12 06:30:04 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 12 Jan 2004 03:30:04 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> Message-ID: Wilk wrote in message news:<87wu80559x.fsf at blakie.riol>... > ketulp_baroda at yahoo.com writes: > > > i am developing a web application and i am really confused on what should i use. > > should i use just python and use the cgi module availabe. > > Or should i use application like WebWare.Also there is PSP available. > > I am really confused and need help > > It depends of the kind of application you want to do exactly, there are > many possibilities from cgi to zope... > > Look into the archive of the list, you'll find a lot of answer to this > question. Or describe more what you need. > > bye hey thanks for ur reply i am developing an issue tracking system the primary requirements are 1)it should be platform independent which i think python will take care of 2)it should have customizable gui .I am thinking of using templates for this like Cheetah. Is there any other better solution to Cheetah? The problem i am facing here is i dont know what to use for development of the application. I came across many ways to develop web application in python which I already specified like i)the cgi module in python ii)Python Server Pages iii)Quixote iv)WebWare v)Zope etc. I want to choose such an environment so that i dont have to install other softwares to run my application.For eg. I think if I develop using zope then the client also has to install zope to run my software and i dont want this. From maketo at gronland.freeshell.org Mon Jan 26 00:36:17 2004 From: maketo at gronland.freeshell.org (Ognen Duzlevski) Date: Mon, 26 Jan 2004 05:36:17 +0000 (UTC) Subject: ReadDirectoryChangesW (windows) References: Message-ID: Mark Hammond wrote: >> I don't have much experience using pywin32 and I am puzzled by the last line "Must be None". Does this mean >> asynchronous access is not supported? Or am I ready to actually RTFM if someone can politely point me to one? :) > I'm afraid it is not yet supported. Patches gratefully accepted (and I > am willing to help) :) I am willing to work on this if I am pointed in the right direction :). I checked out the code in win32file.i and it suggests to look at ReadFile(). I think I can come up with something. Ognen From tzot at sil-tec.gr Thu Jan 15 09:54:32 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 15 Jan 2004 16:54:32 +0200 Subject: TUPLE & LIST References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: On Thu, 15 Jan 2004 15:08:42 +0100, in comp.lang.python you wrote: >HI, > >1) what are the differences between list and tuple? A list is a mutable (ie updatable) container for objects; you can add or remove objects as much as you like. A tuple is an immutable (ie not updatable) container, which, once created, cannot change. The general idea is that a tuple is something like a record in Pascal or a struct in C (without any named members), so the order of its contents is important. For example, the function localtime of the time module returns a tuple, whose first member is the year, second member is the month etc. OTOH, the order of some list's contents should bear no special meaning; therefore a list has methods as .sort(), .reverse() etc. Examples: Use a list for a list of names. Use a tuple for (x,y) coordinates in some area. Use a list of (name,phone,address) tuples for your poor man's address book which you will implement in python. >2) how to concatenate tuple and list? no method, no op?tor? Convert either one to the type of the other. If the final result should be a tuple, do something like: final_tuple= your_tuple + tuple(your_list) But you probably want a list, so do something like: final_list= list(your_tuple) + your_list >3) im looking the fucking manual, and cant add value in my tuple, when it >already created :/ That's the whole idea, like the FM says in http://www.python.org/doc/current/ref/types.html . A tuple cannot be changed, therefore it consumes less space than a list and can be used as a key, say, in a dictionary (unlike a list). > how to do it? # You can't, but tuples can be concatenated: >>> a = 1,2,3 >>> b = 4,5,6 >>> print a (1, 2, 3) >>> print b (4, 5, 6) >>> print a+b (1, 2, 3, 4, 5, 6) # or sliced: >>> print a[:2]+b[2:] (1, 2, 6) # or indexed >>> print "the first member of %s is %s" % (a, a[0]) HTH -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From deets_noospaam at web.de Mon Jan 26 17:07:14 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 26 Jan 2004 23:07:14 +0100 Subject: Newbie : innerproduct function from Numarray References: Message-ID: > 1) > from Numarray import innerproduct > output = [] > temp = vector1 + vector1 # temp is twice the length of vector1 > for i in range(2000): > output.append(innerproduct(temp[i:(i+2000)],vector2) > 2) > output = [] > temp = vector1 + vector1 > for i in range(2000): > sum = 0 > for j in range(2000): > sum += temp[i+j] * vector2[j] > output.append(sum) > > I thought the first method using Numarray should be faster. > But it looks like the second method is faster. > Am I doing anything wrong? > Do you guys know any faster way to do this? First of all, I assume that both results are equal :) >From the numarray-docs: ---- innerproduct(a, b) innerproduct produces the inner product of arrays a and b. It is equivalent to matrixmultiply(a, transpose(b)). ---- I'm not sure what this means mathematically (I understand the operation made, but I'm not sure what an inner product _means_). However, what you do with your hand-written code doesn't look like what I would write if I would come up with my own implementation of the aforementioned definition of innerproduct. Matrix-multiplication is O(n**3), while your code is in O(n**2). So it seems that your special-case with vectors, not arrays, produces an easier to compute variant of innerproduct - and the differenes of n-times is of course important. BTW: Its better to use xrange instead of range, it won't create the actual list of numbers, but an iterable object instead - saves memory and time :) Diez From gerrit at nl.linux.org Sun Jan 4 08:43:37 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 14:43:37 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <20040103165041.GA31412@nl.linux.org> <3FF740ED.9020909@rogers.com> Message-ID: <20040104134337.GA15231@nl.linux.org> Peter Otten wrote: > While a string is the default that you read from files and GUI widgets, a > filename will never be. I'm not so sure about that. A GUI where a file is selected from the list could very well return a Path object - it won't for a while, of course, but that's a different issue. But I agree that is often isn't. Just as an integer is not something you read from a file, etc. > So expect to replace e. g. > > os.path.exists(somestring) > > with > > os.filename(somestring).exists() > > which is slightly less compelling than somefile.exists(). I would rather read: path(somestring).exists() which is better than os.filename(somestring).exists() and, IMO, better than os.path.exists(somestring). I think path should be a builtin. > Are unicode filenames something we should care about? That's a difficult issue. I don't know how to solve that. > Should filename really be a subclass of str? I think somepath[-1] could > return the name as well. It could. But I don't think it should. This would mean that the index of a path returns the respective directories. Explicit is better than implicit: somepath[-1] is not very explicit as being a basename. > Should files and directories really be of the same class? Directories could be a subclass, with some more features. But... > These to me all seem real questions and at that point I'm not sure whether a > filename class that looks like a light wrapper around os.path (even if you > expect os.path to be implemented in terms of filename later) is the best > possible answer. ...questions exist to be answered. I don't claim to know all answers, but I think OO-ifying os.path is a good thing. How - that's another issue, which is PEP-worthy. >From earlier discussions, I get the impression that most people are sympathic about OO-ifying os.path but that people don't agree in how to do it. If we can agree on that, the only thing we need to do is upgrading the BDFL's judgement from lukewarm to liking :) I've written a Pre-PEP at: http://tinyurl.com/2578q It is very unfinished but it is a rough draft. Comments welcome. yours, Gerrit. -- 132. If the "finger is pointed" at a man's wife about another man, but she is not caught sleeping with the other man, she shall jump into the river for her husband. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From spam-trap-095 at at-andros.demon.co.uk Sun Jan 4 16:17:49 2004 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 4 Jan 2004 21:17:49 +0000 Subject: Sending e-mail with python 1.5.2 References: <7xisjrsox7.fsf@ruckus.brouhaha.com> Message-ID: <3B5VWew9LI+$EwTm@at-andros.demon.co.uk> Thanks. smtplib was what I was looking for. In article <7xisjrsox7.fsf at ruckus.brouhaha.com>, Paul Rubin writes >I thought 1.5.2 had the smtp package. If not, how about just using >popen to send the mail through /bin/mail. -- Andrew McLean From python at quixs.com Tue Jan 20 11:57:17 2004 From: python at quixs.com (Lars Heuer) Date: Tue, 20 Jan 2004 17:57:17 +0100 Subject: Please Help Me (Re: needed PyXPCOM tutorial.) In-Reply-To: <425cc8d1.0401200844.f6dcf9c@posting.google.com> References: <425cc8d1.0401150908.287de0d8@posting.google.com> <425cc8d1.0401170903.3c331ab9@posting.google.com> <425cc8d1.0401200844.f6dcf9c@posting.google.com> Message-ID: <1112279586.20040120175717@quixs.com> Hi mir, > Please help me find some tutorials on pyxpcom. my project is at hold due to it. Maybe you should begin to ask specific questions, either in this mailinglist or pyxpcom at listserv.ActiveState.com or pyxpcom at mozdev.org Maybe someone knows the answer. Here's an additional link: > http://www.mozilla.org/docs/xul/xulnotes/xulnote_oven.html and some sourcecode from the article: > http://www.mozilla.org/docs/xul/xulnotes/XUL.py.txt Best regards, Lars From mi-mal at o2.pl Fri Jan 9 09:19:51 2004 From: mi-mal at o2.pl (Mimal) Date: Fri, 09 Jan 2004 15:19:51 +0100 Subject: CGI module problem: duplicated output Message-ID: Hello, I started to learn how to use python with CGI. I went through some tutorials, but then I found one problem, that seems to be something stupid. I tried to find answer using google, but I couldn't. This is my simple CGI script: #!/usr/bin/python import cgi print "Content-type: text/html\n" print "Hello, world!" After I run it under Apache I got (HTML source code): Hello, world!Content-type: text/html Hello, world! I tried to run it under bash console. I got this: Hello, world! Content-type: text/html Hello, world! That's very strange for me. I'm using Mandrake 9.2 + Apache 2 + Python 2.3, but the same problem occurs under WinNT + Python 2.1 and WinXP + Zope + Python 2.3. Thanks in advance for help! -- Mimal From jcarlson at nospam.uci.edu Mon Jan 26 10:14:27 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 07:14:27 -0800 Subject: need something like threads, or just multiple simulateous exec's In-Reply-To: References: Message-ID: Serge A. Ribalchenko wrote: > Hi all, > > I'm new in python coding... > Can someone point me how can I do such a usual thing? I need to ping > some hosts, and harvest results in one list. Just cause there is about > 120 hosts in the LAN, and approx. 10% is down at working hours, pinging > each host at a time from cycle is VERY slow solution. > I did: > retv = os.popen('ping -c 1 ' + ip + ' |grep \"1 packet\" |awk \'{print > $4}\'') > res = retv.read() > In cycle. BUT. I need something FASTER. And I feel fear to scary word > 'thread'. May someone give me some examle using threads for this > purpose? Thanks. > > > Best wishes, > ~ Serge. > import threading import Queue import os output = Queue.Queue() def f(ip, output=output): output.put(os.popen('ping -c 1 ' + ip + ' |grep \"1 packet\" \ |awk\'{print > $4}\'') for ip in host: threading.Thread(target=f, args=(ip,)).start() for ip in host: print output.get() - Josiah From t-meyer at ihug.co.nz Tue Jan 20 20:08:20 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 21 Jan 2004 14:08:20 +1300 Subject: Installing SpamBayes In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1304BA3BE9@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677851@its-xchg4.massey.ac.nz> FWIW, you're probably better asking these questions on the spambayes mailing list - spambayes at python.org. > The instructions that came with SpamBayes says it. THey say > to either run the setup.py file in the Python GUI (IDLE) or > froma command prompt. I have tried both to no avail... You should ensure that you have an official spambayes release - download it from the sourceforge site: . The instructions (presumably README.txt) do not say anything about IDLE. Forget about using a GUI - use a command prompt. What you need to do depends on what type of command prompt that is - it seems like you're using Outlook Express, so it's probably a Windows one. In that case, you might need to specify the path to python explicitly, if it's not on the PATH. Try using this command in the command prompt (ensuring that you are in the directory that you expanded the spambayes archive into): c:\python23\python.exe setup.py install Note that this assumes that you installed Python 2.3 into C:\Python. If that's not the case, you'll need to adjust that a bit. =Tony Meyer From anthony at interlink.com.au Wed Jan 21 09:55:16 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 22 Jan 2004 01:55:16 +1100 Subject: Interfacing with Voice modem In-Reply-To: Message-ID: <20040121145516.ECB8D25ADD5@bonanza.off.ekorp.com> >>> Etienne Labuschagne wrote > Hi all, > > A callcenter-like app that we are writing in Python will need recording > functionality for voice conversations. I am thinking of doing this through > a voice modem. It's not using a voice modem, but Shtoom (shtoom.sf.net) will soon have applications for recording &c using VoIP. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From borkxorfoo at hotmail.com Tue Jan 27 04:34:42 2004 From: borkxorfoo at hotmail.com (bor) Date: Tue, 27 Jan 2004 01:34:42 -0800 Subject: Fw: How does compare work?..Of no help, but... Message-ID: of no help, so just if you hate that sort of thing... if 2 > '1' : print "greater" else : print "less_or_equal" prints less_or_equal As it should, because the condition 2>'1' is not true.. Give a machine a conditional statement that doesn't return true, followed by an else... etc Under most circumstances, python is fairly logical. In this case, too. However... class C: def __init__(self): pass X=C() if 2 > X : print "greater" prints greater Now *here* I see exactly what you're saying. I'd noticed this slight oddness too.. First example doesn't really exhibit the behaviour, but this one bothers slightly. I'm not really on top of the technical stuff about python, but I'd had all sorts of obvious thoughts about this one like could the comparison be taking an instance to have 'no' numerical value ie 'none' when using some particular comparison method? I'd be interested to know this one myself... ============================= M. Harris Sr Developer DNM, Inc. From forshtat at hotmail.com Sat Jan 31 12:18:14 2004 From: forshtat at hotmail.com (Ziv Forshtat) Date: 31 Jan 2004 09:18:14 -0800 Subject: Simple web proxy - help needed Message-ID: Hi all, I'm looking for a simple web proxy in python to use in order to demonstrate a web page classifier that I have developed. I checked around the web and tried some of the existing free servers such as the Tiny proxy server, CTC and others. The problem is that at least on my winxp machine all of these servers only seem to work with some sites but consistently generate exceptions with others. I keep getting "connection reset by peer" and "software caused connection abort"... Perahps someone has already encountered this problem and solved it?? Basically, what I need is to plug my web page classifier into a simple web proxy, so that pages pass through my classifier before they are relayed to the client. I really need to get this - or something of the sort - done as part of a university project. Another option might be in the form of an internet browser plugin that will communicate with my classifier to do the job. Problem is - I don't have to much background in writing proxies, nor in writing plugins. Any help and suggestions would be welcome. Ziv From hans at zephyrfalcon.org Sun Jan 25 19:34:57 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun, 25 Jan 2004 19:34:57 -0500 Subject: xrange not hashable - why not? In-Reply-To: <40145F20.7070402@zephyrfalcon.org> References: <20040125144724.GA13741@nl.linux.org> <40145A07.2070906@zephyrfalcon.org> <20040126001145.GB2593@unpythonic.net> <40145F20.7070402@zephyrfalcon.org> Message-ID: <401460B1.40309@zephyrfalcon.org> I wrote: > Huh. This is really weird: > > (C:\) $ python22 > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> hash(xrange) > 503376880 Um, duh... >>> hash(xrange(0)) Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From gerrit at nl.linux.org Sun Jan 25 09:47:24 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 25 Jan 2004 15:47:24 +0100 Subject: xrange not hashable - why not? Message-ID: <20040125144724.GA13741@nl.linux.org> Hi, why is an xrange object not hashable? I was trying to do something like: comments = { xrange(0, 4): "Few", xrange(4, 10): "Several", xrange(10, 100): "A lot", xrange(100, sys.maxint): "Can't count them"} for (k, v) in comments.items(): if n in k: commentaar = v break Because: - I found it easier to extend than: if 0 <= n < 4: return "few" elif ... # etc - And better readable than: if k[0] <= n < k[1]: # using tuples - And much more memory efficient than tuple(...) (especially the last one ;-) It would not be difficult to let xrange have a hash: hash((self.start, self.step, self.stop)) would be sufficient, I think. Hmm, start, step and stop appear to have disappeared in Python 2.3... certainly makes it somewhat more difficult. I shouldn't even to containment testing according to PEP 260, and Python 2.3.3 should warn me not to do... it doesn't, however. So, should I use one of the alternatives after all? Or does someone have something better to offer? yours, Gerrit. From __peter__ at web.de Mon Jan 19 12:00:59 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jan 2004 18:00:59 +0100 Subject: subclassing "file" References: Message-ID: Uwe Mayer wrote: > Hi, > > when extending a build in class, what does the constructor __init__(...) > have to return? > and how does the constructor call its base-class construtor? (or is this > done automatically?) > > I want to derive from "file" to create a class that reads record from a > binary file: > > class myFile(file): > def __init__(self, filename, mode="r", bufsize=-1): > ....?... > > just calling the basename and the constructor does not work: > >>>> f = myFile("testfile") >>>> f > ', mode '' at ...> > > What am I missing? > > Thanks for your comments > Ciao > Uwe When you don't want to do anything in the constructor __init__(), it suffices to override the methods of interest, e. g.: >>> class myfile(file): ... def write(self, s): ... file.write(self, s.upper()) ... >>> f = myfile("tmp.txt", "w") >>> f.write("a foolish consciousness") >>> f.close() >>> file("tmp.txt").read() 'A FOOLISH CONSCIOUSNESS' Otherwise call base.__init__(self, someargs), e. g: From ATPL_SMTP_Gateway at ggn.aithent.com Fri Jan 30 04:48:02 2004 From: ATPL_SMTP_Gateway at ggn.aithent.com (ATPL_SMTP_Gateway at ggn.aithent.com) Date: 30 Jan 2004 15:18:02 +0530 Subject: Content violation Message-ID: This is an automated response. Content violation found in email message. Email Message Dropped. From: python-list at python.org To: shaveenk at ggn.aithent.com File(s): test.exe Matching filename: *.exe From noemail at noemail4u.com Fri Jan 9 07:03:16 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 09 Jan 2004 12:03:16 GMT Subject: os.system always opens new window on Windows XP/2000 References: Message-ID: <787bf9d383653f297a4d86a6dad2733e@news.teranews.com> On 6 Jan 2004 10:45:59 -0800, ohgoddearlord at yahoo.com (John) wrote: >Can anyone tell me how to run a bunch of commands in the same command >line window? When I do this: > >system("command1") >system("command2") >... > >it opens a new window for every system call. The alternative I can >think of is to write out the command to a batch file and run that, but >I'm wondering if there is a better way to do it. I would recommend reading a little more about the os, shutil, and system modules and doing it all in Python. I would especially advise you to do that if you're seriously considering a batch file instead. Unless you're going to have people without Python run the same batch file, you may as well build your script in Python, which is something it is touted for being good at. --dang From jjl at pobox.com Thu Jan 15 08:51:48 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 13:51:48 +0000 Subject: best book References: <38ec68a6.0401141946.70fa3aa5@posting.google.com> Message-ID: <87zncp9v63.fsf@pobox.com> afriere at yahoo.co.uk (Asun Friere) writes: > Terry Carroll wrote in message news:... > > On Thu, 15 Jan 2004 03:32:31 +0530, km wrote: > > > My favorite to start is O'Reilley's "Learning Python." > > > > Try to borrow it, rather than buy it, though, or at least buy a used copy. > > > The problem with that is that a used or borrowed copy is unlikely to > be the (new) 2nd edition, (see > http://www.oreilly.com/catalog/lpython2/) which covers up to Python > 2.3. (The older version is badly outdated). Besides which, if you > actually buy a copy they might consider a 3rd edition at some time in > the future. You can subscribe to safari.oreilly.com for 2 weeks, then cancel and pay nothing. John From skip at pobox.com Mon Jan 26 15:46:45 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 26 Jan 2004 14:46:45 -0600 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <090801c3e44b$1b434760$6401fea9@YODA> References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> <16405.30020.406117.575663@montanaro.dyndns.org> <090801c3e44b$1b434760$6401fea9@YODA> Message-ID: <16405.31925.108832.399438@montanaro.dyndns.org> Dave> Skip wrote: >> Pardon me, but I don't want "a regular guy" in this particular position. I >> want the god damned smartest, most capable person we can find. Dave> The real problem is that these days there's no way the smartest, Dave> most capable person would ever run for public office. Yeah, I know. I just needed to get that off my chest. Skip From peter at engcorp.com Mon Jan 12 09:37:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 09:37:51 -0500 Subject: Straw poll on Python performance (was Re: Python is far froma top performer ...) References: Message-ID: <4002B13F.131CD509@engcorp.com> "Michael T. Babcock" wrote: > > >From: "Peter Hansen" > > > >I have to say that I do, but I'm also dealing with datasets up to about > >500MB in the worst case - but about 10-20MB in the normal case. Please edit your attributions more carefully. I did not write the above; "Tim Delaney" wrote it. -Peter From exarkun at intarweb.us Mon Jan 19 23:29:24 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 19 Jan 2004 23:29:24 -0500 Subject: speedy Python strings? In-Reply-To: <100p9kl96uri9e1@corp.supernews.com> References: <100p9kl96uri9e1@corp.supernews.com> Message-ID: <20040120042924.GB5184@intarweb.us> On Mon, Jan 19, 2004 at 10:53:47PM -0500, Francis Avila wrote: > Stuart D. Gathman wrote in message ... > ># text = struct.unpack("L", self.buffer[:4]) > ># self.buffer = self.buffer[4:] > > pos = self.pos > > text = struct.unpack("L", self.buffer[pos:pos+4]) > > self.pos = pos + 4 > > > In this vein, I would also recommend looking at the array module. You > didn't describe the data structure, but if each record is simply a list of > 4-byte integers, you could convert the whole record to ints at once like so: > > record = array.array('L', stringorlist) > Then, perform your loops on record, which will be a list-like object > supporting item insertion and deletion, and conversion to bytestrings and > other Python base types. > Also note the existence of fromfile() - the array module actually makes it possible to do this incredibly efficiently: a = array.array('L') a.fromfile(openFileObj, count) Jp From fumanchu at amor.org Fri Jan 9 17:34:58 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 9 Jan 2004 14:34:58 -0800 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) Message-ID: > Do you spend a "significant" amount of time actually > optimizing your Python applications? (Significant is > here defined as "more than five percent of your time", > which is for example two hours a week in a 40-hour > work week.) No, I don't. The big object server I'm working on now for four months (which actually *has* some performance requirements) has had _one_ optimization round. I noticed some slowness, profiled the problem down to the DB layer, and solved it by switching my ADO recordset to read-only. That cut the load time of objects to 1/3 of what it was before the optimization. All the other operations to get that data laid out on a web page were insignificant in comparison. Generally, I tend to "worry" far more about interface design (for both users and developers) than performance. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mark at mceahern.com Fri Jan 30 09:25:49 2004 From: mark at mceahern.com (Mark McEahern) Date: Fri, 30 Jan 2004 08:25:49 -0600 Subject: conditional expression sought In-Reply-To: References: Message-ID: <401A696D.50906@mceahern.com> Elaine Jackson wrote: >Sorry to take so long but I wasn't sure what a "unit test" was (the other guy's >post clarified it). Tell me if this isn't what you're looking for: > >falsies=[0,0.0,[],(),{},'',None] >truies=[49,3.14,[1,2,3],(4,5,6),{7:8,9:10},'nonempty'] > >def demo(A,B): > print "If A is ",A > print "and B is ",B > print "then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = ", > print (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) > >A=[] >from random import randint >for i in range(3): > A.append(bool(randint(0,1))) >B=truies[0:3] >demo(A,B) > >A=[False,False,False] >B=falsies[0:3] >demo(A,B) >print "I would have liked this to be B[2] = ",B[2] > > Try this: def whatever(A, B): """I don't know what to call this function because it doesn't really make sense to me, but, whatever...""" c = zip(A, B) last = len(c) - 1 for i, item in enumerate(c): a, b = item # If both items are true, return b. if a and b: return b # If we're at the last item, return b. if i == last: return b print whatever(A, B) import unittest class test(unittest.TestCase): def testAllFalse(self): A = [False, False, False] B = [0, 0.0, []] expected = [] actual = whatever(A, B) self.assertEquals(actual, expected) def testSomeTrue(self): A = [0, 1, 0, 1, 0, 1] B = ['a', 'b', 'c', 'd', 'e', 'f'] expected = 'b' actual = whatever(A, B) self.assertEquals(actual, expected) unittest.main() From mark at diversiform.com Wed Jan 28 12:22:45 2004 From: mark at diversiform.com (mark) Date: Wed, 28 Jan 2004 09:22:45 -0800 Subject: Curious string behavior Message-ID: <000001c3e5c3$5a63a8d0$5501a8c0@markxp> I've encountered an anomaly while using the string module (specifically, string.split). Here's the snippet: import string address2 = ' ' line = 'function, dealer, type, firstname, lastname, vin, blank' print 'Address2 Type (first check): ', type(address2) function, dealer, type, firstname, lastname, vin, blank = string.split(line, ',') print 'Address2 type (second check): ', type(address2) I've extracted this from a larger script, but the error happens roughly the same way. Now, here's what I would expect to see: Address2 Type (first check): Address2 type (second check): Here's what I get instead: Address2 Type (first check): Address2 type (second check): Traceback (most recent call last): File "C:\PROGRA~1\Python\lib\site-packages\Pythonwin\pywin\framework\scriptut ils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Program Files\Python\test1.py", line 7, in ? print 'Address2 type (second check): ', type(address2) TypeError: 'str' object is not callable What the heck is going on here? I figure I'm just missing something. - Mark Daley Product Manager Diversiform, Inc. 1-800-444-3445 -------------- next part -------------- An HTML attachment was scrubbed... URL: From Florian.Lindner at xgm.de Fri Jan 30 12:11:12 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Fri, 30 Jan 2004 18:11:12 +0100 Subject: HowTo Search in nested lists Message-ID: Hello, I've two nested lists which are representing a table or matrix. A = [1, 2, 3] B = [4, 5, 6] C = [7, 8, 9] t = [A, B, C] print t[0][2] # Prints 3 Now I found to search for certain values in a certain column. For example: column 1, search for 5, return 1, because 5 is found in the first column of the second element of t I hope I could explain what I want. Is there any way to do that except: for i in len(t): if t[i][1] == "phrase": found = i break Thx, Florian From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jan 16 04:36:44 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 16 Jan 2004 10:36:44 +0100 Subject: Quick question..... In-Reply-To: References: <379178f1.0401151634.556bb405@posting.google.com> Message-ID: <4007b0ac$0$322$e4fe514c@news.xs4all.nl> David M. Cooke wrote: > At some point, featherstone80 at hotmail.com (Narsil) wrote: >>NameError: global name 'sum' is not defined >> >>What did I do wrong? > > > 'sum' as a builtin was introduced in python 2.3. You're using an older > version. > If you don't have sum, try: reduce(lambda x,y: x+y, numberlist) instead. --Irmen From max at alcyone.com Sat Jan 10 05:02:48 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jan 2004 02:02:48 -0800 Subject: end of a pickle file References: Message-ID: <3FFFCDC8.C4F361AF@alcyone.com> Elaine Jackson wrote: > How can I tell when I've gotten to the end of a pickle file? TIA Try reading another object and getting the EOF error :-). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Punctuality is the virtue of the bored. -- Evelyn Waugh From yshurik at fhb.kiev.ua Sat Jan 17 06:27:59 2004 From: yshurik at fhb.kiev.ua (yshurik) Date: Sat, 17 Jan 2004 13:27:59 +0200 Subject: Best Python IDE Code Completion! References: Message-ID: John wrote: > Hi, > Could you give your opinions on the best code completion in Python > IDEs. My only complaint with PythonWin has been that the code > completion support is incomplete. The interactive mode has better > behavior than the editor. Tried to fix it but could not. Boa is not > too different. At least when I last checked (a few months ago) Komodo > and Visual Python were not very different either. > > Wing IDE seems converse. The editor auto list members is great but > has no calltips. The interactive window has no completion at all. > > I have not checked PythonWorks and Black Adder in a while but their > web sites do not seem to brag much in this direction. About BlackAdder: because it is oriented to GUI programming. in version 1.1 it will have completion for Qt classes and functions. and completion to all words which happens in edited text. (it is Vi - like style of completion - Ctrl-N, Ctrl-P) > > Python has great introspective capabilities and we have a great open > contributing community. What technical difficulties keep us from > having REAL code completion like MS, Borland and several Java IDEs > (All of which have been funded at one time or the other if not > entirely - perhaps this is the reason?) > > For me, code completion is a very important part of the coding > experience and I really miss it in Python in it's full effect. -- Best regards From rmkrauter at yahoo.com Sun Jan 25 22:37:19 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sun, 25 Jan 2004 22:37:19 -0500 Subject: efficient updating of nested dictionaries In-Reply-To: References: Message-ID: <1075088239.15570.15.camel@vaio> The following is probably too dependent on the data type of the keys, but it may be suitable in some programs. It's certainly not a general solution for all cases. Others will have much better ideas, but here goes anyway ... You may want to use a non-nested dict with a 'superkey' composed of the concatenation of the three keys, seperated by some delimiter. use MY_DICT[KEY_X+'_'+KEY_Y+'_'+KEY_Z]=FOO Then you could use update().You would just have to do some pre- and post-processing of the keys. i.e. splitting or joining the 'superkey' by the delimiter you choose. Although, that's probably kind of lame - I bet others will have much better suggestions. I'm interested in how other people do this too. Rich On Sun, 2004-01-25 at 21:33, omission9 wrote: > I have a dictionary that looks like this > MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO > > I am having a problem updating this with a simple > MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting > into the inner dicts. > Getting the keys of each and iterating through and updating each one is > terribly slow as the number of keys gets bigger and bigger. > What is the bst way to update my nested dicts? > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From francisgavila at yahoo.com Tue Jan 13 17:37:39 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 13 Jan 2004 17:37:39 -0500 Subject: how can I execute a function string References: Message-ID: <1008srnl5kni5c4@corp.supernews.com> Premshree Pillai wrote in message ... >You need to use eval() to run code on-the-fly. See >http://www.python.org/doc/current/lib/built-in-funcs.html Eval only evaluates expressions, not statements. A function definition is a statement. (Think about it: what would eval() return?) -- Francis Avila From donn at drizzle.com Wed Jan 7 01:08:35 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 07 Jan 2004 06:08:35 -0000 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module References: None Message-ID: <1073455713.389751@yasure> Quoth Michael Chermside : | Peter writes: |> There's a new PEP available: |> |> PEP 324: popen5 - New POSIX process module |> |> A copy is included below. Comments are appreciated. ... | And I vote +1 on changing the name from "popen5" to something else. | "process" (as suggested in the PEP) isn't too bad, but I'd certainly be | open to another name. If this is to replace the entire rest of the popenX | family for most normal purposes, a separate, more comprehensible name | will help newbies find it. "process" is not only ambiguous, it's a little off-target if the software in question is more about executing foreign commands, as opposed to process management in general. So I'd be open to another name, too. Donn Cave, donn at drizzle.com From ferrell at diablotech.com Wed Jan 21 13:13:40 2004 From: ferrell at diablotech.com (Robert Ferrell) Date: 21 Jan 2004 10:13:40 -0800 Subject: Redefining __call__ in an instance References: <73b00f0c.0401151529.676347b6@posting.google.com> Message-ID: <73b00f0c.0401211013.29b5718a@posting.google.com> Jason Mobarak wrote in message news:... > def firstFunc (s, word='up'): > print "foo" > > class callNoWork(object): > def __new__ (cls): > cls.__call__ = firstFunc > return object.__new__(cls) > > callNoWork()() > > # Dunno if you've read this, but it explains this: > # http://python.org/2.2.1/descrintro.html Thanks for the pointer. I had read this a while ago, it didn't all sink in, and I'd forgotten about it. That was exactly the info that I needed. In particular, it says that __call__ is a static method, so it is not possible to define that differently for each instance. The code above was a good reminder for me, but because __call__ is a static method, any new instantiation redefines __call__ for all existing instances. Thanks for the pointer, -robert From elainejackson7355 at home.com Thu Jan 29 20:06:55 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 30 Jan 2004 01:06:55 GMT Subject: conditional expression sought References: Message-ID: Sorry to take so long but I wasn't sure what a "unit test" was (the other guy's post clarified it). Tell me if this isn't what you're looking for: falsies=[0,0.0,[],(),{},'',None] truies=[49,3.14,[1,2,3],(4,5,6),{7:8,9:10},'nonempty'] def demo(A,B): print "If A is ",A print "and B is ",B print "then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = ", print (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) A=[] from random import randint for i in range(3): A.append(bool(randint(0,1))) B=truies[0:3] demo(A,B) A=[False,False,False] B=falsies[0:3] demo(A,B) print "I would have liked this to be B[2] = ",B[2] "Mark McEahern" wrote in message news:mailman.1000.1075402284.12720.python-list at python.org... | Elaine Jackson wrote: | | >If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, | >then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without | >evaluating any other B_i. This is such a useful mode of expression that I would | >like to be able to use something similar even when there is an i with | >bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) | >or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious | >reasons. Does anybody know a good way to express this? Any help will be mucho | >appreciado. | > | Why not write a unit test that demonstrates the behavior you want? | It'll then likely be obvious to someone both what your problem is and | what a likely solution is. | | Cheers, | | // m | From theller at python.net Thu Jan 29 09:22:01 2004 From: theller at python.net (Thomas Heller) Date: Thu, 29 Jan 2004 15:22:01 +0100 Subject: Printing From Python References: <8089854e.0401290555.501f0695@posting.google.com> Message-ID: <7jzahm2e.fsf@python.net> michael at foord.net (Fuzzyman) writes: > I looked through the manual, I looked on the web and could find very > little on this subject.... > > The closest I could find was : > http://www.faqts.com/knowledge_base/view.phtml/aid/4549. > > Saying that printing (to a printer :-) wasn't easy (at least on > windows - let alone *cross* platform) - and that was dated 2000. > > Oh and - http://mail.python.org/pipermail/python-list/2002-September/121462.html > from 2002 giving two different methods for Unix and Windows... the > windows one doesn't work across our network........ Although I am connected to a network printer, I have no problems opening lpt1:, write some data to it, and the printer prints it: C:\>net use Neue Verbindungen werden gespeichert. Status Lokal Remote Netzwerk ------------------------------------------------------------------------------- [...] Getrennt LPT1 \\server\lexmarkps Microsoft Windows-Netzwerk Der Befehl wurde erfolgreich ausgef?hrt. C:\>copy con: lpt1: hello, world ^Z 1 Datei(en) kopiert. C:\> Another thing that comes to mind is something like 'notepad /p x.txt'. If you want to print other things than simple text files, it gets more complicated IMO. Thomas From marco at bubke.de Wed Jan 21 13:13:01 2004 From: marco at bubke.de (Marco Bubke) Date: Wed, 21 Jan 2004 19:13:01 +0100 Subject: Numarray und NA_NewAll References: Message-ID: Sorry, little stupid bug is in the it. It must be tUInt8. From richardshea at fastmail.fm Tue Jan 13 06:15:48 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 13 Jan 2004 03:15:48 -0800 Subject: Accessing "GIS (ESRI shape file)" files from Python ? References: <282f826a.0401121907.498543e6@posting.google.com> Message-ID: <282f826a.0401130315.5b92b2aa@posting.google.com> That's great - thanks very much just downloading Thuban now. thanks again. richard shea. From db3l at fitlinxx.com Thu Jan 22 13:51:47 2004 From: db3l at fitlinxx.com (David Bolen) Date: 22 Jan 2004 13:51:47 -0500 Subject: Looking for advice: supporting multiple embedded interpreters References: Message-ID: Paul Miller writes: > What I am wondering is if there a reliable method in 2.3 that does > what I need? > > It has recently come to my attention that Lutz Paelike is in exactly > the same situation I am in, so I don't think this is a fringe concept. I can't address why it doesn't work in 2.3, but just a question - have you thought of not using independent interpreter states, but just tracking the contents of sys.modules and clearing out any new modules at reload time? That would force even nested imports to be reloaded. You can find an example of doing this in the unittestgui.py module, for example, that is part of PyUnit, as it uses this approach to ensure that all modules under test are reloaded at the start of execution of a test suite. I expect that you might be able to get even fancier by installing a custom import hook, but just flushing sys.modules is pretty simple and should work in any Python release. Of course, it won't deal with stray references you may still have around to the old module or module objects, but since the new interpreter approach definitely can't be exhibiting that behavior anyway, I expect you aren't using any older objects after such a reload. -- David From poyol at hotmail.com Mon Jan 19 09:15:50 2004 From: poyol at hotmail.com (OPQ) Date: 19 Jan 2004 06:15:50 -0800 Subject: py2exe 0.5.0 (finally) released References: Message-ID: Thomas Heller wrote in message news:... > **py2exe 0.5.0** (finally) released > py2exe is a Python distutils extension which converts python scripts > into executable windows programs, able to run without requiring a > python installation. > > Enjoy, > > Thomas Great ! Works flawlessly for me. The ptyhoncom support is much better for me. Sometimes, in the past, py2exe would forget to include (because of me) some pythoncom.dll. Not anymore. But anyway, there is a little annoying point: in the past (0.4.x), while compiling, py2exe would turn all necessary files to pyc or pyo in-place And then, after 1 compilation step, it wouldn't do it anymore, but just for the file which have changed. Now, since it put all the file in the zip archive, It won't generate .pyo files in-place, but only in the archive. And thus, each time I compile py application, I see that py2exe bye-compile stuff that didn't change, but do not exists in .pyo. I may be wrong in my analyse, but that's how I see it. Other stuff: for the same EXE, I have (totally arbitrary number) 8.6 Mb of data with py2exe 0.4 11.7 M with 0.5 (zipfile activated) Try to explain that ! Anyway, great stuff, great samples to ---OPQ From zunbeltz at wm.lc.ehu.es.XXX Mon Jan 26 04:20:06 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 26 Jan 2004 10:20:06 +0100 Subject: unittest Message-ID: Hi, I am using unittest for the first time. I have read chapter 7 of dive into pyhton (Unit Test). I have the following code from spacegroup import * import pygroups.misc.matrix as matrix import unittest class KnowValues(unittest.TestCase): KnownRotationMatrices = [ ((Rotational3Part([[-1,0,0],[0,1,0],[0,0,-1]])), (1, -1, 2, matrix.vector([0,1,0]))) ] def TestRotationalPartdeterminant(self): """ RotationalPart. determinant with known values.""" for i in self.KnownRotationMatrices: det = i[0].determinant() self.assertEqual(det,i[1][0]) if __name__ == "__main__": unittest.main() but when i run this scrip i get the following output ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Why the test didn't run? any idea? TIA Zunbeltz From max at alcyone.com Mon Jan 12 14:45:01 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 12 Jan 2004 11:45:01 -0800 Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> Message-ID: <4002F93D.298A2394@alcyone.com> "David M. Cooke" wrote: > In which case he's probably better off with his original format > (almost): > > cmd = '"$executable" -start "$startTime" -end "$endTime" -dir \ > "$directory"' > os.environ['executable'] = 'blah' > os.environ['startTime'] = '12' > os.environ['endTime'] = '18' > os.environ['directory'] = './' > os.system(cmd) This doesn't resolve the underlying possibility for mailicious people in control of the contents of those variables to get it to execute arbitrary shell code. (In his case he says it isn't an issue, but still.) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ It was involuntary. They sank my boat. -- John F. Kennedy (on how he became a war hero) From pln at razzle.Stanford.EDU Tue Jan 6 00:51:08 2004 From: pln at razzle.Stanford.EDU (Patrick L. Nolan) Date: Tue, 6 Jan 2004 05:51:08 +0000 (UTC) Subject: Grab input&output of program on Windows References: Message-ID: Tero Pihlajakoski wrote: > Patrick L. Nolan wrote: >> I'm going nuts trying to port an application from Linux >> to Windows. We have a python/Tkinter script which runs >> a C++ application. It starts it with popen4 and >> communicates through the two pipes. It reads text output >> from stdout until a prompt appears, then sends commands >> through stdin. > Sorry, if this is basic, but: Did you flush() after write()? Try using > popen2() (there was something about popen4() on win32...), if possible > (import popen2, etc.)? Thanks. I skimped on the details to avoid scaring off potential readers. Yes, I did try flushing the streams. I'm using win32pipe.popen4() on windows and popen2.popen4() on linux. Win32pipe is supposed to be the one that works.... -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From tchur at optushome.com.au Fri Jan 9 20:47:50 2004 From: tchur at optushome.com.au (Tim Churches) Date: 10 Jan 2004 12:47:50 +1100 Subject: Databases: Which one's right for me? In-Reply-To: <4378fa6f.0401091717.1ae63541@posting.google.com> References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: <1073699270.1186.121.camel@emilio> On Sat, 2004-01-10 at 12:17, Marc wrote: > Hi all, > > Having never used a database before and immersing myself in reading > stuff about databases over the last two days I have come to this > conclusion, I still don't know which one I need. I've been using > Python for a while, storing things that I'll need later in files. I am > now looking for a better solution; ergo the need for a database. > > Basically I need a db that will travel with my executable script and > faithfully store and edit the data needed in that script. People using > this script will need to be stand alone users. Having a client/server > arrangement is not possible over a network. You know about pickling, don't you, specifically cPickle. If not, investigate that first. > Also, installing some type of db engine outside of Python is also not > possible. This rules out installing such readily available databases > as mySQL or any other type of db that must have a separate install. > Everything must be contained within the Python executable package. > However, all of the users WILL have MS Access already installed. So > that is a good possibility, and I have already played around with DAO > and run a couple of scripts with it. ... > So from reading I've narrowed it down to two possibilities - MS Access > with DAO and Gadfly. What I can't get from reading is experience or > someone who has done this type of thing before and already knows which > one will work best based on what I need to do. Or, if there exists > another solution other than the two I mentioned, please throw that out > there because it's almost impossible to completely examine every > possibility out there. All suggestions are helpful. Look at the support for the various flavours of the BSD database which are part of the standard Python library, and also the shelve interface to those databases. Also look at PySQLite (see http://pysqlite.sourceforge.net/ ) and MetaKit (http://www.equi4.com/metakit/python.html). -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From tim.one at comcast.net Thu Jan 1 00:07:47 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 1 Jan 2004 00:07:47 -0500 Subject: fatal error: GC object already tracked In-Reply-To: Message-ID: [Vikram] > i have a program which uses multiple threads and downloads pages using > pycurl and processes these pages among other things. the program works > fine with python 2.2 and pycurl 7.10.8 ; > > with python 2.3 i get two kinds of errors maybe related? a) python > dumps core and prints out "Fatal Python error: GC object already > tracked" That error check is new in 2.3, but a program trying to track a GC object that's already been tracked has always been breaking the rules. Because that's a very low-level problem with C code, you may or may not see an immediate problem as a consequence of breaking the rules. A segfault is one possible bad consequece; arbitrary memory corruption is another; no obvious problem at all is a third. Luck of the draw. I'm not familiar with pycurl, but if any of it is written in C, the root cause is almost certainly that pycurl is using the Python C API incorrectly. > b) the program just waits at update_refs() function inside > the python GC code path and doesn't append anything to the logs nor > perform any activity. update_refs() is a very simple function, and the only way I can see for it to get stuck is if somebody is mucking with Python objects in another thread while cyclic gc is running. The other thread would be in error then, as the global interpreter lock is always held by the thread running cyclic gc when cyclic gc is running, and it's strictly forbidden (but, alas, impossible to *enforce* at the C level) for any thread to do anything with Python objects when it doesn't hold the GIL. This symptom is one that's never been reported before, but is consistent with the theory that pycurl is using the Python C API incorrectly. > any idea why or suggestions ? > > Vikram > > ps: the Fatal Python error: GC object already tracked" error seems to > be an open bug filed by someone else in october 2003. I figure you mean this: http://www.python.org/sf/816476 Since that was also reported against pycurl, nothing else like it has ever been reported, and there's been no followup from the OP in 3 months, I just closed that as "presumed 3rd party". Your best bet is to take it up with the pycurl folks, since the evidence points at pycurl. From mday at apple.com Tue Jan 27 18:31:50 2004 From: mday at apple.com (Mark Day) Date: Tue, 27 Jan 2004 15:31:50 -0800 Subject: map float string '0.0' puzzle References: Message-ID: <270120041531508319%mday@apple.com> In article , j vickroy wrote: > >>> row = ('0.0', '1.0', None) > >>> map(lambda setting: setting and float(setting) or None, row) > [None, 1.0, None] > >>> map(lambda setting: setting and (setting,float(setting)) or > (setting,None), row) > [('0.0', 0.0), ('1.0', 1.0), (None, None)] > >>> > > Specifically, why is the return value of the first map operation: > [None, 1.0, None] Break it down into something simpler so you can see what's going on. Let's see what that lambda is evaluating to when setting is '0.0': >>> '0.0' and float('0.0') or None >>> print '0.0' and float('0.0') or None None That expression evaluates as: ('0.0' and float('0.0')) or None which means ('0.0' and float('0.0')) must be false. >>> '0.0' and float('0.0') 0.0 Now you see that the expression reduces to: 0.0 or None The key is that 0.0 is considered false: >>> bool(0.0) False >>> print 0.0 or None None which means the expression reduced to the equivalent of: False or None and so you get None as the result. Hope that helps. -Mark From ykingma at accessforall.nl Wed Jan 21 03:19:59 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Wed, 21 Jan 2004 09:19:59 +0100 Subject: Weaver/Yarn Pattern in Python References: Message-ID: <400e362f$0$322$e4fe514c@news.xs4all.nl> Christian Stork wrote: > Hello everybody, > > I am using Python to prototype a compression algorithm for tree-shaped > data, e.g., XML data or abstract syntax trees. I use a variant of the > visitor design pattern--called weaver/yarn pattern--in order to > traverse the tree that is being compressed or decompressed. I do not > know of any other interesting application of the weaver/yarn pattern, > but it seems like a very suitable subject of study for different > implementation strategies. Essentially, I am asking for input on my > design decisions. > > First, let me give you a simple example of the traditional visitor > pattern. The following diagram illustrates a depth-first traversal of > a mini tree by a visitor. The basic idea is that the tree accepts a > visitor and helps it to do a kind of type-dispatch based on the kind > of nodes. > ... > > The advantage of this ping-pong between the tree and visitor v is that > v encapsulates related processing instructions. Several different > visitors can be maintained independently of each other and without > forcing changes to the tree node classes. The tree nodes only need to > provide a node.accept(visitor) method. Type-checking can ensure > the match between the visitor and the tree data structure. > > Normally, visitors encapsulate different processing passes, which are > run one after the other, each time traversing the whole tree. I have > implemented the compression of trees as several (sub)visitors c1..cN > even though they could have been implemented as one big visitor. > Besides the easy recombinability of visitors this has the added > advantage that I can use the same visitors for compression and > decompression where this is appropriate. > > But now I have a problem when decompressing. In order to run one > visitor after another the first one expects to traverse the whole > tree. But this is impossible in case of a decompressor. It lies in > the very nature of the application that the tree is being constructed > while the visitors work on it. Conceptually the solution is easy. > The decompression subvisitors d1..dM have to process the partially > available tree upto the point of traversal where it is available. At > each node execution has to iterate over the applicable code of d1..dM > in the given order. This necessitates a decomposition of visitors > into something that we call yarns and these yarns are weaved by one > visitor, which we call the weaver. Thus the name "Weaver/Yarn > Pattern" for this variation of the visitor pattern. > > The following exemplifies my current implementation of the w/y pattern > for a recursive descent (ie depth-first traversal) visitor. For each > (sub)visitor d1..dM the former d.visitX(x) method is divided into > several y.weaveX_...() methods. At entry and exit the weaver invokes > y.weaveX_First() and y.weaveX_Last(). Each descent into a child is > surrounded by y.weaveX_Before(kidno) and y.weaveX_After(kidno) method > calls. > ... > > By now it should be obvious that the boilerplate for this approach > becomes quite extensive and it would be desirable to reduce it. To > mitigate the problem I did three things: > > - Automatically generate templates for yarn classes. The actual code > can be filled in. Disadvantage: No convenient way to deal with > changes to the tree data structure. > > - The node.accept(weaver) methods are changed to call a "generic" > weaver.weave(node) method (instead of weaver.visitX(node)), which > hackishly constructs all the calls to the yarns by assembling the > method names from the __class__.__name__ and one of "First", "Last", > "Before", and "After". > > This solution does pretty much what I want: > > - Writing selected yarn methods allows me to express with little > overhead /what/ code to execute /when/ in the weaving process. > > - Once the weaver/yarn interaction machinery is set up correctly, the > debugger points me to real code in case of bugs. This is an > advantage over approaches that create classes at runtime, e.g., use > of metaclasses or the "new" module. > > OTOH, I'm not perfectly happy with this solution since it's totally > "hackish". For example, I have to use a function, hand-written > specifially for this purpose, in order to "type-check" the > correspondence of the tree types and the yarns. > ... Have a look at aspect oriented programming: http://www.ccs.neu.edu/home/lieber/AOP.html In theory it sounds like a good match for what you need. I don't know how well Python supports this, perhaps you can use a metaclass for this, but I'm not sure. Have fun, Ype -- email at xs4all.nl From yshurik at fhb.kiev.ua Sat Jan 17 05:47:57 2004 From: yshurik at fhb.kiev.ua (yshurik) Date: Sat, 17 Jan 2004 12:47:57 +0200 Subject: QT usage confusion References: <40069912$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: Guyon Mor?e wrote: > hmmm, all this time that I am fooling around with python I never took a > good look at (py)QT. > I want to have a go at it, after being a bit disapointed about the > alternatives. > > I have read multiple docs about it and searched this newsgroup I came to > the conclusion that, as I am a windows user, I have only 2 options: > > - buy a commercial qt license > - try it out for 30 days (!) > > that sucks ;) You can try demo version of BlackAdder which provide demo version of PyQt. If you will need to create commercial apps, then BlackAdder with PyQt costs about $400 (Qt costs more than 1k how i remember) > > am I wrong? > please tell me I'm wrong. -- Best regards From okyoon at stanford.edu Mon Jan 26 16:29:25 2004 From: okyoon at stanford.edu (Ohkyu Yoon) Date: Mon, 26 Jan 2004 13:29:25 -0800 Subject: Newbie : innerproduct function from Numarray Message-ID: I have two vectors that have about 2000 elements. I need to calculate the innerproducts of those vectors 2000 times where one of them cycles left(ie 1234, then 2341, then 3412, etc) Basically, I want to calculate A*x, where A is a left-circulant cyclic matrix, and x is a vector. I tried it two ways. vector1 & vector2 are lists. 1) from Numarray import innerproduct output = [] temp = vector1 + vector1 # temp is twice the length of vector1 for i in range(2000): output.append(innerproduct(temp[i:(i+2000)],vector2) 2) output = [] temp = vector1 + vector1 for i in range(2000): sum = 0 for j in range(2000): sum += temp[i+j] * vector2[j] output.append(sum) I thought the first method using Numarray should be faster. But it looks like the second method is faster. Am I doing anything wrong? Do you guys know any faster way to do this? Thank you. From oliver.schoenborn at utoronto.ca Fri Jan 16 16:46:25 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Fri, 16 Jan 2004 16:46:25 -0500 Subject: Lazy cascading menu in Tkinter with postcommand Message-ID: Hi folks, here's a challenge: I have a dynamically created cascading menu in Tkinter that can be quite large because it is created from a file. I tried using lazy creation so only the menu item that is actually selected by the user gets children menu items created under it, but that fails. I did this by use of postcommand callback, in which I dynamically add the children menu items to the parent. However, a print statement in the postcommand callback shows that: 1) *ALL* cascading menu items in a hierarchy get the postcommand event, every time the user selects the top menu item 2) all children that have just been added to a cascading menu item in the postcommand callback will hear that postcommand event So in the end, the first time the user clicks on the top menu item, the whole menu hierarchy gets created (though only the top level is displayed of course). Anyone know how to get around this? I'm considering bypassing the built-in cascading menu and creating my own via popup menus and filtering for "on entry" of the buttons, but there should be a simpler method. Thanks in advance for any help, Oliver From zorlord at zorlord.karoo.co.uk Mon Jan 5 20:53:12 2004 From: zorlord at zorlord.karoo.co.uk (greg) Date: Tue, 6 Jan 2004 01:53:12 -0000 Subject: Probles parsing a text file Message-ID: heres my text file(well the first two lines of it) ######################################### # Default BMUS server CFG file # this file is written with the following code fi = open('bmus.cfg', 'w') print 'file opened' cfg = [] cfg.append('#########################################\n') cfg.append('# Default BMUS server CFG file #\n') fi.writelines(cfg) i heres the script that im using to parse the file fi = open('bmus.cfg', 'r') if fi: print('Reading Server CFG file') ll = fi.readlines() for line in ll: print(str(line)) if line[:2] == '#' or len(line) == 0: pass else: eval(line) print("line executed") else: print('Could not read Server CFG') heres the error im getting D:\DEMOFI~1\blender\pong1>bmus-001-thread-server.py Reading Server CFG file ######################################### Traceback (most recent call last): File "D:\DEMOFI~1\blender\pong1\bmus-001-thread-server.py", line 73, in ? eval(line) File "", line 1 ######################################### ^ SyntaxError: unexpected EOF while parsing im using one py script to ouput the txt file using \n as the end of line to avvoide any possible windows problems (with it using \r\n). and then the fiel is erroring here when im reading it back into my program.. many thnas for your help Greg Brant From fumanchu at amor.org Wed Jan 21 19:24:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Jan 2004 16:24:49 -0800 Subject: PyTime Object and Application Crashing Message-ID: Mark Hammond wrote: > Robert Brewer wrote: > > > 12/30/1899 the application crashes. > > > > AFAICT all dates on or before that date will crash. > > That is a new one for me :) I have fixed the crash here, but calling > Format() (which print does under the covers) will still fail > for those dates - but with a ValueError. Yes, I should have been more explicit--I always got the crash on calling Format(). Since you have more intimate knowledge of this arena than anyone else, do you have a better solution than my casting to and from float? Robert Brewer MIS Amor Ministries fumanchu at amor.org From gandalf at geochemsource.com Thu Jan 29 16:41:32 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 29 Jan 2004 22:41:32 +0100 Subject: Masked bitmap from bitmap Message-ID: <40197E0C.3000407@geochemsource.com> Hi Gurus! Here is a problem with wxPython. I would like to load bitmaps and create a mask for them at once. Here is my idea: the mask colour for the bitmap should be the colour of the pixel in the top left corner. (The same way Delphi does with TImageList.) E.g. the bitmap should be transparent everywhere with the same colour. I read the documentation, and I could not find an easy way to do this. Here is what I have tried: 1. Create a wxIcon directly (which is a wxBitmap, I only need a masked wxBitmap.) This does not suit for me, since I need to load bitmaps on all platforms. wxIcon cannot handle the BMP format on all platforms. This is from the docs (about the type parameter of wx.Icon): >wxBITMAP_TYPE_ICO Load a Windows icon file. >wxBITMAP_TYPE_ICO_RESOURCE Load a Windows icon from the resource database. >wxBITMAP_TYPE_GIF Load a GIF bitmap file. >wxBITMAP_TYPE_XBM Load an X bitmap file. >wxBITMAP_TYPE_XPM Load an XPM bitmap file. > >The validity of these flags depends on the platform and wxWindows configuration. If all possible wxWindows settings are used, the Windows platform supports ICO file, ICO resource, XPM data, and XPM file. Under wxGTK, the available formats are BMP file, XPM data, XPM file, and PNG file. Under wxMotif, the available formats are XBM data, XBM file, XPM data, XPM file. wxIcon cannot handle BMP on the Windows platform so I cannot use wxIcon. 2. Load wxBitmap and use wxIcon.CopyFromBitmap. Is not okay. This is from the docs: >Copies bmp bitmap to this icon. Under MS Windows the bitmap must have mask colour set. Back to the stove: once I have a bitmap with a mask, I do not really need a wxIcon. :-( For most platforms, this solution would be fine but not on M$ Windows. 3. Load a bitmap and specify the mask by hand. That would be great. Unfortunately, I cannot get the colour of the top left pixel. There is no such method, or I could not find it :-/ Even if there were one, I would had created the mask by hand, in Python. I cannot set pixels' colours (no method for that). And of course, this would be very slow. 4. Load the bitmap in PIL, create the mask by hand, save the mask into a different file/object, load the bitmap and the saved mask into different objects, finally combine them. Oh yeah, I can imagine this would work. But it is too difficult and it would be very very very slow. There must be a better way. Please note that I do not want to use C/SWIG or any external tool. I would like to use pure Python with wxPython if possible. Can somebody help me? A code fragment or a link would be great. Thanks in advance, Gandalf -------------- next part -------------- An HTML attachment was scrubbed... URL: From swalters_usenet at yahoo.com Tue Jan 13 21:06:46 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Wed, 14 Jan 2004 02:06:46 GMT Subject: Does anyone else not find the fun in programming...? References: Message-ID: |Thus Spake Chris Lyon On the now historical date of Tue, 13 Jan 2004 08:23:46 -0800| > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, I > have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along canals > is fun, Arguing about quite how useless the British Government is fun > but programming ? Do you grind your teeth whenever you hear someone say... Oh, perhaps "Knitting is fun?" I don't like knitting, but my grandmother finds knitting fun, and it causes me no anxiety that she or anyone else gets enjoyment that way. Why is it, then, that me saying "programming is fun" upsets you? Is it jealousy that causes you to grind your teeth, or something else? You see, I get a certain feeling of reward when I solve a problem. This might be a particularly tough math problem, or a programming problem, or most any other kind of "self challenge." First it's a feeling of intrigue and fascination, then a feeling of triumph. I'll try to draw some more mundane situations that gave me the same feeling. With perhaps only a difference in adrenaline level, I get the same kick from programming that I got when I sacked a quarterback or scored a touchdown playing football (american) during high school. I get the same kick as when I first benchpressed my own weight. And as when I completed my first 10k run, and again when I won my first 10k run. There's something to point out about the past few examples. I didn't necessarily enjoy all the weightlifting and running and training for football, but in the end, it was well worth it to me. During the process of solving a problem, I get the same feeling as I get while chatting up an interesting girl in a bar. (No, the playful fascination part, not the sexual part.) I also get the same feeling as watching a good movie. There's some level of intrigue involved. The list goes on, but maybe now you can see what I get out of it. No doubt there are things that give you the same feeling. Too bad you haven't yet found a line of work that incorporates them. > Do I need help ? Perhaps from a career counselor. I have a philosophy about time, money, happiness and freedom. There are those who say that time is money, and I disagree with them. If I lose money, I can get it back. If I lose time, it's gone forever. We've all heard the cliche "Money can't buy happiness," which is only a half-truth. Money doesn't buy happiness, but it can buy the freedom to pursue happiness. So, when I consider a job, I ask myself "Will this job result in a net gain of happiness and freedom for me?" I am, after all, selling pieces of my very own existence (time) for money. Thus, I try hard to find jobs that I will enjoy, even if they don't pay as much, because I'll be spending an awful lot of my existence working. HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From avera at coes.org.pe Thu Jan 29 10:23:37 2004 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 29 Jan 2004 10:23:37 -0500 Subject: sending mail cc, bcc Message-ID: <000f01c3e67b$de344800$1603a8c0@pc22> Hello: I have a library called smtplib that send email I use these lines to use it: (from -->to) ------------------------------------ server = smtplib.SMTP(server) server.sendmail(fromaddr, toaddrs, message) ------------------------------------ But I'd like to include some mails CC ,BCC. (from -->to) ( |-->cc ) ( |-->bcc) Does anyone have a library to make it? (mail: from, to, cc, bcc) Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at zoran.com Thu Jan 1 02:56:09 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 31 Dec 2003 23:56:09 -0800 Subject: Graph in wxPython References: Message-ID: <4f0a9fdb.0312312356.75a4fe15@posting.google.com> Hello "Oh Kyu Yoon", > Does anyone know how to implement plots from scipy, chaco, etc > into wxPython widget? Save them as an image and use wxImage? HTH. Miki From michael at foord.net Thu Jan 29 08:55:09 2004 From: michael at foord.net (Fuzzyman) Date: 29 Jan 2004 05:55:09 -0800 Subject: Printing From Python Message-ID: <8089854e.0401290555.501f0695@posting.google.com> I looked through the manual, I looked on the web and could find very little on this subject.... The closest I could find was : http://www.faqts.com/knowledge_base/view.phtml/aid/4549. Saying that printing (to a printer :-) wasn't easy (at least on windows - let alone *cross* platform) - and that was dated 2000. Oh and - http://mail.python.org/pipermail/python-list/2002-September/121462.html from 2002 giving two different methods for Unix and Windows... the windows one doesn't work across our network........ Any 'print' modules out there - that implement cross platform printing interfaces ? Fuzzy -- 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.voidspace.org.uk/atlantibots/pythonutils.html Pythonutils - home of dateutils, ConfigObj, StandOut etc..... From martin at v.loewis.de Sat Jan 3 07:11:48 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 03 Jan 2004 13:11:48 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: Gerrit Holl wrote: > Any comments? It should be possible to implement that type without modifying Python proper. It might make a good recipe for the cookbook. Any volunteers? Regards, Martin From cbh at newenglandhomes.net Fri Jan 23 13:17:12 2004 From: cbh at newenglandhomes.net (CB Hamlyn) Date: Fri, 23 Jan 2004 13:17:12 -0500 Subject: File Install Program Using Python? References: <1012ij4idech2d6@corp.supernews.com> Message-ID: <1012p0i3foqh9e0@corp.supernews.com> Thank you so much. I'd like to learn it and you've all given me a great head start! "Dave Brueck" wrote in message news:mailman.700.1074876093.12720.python-list at python.org... > CB Hamlyn wrote: > > Hello, I'm currently working on a Modification for the PC game Battlefield > > 1942. I'm a pretty good VBA Programmer with some Foxpro under belt as well. > > After reading a ton of stuff on-line I'm simply floored by everything Python > > has to offer. > > > > Anyway, I want to create an installation program that takes a folder and all > > it's sub-folders and copies them from a compressed form into the proper > > directory. Basically a simplified version InstallSheild or whatever. > > > > I assume Python is capable of such a feat and I'm wondering if anyone can > > spin me around, point me in the right direction and shove me toward my goal. > > It's definitely possible, but are you more interested in doing it for your own > educational purposes or for getting the job done? If it's the latter then free > installers like InnoSetup and the WinAmp installer will save you a lot of time > since they already work well. > > If you just want to do this to learn more, then look into the ZipFile class in > the zipfile module for starters. You can add a lightweight GUI using Mark > Hammond's win32 extensions or Venster, and finally convert it into an > executable with py2exe or one of the other packagers out there. > > -Dave > > From francisgavila at yahoo.com Wed Jan 7 09:10:07 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 7 Jan 2004 09:10:07 -0500 Subject: Code Objects / Variable Names References: Message-ID: F. Schaefer wrote in message ... >PROBLEM: > > How can you know what variables are involved in a code object. > > It is not possible to execute the code object simply into a > dictionary and then watch the defined variables. This is > because these code objects only contain conditions, that > read out variables. This seems a strange requirement. Perhaps you could elaborate on what you're doing and we could suggest alternative approaches? One *rarely* needs to pass around raw code objects in Python, and both producing and executing them is considerably slower than just about any other construct you could use (not that it matters much). >EXAMPLE: > > For the following (compiled) condition > > (door == "ajar" and alternator == "off") || time > 25 > > I need to extract, that the variables 'door', 'alternator' and 'time' > are involved. >>> cobj = compile('(door == "ajar" and alternator == "off") or time > 25', '', 'exec') >>> dir(cobj) ['__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'] >>> cobj.co_names ('door', 'alternator', 'time') See "Code objects" under "Internal Types" in section 3.2, "Standard Type Hierarchy," of the Python Language Reference Manual. >>> import dis #just for fun. >>> dis.disco(cobj) 1 0 LOAD_NAME 0 (door) 3 LOAD_CONST 0 ('ajar') 6 COMPARE_OP 2 (==) 9 JUMP_IF_FALSE 10 (to 22) 12 POP_TOP 13 LOAD_NAME 1 (alternator) 16 LOAD_CONST 1 ('off') 19 COMPARE_OP 2 (==) >> 22 JUMP_IF_TRUE 10 (to 35) 25 POP_TOP 26 LOAD_NAME 2 (time) 29 LOAD_CONST 2 (25) 32 COMPARE_OP 4 (>) >> 35 POP_TOP 36 LOAD_CONST 3 (None) 39 RETURN_VALUE -- Francis Avila From jdhunter at ace.bsd.uchicago.edu Sat Jan 3 01:33:03 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 03 Jan 2004 00:33:03 -0600 Subject: Text-to-HTML processing program In-Reply-To: (philh@invalid.email.address's message of "Sat, 3 Jan 2004 05:51:33 +0000") References: Message-ID: >>>>> "phil" == phil hunt writes: phil> Does anyone know of a text-to-HTML processing program, phil> ideally written in Python because I'll probably be wanting phil> to make small modifications to it, which is simple and phil> straightforward to use and which uses a simple markup phil> language (something like Wikipedia markup would be ideal)? Structured text is one of the simplest markups around (and sufficiently powerful to make nice looking hardcopy) and is well supported in python http://www.zope.org/Members/millejoh/structuredText http://docutils.sourceforge.net/docs/rst/quickstart.html Beyond that, search google groups for structured text group:*python* Here's a link to a post from me about the conversion of one of the old diehards in our hospital to structured text: http://mail.zope.org/pipermail/zope/2002-May/115243.html. JDH From chalaouxfr at wanadoo.fr Mon Jan 26 15:54:08 2004 From: chalaouxfr at wanadoo.fr (chalaouxfr) Date: Mon, 26 Jan 2004 21:54:08 +0100 Subject: Mirroring behind a Firewall Message-ID: Hi All, I would to mirror databases, with Python if possible. WGet is broken since version 1.7 if you want to mirror behind a Firewall !! What is the better solution to realize this mirrors ? Have you simple script examples or url of even commercial programs ? Bye, FR. From ramen at lackingtalent.com Fri Jan 9 21:39:12 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 10 Jan 2004 02:39:12 -0000 Subject: Python and Jython are kinda different References: <87wu81jjg2.fsf@pobox.com> <8765fkrig3.fsf@pobox.com> Message-ID: In article , Jp Calderone wrote: > All generators can be re-written with classes using the iterator protocol. > Here's a simple example: Thanks for the nice example. Unfortunately: Jython 2.1 on java1.4.2_01 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> execfile('your-nice-example.py') >>> for j in FooGen(): print j ... Traceback (innermost last): File "", line 1, in ? AttributeError: __getitem__ Bring back any memories of the days before generators? ;) >> - properties > > This is getting closer, I think. More generator, descriptors are pretty > honkin' fundamental these days. On the other hand, most behavior > acheivable with properties can be achieved with __g/setattr__, albeit it > quite as conveniently. Yes, but from my experience the property() builtin is so much more convenient than __get/setattr__ that I am much more likely to use properties in CPython. With Jython, I have to overcome my laziness, since it means writing a fair bit of boilerplate. (example follows) >> - getattr/getitem behavior (which is even different from CPython 2.1) > > I guess I haven't used Jython enough to know what's going on here. Here's an example. I sometimes find it useful to create dictionaries that allow either attribute or item access, a la JavaScript/ActionScript. In CPython, I can use the (comment to a) recipe from ASPN: class attrdict(dict): def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52313) This seems like it would be a very simple port to Jython, right? It's actually a bit hairy. In order to get it to work, I had to do the following: class attrdict(UserDict): "Dictionary that allows keys to be used as object attributes." def __init__(self, dict=None, **kwds): """attrdict() constructor (behaves like Python 2.3's dict()). Optionally takes a source dictionary or keyword arguments.""" if hasattr(dict, 'items'): UserDict.__init__(self, dict) else: UserDict.__init__(self) if dict is not None: for key, value in dict: self[key] = value if kwds: self.update(kwds) def __getattr__(self, name): if self.__dict__.has_key(name): raise AttributeError, name elif name == '__members__': return self.keys() elif name.startswith('__') and name.endswith('__'): raise AttributeError, name else: return self[name] def __setattr__(self, name, value): if name == 'data': self.__dict__[name] = value else: self[name] = value def __delattr__(self, name): del self[name] Whew! Now we're rolling with any version of CPython or Jython 2.1 and up. I wish I could explain to you how much I had to screw with this to get it to work. It turns out that the constructor for UserDict tries to create an attribute called "data", which calls my custom __setattr__, and it gets stuck in an infinite loop. Many combinations and stack exceptions later, I finally got what used to be a five-line class working in Jython. Now, I hope you understand why I'm more privy to properties in CPython. =) >> - type factories being classes > > This seems pretty important to me, probably the most important on the > list. Metaclasses existed before 2.2, but not without writing an extension > module. Hmmm... well, metaclasses would be nice, too, but mostly I was thinking of whether you subclass "dict" or "UserDict" or "types.DictType", and whether or not things like "str.join" are available. The former, as you can see, can make a big difference in how you code things. The latter isn't so significant. >> - dictionary support for "in" keyword > > This seems pretty trivial to me. It's just a transformation of > dict.has_key(). Yep, and there were many such transformations I had to hunt down and fix by hand when trying to port the "sets" module. A pretty small module, too. It was error-prone, and I actually missed a serious performance error when I posted the patch to c.l.p. If anyone is interested, I can post a better patch, or just send you the file (contact me by email - r!a at m#e%n AT r^a at m#e&n!f at e&s#t PUNTO com - remove the line noise of course). >> > I believe GvR said that PyPy might (might!) become a sort of >> > executable standard for Python in the future, though. >> >> I think that's an impressive idea, but it almost seems like the resources >> spent in keeping PyPy and CPython in parallel could be better spent keeping >> Jython and CPython in parallel, seeing as nobody is calling PyPy "Python" >> currently. > > Can't say I agree here, probably because I don't much care about Java ;) > I think PyPy has a lot more bang for the buck for your average Python > programmer. Jython might be nice to bring in some of the Java people, or > make some of that Java work easier when you absolutely have to use it, but > for your average Python application, it hardly enters into the picture. > PyPy, on the other hand opens up a lot of possibilities for future > improvements to the language (because it is easier to prototype new features > in Python than in C) as well as improvements to existing features. Well, I have to admit I'm a bit biased. I work in a Java team, and I've been trying to incorporate Python into the existing infrastructure for the past year or so. So, personally, I'm not the world's biggest Java fan, and I find PyPy much more interesting, but Jython has more immediate usefulness. However, I do find myself doing a lot of extra work to keep my code portable between Jython and CPython, since it facilitates reuse. I agree that PyPy presents new possibilities for language experimentation, and being a total language nerd myself, I'm all for it. =) However, I just want to make the point that Jython is becoming less and less "Python" as the evolution of CPython begins to affect the actual style in which Python code is written. And this makes the popular claim, that Python is the language, and CPython and Jython are two implementations, a bit misleading. But it's a lot easier to complain than to contribute. That I'll readily admit. =) Thanks, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From gandalf at geochemsource.com Mon Jan 19 11:52:08 2004 From: gandalf at geochemsource.com (Gandalf) Date: Mon, 19 Jan 2004 17:52:08 +0100 Subject: secure unpickle? References: <871xpwxe5g.fsf@pobox.com> Message-ID: <400C0B38.1080703@geochemsource.com> John J. Lee wrote: >Gandalf writes: >[...] > > >>I'm using this module (based on the documentation you mentioned): >> >> >[...snip...] > >What does this have to do with the question? He was worried about >security of pickle, not asking how to call dumps() and loads(). > > Well, in that case, get my humble apologies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alanmk at hotmail.com Fri Jan 23 10:30:35 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 23 Jan 2004 15:30:35 +0000 Subject: cgi concurrency approaches? References: <7x7jzjgso7.fsf@ruckus.brouhaha.com> <66s11056aptit3vd2inv3p3r07v95k52ha@4ax.com> Message-ID: <40113E1B.9D27A13@hotmail.com> [replying to someone else's reply because I missed the original] [Paul Rubin] > I'm wondering if folks here have favorite lightweight ways of dealing > with concurrency in cgi's, [snip] > but of course there's the obvious race > condition if two people hit the > cgi at the same time. > > Fancier solutions include running an transactional database in another > process and connecting to it, setting up a daemon that remembers the > counter value in memory and serializes access through a socket that > the cgi opens, using a file-system specific hack like linking to > counter file to lock it, having a timeout/retry if the counter is > locked, with a possible hangup if a lock file gets left around by > accident, etc. Each is a big pain in the neck. > Anyone have some simpler approaches? I don't know about a platform independent solution, but if you were willing to limit yourself to certain varieties of Unix, e.g. Linux, it would probably be relatively easy to implement a persistent counter using something like System V message queues, or shared memory + semaphores. This obviously will work only on systems which support System V IPC. Here is a brief page about System V IPC http://www.science.unitn.it/~fiorella/guidelinux/tlk/node56.html And here's a module, which I've never used, which purports to provide a python interface to System V IPC facilities, if available. http://www.theory.org/~mac4/software/ Given the above facilities, there are two ways I would approach the problem of a persistent counter. 1. Use a dedicated Queue, and hold the counter value inside a single message which "lives" on that queue. Those incrementing the counter read the single message from the queue, increment it and put it back on the queue. Any processes awaiting access to the "counter message" would then do a blocking read on the queue. Since all puts and gets of messages are atomic, you are guaranteed only atomic updates to your counter. However, you could lock your system up if one of your accessing CGI processes did not put the counter back again! You can use timeouts as well, if my memory serves (it's been a long time since I used System V IPC). You can also get fancy, with priorities, etc. 2. Store the value in pre-created shared memory partition, protected by a semaphore. Since there are shared memory python modules for several platforms, you might have a better chance with this approach on non-unix platforms. The Python Object Sharing (POSH) module might provide wrappers to some useful functionality, although the module itself might be a little heavyweight for providing a simple persistent counter. http://poshmodule.sourceforge.net/posh/html/posh.html HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From michael at foord.net Tue Jan 6 07:28:08 2004 From: michael at foord.net (Fuzzyman) Date: 6 Jan 2004 04:28:08 -0800 Subject: IDLE not working under windows..... Message-ID: <8089854e.0401060428.5a4c165d@posting.google.com> At least I've been advised by the 'officials' (in response to my bug report at sourceforge) to only start IDLE with the '-n' argument because sub-processes 'don't work' on windows. In fact the problem is that IDLE currently only uses a single socket and so hangs if you try to open a second version of the shell..... Which means so long as I rememebr to only open one shell it works fine...... So I have two file associations for IDLE now...... The trouble is that opening without a subprocess means that if you edit any modules you have to close IDLE and reload the main program to test changes in the module... which is mightily a pain..... So IDLE on windoze is very much a work in progress............... Fuzzy From me at here.there.com Tue Jan 13 15:59:04 2004 From: me at here.there.com (Peter Ashford) Date: Wed, 14 Jan 2004 09:59:04 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: Brandon, don't be such an arsehole. OS developers do things their own way and offer their labour for free. If you don't like it noone will care - but don't denegrate people just because they don't do things your way. FYI, porting GPL'd Windows code to Linux can be painful as well as vice versa. Quit insulting people who have done nothing worse than offer you code and tools for free. From bart_nessux at hotmail.com Tue Jan 27 20:38:51 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 27 Jan 2004 20:38:51 -0500 Subject: threads In-Reply-To: References: <401706AB.6020703@hotmail.com> Message-ID: Aahz wrote: > In article <401706AB.6020703 at hotmail.com>, > Bart Nessux wrote: > >>Thank you both for the info on threads in Python it was very helpful to >>me, I've written something that I think can benefit from threading... >>here is the code, I copied this from a few books and a few Web examples >>and modified it to suit my test: >> >>class trivialthread(threading.Thread): >> def url_open(self): >> for x in xrange(999999): >> f = urllib.urlopen("http://xxx.xxx.xxx") >> f.read() >> f.close() >> print self, x > > > Rename ``url_open()`` to ``run()``. You might want to read the > slideshow on my web site, paying particular attention to the examples. Wow, that was a simple fix... thanks for the link. Threads are indeed powerful. It's hard to believe what a difference they can make. Question: is this equivalent to running the function in parallel? For example, say I open 15 shells and run the program... is that doing the same thing that threads do? From exarkun at intarweb.us Fri Jan 9 11:10:52 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 9 Jan 2004 11:10:52 -0500 Subject: how to speedup this code? In-Reply-To: References: Message-ID: <20040109161052.GA3140@intarweb.us> On Fri, Jan 09, 2004 at 03:21:29PM +0000, Ognen Duzlevski wrote: > Hi all, > > I have rewritten a C program to solve a bioinformatics problem. Portion > where most of the time is spent is: > > def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): > global ONEINDELPENALTY,OPENGAPPENALTY > > for ndx1 in range(1,tlen+1): > for ndx2 in range(1,qlen+1): > delmat[ndx1][ndx2] = Min(delmat[ndx1-1][ndx2]+ONEINDELPENALTY, \ > Min(scoremat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY, \ > insertmat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY)) > insertmat[ndx1][ndx2] = Min(insertmat[ndx1][ndx2-1]+ONEINDELPENALTY, \ > Min(scoremat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY, \ > delmat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY)) > scoremat[ndx1][ndx2] = Min(scoremat[ndx1-1][ndx2-1], \ > Min(delmat[ndx1-1][ndx2-1], insertmat[ndx1-1][ndx2-1])) + \ > GetFitnessScore(tseq,ndx1-1,qseq,ndx2-1) You should definitely be using Numeric Python for this. > > def Min(a,b): > if a< b: > return a > else: > return b The builtin function "min" does exactly this, and probably does it quite a bit faster. > > In C this is not a big deal, delmat, scoremat and insertmat are int > matrices dynamically allocated and the loop-inside-a-loop is pretty fast. > However, on python (2.3) it is very slow. So for comparison, my C version > takes 8 seconds to execute and the python version takes around 730 > seconds. I have narrowed down through visual observation (print before and > print after entry into the above nested loop) that most of the time is > spent in there. I have also tried the Numeric package with their arrays. > It speeded things up somewhat but not considerably. Did you loop over the arrays and perform the same operations as DynAlign above does? If so, that's not the best way to do it. Use the matrix operations it provides. You'll know when you have written a good Numeric solution when your code no longer has any `for' loops. Jp From jetman516 at hotmail.com Fri Jan 16 15:48:07 2004 From: jetman516 at hotmail.com (The Jetman) Date: 16 Jan 2004 12:48:07 -0800 Subject: SimpleXMLRPCServer References: Message-ID: Maxim Khesin wrote in message news:... > whitekid wrote: > > > SimpleXMLRPCServer.py is Just Simple! > > > > A few days age. I considered XMLRPC framework for our service. > > But finally I choose WebWare. > > > > Read paper below: http://webware.sourceforge.net/Papers/IntroToWebware.html > > Ok, but I am interested in the XML-RPC protocotl, so how is webware > supposed to help me? Maxim: Are you interested in something straight fwd and lightweight for RPC (the part of the thread I could read didn't cover this) ? Then, XMLRPC is great, not nec better than anything else, just great (of the quick-and-dirty variety.) I just rolled out my own SysProxy for FreeBSD, on behalf of Windows. I had it running in a day or so and it's great. Essentially, it executes FBSD cmds/Python subroutines on behalf of a Windows client (an Access program.) I will definitely extend and use it (SysProxy) into the future. Later....Jet From db3l at fitlinxx.com Tue Jan 20 20:26:26 2004 From: db3l at fitlinxx.com (David Bolen) Date: 20 Jan 2004 20:26:26 -0500 Subject: always the same object (2) References: Message-ID: Uwe Mayer writes: (...) > I use struct.unpack() to unpack data from a binary file and pass the > returned tuple as parameter to __init__ of a class that's supposed to > handle the data: > > class DataWrapper(): > data = { } > def __init__(self, arg): #arg will contain a tuple > data['var1'], data['var2'] = arg Is this actual code? You should get a SyntaxError on your use of () in the class line, and a NameError on your use of data[] since there is no local data name within the __init__ function. I'm assuming your real code actually does self.data, and skips the () on the class statement, but in the future, it's really best if you can post actual operating code when discussing a problem. > result = [ ] > while not : > data = struc.unpack("4s4s", f.read(8)) > record = DataWrapper( data ) # pass tuple from unpack > result.append( record ) > > Then "result" contains a list with different objects, but the strings > in data['var1'] and data['var2'] are all the same. > > Any ideas how to avoid this? Yes, don't make data a class-level object. By doing this you have a single instance of the dictionary that data is pointing to, which is shared among all of your DataWrapper instances. Since that class object is mutable, all of your changes in each instances __init__ affect that single object. Instead, move the creation of the instance name (and object) to the __init__ in your instance. This can be a subtle point sometimes, because you won't run into this problem with class level immutable objects (such as ints), because any assignment to the same name in an instance becomes a rebinding operation, thus making the name an instance variable at that point in time. This can be very convenient for implementing class level defaults that take up no space in each instance, but doesn't work the same as mutable types. Note that if you really mean to do it, using a mutable type at class level can be a very useful construct, since it permits sharing of information among all instances of a class. But you have to be expecting it :-) For example, the immutable case: >>> class Foo: ... var = 10 ... def set_var(self, value): ... print 'Var ID:', id(self.var) ... self.var = value ... print 'Var ID:', id(self.var) ... >>> x = Foo() >>> print id(Foo.var), id(x.var) 7649236 7649236 >>> x.set_var(5) Var ID: 7649236 Var ID: 7649224 >>> print id(Foo.var), id(x.var) 7649236 7649224 >>> print Foo.var, x.var 10 5 Foo.var always references the same object, but once an assignment has been made within the instance, it no longer points to the same object as initialized at class level. Thus, each instance references independent objects with their own values. Contrast this with the mutable case: >>> class Foo: ... var = [] ... def set_var(self, value): ... print 'Var ID:', id(self.var) ... self.var.append(value) ... print 'Var ID:', id(self.var) ... >>> x = Foo() >>> y = Foo() >>> print id(Foo.var), id(x.var), id(y.var) 8042256 8042256 8042256 >>> print Foo.var, x.var, y.var [] [] [] >>> x.set_var(10) Var ID: 8042256 Var ID: 8042256 >>> y.set_var(5) Var ID: 8042256 Var ID: 8042256 >>> print id(Foo.var), id(x.var), id(y.var) 8042256 8042256 8042256 >>> print Foo.var, x.var, y.var [10, 5] [10, 5] [10, 5] I made the class object a list and appended values to it just to highlight how calls to multiple instances were affecting the same object, but the principle is the same with a dictionary or any other mutable object. Since the changes in set_var are made by mutating the existing object (versus rebinding the same name to a new object), all the instances share the single Foo.var list. So you could use this construct if you really wanted an object that was seen by all instances and updated by any instance. But if you just wanted an empty list (or dictionary) independently in each instance, you'd want to do something like: >>> class Foo: ... def __init__(self): ... self.var = [] ... def set_var(self, value): ... print 'Var ID:', id(self.var) ... self.var.append(value) ... print 'Var ID:', id(self.var) ... >>> x = Foo() >>> y = Foo() >>> print id(Foo.var) Traceback (most recent call last): File "", line 1, in ? AttributeError: class Foo has no attribute 'var' >>> print id(x.var), id(y.var) 7756800 8053200 >>> x.set_var(10) Var ID: 7756800 Var ID: 7756800 >>> y.set_var(5) Var ID: 8053200 Var ID: 8053200 >>> print id(x.var), id(y.var) 7756800 8053200 >>> print x.var, y.var [10] [5] -- David From tchur at optushome.com.au Wed Jan 14 01:39:59 2004 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 14 Jan 2004 17:39:59 +1100 Subject: Safe prime numbers in Python Message-ID: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From rganesan at myrealbox.com Sun Jan 11 06:43:38 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Sun, 11 Jan 2004 17:13:38 +0530 Subject: QOTW? References: Message-ID: >>>>> "Samuel" == Samuel Walters writes: > I/O is one of our strengths, because we understand that most programs are > not algorithmically bound, but rather I/O bound. I/O is a big > bottle-neck, so we should be damn good at it. The fastest assembly > program won't do much good if it's always waiting on the disk-drive. Actually, Python is much slower than Perl for I/O. See the thread titled "Python IO Performance?" in groups.google.com for a thread started by me on this topic. I am a full time C programmer but do write occasional Python/Perl for professional/personal use. To answer the original question about how much percentage of time I spend optimizing my Python programs - probably never. However I did switch back to using Perl for my most of my text processing needs. For one program that was intended to lookup patterns in a gzipped word list, performance of the original python version was horribly slow. Instead of rewriting it in Perl, I simply opened a pipe to zgrep and did post processing in python. This turned out to be much faster - I don't remember how much faster, but I remember waiting for the output from the pure python version while the python+zgrep hybrid results were almost instantaneous. Ganesan -- Ganesan R From Florian.Lindner at xgm.de Sun Jan 4 16:36:30 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 04 Jan 2004 22:36:30 +0100 Subject: Problems compiling python References: <3FF88279.33BF192A@alcyone.com> Message-ID: Erik Max Francis wrote: > Florian Lindner wrote: > >> I want to compile that small python script: > ... >> bastet:/ # chmod u+x test.pyc >> bastet:/ # ./test.pyc >> ./test.pyc: line 1: syntax error near unexpected token `;' >> '/test.pyc: line 1: `;?? >> bastet:/ # >> >> What is wrong? > > A compiled Python file (.pyc) is not an executable. (Specifically, in > the Unix world, it does not contain a bangpath.) Instead, just pass it > as an argument to the Python interpreter: > > max at oxygen:~/tmp% cat > hello.py > print "Hello, world!" > ^D > max at oxygen:~/tmp% python > Python 2.3.3 (#1, Dec 22 2003, 23:44:26) > [GCC 3.2.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import py_compile >>>> py_compile.compile('hello.py') >>>> ^D > max at oxygen:~/tmp% ls hello.py* > hello.py hello.pyc > max at oxygen:~/tmp% rm hello.py > max at oxygen:~/tmp% python hello.pyc > Hello, world! Can I run these scripts under another UID than the user executing them? (SUID) Thx, Florian From aprogrammer at fastmail.fm Wed Jan 21 22:43:22 2004 From: aprogrammer at fastmail.fm (Ikot) Date: 21 Jan 2004 19:43:22 -0800 Subject: Converting a string to integer/float Message-ID: <2981adb9.0401211943.e1ae272@posting.google.com> Hello, I am stuck with a problem, might be very trivial, to ask here, but dont find a way out. I read a string like 12345.678 from a text file, which will be string for me, but how do I convert it into a float for my use ? Thanks Ikot From adalke at mindspring.com Wed Jan 14 17:41:01 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 14 Jan 2004 22:41:01 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> Message-ID: <1AjNb.8936$1e.894@newsread2.news.pas.earthlink.net> Brandon J. Van Every: > Is there something fundamentally *wrong* with recognizing how useless people > are to your purposes? Nope. But if you blabber it to everyone in the manner you have then when you do need someone else's help you're less likely to get it. It's made even worse when you make claims related to your profession (like "Even 12 years ago, "Computer Graphics: Principles and Practice" didn't teach texture mapping. Along came DOOM.") which is proveably false for several reasons (http://groups.google.com/groups?selm=aemtb.1153%24sb4.720%40newsread2.news. pas.earthlink.net&oe=UTF-8&output=gplain ) because then people tend to remind others of your follies to show that your knowledge is less than you think it is. Andrew dalke at dalkescientific.com From martin at v.loewis.de Sat Jan 24 04:11:49 2004 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 24 Jan 2004 10:11:49 +0100 Subject: How to build Tkinter as extension module? In-Reply-To: References: Message-ID: Guido Schimmels wrote: > When I build python with tkinter support (Linux), the python interpreter > is linked to the tcl/tk shared libraries, thus making them a hard > dependency. That is unfortunate. A friend told me, Debian supports tkinter > via an autonomous extension module. I have looked at the Debian rules file > but wasn't able to discover the trick. Don't add _tkinter in Modules/Setup, or uncomment the *shared* line in Setup. Regards, Martin From jepler at unpythonic.net Sun Jan 25 19:11:45 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 25 Jan 2004 18:11:45 -0600 Subject: xrange not hashable - why not? In-Reply-To: <40145A07.2070906@zephyrfalcon.org> References: <20040125144724.GA13741@nl.linux.org> <40145A07.2070906@zephyrfalcon.org> Message-ID: <20040126001145.GB2593@unpythonic.net> On Sun, Jan 25, 2004 at 07:06:31PM -0500, Hans Nowak wrote: > So far, everybody who replied seems to agree or assumes that xrange indeed > isn't hashable. However: [...] It wasn't in older versions: $ 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. >>> hash(xrange(0)) Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type Jeff From PeterAbel at gmx.net Fri Jan 16 07:33:17 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 16 Jan 2004 04:33:17 -0800 Subject: Inserting while itterating References: Message-ID: <21064255.0401160433.671f5291@posting.google.com> "Thomas Guettler" wrote in message news:... > Hi, > > Simple excerise: > > You have a sorted list of integers: > l=[1, 2, 4, 7, 8, 12] > > and you should fill all gaps: > > result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > How would you code this? > > Constrain: The original list should be changed, > don't create a copy. > > thomas >>> l = [1, 2, 4, 7, 8, 12] >>> id(l) 27295112 >>> for i in range(len(l)-1,0,-1): ... for j in range(l[i]-l[i-1]-1): ... l.insert(i,l[i]-1) ... >>> id(l) 27295112 >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> Tested, but no idea about timing. Regards Peter From rimbalaya at yahoo.com Wed Jan 21 00:18:17 2004 From: rimbalaya at yahoo.com (Rim) Date: 20 Jan 2004 21:18:17 -0800 Subject: Introspection and member ordering Message-ID: <6f03c4a5.0401202118.d17d7a8@posting.google.com> Hi, Is there a way to get any sort of introspection which would return the content of an instance *in the order they were declared or executed* as opposed to alphabetical order? Example: >>> class a: ... def __init__(self): ... self.value = 12 ... self.avalue = 78 >>> class b(a): ... def __init__(self): ... a.__init__(self) ... self.bvalue = 5 ... def f(self): ... self.z = 3 ... >>> c=b() >>> c.__dict__ {'bvalue': 5, 'avalue': 78, 'value': 12} Wrong answer, I am looking for something that would give me {'value':12, 'avalue':78, 'bvalue':5'} I tried the inspect.getmembers(c) without success. Anyone has some advice how I can get the members listed in declaration or execution order? Thanks -Rim From Florian.Lindner at xgm.de Mon Jan 5 12:20:20 2004 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 05 Jan 2004 18:20:20 +0100 Subject: Get UID of username Message-ID: Hello, how can I find out the UID of a username on a linux system? Thx, Florian From skip at pobox.com Sun Jan 4 10:47:46 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 4 Jan 2004 09:47:46 -0600 Subject: Recurring dates module [was: Project dream] In-Reply-To: <20040104.002126.-3883603.2.eltronic@juno.com> References: <20040104.002126.-3883603.2.eltronic@juno.com> Message-ID: <16376.13730.492349.402651@montanaro.dyndns.org> eltronic> rats, datetime IIR is only py2.3 unless it already works in eltronic> py2* or some kind soul has backported it ala sets and some of eltronic> itertools. Tim originally wrote datetime in Python. You can grab the latest version from the CVS sandbox: http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/sandbox/datetime/datetime.py It seems it's been awhile since it was updated (nearly a year ago), so you may have to tweak it to add recent functionality. There has been recent discussion on python-dev about what to do with the Python version of a module after it's been rewritten in C. It would be nice if someone figured out a way to keep datetime.py in sync with the C version. Nice properties include: * continued availability in the source tree without installation * ability to specify the Python version of a module when running regression tests Skip From nospam-deets at web.de Fri Jan 23 08:05:11 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Fri, 23 Jan 2004 14:05:11 +0100 Subject: Server and Client Socket problem References: Message-ID: Hi, > import socket > def run(): > servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > servidor.bind(('localhost', 6969)) > servidor.listen(1) > while 1: > (conexion, direccion) = servidor.accept() > datos = conexion.recv(4069) > print "Servidor Recibe", datos > if datos == "quit": > servidor.close() > break > > run() This code can obviously not run, as its not properly indented. I'm sure that indentation got somehow lost when you create the posting, but as long as you don't provide it in a executable fashion, we can't help you. However, as someone beeing recently converted from hand-made socket programming to twisted, I suggest instead of working with sockets yourself, you better investigate into the twisted framework. Its very well documented. Regards, Diez B. Roggisch From usenet at mail-2-me.com Thu Jan 22 08:50:58 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: 22 Jan 2004 05:50:58 -0800 Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain Message-ID: Hi! I'm trying to get the PDC-Computername of a foreign WinNT-domain, but I only managed to get the PDC of my own domain with this code: pdc=win32net.NetGetAnyDCName() I think it should be possible to get the PDC of a foreign domain (which is a trusted domain) with this code. If I'm right with this assumption, could anyone give me an example-code? Or tell me that I'm wrong, then I can concentrate on something else... Thanks! Dirk From skip at pobox.com Sun Jan 25 15:29:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 25 Jan 2004 14:29:41 -0600 Subject: Python and writing a CSV file In-Reply-To: References: <20040121232549.GA28328@mail.theserver.ath.cx> <009501c3e07e$80b62e30$97443d42@homebass1> <16399.7079.192926.761791@montanaro.dyndns.org> <000c01c3e2b7$a6eabcc0$97443d42@homebass1> Message-ID: <16404.10037.814575.148874@montanaro.dyndns.org> Norm> writer = csv.writer(file('csv_test.CSV', 'w')) ... Norm> So the question is, where does the extra crlf in the csv file come Norm> from? And how do I get rid of it? Try opening the CSV file in binary mode: writer = csv.writer(file('csv_test.CSV', 'wb')) Skip From yet-another at no-domain.cn Thu Jan 1 02:25:50 2004 From: yet-another at no-domain.cn (Jules Dubois) Date: Thu, 1 Jan 2004 00:25:50 -0700 Subject: Where to go from here? newbee References: Message-ID: <1koon5kaqkghf.211m8yj2j32t$.dlg@40tude.net> On Wed, 31 Dec 2003 23:22:43 -0600, in article , Richard wrote: > Just downloaded python for the fun of it. > What do I run to begin coding with? > Version 2.3.3 Yes, unless you have some reason to use an older release. > When I run the "command line" thing, I get a dos window. > Now what? Type some commands and see how the interpreter works. Go to http://www.cs.unm.edu/~ej and click on these links. Python Hacking I (Just do it!) Python Hacking II (types, functions, exceptions) Python Hacking III Type the commands and see what happens. Go to http://www.python.org/ and find some more advanced tutorials. From claird at lairds.com Wed Jan 28 12:25:32 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Jan 2004 17:25:32 -0000 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> <40177f07$0$1730$5a62ac22@freenews.iinet.net.au> <101fkp3nd3ea84c@news.supernews.com> Message-ID: <101fs4c77g79vdc@corp.supernews.com> In article <101fkp3nd3ea84c at news.supernews.com>, John Roth wrote: > >"Derek Fountain" wrote in message >news:40177f07$0$1730$5a62ac22 at freenews.iinet.net.au... >> > What do you need this for? If you can be more specific, we might be >able >> > to help you a little better. >> >> I have a Tcl/Tk script which uses a canvas to graphically represent the >data >> stored in the program. Whenever the data store is updated, a Tcl trace >> automatically triggers to ensure the graphical display is kept consistent >> with the data. I was after a simple way to convert the script to Python >> Tkinter. Without the eqivalent of Tcl traces I'm probably going to have to >> think about it... ;o) > >There's a facility where you can associate a widget with a >variable so that when the variable changes the widget's >value changes, and vice versa. I don't offhand remember the >details though. You'll need to look at one of the references. >The variable has to be a subclass of a special Tkinter class >for this to work, though. . . . textvariable--but that applies only for a few widgets, and only for equivalence of the widget content and the indicated variable; there's no formatting or other pro- cedural computation. -- Cameron Laird Business: http://www.Phaseit.net From sdeibel at wingide.com Fri Jan 16 11:23:18 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Fri, 16 Jan 2004 11:23:18 -0500 (EST) Subject: wxPython worries In-Reply-To: <92c59a2c.0401152257.5b93167b@posting.google.com> Message-ID: On Fri, 15 Jan 2004, MetalOne wrote: > wxWindows and Tk are the only toolkits that wrap native Windows > controls. The others all emulate controls. I am thinking about > trying out another toolkit. > FOX, FLTK or GTK. GTK2 is worth looking at if you're writing a complex GUI and are worried about running into problems with wx's wrapper approach and small differences between what the underlying widgets support. It's fairly complex and probably has a steeper learning curve, but has a nice design. I'm continuously amazed at what I can write on one OS and run w/o problems on others. On Windows, you will want to use the gtk-wimp theme, which makes it look and act more like native Windows apps (via emulation): http://gtk-wimp.sourceforge.net/ There are various GUI builders for GTK but I've found writing the GUI code manually to be easy enough to do. If you try to use it and need to build from sources, let me know and I'll share some Python scripts that make building on Windows (and other platforms) easier. Stephan Deibel -- Wing IDE for Python Archaeopteryx Software, Inc Take Flight! www.wingide.com From michele.simionato at poste.it Tue Jan 6 08:22:09 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 6 Jan 2004 05:22:09 -0800 Subject: RELEASED: allout-vim 031229 References: <87d69yqsos.fsf@pobox.com> Message-ID: <95aa1afa.0401060522.630e5cbb@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87d69yqsos.fsf at pobox.com>... > Fran?ois Pinard writes: > No, actually, a *real* OT comment: I'm pretty sure I've seen two big > pieces of code, by two French authors, in which the word "eventually" > is used all over the place, in a way that clearly means something to > French people . "eventually" --> "finally", perhaps? I don't > think it's as simple as that, though. One example: > > http://pybliographer.org/ > > > John "Eventuellement" (or the Italian "eventualmente") means "possibly", not "eventually". See also http://www.learn-french-now.com/french-false-friends.html From james at logicalprogression.net Fri Jan 16 19:51:05 2004 From: james at logicalprogression.net (James Henderson) Date: Sat, 17 Jan 2004 00:51:05 +0000 Subject: Bug or feature? In-Reply-To: <16392.27363.264594.821314@montanaro.dyndns.org> References: <200401162241.07500.james@logicalprogression.net> <16392.27363.264594.821314@montanaro.dyndns.org> Message-ID: <200401170051.05989.james@logicalprogression.net> On Friday 16 January 2004 10:51 pm, Skip Montanaro wrote: > >> Of course, it should be noted that, in Python, "a += b" is only > >> sometimes synonymous with "a = a + b". The rest of the time, it's > >> hard to say what it is synonymous with :) > > James> What do you have in mind? J. > > For immutable objects, += works as you'd expect: return a new object, > leaving the old object unchanged. That's not the case for mutable objects, > > to wit: > >>> foo = [1] > >>> bar = foo > >>> foo += [2] > > The object referenced by foo is modified in-place... > > >>> bar > > [1, 2] > > >>> foo = foo + [2] > > Here foo is bound to a new object, leaving the old object (still referenced > by bar) unchanged. > > >>> foo > > [1, 2, 2] > > >>> bar > > [1, 2] > > Skip Thanks for pointing that out. It's also the case the += may be more efficient, although that doesn't undermine my original point about surface behaviour. For any third party interested the details are at: http://www.python.org/doc/current/ref/augassign.html Back to the original topic, I have to agree with Robert Brewer that Alexey Nezhdanov's proposal was capable of several other interpretations than a switch to right-to-left evaluation. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From dlmurray at micro-net.com Mon Jan 5 01:42:42 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Sun, 4 Jan 2004 23:42:42 -0700 Subject: Why does this fail? References: <84fc4588.0401042209.60cdb724@posting.google.com> Message-ID: Thank you for the information. I will check them out after I finish my effort. My purpose isn't to obtain a spider program, it is to learn Python by doing. If the exercise will result in something that I can use, it gives me incentive to not abandon the effort because the exercise is interesting to me. The sources that you pointed out should be rich in information on how I could have done it better if I had been more experienced in Python (knowledgeable about it's libraries, etc.) Whenever I learn something new I like to work at it, get help if I'm stuck on something silly (why waste time?), assess what I did against a higher standard, repeat. It's just the way that I learn. I can see that this forum will be just what I need for a chunk of that process. I appreciate it. Regards, Dave ----- Original Message ----- From: "Anand Pillai" > I could not help replying to this thread... > > There are already quite a lot of spider programs existing > in Python. -- > This is the main reason why developers release programs as > opensource. Help the community, and help yourselves. Re-inventing > the wheel is perhaps not the way to go. From james at eccehomo.co.uk Wed Jan 14 09:54:44 2004 From: james at eccehomo.co.uk (James Goldwater) Date: Wed, 14 Jan 2004 14:54:44 +0000 Subject: wxPython worries Message-ID: <40055834.4080200@eccehomo.co.uk> I'm starting a new hopfully-commercial project soon, and I face a dilemma about whether Python with wxPython would be appropriate. The project has 3 main areas: a) manipulation of lists and trees, using.. b) a hopefully dead-sexy gui, all in order to... c) eventually pump out certain bits of the datastructure over the network in semi-realtime (< 10ms accuracy or so). The target is Win32 for now (98 - XP). Now, if it were up to me, I'd use Delphi - it's what I know best. But I'm working with a less experienced developer with whom I have no languages in common. He's keen to get started on C#, I've toyed with C# and though it looks easy, I don't see any major gains over what I already know. I've read a lot about python and done some mini-stuff in it, and been impressed with it's ease and conciseness. What worries me is wxPython: looking at the demo code, it's quite verbose and 'bitty'. I'm also unclear as to how easy custom controls are to build. Am I just being confused by my newbie-ness, or are my initial concerns justified? What's anybody else's experiences with gui programming in wxPython like vs a RAD like Delphi or .NET? Thanks, James. From ih8spam at spamtrap.com Tue Jan 13 17:42:07 2004 From: ih8spam at spamtrap.com (WTH) Date: Tue, 13 Jan 2004 17:42:07 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <1008su65sie7m72@corp.supernews.com> >the others write software that'll > make them money for fixing their own mistakes after the fact ;) Ixnay on the ecretsay... WTH From dj00302003 at yahoo.com Fri Jan 9 21:38:08 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 9 Jan 2004 18:38:08 -0800 Subject: wxPython Application over the net Message-ID: <1d17eeb7.0401091838.3eef2093@posting.google.com> We have an application in wxPython that works quite well on our local computers, but we want people to be able to run the program over the internet. One way that would work is to use an Xwindows server and just have people connect to the program on our local host, but we would like to work in an internet browser because not everyone has an Xserver. Is there any reasonable way to run a wxPython app inside a browser? From jcarlson at nospam.uci.edu Tue Jan 27 16:49:16 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 27 Jan 2004 13:49:16 -0800 Subject: I support PEP 326 In-Reply-To: References: <10105bn3bsi63c9@news.supernews.com> Message-ID: Andrew Koenig wrote: >>The issue is that when Min and None are in a sequence that gets sorted, >>you can end up with Minimums and Nones getting interspersed like so: >>[Min, None, Min...] > > > If Min and None were two different names for the same object, such behavior > would be moot. > However, the following anomalies might then appear: > > >>> None > None > >>> Min > None > > (after all, if they're the same object, how is the interpreter to know which > print name to use?) Additionally, None comparing smaller than everything else is neither intuitive, nor really documented (as reiterated a few times by a few different people in python-dev). It was an arbitrary decision, but better than None comparing larger than everything. - Josiah From sidharthk at hotmail.com Wed Jan 28 12:07:39 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Wed, 28 Jan 2004 22:37:39 +0530 Subject: isinstance() bug References: Message-ID: i dont know unix. how does abs path work with sym-links. From jjl at pobox.com Wed Jan 14 19:28:07 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 00:28:07 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <87u12z90eq.fsf@pobox.com> Message-ID: <87vfnerr6w.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > "David M. Cook" writes: > > > In article <40029dad$0$28706$a729d347 at news.telepac.pt>, Bicho Verde wrote: > [...] > > You could casually pick up enough Python to be useful in a week or so of > > evenings. > > > > Perl is not much harder, > > It *seems* so when you first learn it... > > > but has a lot of "gotchas". > > ... and they never end! Ilya Zakharevich (a "Perl God"): [...] Can't resist another bit of Perl-bashing: I just noticed this bit of the FSF's license page. There's an amusing (and not accidental, I think) parallel between the language and its license: http://www.fsf.org/licenses/license-list.html The (Original) Artistic License. We cannot say that this is a free software license because it is too vague; some passages are too clever for their own good, and their meaning is not clear. We urge you to avoid using it,[snip...] John From fumanchu at amor.org Tue Jan 13 12:44:32 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Jan 2004 09:44:32 -0800 Subject: Does anyone else not find the fun in programming...? Message-ID: > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, > I have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along > canals is fun, Arguing about quite how useless the British Government > is fun but programming ? Different people find different activities to be "fun" (for various definitions of "fun"). I personally enjoy _design_, and programming provides a context for that, but there are other vehicles for meeting my daily design quota. Python in particular allows me to focus on higher-level design issues (compared to other languages I've used). One of the interesting things about computers in general is their ability to be a vehicle for most things people enjoy, if only virtually. My sincere sympathies to anyone who is stuck programming (or doing any other kind of work with computers) for a paycheck only. FuManChu From __peter__ at web.de Sun Jan 4 11:27:00 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jan 2004 17:27:00 +0100 Subject: how to make a code object a function References: Message-ID: Diez B. Roggisch wrote: > Interesting - from the docs, I can't see that types.MethodType has a > constructor like this. It get's really funny if you look into the source (types.py): class _C: def _m(self): pass ClassType = type(_C) UnboundMethodType = type(_C._m) # Same as MethodType _x = _C() InstanceType = type(_x) MethodType = type(_x._m) Seems we caught them cheating here :-) > Just out of curiosity - is there a way to know the name of a code object > you know nothing about except that it will become a function definition? I > guess I could go for some AST-stuff looking for a "def foo" statement, so > I know I will end up having defined foo when exec'ing the code object. You could provide a separate namespace and then extract only the callables: >>> d = {} >>> exec "factor=2\ndef alpha(s, t): print factor*t" in d >>> d.keys() ['__builtins__', 'alpha', 'factor'] >>> funcs = dict([(n,f) for n, f in d.iteritems() if callable(f)]) >>> funcs {'alpha': } >>> funcs["alpha"](None, 2) 4 Peter From swalters_usenet at yahoo.com Sun Jan 18 17:00:54 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 22:00:54 GMT Subject: Forums for Teachers Using Python - Where are they? References: Message-ID: | Mike C. Fletcher said | > Official forum of this type is the Education Special Interest Group > (sig), or edu-sig. You can find out more, subscribe and the like here: > > http://mail.python.org/mailman/listinfo/edu-sig Thank you. Like your car-keys, stuff like that is always in the most obvious spot you didn't check. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From tim.one at comcast.net Fri Jan 30 10:49:11 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 30 Jan 2004 10:49:11 -0500 Subject: NEWLINE character problem In-Reply-To: Message-ID: [Nuff, replying to someone who has strings with various line-end conventions] > Say your string is s; then you could use the following > function (untested!) to make sure that s uses \n only: > > def fix_lineendings(txt): > if txt.count('\r\n'): # MS DOS > txt = txt.replace('\r\n', '\n') > elif txt.count('\r'): # Mac > txt = txt.replace('\r', '\n') > > return txt > > Simply write: s = fix_lineendings(s) That's in the right direction. There's no need to count the *number* of each kind of oddball, and .count() does all the work that .replace() does anyway if there aren't any oddballs. So the one-liner: return s.replace('\r\n', '\n').replace('\r', '\n') does the same, but quicker. Note that, as an internal optimization, .replace() doesn't build a new string object unless it finds something to replace, so it's actually slower to do an "if" test first. >>> s = 'abcdefghi\n\n' # doesn't contain any oddballs >>> t = s.replace('\r\n', '\n').replace('\r', '\n') >>> s == t True # nothing was replaced >>> s is t True # more, the same string object was returned by both .replace()s >>> From sabu at mad.scientist.com Mon Jan 19 00:22:02 2004 From: sabu at mad.scientist.com (Xavier Kaotico) Date: Mon, 19 Jan 2004 00:22:02 -0500 Subject: STDIN remote address? Message-ID: <20040119052202.710.qmail@mail.com> Greetings, I have come up to a stand still here with a small bit of code. My purpose is to figure out the remote IP address associated with stdin. I tried porting the following code (which did this easily in C): struct sockaddr_in sin; unsigned int nl = sizeof (struct sockaddr_in); int test = getpeername (IO_STDIN, (struct sockaddr *) &sin, &nl); I heard there was a libc call which gave me the exact information I needed, but I have not looked into it yet. Does anyone have any idea how this can be pulled off? Oh, and the furthest I got was looking into socket.fromfd(), but I got sidetracked. Thanks in advance! -- _______________________________________________ Get your free email from http://www.mail.com From jcarlson at nospam.uci.edu Sat Jan 24 04:01:11 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 24 Jan 2004 01:01:11 -0800 Subject: pty difficulties In-Reply-To: <2e262238.0401232202.5b21eba8@posting.google.com> References: <2e262238.0401232202.5b21eba8@posting.google.com> Message-ID: > while True: > readable = select(connections.keys(), [], [])[0] > for f in readable: > data = read(f.fileno(), 1024) > connections[f].write(data) > connections[f].flush() I believe your problem exists in the write and flush. All you seem to be doing is checking to see if your reading file handles are capable of reading, you never check to see if you can write to anything. Your lisp interpreter showcases the fact that it is not ready to get a write while it is interpreting, by failing. I believe the following should fix you up: while True: readable = select(connections.keys(), [], [])[0] for f in readable: if select([], [connections[f]], [], 0)[1]: data = read(f.fileno(), 1024) connections[f].write(data) connections[f].flush() - Josiah From owner-mutt-announce at mutt.org Tue Jan 27 04:39:37 2004 From: owner-mutt-announce at mutt.org (owner-mutt-announce at mutt.org) Date: 27 Jan 2004 09:39:37 -0000 Subject: mutt-announce@mutt.org: Non-member submission from python-list@python.org Message-ID: <20040127093937.10211.qmail@agent57.gbnet.net> Your submission to the list has been forwarded to the list owner for approval because you do not seem to be on that list. If you want to join the list, send email to , with "subscribe mutt-announce" in the message text (not the subject). From astrand at lysator.liu.se Sat Jan 3 17:27:12 2004 From: astrand at lysator.liu.se (Peter Astrand) Date: Sat, 3 Jan 2004 23:27:12 +0100 (CET) Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: <3FF73920.8090402@v.loewis.de> Message-ID: On Sat, 3 Jan 2004, Martin v. Loewis wrote: > > - One "unified" module provides all functionality from previous > > functions. > > I doubt this is a good thing. Different applications have different > needs - having different API for them is reasonable. I don't agree. I have used all of the existing mechanism in lots of apps, and it's just a pain. There are lots of functions to choose between, but none does what you really want. > > - Cross-process exceptions: Exceptions happening in the child > > before the new process has started to execute are re-raised in > > the parent. This means that it's easy to handle exec() > > failures, for example. With popen2, for example, it's > > impossible to detect if the execution failed. > > This is a bug in popen2, IMO. Fixing it is a good thing, but does not > require a new module. "Fixing popen2" would mean a break old applications; exceptions will happen, which apps are not prepared of. > > - A hook for executing custom code between fork and exec. This > > can be used for, for example, changing uid. > > Such a hook could be merged as a keyword argument into the existing > API. Into which module/method/function? There is no one flexible enough. The case for redirecting only stderr is just one example; this is simple not possible with the current API. > > - All combinations of file descriptor redirection is possible. > > For example, the "python-dialog" [2] needs to spawn a process > > and redirect stderr, but not stdout. This is not possible with > > current functions, without using temporary files. > > Sounds like a new function on the popen2 module. To support all combinations, 12 different functions are necessary. Who will remember what popen2.popen11() means? > > - Support for connecting several subprocesses (shell "pipe"). > > Isn't this available already, as the shell supports pipe creation, > anyway? With popen5, you can do it *without* using the shell. > > - Universal newline support. > > This should be merged into the existing code. There's already a bug about this; bug 788035. This is what one of the comment says: "But this whole popen{,2,3,4} section of posixmodule.c is so fiendishly complicated with all the platform special cases that I'm loath to touch it..." I haven't checked if this is really true, though. > > - A communicate() method, which makes it easy to send stdin data > > and read stdout and stderr data, without risking deadlocks. > > Most people are aware of the flow control issues involved with > > child process communication, but not all have the patience or > > skills to write a fully correct and deadlock-free select loop. > > Isn't asyncore supposed to simplify that? Probably not. The description says: "This module provides the basic infrastructure for writing asynchronous socket service clients and servers." It's not obvious to me how this module could be use as a "shell backquote" replacement (which is what communicate() is about). It's probably possible though; I haven't tried. Even if this is possible I guess we need some kind of "entry" or "wrapper" method in the popen module to simplify things for the user. My guess is that an communicate() method that uses asyncore would be as long/complicated as the current implementation. The current implementation is only 68 lines, including comments. > So in short, I'm -1 on creating a new module, but +1 on merging > most of these features into the existing code base - they are good > features. Well, I don't see how this could be done easily: The current API is not flexible enough, and some things (like cross-process exceptions) breaks compatibility. Writing a good popen module is hard. Providing cross-platform support (for Windows, for example) is even harder. Trying to retrofit a good popen implementation into an old API without breaking compatibility seems impossible to me. I'm not prepared to try. -- /Peter ?strand From peter at engcorp.com Mon Jan 26 17:27:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Jan 2004 17:27:57 -0500 Subject: TELNET instead PING References: <5f505344.0401260332.184d4225@posting.google.com> <401571B9.F9DF99D0@engcorp.com> Message-ID: <4015946D.B2A218BA@engcorp.com> > Gandalf wrote: > > I think there is no universal way to determine if a remote host is alive or not. That is definitely the case, because of course the firewall could just as easily block all traffic that is not from a specific IP address as well. -Peter From miki.tebeka at zoran.com Sun Jan 18 10:51:38 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 18 Jan 2004 07:51:38 -0800 Subject: re question - finiding matching () Message-ID: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Hello All, To all of you regexp gurus out there... I'd like to find all of the sub strings in the form "add(.*)" The catch is that I might have () in the string (e.g. "add((2 * 2), 100)"), Currently I can only get the "addr((2 *2)" using re.compile("\w+\([^\)]*\)"). To solve the problem a hand crafted search is used :-( Is there a better way? Thanks. Miki From boomer4467 at yahoo.com Sat Jan 3 15:49:56 2004 From: boomer4467 at yahoo.com (Boomer) Date: 3 Jan 2004 12:49:56 -0800 Subject: importing Message-ID: <231bc96c.0401031249.12cff6d7@posting.google.com> Hi all, I'm new to python which explains my problems with this. I'm trying to import a .csv file(from excel) into some fields on my company's software system(which interfaces to an sql database. Each row in this .csv file needs to be split into smaller strings and each respective string applied to it's field in the software then it's saved and the next row starts, here's the code I've come up with so far. f=open ("book1.csv", "r") s=f.readline () while s != "": print s l = s.split(s,",",(11)) PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0]) PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}") PlayIt.SetFieldContent ("SY012ADM1", "001bez", l[1]) PlayIt.SetFieldContent ("SY012ADM1", "005agr", l[2]) PlayIt.SetFieldContent ("SY012ADM1", "006agr", l[3]) PlayIt.SetFieldContent ("SY012ADM1", "009kst", l[4]) PlayIt.SetFieldContent ("SY012EHM1", "005laeh", l[5]) PlayIt.SetFieldContent ("SY012EHM1", "006lauf", l[6]) PlayIt.SetFieldContent ("SY012EHM1", "011vkuf", l[7]) PlayIt.SetFieldContent ("SY012SDM1", "012fest", l[8]) PlayIt.SetFieldContent ("SY012PRM1", "001tpr", l[9]) PlayIt.SetFieldContent ("SY012PRM1", "002wpr", l[10]) PlayIt.SetFieldContent ("SY012PRM1", "003plpr", l[11]) PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}") s=f.readline () f.close () here's the error Traceback (innermost last): File "", line 5, in ? AttributeError: 'string' object has no attribute 'split' the furthest I get is when I remove the s.split all together then I can actually watch it import the first field correctly and switch focus to the second field where it prints a comma and then hangs and eventually gives the argument 3: expected string list found Someone told me I need to import the string module using "import string" somewhere in my code, but when I do this I get an error stating that no such module exists. I run this as script inside a macro from another program and I believe the version of python this program uses is 2.2.1. Does anyone have any ideas? Any help would be wonderful!!! From francisgavila at yahoo.com Mon Jan 12 11:09:50 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 12 Jan 2004 11:09:50 -0500 Subject: Python installation breaks Outlook Express References: Message-ID: <1005hodg7nqu129@corp.supernews.com> Y2KYZFR1 wrote in message ... >This has nothing to do with Python and posting the same question over >and over will not get a different answer. No need to be rude.... -- Francis Avila From tim.golden at viacom-outdoor.co.uk Wed Jan 21 09:29:45 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Jan 2004 14:29:45 -0000 Subject: Dailing modem. Message-ID: > I need to dail a modem from python and disconnect it again. Assuming you're on Windows (since you're talking about TAPI & COM) look at the win32ras module in Mark Hammond's win32 extensions. 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 python-list at cstork.org Wed Jan 21 18:03:44 2004 From: python-list at cstork.org (Christian Stork) Date: Wed, 21 Jan 2004 15:03:44 -0800 Subject: Weaver/Yarn Pattern in Python In-Reply-To: <400E4559.3020704@prescod.net> References: <20040121062432.GA6158@ics.uci.edu> <400E4559.3020704@prescod.net> Message-ID: <20040121230344.GA11614@ics.uci.edu> Hi Paul, On Wed, Jan 21, 2004 at 01:24:41AM -0800, Paul Prescod wrote: > I've tried to understand your problem statement in detail but it is alot > to keep in the head in pure abstraction (i.e. I don't have your specific > problem and haven't worked on this complicated a tree walker in a while > if ever). Also, I think there may have been some typos that are making > it harder to understand. For instance, is visitB supposed to be > syntactically identical to visitA except it calls weaveB's instead of > weaveA's? I'm sorry that's a typo. :-( Corrections follow below in context... > Is this the boilerplate that offends you? The boilerplate *and* the unnatural name mangling. I guess only some kind of generic function simulation could help me with that one. ;-) (If anybody is interested I could try and come up with a minimal version of my problem in Dylan using generic functions.) > But maybe I can help anyhow. Here's some code from your post: > > > class Weaver: > > "A special visitor which weaves yarns" > > def __init__(self, yarns): > > self.yarns = yarns > > def visitA(self, a): > > for y in self.yarns: > > y.weaveA_First(a) > > for i, k in enumerate(a.kids): > > for y in self.yarns: > > y.weaveA_Before(a, i) > > k.accept(self) > > for y in self.yarns: > > y.weaveA_After(a, i) > > for y in self.yarns: > > y.weaveA_First(a) Last > > def visitB(self, b): > > for y in self.yarns: > > y.weaveA_First(b) B > > for y in self.yarns: > > y.weaveA_First(b) B Above is what I meant. Cut-n-paste typos :( > I'm going to presume that visitB was supposed to be more like: > > > def visitB(self, b): > > for y in self.yarns: > > y.weaveB_First(b) > > ... identical to visitA except A's swapped for B's ... > > If it isn't identical to visitA (except for the B) then I don't know > what the boilerplate is. Well, I didn't intend it to be identical. I meant to leave out the Before and After methods, but your assumption makes a lot of sense given how I presented my problem. :-) In actuality, things are a bit more complicated. Nodes are of different kinds. These kinds are defined by a tree grammar. (You can find more about this in my papers at my home page (see sig).) Anyway, as an example one kind of node might have exactly 3 kids with names K1, K2, K3, and it makes sense to refer to them by these names. Therefore I have method signatures like class SomeYarn: ... def weaveN_Before_K2(self, k2): # here k2 is the actual kid, not an index ... This is slightly more convenient and has the big advantage that this code is still correct after changing the order of kids in the tree (which happend several times). Now, in the case of node classes B and C, they did not have any children according to their node kind. That's why I didn't list the appropriate methods. But I like the (relative) simplicity of your below proposal. So maybe I cut back on some of the convenience features and use a scheme like yours. ... > If I'm understanding right, I think each yarn has a two-D matrix of methods: > > A B C D .... > First > Before > After > Last > > And then you've got another dimension for the yarns (that varies at runtime) > > There are many ways to represent these axes in Python: > > self.yarns[0]["A"]["First"] > self.yarns[0]["A", "First"] > self.yarns[0]["A_First"] > self.yarns[0]["A"].First() Nice and clean solutions. Definitely better than my mangling. > class Weaver: > "A special visitor which weaves yarns" > def __init__(self, yarns): > self.yarns = yarns > def visit(self, a): > for y in self.yarns: > y.threads[a.type].First(a) > for i, k in enumerate(a.kids): > for y in self.yarns: > y.threads[a.type].Before(a, i) > k.accept(self) > for y in self.yarns: > y.threads[a.type].After(a, i) > for y in self.yarns: > y.threads[a.type].Last(a) By now I made one addition to my weaver's visit method: Don't require that all yarn code snippets are present -- just fall back on some default behavior. In our case that means to do nothing. This change allows to reduce the boilerplate of yarns to a degree where I can look at a yarn's definition and immediatly see the non-boilerplate code. (Nothing big, but it helps.) ... > class X_Yarn_A_thread: > self.type == "A" > def First(self, arg): > assert arg.type == self.type > return self.first(arg) > > def Before(self, arg): > assert arg.type == self.type > return self.before(arg) ... Makes sense. Adds a little to the boilerplate tho. > Hacking together method names with strings is only ever a sort of > syntactic sugar for some other design that uses dictionaries "properly". > > Remember that Python has at its core a similar feature set to Scheme and > Lisp which are famously "flexible" and "powerful" and yet do not do any > name manging weirdness. It's great that Python allows that name manging > stuff but if you feel you HAVE to use it then you probably aren't > thinking in terms of higher order functions or objects in contrainers as > you could/should. You should think about hwo to do things without > method-name hacking before deciding that that's a better solution for > some reason of expedience or usability. True. Thanks a lot for help and discussion, Chris -- Chris Stork <> Support eff.org! <> http://www.ics.uci.edu/~cstork/ OpenPGP fingerprint: B08B 602C C806 C492 D069 021E 41F3 8C8D 50F9 CA2F From gerrit at nl.linux.org Sat Jan 3 05:17:34 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 3 Jan 2004 11:17:34 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: <20040103101734.GA29993@nl.linux.org> Hi, I propose to add a "filename" type to Python. Martin v. Loewis wrote: > Sean Ross wrote: > >My question is this: Is there a reason why file objects could not have a > >size method or property? > > Yes. In Python, file objects belong to the larger category of "file-like > objects", and not all file-like objects have the inherent notion of a > size. E.g. what would you think sys.stdin.size should return (which > actually is a proper file object - not just file-like)? A different solution to this problem would be to introduce "filename" type to Python, a subclass of str. The "name" attribute of file would be of this type. This type would inherit a lot of os.path stuff: getsize becomes simpler, more readable, and more object oriented, as do other os.path functions. I think the alternatives look a lot more prety: OLD NEW os.path.realpath(fn) fn.realpath() os.path.getmtime(fp.name) fp.name.getmtime() os.path.ismount(os.path.dirname(fp.name)) fp.name.dirname().ismount() It's more beatiful, simpler, flatter (#3), practical, obvious, easy. problem: what do do with os.path constants? solution: make them class attributes problem: how to handle posixpath, ntpath, macpath? solution: abstract Path class with NTPath, MacPath, PosixPath sublasses which is the actual type of e.g. fn.name on a certain platform problem: backwards compatibility solution: same as string methods problem: "/dev/null" reads as a Path but is a str solution: path("/dev/null") is a little more typing for a lot more luxery problem: what to do with commonprefix? solution: don't know problem: what to do with os.path.walk? solution: use os.walk instead problem: what to do with sameopenfile? solution: make it a file method problem: what to do with join, split? solution: rename to joinpath, splitpath. Any comments? yours, Gerrit. -- 158. If any one be surprised after his father with his chief wife, who has borne children, he shall be driven out of his father's house. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From Robert.Schmitt at cellzome.com Mon Jan 26 05:51:22 2004 From: Robert.Schmitt at cellzome.com (Robert.Schmitt at cellzome.com) Date: Mon, 26 Jan 2004 11:51:22 +0100 Subject: logging package problems Message-ID: I found that the configuration system of the new logging package of Python 2.3 has some unintuitive idiosyncracies that are worth mentioning because they can cost you quite some development time and are not documented elsewhere. I used the logging configuration file shown below. My aim was to log only the INFO messages, but log DEBUG messages for one particular module (called webTestLogin.py). Here's what I found out: - if your init logging in your module with the line log = logging.getLogger() then the logging module will determine the module where the call originated and in your log files you'll find lines like 2004-01-26 11:21:15,890 [INFO] creating ticket for this session [in webtestlogin] where webTestLogin mysteriously lost its capitalization. Now, this does *not* mean that webtestlogin will also be the 'qualname', i.e. the name of a channel that you can use to log messages from this module to a different place or in a different manner; for that to work, you'll need the following line of code: log = logging.getLogger('webtestlogin') (making 'webtestlogin' a channel, or some sort of logical logging unit that allow its calls to be handled differently from the other log calls in your program). The documentation says qualname is the 'fully qualified name', but doesn't contend on what that is; I tried the complete package name, that didn't work ('com.cellzome.pandora.webTestLogin'). - capitalization *is* very important; if you use lowercase in the code, you'll need lowercase in the logging config file as well (see the qualname line below) - 'propagate' forwards log messages to other loggers, so you may e.g. log the same line to two different places - so far so good. But: If you set propagate to 1 in the [logger_webtestlogin] shown below, the root logger will log DEBUG messages too, even though it was told to log only INFO - just because the message has been forwarded (?!?) Generally I think that propagation follows the order of the loggers, but I still don't get the complete picture. - the config file scanner/parser is not very robust; if you use spaces in a list for aesthetic reasons (e.g. keys=root, webtestlogin) the key list will be ('root', ' webtestlogin'). This can produce quite esoteric errors :-) Maybe I didn't get the point/purpose of the framework on some of those issues, but then again it might be worth to extend the existing documentation a bit. Cheers, Robert F Schmitt, Cellzome AG Meyerhofstr. 1, D-69117 Heidelberg, Germany Tel + 49 6221 137 57 405, Fax + 49 6221 137 57 202 www.cellzome.de ------------------------------------------------------------------------------------ The vast majority of our imports come from outside the country." - George W. Bush "If we don't succeed, we run the risk of failure." - George W. Bush /////////////////////////////////////////////////////////////////// /////////////// config file /////////////// /////////////////////////////////////////////////////////////////// ########################################################### # general references [loggers] keys=root,webtestlogin [handlers] keys=drogenHandler,stdoutHandler [formatters] keys=taschenFormat,textOnlyFormat ########################################################### # loggers [logger_webtestlogin] level=DEBUG handlers=drogenHandler,stdoutHandler propagate=0 qualname=webtestlogin [logger_root] level=INFO handlers=drogenHandler,stdoutHandler propagate=1 ########################################################### # handlers [handler_drogenHandler] class=FileHandler level=NOTSET formatter=taschenFormat args=('pandora.log', 'w') [handler_stdoutHandler] class=StreamHandler level=INFO formatter=textOnlyFormat args=(sys.stdout,) ########################################################### # formatters [formatter_taschenFormat] format=%(asctime)s [%(levelname)s] %(message)s [in %(module)s] [formatter_textOnlyFormat] format=%(levelname)s %(message)s -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagenellina at softlab.com.ar Fri Jan 2 20:40:53 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 02 Jan 2004 22:40:53 -0300 Subject: Debugging a script In-Reply-To: Message-ID: <5.2.1.1.0.20040102223740.0242b550@192.168.0.115> At 2/1/2004 20:23, you wrote: >I've got a (python) program which crashes. WHat I'd like to do is something >loke this: > > try: > lots of stuff, or > more pertinintly, the code which is failing > except: > drop in to the debugger > >So that I can print various things. > >Also, is there a way to display the line number - eg: > except something: > print ("DEBUG: exception %s at line number %s" % > (sys.exc_type, >sys.linenumber)) Better to print a full traceback instead of just one line number. Look at the traceback module: except: import traceback traceback.print_exc() Gabriel Genellina Softlab SRL From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jan 18 10:18:58 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 18 Jan 2004 16:18:58 +0100 Subject: Problems creating mail content using email.MIMEText, non-ASCII encoding In-Reply-To: <4005c2ab$0$321$e4fe514c@news.xs4all.nl> References: <4005c2ab$0$321$e4fe514c@news.xs4all.nl> Message-ID: <400aa3e5$0$329$e4fe514c@news.xs4all.nl> I wrote: > I'm trying to create e-mail content using the email.MIMEText module. > It basically works, until I tried to send mail in non-ascii format. [...] > The first one in iso-8859-15 format looks okay but is in quoted-printable, > and either my mail clients are wrong (unlikely, I've never had this kind > of problems with them) or the content is wrong, because what > I'm seeing this in Mozilla mail and my webmail client: > "body text including an Euro char AC" (a space before 'AC'!) > > My UTF-8 attempt failed totally as you can see. I solved it. First, I concluded that you have to encode the message body yourself before putting it in the MIMEText object. So I now encode my unicode message body like this: mail=MIMEText(body.encode('iso-8859-15','replace'), _charset='iso-8859-15') Also, I had to override the default 'utf-8' email.Charset to avoid having the message body encoded in base-64 when using utf-8: import email.Charset email.Charset.add_charset( 'utf-8', email.Charset.SHORTEST, None, None ) The resulting emails and headers look very similar to what Mozilla Mail is generating, and the received emails display well. I'm happy :) --Irmen From teengo at yahoo.com Mon Jan 12 22:03:43 2004 From: teengo at yahoo.com (Ticachua) Date: 12 Jan 2004 19:03:43 -0800 Subject: How to intercept a keypress using python? References: Message-ID: Samuel Walters wrote in message news:... > |Thus Spake Ticachua On the now historical date of Mon, 12 Jan 2004 > 09:50:38 -0800| > > > Hello all, > > > > Does anyone know how to intercept user's keypress or mouseclick in Python? > > I'd like to write a small tool (Python-based preferrably) running on > > Windows to capture the user's keypresses and mouseclicks and write them to > > a file. > > > > Thanks for your help. > > Some people in alt.2600 and alt.crackers will certainly know where to find > such tools. Have you asked there? Thanks Samuel. I'll try those groups. From fuf at mageo.cz Wed Jan 28 13:40:40 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 19:40:40 +0100 Subject: C API: how to tell if x is a new style instance? Message-ID: <20040128184040.GD11485@foof.i3.cz> hello everyone, i've tried to find a way to determine in the python C-API if x is an instance of a (damned) new style class, but failed :/ can someone please tell me how this could be accomplished? thank you, -- fuf (fuf at mageo.cz) From aahz at pythoncraft.com Wed Jan 21 20:01:11 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Jan 2004 20:01:11 -0500 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <400AB936.BA1D9D73@hotmail.com> <7934d084.0401181805.71029c2f@posting.google.com> <400EE6B5.27C6B694@hotmail.com> Message-ID: In article <400EE6B5.27C6B694 at hotmail.com>, Alan Kennedy wrote: > >Yes, you're right. Using a Queue in this situation does require the >use of a dedicated thread for the producer. There is no way to "pull" >values from a generator to multiple consumers through a Queue.Queue. >The values have to be "pushed" onto the Queue.Queue by some producing >thread of execution. Correct. >The way I see it, the options are > >Option 1. Spawn a separate thread to execute the producing generator. >However, this has problems:- > >A: How do the threads recognise the end of the generated sequence? >This is not a simple problem: the Queue simply being empty does not >necessarily signify the end of the sequence (e.g., the producer thread >might not be getting its fair share of CPU time). > >B: The Queue acts as a (potentially infinite) buffer for the generated >values, thus eliminating one of the primary benefits of generators: >their efficient "generate when required" nature. This can be helped >somewhat by limiting the number of entries in the Queue, but it is >still slightly unsatisfactory. > >C: A thread of execution has to be dedicated to the producer, thus >consuming resources. There are a number of ways of mitigating A and B; they mostly involve using an extra Queue.Queue to send tokens to the generator thread when a consumer wants data. The generator thread then sends back a token that (among other things) contains an attribute specifically for notifying the consumer that the generator is exhausted. See http://www.pythoncraft.com/OSCON2001/ThreadPoolSpider.py and http://www.pythoncraft.com/OSCON2001/FibThreaded.py for examples that show the technique, though they're not directly relevant to this case. My point is that I haven't (yet) seen many good use cases for sharing a generator between threads, and I'm guessing that many people will try using generators inappropriately for problems that really are better suited to Queue.Queue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From rodrigob at elo.utfsm.cl Mon Jan 26 15:49:06 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Mon, 26 Jan 2004 17:49:06 -0300 Subject: part string to block of information References: Message-ID: <4015796b$1_1@nova.entelchile.net> convert the string to a known encoding (or binary format), where each char has fixed size and play with the lenght. "Jos? Carlos" escribi? en el mensaje news:bv3rro$mp6$1 at nsnmrro2-gest.nuria.telefonica-data.net... > Hi. > > How can i part a big string to block of information of (4Kb for example).? > i?m trying send it from a socket client to server and how can i calculate > the time it?s coming. > > Thank you. > > Regards. > > Jos? Carlos > www.siadv.com > > > From newsgroups at jhrothjr.com Thu Jan 8 17:28:02 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Jan 2004 17:28:02 -0500 Subject: Descriptor puzzlement References: Message-ID: "Robert Brewer" wrote in message news:mailman.191.1073577858.12720.python-list at python.org... Peter Otten wrote: > John Roth wrote: > > It doesn't look like the descriptor protocol is getting > > invoked at all. > > The descriptor protocol works on the class, not the instance, so > > class AnotherObject(object): > prop = AnObject("snafu") > > or something similar should work. This means in particular > that you have to > store the property's state in the AnotherObject rather than > the AnObject > instance. I got bit by this myself, a while ago. Would there be any benefit to providing something like what John wanted, where the descriptor can maintain its own state, and be referenced by the owner instance (instead of the owner class)? I could sure use it in a couple of spots where my __getattr__/__setattr__ code is getting ugly. [reply by John Roth] Interesting thought. What was in the back of my mind for this experiment was the ability to insert metadata in the descriptor. I'm still not sure I can do that. I found I couldn't do it with the property descriptor (at least the experiment I tried failed, but now that I think of it I might have attempted it from the instance rather than the class.) John Roth Robert Brewer MIS Amor Ministries fumanchu at amor.org From http Thu Jan 8 21:30:50 2004 From: http (Paul Rubin) Date: 08 Jan 2004 18:30:50 -0800 Subject: Pesky reverse() References: <3t3svvs7ni8l8jnn1l1v60oogirqoaa85f@4ax.com> Message-ID: <7xfzep6eg5.fsf@ruckus.brouhaha.com> engsolnom at ipns.com writes: > print my_list.reverse() doesn't work. The reverse() method reverses the list in place and returns None. > But I want both a 'forward' and 'reverse' list: > > new_list = my_list # should save a 'forward' copy, right? Nope No, both new_list and my_list are bound to the same list, like in C you might have two pointers to the same structure. To make a copy, use new_list = my_list[:] > my_list.reverse() actually reverses both copies, since Python is a bit too > helpful sometimes, and I understand why. > > So the question is, how do I get a forward and reverse list? new_list = my_list[:] new_list.reverse() From robin at jessikat.fsnet.co.uk Wed Jan 21 13:00:07 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 21 Jan 2004 18:00:07 +0000 Subject: ReportLab 1.19 Released Message-ID: Version 1.19 of the ReportLab Toolkit has been released. Fixes from Max Neunh?ffer (pyRXP) and Peter Borocz (pdfmetrics). ReportLab graphics now has some 3D charts. Support for True Type Fonts in renderPM. Henning von Bargen's LongTables optimisation. Marc Stober's underline fixes. Restored/improved platypus layout error detection. New platypus FlexFigure flowable. ReportLab is now mostly jython compatible, but Python-2.3 no longer gives warnings. Pythonpoint improvements. Many bugfixes. ReportLab Links http://www.reportlab.com http://www.reportlab.org/downloads.html http://sourceforge.net/projects/reportlab -- Robin Becker From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 3 18:16:22 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 04 Jan 2004 00:16:22 +0100 Subject: Cheetah best for templating? References: Message-ID: Roger Jack: >Is Cheetah the best tool to use for templating source code files >and then generating code? I've choosen it for a project recently and IMO it's a good templating system. It would be good to get a little more guidance for using it in an easy PHP-way with mod_python, but other than that I have no gripes. -- Ren? Pijlman From diego.andrade at smartech.com.br Fri Jan 9 13:27:11 2004 From: diego.andrade at smartech.com.br (Diego.andrade) Date: Fri, 9 Jan 2004 15:27:11 -0300 Subject: Tcl/Tk Support Message-ID: Hi, Im not a Python programer, but I need to use Python on some aplications CVS related. Im trying to install ViewCVS who need Tkinter library. But It doesnt Work. Im using RedHat 9 Default Installation, to test if Tcl/Tk suport for Python is working I Type in the Python console import tkinter and received the following output: [root at Diego-Linux root]# 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 tkinter Traceback (most recent call last): File "", line 1, in ? ImportError: No module named tkinter >>> Im searching over the Python.org for a explanation of what I have to do but with no sucess... Thanks for help. Diego. ________________________________________________ Message sent using UebiMiau 2.7.2 From zunbeltz at wm.lc.ehu.es.XXX Fri Jan 9 07:25:59 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 09 Jan 2004 13:25:59 +0100 Subject: __init__, __slot__ and **keywordargs References: Message-ID: Peter Otten <__peter__ at web.de> writes: > > You misspelt: in fact it's __slots__, and it will work as expected. As far Hurg!!! :-( This kine of mistakes will become me crazy. > as I know slots are an optimization technique that is useful to save some > space, when you have many (that would be millions) of small objects. It's > not meant as a safety belt for the programmer. But, I think it can be considered "a safety belt for the programmer" , When you do instance.attribute you get and AttributeError if attribute is not in the __slots__ (It would help to avoid misspells, like i've done!!) > In your case, I wouldn't use it, but rather not initialize the attributes > not given as constructor - __init__() - arguments. Also, I would consider > the ability to provide additional arguments, say "Nickname", not a > bug but What do you mean with additional arguments? (My code was not the full code) > a feature. Of course you have to change your client code to test for > Not yet :-) I'm in planning stage yet and this code was only to play a bit to see what can i do. > hasattr(person, "Birthday") > > instead of > > person.Birthday is None > Thanks for this suggestion, I think i'll use hasattr. Zunbeltz > Peter > > -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From tim.golden at viacom-outdoor.co.uk Thu Jan 22 08:54:25 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 22 Jan 2004 13:54:25 -0000 Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain Message-ID: >Hi! > >I'm trying to get the PDC-Computername of a foreign WinNT-domain, but >I only managed to get the PDC of my own domain with this code: >pdc=win32net.NetGetAnyDCName() If you don't specify any params to that call, win32net will assume you're looking at your own domain. It can take two params: server & domain. If you do this: pdc = win32net.NetGetAnyDCName (None, "name_of_other_domain") it should work. 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 randall at tnr.cc Thu Jan 8 18:42:20 2004 From: randall at tnr.cc (Randall Smith) Date: Thu, 08 Jan 2004 23:42:20 GMT Subject: Python and SOAP In-Reply-To: <67ce7525.0401081515.cdde341@posting.google.com> References: <67ce7525.0401081515.cdde341@posting.google.com> Message-ID: Download soappy http://pywebsvcs.sourceforge.net/ Randall JuiceMan wrote: > Hi, i've been trying to access the my company's SOAP webservice with > no luck. > I'm using the httplib library. > > This is my code: > > > > from httplib import HTTP > from urllib import quote > > # Establish SOAP data > > SOAPdata = '' > SOAPdata = ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > xmlns:xsd="http://www.w3.org/2001/XMLSchema" > xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' > SOAPdata = SOAPdata + '\n ' > SOAPdata = SOAPdata + '\n xmlns="COM.COAIR.WWW.Technology.CoWebServices.COWSEmployeeServiceCenter">' > SOAPdata = SOAPdata + '\n XXXXXX' > SOAPdata = SOAPdata + '\n XXXXXX' > SOAPdata = SOAPdata + '\n XXXXX' > SOAPdata = SOAPdata + '\n ' > SOAPdata = SOAPdata + '\n ' > SOAPdata = SOAPdata + '\n' > > postdata = quote(SOAPdata) > > > print "\n************************* OUTGOING SOAP > ************************************" > print postdata > > # Begin HTTP request > req = HTTP("insidecoair5") > req.putrequest("POST", > "/cowsemployeeservicecenter/cowsemployeeservicecenter.asmx") > req.putheader("Accept", "text/xml; charset=utf-8") > req.putheader("Content-Type", "text/xml; charset=utf-8") > req.putheader("Content-Legth", str(len(postdata))) > req.putheader("SOAPAction", > "COM.COAIR.WWW.Technology.CoWebServices.COWSEmployeeServiceCenter/checkPassword") > > req.endheaders() > > # Send SOAP body > req.send(postdata) > > > ec, em, h = req.getreply() > print "\n*************************** HTTP RESPONSE > **********************************" > print ec, em > > print "\n*************************** HTTP HEADER RESPONSE > ***************************" > print h > > # get file-like object from HTTP response > # and print received HTML to screen > fd = req.getfile() > textlines = fd.read() > fd.close() > > print "\n************************** INCOMING SOAP > ***********************************" > print textlines > > > I get back a faultstring with a "THe root element is missing" error > > I cant seem to see what im doing wrong. Any help would be greatly > appreciated. From gstein at lyra.org Wed Jan 28 10:37:23 2004 From: gstein at lyra.org (gstein at lyra.org) Date: Wed, 28 Jan 2004 07:37:23 -0800 Subject: received your email Message-ID: <200401281537.i0SFbNlj023800@nebula.lyra.org> Hi, [ Re: Hello ] I have received your email, but it may take a while to respond. I'm really sorry to have to hook up this auto-responder, as it is so impersonal. However, I get a lot of email every day and find it very difficult to keep up with it. Please be patient while I try to get to your message. Please feel free to resend your message if you think I've missed it. I'll always respond to personal email first. If your email is regarding some of the software that I work on (if you have questions, comments, suggestions, etc), then please resend it to the appropriate mailing list: mod_dav WebDAV ViewCVS Subversion edna Thank you! Cheers, -g -- Greg Stein, http://www.lyra.org/ From xah at xahlee.org Mon Jan 26 22:04:31 2004 From: xah at xahlee.org (Xah Lee) Date: 26 Jan 2004 19:04:31 -0800 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> <40136b6d@news.victoria.tc.ca> <7fe97cc4.0401260943.2442ba4e@posting.google.com> Message-ID: <7fe97cc4.0401261904.4880149a@posting.google.com> a correction to my previous post. In my previous post i said one of the stupidity of Perl's File::Basename module is that it requires user to tell it OS type. This is incorrect. Thanks to Walter Roberson (roberson at ibd.nrc-cnrc.gc.ca) for this correction. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From automator at no.spam.please.wowway.com Tue Jan 20 19:47:53 2004 From: automator at no.spam.please.wowway.com (Tim O'Connell) Date: Tue, 20 Jan 2004 19:47:53 -0500 Subject: CD Insert Notification in WinXP Message-ID: Hi, I'm using Python 2.3 on a Win XP box, and I'm trying to find if there's a library of some sort that will give you a callback (or something comparable) when a new disc is inserted into a CD Rom drive. I've done a little googling and nothing's come up, so I'm not holding my breath. :) If not, I'm thinking of implementing a thread to periodically read the volume serial number using GetVolumeInformation from Mark Hammond's Win 32 extensions, then doing a compare against the last known value. Does this sound "sane"? Any recommendations would be useful. Thanks! Tim From a at agni.us Mon Jan 12 23:16:58 2004 From: a at agni.us (a at agni.us) Date: Tue, 13 Jan 2004 04:16:58 GMT Subject: Stackless and Discrete event Simulation Message-ID: <_iKMb.157428$Dp5.77359@fe3.columbus.rr.com> Can python community points out advantage and disadvantage of using stackless python over python for a discrete event simulation model? From graham__fawcett at hotmail.com Mon Jan 12 13:52:33 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 12 Jan 2004 10:52:33 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: Wilk wrote in message news:<87oet9grqy.fsf at blakie.riol>... > ketulp_baroda at yahoo.com writes: > > > The problem i am facing here is i dont know what to use for > > development of the application. I came across many ways to develop web > > application in python which I already specified like > > i)the cgi module in python > > ii)Python Server Pages > > iii)Quixote > > iv)WebWare > > v)Zope etc. > > I want to choose such an environment so that i dont have to install > > other softwares to run my application.For eg. I think if I develop > > using zope then the client also has to install zope to run my software > > and i dont want this. > > When you use one of theses servers, you don't need to install anything > else than a classic browser on the client side. > On the server side, most of the servers will not need anything else, you > can even start without server with the batterie include : > BasicHTTPServer (it was somes examples on this list somes days ago). Just a guess, but I suspect the OP is using the term "client" in the business sense, not the client/server sense; that is, he's trying to write a Web application that is easy to deploy on his clients' (customers') servers. If it has to be a one-shot install, I would suggest a Web server written in Python -- Medusa or Twisted, probably -- that you could bundle with your Python app. Find a Web app framework that (a) works on Medusa or Twisted and (b) has the templating features you require/desire. I wouldn't jump at using Twisted's app framework (Woven?) on top of Twisted's Web server, though. No disrespect intended to the Twisted community or their great body of work; it's just that server and app-framework are two separate concerns: one day you might want to or need to switch Web servers, and you need to know that your framework is portable. I'm no Twisted expert: perhaps Woven is indeed portable, and a kindly Twisted person will elaborate here. -- Graham From llothar at web.de Thu Jan 15 01:12:37 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Jan 2004 22:12:37 -0800 Subject: what is best for web development?? References: <87oet9grqy.fsf@blakie.riol> <6ee58e07.0401140638.672d50a7@posting.google.com> <100b4qoeeeq7d57@corp.supernews.com> Message-ID: <6ee58e07.0401142212.424eea09@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<100b4qoeeeq7d57 at corp.supernews.com>... > > I'm unsure what you're recommending. We're considering a self-contained > Web application, including the Web server itself. Are you proposing: > 1. An installer which does a conventional Apache > installation, except with enough stuff confi- > gured so it comes up in a safe state, PLUS > a separate installation segment just for the > Python-based part; or > 2. A custom installer which knows internal details > of both Apache and the Python-based application? > > What advantage do you see for either of these over the pure-Python ap- > proach suggested above? Is your point that customers feel more > comfortable with "Apache inside"? I would use (2), simply because (1) could have influences with an existing installation. I hate the window programs who install apache/php and kill my machine (like Numegas PHPEd or Magumas older version). Such an installation should never use the standart paths, ports or anything else. And yes "Apache inside" is a very good marketing argument. Apache has proven to be robust to most of the denial of service attacks and if there is a good administrator in the company he can update it easily with security patches. I found that companies that are sensitive to security issues try to avoid home grown server as much as possible. From __peter__ at web.de Sun Jan 18 17:58:47 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 Jan 2004 23:58:47 +0100 Subject: re question - finiding matching () References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: Miki Tebeka wrote: > To all of you regexp gurus out there... So not asking me, but anyway... > I'd like to find all of the sub strings in the form "add(.*)" > The catch is that I might have () in the string (e.g. "add((2 * 2), > 100)"), > > Currently I can only get the "addr((2 *2)" using > re.compile("\w+\([^\)]*\)"). To solve the problem a hand crafted search is > used :-( > > Is there a better way? Iff you are looking into Python code, you could also use the compiler module. The following script scans itself for occurences of add() function calls. import compiler def sample(): """ add(xxx) <- will not be found """ x.add(1) # <- will not be found add(a*(b+c)) add(a, b) add() add((1*1),2)+add((2)) class Visitor: def visitCallFunc(self, node): if getattr(node.getChildren()[0], "name", None) == "add": print node tree = compiler.parseFile(__file__) compiler.visitor.walk(tree, Visitor()) Peter From gduzan at bbn.com Mon Jan 12 13:16:08 2004 From: gduzan at bbn.com (Gary D. Duzan) Date: Mon, 12 Jan 2004 18:16:08 GMT Subject: Why " ".some_string is often used ? References: Message-ID: In article , Dave Benjamin wrote: > >The argument is more of a technical issue. There are only two kinds of >strings. There are many kinds of "iterables". So, it's easier to define >"join" on the string, and force implementers of custom string types to >implement "join" as well (since this is more rare) than to define "join" on >an iterable and force implementers of the many kinds of iterables to define >"join" as well. Conceptually, I'm not sure that the case is so strong that >"join" is a string method. > > [ ... ] > >Sometimes, object-orientedness gets in the way, and I think this is one of >those cases. "str.join" is probably the winner here, but since it's really >just a string method being used "out of context", the delimeter is the first >argument, and this doesn't read well to me. I think that "string.join" makes >more sense; it says "join this sequence using this delimeter" instead of >str.join's "join using this delimeter this sequence". Why not something really simple which does something like this? def myjoin(seq,sep): def _addsep(l, r, s=sep): return l+s+r return reduce(_addsep, seq) >>> myjoin(['a','b','c'], ",") 'a,b,c' >>> myjoin(['a','b','c'], "") 'abc' >>> myjoin([1,2,3,4], 0) 10 >>> myjoin("abcd", ',') 'a,b,c,d' It might not be the fastest, but it is straightforward and generic, and could be optimized in C, if desired. Gary Duzan BBN Technologies A Verizon Company From mark at mceahern.com Sun Jan 18 14:39:57 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 18 Jan 2004 13:39:57 -0600 Subject: Printing variable names In-Reply-To: References: Message-ID: <400AE10D.3080403@mceahern.com> Mike wrote: >mylist = [a, b, c] > >I want to print out the names of the variables in mylist (not the >values of a, b, and c). How do I go about doing this. Thanks. > >Mike > > There's no simple answer to this. Consider the fact that you can have more than one name bound to any given mutable instance. What if: a = range(10) b = a mylist = [a] what name do you want printed for the first item in mylist--'a' or 'b'? One idea is to use a dictionary instead. Then: for key, value in mydict.iteritems(): print '%(key)s = %(value)s' % locals() I'm curious what problem you're trying to solve. Cheers, // m From tweedgeezer at hotmail.com Mon Jan 26 11:42:11 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 26 Jan 2004 08:42:11 -0800 Subject: unittest References: Message-ID: <698f09f8.0401260842.6fc8a35c@posting.google.com> Change your method name to begin with "test" instead of "Test" and it should work. Jeremy From michael at telcopartners.com Thu Jan 15 01:53:54 2004 From: michael at telcopartners.com (Michael Spencer) Date: 14 Jan 2004 22:53:54 -0800 Subject: Tkinter.Text.edit_modified() TypeError Message-ID: <502a6f2c.0401142253.5e028471@posting.google.com> Using: Python 2.3.3 Tkinter.TclVersion = 8.4000000000000004 Windows XP Calling edit_modified() on a Tkinter.Text object raises TypeError when it gets a Boolean True response. Exception in Tkinter callback Traceback (most recent call last): File "D:\Python23\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "\\Cc1040907-a\c$\Documents and Settings\Michael\My Documents\PyDev\GUI\T Egui.py", line 64, in command = lambda tag = maketag(i), label = label:menudispatch(label,tag)) File "\\Cc1040907-a\c$\Documents and Settings\Michael\My Documents\PyDev\GUI\T Egui.py", line 27, in menudispatch return func() File "\\Cc1040907-a\c$\Documents and Settings\Michael\My Documents\PyDev\GUI\T Egui.py", line 49, in handle_File_Close if tbx1.edit("modified"): File "D:\Python23\lib\lib-tk\Tkinter.py", line 2819, in edit return self._getints( File "D:\Python23\lib\lib-tk\Tkinter.py", line 972, in _getints return tuple(map(getint, self.tk.splitlist(string))) TypeError: coercing to Unicode: need string or buffer, bool found From usenet_spam at janc.invalid Fri Jan 9 17:06:11 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 09 Jan 2004 22:06:11 GMT Subject: Python is far from a top performer according to benchmark test... References: Message-ID: Tim Churches schreef: > I notice that the author of those benchmarks, Christopher W. > Cowell-Shah, has a PhD in philosophy. Perhaps Python's very own > philosophy PhD, David Mertz, might like to repeat the benchmarking > exercise for one of his columns, but including manipulation of more > realistic data structures such as lists, arrays and dictionaries, as > Carl suggests. And then don't forget to publish it on /. or nobody sees it... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jcarlson at nospam.uci.edu Thu Jan 22 22:25:16 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 19:25:16 -0800 Subject: I support PEP 326 In-Reply-To: References: <401081A1.E4C34F00@alcyone.com> Message-ID: > Or, expressing the idea that they're the ends of a number line: > > PosInf, NegInf > PosInfinity, NegInfinity > PositiveInfinity, NegativeInfinity > > If IEEE floating point was done correctly everywhere, I'd say make > them the corresponding floating-point constants (Inf+ and Inf-). > > Or, > FreakingHuge, FreakingHugeTheOtherWay PosInf, NegInf PosInfinity, NegInfinity PositiveInfinity, NegativeInfinity All suggest that the Max and Min (or whatever you want to call them) are numbers. Such a thing is misleading, and also tends to tie PEP 326 with PEP 754 (IEEE 754 Floating Point Special Values, which makes the case for a consistant name for +/- FP Infinity). As stated in my PEP: Guido has brought up [2]_ the fact that there exists two constants that can be used in the interim for maximum values: sys.maxint and floating point positive infinity (1e309 will evaluate to positive infinity). However, each has their drawbacks. - On most architectures sys.maxint is arbitrarily small (2**31-1 or 2**63-1) and can be easily eclipsed by large 'long' integers or floating point numbers. - Comparing long integers larger than the largest floating point number representable against any float will result in an exception being raised:: >>> cmp(1.0, 10**309) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to float Even when large integers are compared against positive infinity:: >>> cmp(1e309, 10**309) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to float - These same drawbacks exist when numbers are small. From klapotec at chello.at Thu Jan 29 18:41:33 2004 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 29 Jan 2004 23:41:33 GMT Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: On Thu, 29 Jan 2004 17:21:19 -0500, cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: >At some point, LittleDanEhren at yahoo.com (Daniel Ehrenberg) wrote: > [snip-a-lot] > >> For embedding, Io doesn't have to use Py_ALL_CAPS, instead it just >> uses IoCamelCase, which looks much better. Interfaces to C are much >> more object oriented. > >Ok, these two points are window-dressing: minor spelling and >punctuation issues (which seems to be what most language wars are about). > >Heck, use boost::python for C++ interfaces; those function names are >even shorter. Or use pyrex to generate wrappers, writing them in a >Pythonesque language. > >> Many users of Io (myself included) have switched over from Python for >> these reasons. >> >> I guess there are still the obvious advantages of Python over Io, >> including >> *large community >> *more bindings to stuff > >Yep. That's a *big* difference, I'd say. Using any language (other than a Lisp) which is sufficiently powerful mostly comes down to personal preference regarding syntax. Library and community support will of course grow for new languages if enough people find it 'fits their minds' better than anything previously available. > >> *strict coding conventions >> *inflexible so everything is the same > >Can you elaborate a bit on why Python is inflexible? I find Python to >be extremely flexible. If inflexibility means not being able to arbitrarily change the syntax, then I'm all for it, because it does help consistency and readability, which I like very much in my programs, especially when not working on them alone... Python seems to have found a good middle ground between strictness and dynamism. If I wanted a 'flexible' language, I'd use Lisp, or Forth. -- Christopher From skip at pobox.com Thu Jan 15 15:51:35 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Jan 2004 14:51:35 -0600 Subject: Inserting while itterating In-Reply-To: <1074140382.26201.26.camel@dev.internal> References: <1074140382.26201.26.camel@dev.internal> Message-ID: <16390.64855.461276.130438@montanaro.dyndns.org> >>>>> "Mark" == Mark McEahern writes: Mark> On Wed, 2004-01-14 at 02:43, Thomas Guettler wrote: >> Hi, >> >> Simple excerise: >> >> You have a sorted list of integers: ... >> and you should fill all gaps: ... >> How would you code this? >> >> Constrain: The original list should be changed, don't create a copy. Mark> In the spirt of unit testing... Mark> #!/usr/bin/env python ... Here's a version which is much faster if you have large gaps and appears to be only marginally slower if you have small gaps. Skip #!/usr/bin/env python #!/usr/bin/env python def fillGaps1(seq): expectedLength = seq[-1] - seq[0] + 1 i = 1 while i < expectedLength: if seq[i] - seq[i-1] > 1: seq.insert(i, seq[i-1] + 1) i += 1 def fillGaps(seq): expectedLength = seq[-1] - seq[0] + 1 i = 1 while i < expectedLength: if seq[i] - seq[i-1] > 1: gap = seq[i-1] - seq[i] fill = range(seq[i-1]+1, seq[i]) seq[i:i] = fill i += len(fill) i += 1 if __name__ == "__main__": import timeit print "timing with one large gap:" t = timeit.Timer(setup='from fillgaps import fillGaps1 as fillGaps', stmt='fillGaps([1, 5000])') print "old fillgaps:", t.timeit(number=100) t = timeit.Timer(setup='from fillgaps import fillGaps', stmt='fillGaps([1, 5000])') print "new fillgaps:", t.timeit(number=100) print "timing with many small gaps:" t = timeit.Timer(setup='from fillgaps import fillGaps1 as fillGaps;l=range(1,5001,2)', stmt='fillGaps(l)') print "old fillgaps:", t.timeit(number=100) t = timeit.Timer(setup='from fillgaps import fillGaps;l=range(1,5001,2)', stmt='fillGaps(l)') print "new fillgaps:", t.timeit(number=100) import unittest class test(unittest.TestCase): def test(self): for fg in (fillGaps1, fillGaps): l = [1, 2, 4, 7, 8, 12] fg(l) self.assertEquals(l, range(1, 13)) l = [1, 5000] fg(l) self.assertEquals(l, range(1, 5001)) unittest.main() From graham__fawcett at hotmail.com Thu Jan 15 00:28:57 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 14 Jan 2004 21:28:57 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> <6ee58e07.0401140638.672d50a7@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0401140638.672d50a7 at posting.google.com>... > graham__fawcett at hotmail.com (Graham Fawcett) wrote in message news:... > > Wilk wrote in message news:<87oet9grqy.fsf at blakie. > > > If it has to be a one-shot install, I would suggest a Web server > > written in Python -- Medusa or Twisted, probably -- that you could > > bundle with your Python app. Find a Web app framework that (a) works > > on Medusa or Twisted and (b) has the templating features you > > require/desire. > > I would not recommend this. A distribution with an own apache server > seems to be the best. It is easy to hide the setup and the customers > know that there is a good working technologie behind the scenes. And > it can be managed by every normal administrator. This is a very > important point for larger customers. Therefore, you are suggesting ASP running on IIS? Or JSP + SunONE + Oracle? <0.5 wink> Few Python solutions would satisfy the customer who bears this level of concern. There are countless potential customers for Intranet applications who will never be able to install Apache. Many of them will never meet a "normal administrator" -- by which I assume you mean the "FOSS-savvy, got Knoppix right here on my keydrive" variety, not the MS/Lotus/Netware kind -- let alone employ one. They still deserve and will pay for Intranet apps, and the company that can deliver and deploy them easily will have a business advantage. (I will never forget the first time I delivered such an app to a client, and told him "just run the setup program", and he had a fully functional Web app -- Web server, database and all -- running 40 seconds later. Nor will I forget the funny sound his jaw made as it hit the floor.) Lastly, almost any app that will run on a Python web server will also run on Apache et. al., right? Unless you design it with Apache-centric features; but I don't know if your concerned customer would appreciate unnecessary platform lock-in! Offer both a Quick-Start and an FCGI flavour of your app, and let the customer decide what he's capable of administering. In my book, an application that scales down (embedded httpd) as well as up (Apache, etc.) beats a scaled-up-and-nowhere-to-go app any day. Best wishes, -- G From nomail at hursley.ibm.com Tue Jan 27 21:18:59 2004 From: nomail at hursley.ibm.com (Derek Fountain) Date: Wed, 28 Jan 2004 10:18:59 +0800 Subject: Tcl style traces Message-ID: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Does Python have something similar to Tcl style tracing? That is, the ability to call a subroutine when a variable is written to or read from? From tepihlaj at paju.oulu.fi Mon Jan 5 20:04:31 2004 From: tepihlaj at paju.oulu.fi (Tero Pihlajakoski) Date: 6 Jan 2004 01:04:31 GMT Subject: Python/C and PYTHONPATH References: Message-ID: Samuel Walters wrote: > |Thus Spake Tero Pihlajakoski On the now historical date of Mon, 05 Jan > 2004 22:39:19 +0000| >> I'll see if it's actually the C-part that's causing problems, but I worked >> it around by adding: >> >> PyRun_SimpleString("import sys\nsys.path.insert(0,'')"); >> >> right after the Py_Initialize(). >> >> Works ok. Guess I'm "allowed" to do that(?) > IMLK (In My Limited Knowledge) that seems okay, but it also feels a bit > ham-handed. try this snippet: Ok, there are comments here, somewhere: > ---untested code--- > #include > #include > /* prototyping may not be neccessary... dunno...*/ > extern char *getenv(const char *name); > extern char *setenv(const char *name, const char *value, int overwrite); > /* comment them out if gcc complains about redeclarations. */ > /* append something to pythonpath */ > /* returns 0 on failure, 1 on creation of the env variable and 2 on an append > oh, and -1 in cases of catastrophic miscompilation */ > int myPyPathAppend(char *extrapath) > { > char *buffer = NULL; > /* size to taste... You should do this dynamically to avoid future buffer overrun attacks*/ > char eventual_path[1024] = { 0 }; > /* take note: after getenv, buffer points to an external constant character buffer. > do NOT try to modify it directly. use strcpy(char *dest, char *src) > (he says knowingly... is she into photography mate?) > */ > if( (buffer = getenv("PYTHONPATH")) == NULL ) > { > /* we're here because PYTHONPATH is not already part of the environment. */ > > setenv("PYTHONPATH", extrapath, 1); /* the last argument makes sure that we create the env var*/ > /* did it go happen .. you should check this more rigorously*/ > if( (buffer = getenv("PYTHONPATH")) == NULL) > { > /* we failed... abend. */ > return 0; > } > else > { > /* success! cheers! */ > return 1; > } > return -1; /* dead code... should never reach here */ > } > else > { > /* PYTHONPATH already exists. append ';', then our new path and update it. */ Here. I might not want to add ';' or ':', depending on the OS (probably not)? I can solve this with #ifdefs for WIN32 and Linux, but everytime I want to run it on a new system, I'd have to find out the delimiter... It also needs a buffer underrun check on that [1024]. I'll stick with the PyRun_... for now, but I'll definitely save this code, so thanks. Again. Also, found this piece from sys.path docs (now that my net is up and running): ... "A program is free to modify this (sys.path) list for its own purposes." ... > > /* find the "=" in the buffer... > from string.h > extern char *strstr (__const char *__haystack, __const char *__needle) > there's a better way to do this, but I can't recall the function off the top of my head > */ > buffer = strstr(buffer, "=") + 1; /* +1 because buffer points to the equals. we want the string starting after it. */ > > /* copy the old PYTHONPATH string */ > strcpy(eventual_path, buffer); > strcat(eventual_path, ";"); > strcat(eventual_path, extrapath); > setenv("PYTHONPATH", extrapath, 1); /* the last argument makes sure that we create the env var*/ > /* did it go happen .. you should check this more rigorously*/ > if( (buffer = getenv("PYTHONPATH")) == NULL) > { > /* we failed... abend. */ > return 0; > } > else > { > /* success! cheers! */ > return 2; > } > return -1; /* dead code... should never reach here */ > } One if and two elses, have you started "getting ready" for the party already? ;) Or maybe it's fuzzy logic ;) > else > { > /* PYTHONPATH already exists. append ';', then our new path and update it. */ > /* find the "=" in the buffer... ... snip ... > } > return -1; /* deader code... should *really* never reach here */ > } > ---untested code--- > I haven't tested, compiled or even read through this code. > I'm late for a party and still added comments > That means you get punctuation patrol :-P > Check the semicolons, check the braces > Hey, I hear that in some companies they call this teamwork methodology > "extreme-programming" We're buzzword compliant! - Tero -- From sross at connectmail.carleton.ca Sat Jan 3 13:48:12 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 13:48:12 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> Message-ID: <%5EJb.20472$Vl6.3783985@news20.bellglobal.com> "Sean Ross" wrote in message news:11EJb.20461$Vl6.3782481 at news20.bellglobal.com... >then a/b is represented by [1] as 'represented' is the wrong word here, but hopefully, you get the idea ... From fisher at energy.uch.net Mon Jan 26 07:17:22 2004 From: fisher at energy.uch.net (Serge A. Ribalchenko) Date: Mon, 26 Jan 2004 14:17:22 +0200 Subject: TELNET instead PING In-Reply-To: <5f505344.0401260332.184d4225@posting.google.com> References: <5f505344.0401260332.184d4225@posting.google.com> Message-ID: DCK wrote: > Hello :) > > Into group-archive i found most e-mails, which touches PINGing. > In my work i've used TELNET for testing if host is operational. > Sometimes, for unknown reasons, workstation doesn't respond > for PINGing. But in WinNT network, all hosts has a nbsession > listening on port 139. I always use this script instead PING > command (hope, will be usefull for someone :) ): thanks a lot. Can you do the same using ARP who-has request ? :) From rmkrauter at yahoo.com Fri Jan 23 23:31:57 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri, 23 Jan 2004 23:31:57 -0500 Subject: Batch commands on Windows In-Reply-To: References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <1074918717.4458.142.camel@vaio> Each of your system calls spawns it's own separate shell with its own set of environment variables. You probably want to look into os.environ (python) or %ENV (perl) to set your shell variables. On Fri, 2004-01-23 at 23:23, Moosebumps wrote: > > Can you give an example of what you mean, in Perl as well as what you > hoped > > would work in Python? I couldn't quite understand what it is that you're > trying > > to do. > > OK, actually on second test, the problem is mostly with IDLE, but not > totally. When I hit F5 under IDLE, it behaves differently with respect to > the command window then if I just run it by double-clicking on the file. > > Here is an example: > > BatchTest.bat: > > set MYVAR=3 > dir > pause > dir > echo %MYVAR% > pause > > BatchTest.py: > > # the intention is to do the same thing as BatchTest.bat, but it doesn't > work under either IDLE or by double-clicking > # in particular the environment variable is not saved, and it doesn't work > if I replace os.system with os.popen > > import os > > os.system("set MYVAR=3") > os.system("dir") > os.system("pause") > os.system("dir") > os.system("echo %MYVAR%") > os.system("pause") > > BatchTest.pl: > > # this actually does the same thing as Python, I was mistaken. I was > mislead by the IDLE behavior. > > system('set MYVAR=3'); > system('dir'); > system('pause'); > system('dir'); > system('echo %MYVAR%'); > system('pause'); > > The general idea is that it would be nice if there weren't any differences > between the batch file and python. From a practical standpoint, it would > encourage a lot of people to switch from nasty batch files to Python scripts > if you could just surround the entire thing with os.batch(' ') or some > similar sort of mechanical textual substitution. Then you could clean it up > gradually. > > I am aware of os.environ and such, and that is useful, but it's not really > the point. > > Of course I could write a function to take a bunch of strings, write a batch > file, save the working directory, execute it, restore the current directory, > then delete the batch file, but that seems like an awful hack. Though I > probably will do that at some point. > > > > What's the deal with that? I thought Python started out as a scripting > > > language. And that seems like the most basic thing that a scripting > > > language should do. > > > > Dunno, although MS-DOS shell scripting is certainly a small subset of > scripting > > in general. Maybe with a concrete example somebody will be able to give > you a > > hand. > > It is a small subset, but an important subset. Shell scripting started > probably when people got sick of typing the same commands into the prompt. > For a language to really support shell scripting, it should provide a way of > automating the process of typing in the commands. As in, there should be no > difference whether you're actually typing, or you're running the script. > > If there is a way and I don't know about it, I would be happy to hear about > it. But I do think it is a pretty big hole. > > MB > -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Jan 28 14:06:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 14:06:25 -0500 Subject: Deprecated modules References: Message-ID: <40180831.D860A0B4@engcorp.com> Richard Philips wrote: > > How can I look for deprecated standard library modules in my scripts > WITHOUT executing these scripts? Grep? From dave at pythonapocrypha.com Sat Jan 24 14:43:30 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 24 Jan 2004 12:43:30 -0700 Subject: progress bar References: <59e5b87.0401231329.6e084d6f@posting.google.com> <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> Message-ID: <04e501c3e2b2$589b1380$6401fea9@YODA> Hoang wrote: > > Try Venster: > > http://venster.sourceforge.net > > > > IIRC the test_coolbar.py script includes a progress bar. > > I wonder what possessed someone to start another GUI framework. Aren't > there more than enough existing ones? The reasoning for it wasn't > immediately apparent on the web page. Well, the intro you read said: "Venster is a highly native Windows GUI toolkit for Python based on the ctypes ffi library. The aim of Venster is to be a very lightweight wrapper around the standard Win32 API, making it easy to write slick windows applications in pure Python. " Being very lightweight is a big deal compared to many other frameworks. I include Venster in one of my applications and it weighs in at under 100KB. If size of download / installer is important, this is a real win compared to the multi-megabyte size of most other frameworks - the entire application (Python + Venster + app) is shipped in a 1.3 MB cab file. The other thing worth noticing from the intro is that Venster is pure Python. Because of that it's very easy to extend and you avoid all sorts of build hassles because there _is_ no build. IMO the main downside of Venster is that it is not yet as mature as other frameworks, so programming in it is not nearly as highlevel as, say, wxPython. Still, there's a number of places where it's a good fit already - at my company we recently started using it in a new application where the UI is either done in Flash or in a few dialog boxes, and Venster creates the Window to host the UI, does the dialog boxes, and handles the events generated by Flash - it'd be overkill to have to include all of wxPython just to get that functionality. -Dave From bsneddonNOspam at yahoo.com Wed Jan 28 09:27:59 2004 From: bsneddonNOspam at yahoo.com (Bill Sneddon) Date: Wed, 28 Jan 2004 09:27:59 -0500 Subject: r prefix bug ... or my lack of understanding? Message-ID: Below is from python 2.3.3 on windows. I have tryed on Pythonwin and Idle and on a Solaris unix build 2.2.2. I know there are work arounds but the behavior seems a bit strange to me. >>> path = r'c:\data' #this is fine >>> print path c:\data >>> path = r'c:\data\' Traceback ( File "", line 1 path = r'c:\data\' ^ SyntaxError: EOL while scanning single-quoted string >>> path = r'c:\data\\' >>> print path c:\data\\ From M.Waack at gmx.de Sat Jan 3 17:38:20 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Sat, 03 Jan 2004 23:38:20 +0100 Subject: Lists are weird when they are instance members References: Message-ID: python newbie wrote: > test.py > ---------------- > > global_filegroup_array = [] # array of filegroup objects > > class FileGroup: > a = 0 > mylist = [] # here it is This is a class variable, not a member or instance variable. Make sure you know the difference. > def put_stuff_in_my_list(self, anyfile): > self.mylist.append( get just a single string from > file) This line creates a member variable "mylist" of the current instance "self" of class "FileGroup" as a copy of the class variable "FileGroup.mylist". Just create your member variables in the c'tor function __init__. This should solve all your problems (ok, at least this problem;) And btw. Python in a nutshell (I haven't read the other books you've mentioned) explains the differences between class and member variables. Mathias From tdelaney at avaya.com Thu Jan 8 19:51:23 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 9 Jan 2004 11:51:23 +1100 Subject: What psyco is goot at [Was: Rookie Speaks] Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE010637C9@au3010avexu1.global.avaya.com> > From: Samuel Walters > > Psyco only optimizes functions as a whole. Oh yeah - that's the killer all right. There's no question where the bottleneck is in terms of how psyco.profile() can work on that particular piece of code. The code in question is in any case a prototype. I was using it as a datapoint to show that you do need to test with the various options to see what works for your application. In that case, the psyco.full() overhead was insignificant compared to the memory usage, and had great advantages. In some other cases, psyco.profile() will be better. Anyway, when the non-psyco code takes an hour, and the psyco.full() version takes 10 minutes, you know you're onto a winner :) Tim Delaney From clifford.wells at comcast.net Mon Jan 26 03:55:46 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 26 Jan 2004 00:55:46 -0800 Subject: Class returning None ? In-Reply-To: <2r4Rb.286342$e6.11127748@twister2.libero.it> References: <2r4Rb.286342$e6.11127748@twister2.libero.it> Message-ID: <1075107345.13581.1060.camel@devilbox.homelinux.net> On Mon, 2004-01-26 at 00:43, George Marshall wrote: > Hi, I'm wondering, what's the best way to check for > success or failure on object initialization ? Raise an exception. > This is my ugly workaround to do that : [snip] > What's the python way to do that ? from exceptions import Exception class SomeError(Exception): pass class mytest: def __init__(self): if not everythingok(): raise SomeError def main(): try: a = mytest() except SomeError: return 1 Regards, Cliff -- Pushing the stone up the hill of failure -Swans From jikosan at myrealbox.com Sun Jan 11 17:37:25 2004 From: jikosan at myrealbox.com (Jikosan) Date: Sun, 11 Jan 2004 22:37:25 GMT Subject: Help with if statement References: <7xk73y8eet.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xk73y8eet.fsf at ruckus.brouhaha.com... Thanks Paul. I so far have only been learning Python from the tutorial and greatly appreciate your tips. | | > #Convert pi and N to log10 and write to a file to graph on Excel. | | Why are you going to graph log(N) vs log(pi)? Do you expect them | to have an exponential relationship? If not, log(N) vs pi, instead | of log(pi), may make more sense. Because my professor wants us to graph it log(N) vs log(pi). Actually, it's log [P(N) - pi/4] vs log N. I misread the question again last night. From anton at vredegoor.doge.nl Sat Jan 31 04:05:04 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 31 Jan 2004 10:05:04 +0100 Subject: HowTo Search in nested lists References: Message-ID: <401b6fee$0$130$3a628fcd@reader2.nntp.hccnet.nl> Christopher Koppler wrote: [Robert] >>Good answers, Christopher. You might consider combining the several >>approaches into a single one by creating an iterator; >Well, just what popped into my mind first. I still have some trouble >getting iterators and generators to pop up before, though often >they're just so much more elegant, as your solution shows. But for >that I have to consciously think about the problem, whereas ordinary >functions are quite entrenched in my brain. I blame my shady past of >Pascal, Visual Basic, Modula 2, C, and Java. At least by now I >instantly think of list comprehensions... One might also consider the following solution which swaps rows and columns by combining the star operator and the zip function : print [i for i,col in enumerate(zip(*t)) if 5 in col] Anton From fuf at mageo.cz Wed Jan 28 08:02:04 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 28 Jan 2004 14:02:04 +0100 Subject: type() for new style classes - buggy? Message-ID: <20040128130204.GA10744@foof.i3.cz> hello, does the type() command work correctly for new style classes? i guess it does not, unfortunately. for example, for a new style class' instance it returns , but for old style class' instance it returns . >>> import types >>> class A(object): pass >>> class B: pass >>> type(A()) >>> type(B()) >>> type(A()) == types.InstanceType 0 >>> type(B()) == types.InstanceType 1 how can one then determine what he's working with when he uses new style classes (either instance or class)? thank you, -- fuf (fuf at mageo.cz) From db2team at hotmail.com Thu Jan 22 05:23:49 2004 From: db2team at hotmail.com (DB2) Date: 22 Jan 2004 02:23:49 -0800 Subject: python As400 References: Message-ID: You will need an ODBC driver for DB2, ie Client Access or StarSQL (www.starquest.com). Bob Jarek Zgoda wrote in message news:... > Enrique pisze: > > > i checked before this website, http://www.iseriespython.com/, but found no > > much information in it (docs) > > Sorry, I meant "check this site to read documentation for > AS/400-specific modules". > > > worse? how much worse? more worse that can be assumed? > > I don't know, I never tried to measure it. > > > and connect python on windows with db2 in as400?? > > No chance except ODBC (http://www.egenix.com/) or ADO (i.e. adodbapi on > SourceForge), anyway you will need Client Access installed. From mwh at python.net Mon Jan 12 14:12:53 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 12 Jan 2004 19:12:53 GMT Subject: script to translate from compiler AST References: Message-ID: Andrey Khavryuchenko writes: > Imagine, I've built an AST that I want to run. I've not found an > easy (read library) way to do that, hence the question. Ah! Try http://groups.google.com/groups?th=f3f7a7f6fac16ca2 Cheers, mwh -- A.D. 1517: Martin Luther nails his 95 Theses to the church door and is promptly moderated down to (-1, Flamebait). -- http://slashdot.org/comments.pl?sid=01/02/09/1815221&cid=52 (although I've seen it before) From carroll at tjc.com Wed Jan 14 17:48:46 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed, 14 Jan 2004 22:48:46 GMT Subject: Unicode and exception strings References: Message-ID: On Wed, 14 Jan 2004 01:32:36 GMT, Terry Carroll wrote: >You can try to extract it as above, and then decode it with the codecs >module, but if it's only the first byte, it won't decode correctly: > >>>> import codecs >>>> d = codecs.getdecoder('utf-8') >>>> x.args[0] >u'\xf8' >>>> d.decode(x.args[0]) >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'builtin_function_or_method' object has no attribute >'decode' >>>> Oops. Copy-and-pasted the wrong line here. Let's try that again: >>> x = ValueError(u'\xf8') >>> import codecs >>> d = codecs.getdecoder('utf-8') >>> d(x.args[0]) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 0: ordinal not in range(128) >>> *That's* the exception I was trying to show, not the AttributeError you get when you use the decoder wrongly! From gerrit at nl.linux.org Mon Jan 19 17:12:59 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 19 Jan 2004 23:12:59 +0100 Subject: __init__(self, *args, **kwargs) - why not always? In-Reply-To: References: Message-ID: <20040119221259.GA11631@nl.linux.org> Jim Jewett wrote: > More specifically, is there any reason not to replace: > > class SubClass(BaseClass): > def __init__(self): > BaseClass.__init__(self) > > with: > > class SubClass(BaseClass): > def __init__(self, *args, **kwargs): > BaseClass.__init__(self, *args, **kwargs) > > on a near-global basis? A subclass may be a specialized case, e.g.: class Tree: def __init__(self, evergreen=False): ... class Spruce(Tree): def __init__(self): Tree.__init__(self, True) or the other way around, e.g. class Enemy: def __init__(self, pos): ... class ShootingEnemy(Enemy): def __init__(self, pos, bullets): Enemy.__init__(pos) ... In both cases I don't want to BaseClass.__init(self, *args, **kwargs)... yours, Gerrit. -- 105. If the agent is careless, and does not take a receipt for the money which he gave the merchant, he can not consider the unreceipted money as his own. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From goodger at python.org Tue Jan 27 21:50:04 2004 From: goodger at python.org (David Goodger) Date: Tue, 27 Jan 2004 21:50:04 -0500 Subject: Confused about a list.sort() In-Reply-To: References: Message-ID: <4017235C.2010605@python.org> list.sort() sorts the list in-place; it doesn't return a new list. Instead of "List1 = List1.sort()" just do "List1.sort()". See the FAQ entry: http://www.python.org/doc/faq/general.html#why-doesn-t-list-sort-return-the-sorted-list -- David Goodger From ewilhelm at somethinglike.sbcglobalDOTnet Thu Jan 22 17:51:46 2004 From: ewilhelm at somethinglike.sbcglobalDOTnet (Eric Wilhelm) Date: Thu, 22 Jan 2004 22:51:46 GMT Subject: Program Python in VIM References: <871xpsc5zf.fsf@tulip.whu.ca> Message-ID: On Thu, 22 Jan 2004 13:08:33 -0600, Paul Moore wrote: > Peter Wu writes: > >> I'm giving vim a try to program Python. The following are the steps I >> follow to code/test a python program. >> >> vi test.py >> [key in some python code] >> :wq >> :!python test.py >> >> >> Is there any other way? I don't want to type 'python test.py' every >> time I've made any modifications. In Emacs, I can simply fire C-c C-c >> to fire the python interpreter. Thanks! > > There's always > > :map ^C^C :w^M:!python %^M > > which makes C-c C-c write the file and then run it in Python. This is good, but what about starting your file with #!/usr/bin/python, setting it as executable with :!chmod 755 %, and then leaving python out of the "run this file" line? Advantage here is that you can then be a Perl programmer as well, or even toss-off some of those really simple deals in Bash script. Another suggestion: maybe leave the ^M off of the end so that you can ^c^c or add some arguments if needed. Of course, if you want emacs-style bindings, you could just use emacs:) I'd be more inclined to connect this one to something closer to the escape key and lose the bucky bits. --Eric From alanmk at hotmail.com Sun Jan 18 11:49:58 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 18 Jan 2004 16:49:58 +0000 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> <40083eac$0$321$e4fe514c@news.xs4all.nl> <40086C6E.8536542C@hotmail.com> <40098f12$0$320$e4fe514c@news.xs4all.nl> Message-ID: <400AB936.BA1D9D73@hotmail.com> [Andrae Muys] >>>>> Found myself needing serialised access to a shared generator from >>>>> multiple threads. Came up with the following >>>>> >>>>> def serialise(gen): >>>>> lock = threading.Lock() >>>>> while 1: >>>>> lock.acquire() >>>>> try: >>>>> next = gen.next() >>>>> finally: >>>>> lock.release() >>>>> yield next [Ype Kingma] >>>> Is there any reason why the lock is not shared among threads? >>>> From the looks of this, it doesn't synchronize anything >>>> between different threads. Am I missing something? [Jeff Epler] >>> Yes, I think so. You'd use the same "serialise" generator object in >>> multiple threads, like this: >>> >>> p = seralise(producer_generator()) >>> threads = [thread.start_new(worker_thread, (p,)) >>> for t in range(num_workers)] [Alan Kennedy] >> Hmm. I think Ype is right: the above code does not correctly serialise >> access to a generator. [Ype Kingma] > Well, I just reread PEP 255, and I can assure you a was missing > something... Ype, Ah: I see now. You thought it didn't work, but for a different reason than the one I pointed out. You thought that the lock was not shared between threads, though as Jeff pointed out, it is if you use it the right way. But it still doesn't work. [Alan Kennedy] >> I believe that the following definition of serialise will correct the >> problem (IFF I've understood the problem correctly :-) >> >> #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= >> import time >> import thread >> import threading >> >> class serialise: >> "Wrap a generator in an iterator for thread-safe access" >> >> def __init__(self, gen): >> self.lock = threading.Lock() >> self.gen = gen >> >> def __iter__(self): >> return self >> >> def next(self): >> self.lock.acquire() >> try: >> return self.gen.next() >> finally: >> self.lock.release() [Ype Kingma] > Looks like a candidate for inclusion in a standard library to me. Well, maybe :-) To be honest, I don't have the time to write test cases, docs and patches. So I think I'll just leave it for people to find in the Google Groups archives ... [Alan Kennedy] >> Also, I don't know if I'm happy with relying on the fact that the >> generator raises StopIteration for *every* .next() call after the >> actual generated sequence has ended. The above code depends on the >> exhausted generator raising StopIteration in every thread. This seems >> to me the kind of thing that might be python-implementation specific. >> For example, the original "Simple Generators" specification, PEP 255, >> makes no mention of expected behaviour of generators when multiple >> calls are made to the its .next() method after the iteration is >> exhausted. That I can see anyway? Am I wrong? [Ype Kingma] > Quoting from PEP 234: > http://www.python.org/peps/pep-0234.html > > "Once a particular iterator object has raised StopIteration, will > it also raise StopIteration on all subsequent next() calls? > ... > Resolution: once StopIteration is raised, calling it.next() > continues to raise StopIteration." Yes, that clears the issue up nicely. Thanks for pointing that out. So the same code will run correctly in Jython 2.3 and IronPython (awaited with anticipation). regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From pln at razzle.Stanford.EDU Mon Jan 19 19:50:01 2004 From: pln at razzle.Stanford.EDU (Patrick L. Nolan) Date: Tue, 20 Jan 2004 00:50:01 +0000 (UTC) Subject: Launching Wordpad on Windows Message-ID: I'm trying to find a clean way to launch a Wordpad editor on Windows. By "clean", I mean that it should work on as many versions of Windows as possible, and it shouldn't require installing any extra software. I assume everyone has win32api and its friends. The problem is to find the path to wordpad.exe. At first I just copied the path from my XP machine: c:\Program Files\Windows NT\Accessories\WORDPAD.EXE I verified that the same path works on W2K, but I don't know about older versions. With some labor I was able to come up with a longer, more obfuscated bit of code: item = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WORDPAD.EXE" key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, item, 0, win32con.KEY_QUERY_VALUE) info = win32api.RegQueryValueEx(key, None) win32api.RegCloseKey(key) editor = win32api.ExpandEnvironmentStrings(info[0]) I would like to solicit learned opinions about this. Which version will work in more versions of Windows? Is there a better approach? -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 9 02:11:28 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 09 Jan 2004 08:11:28 +0100 Subject: what is Python's module search path? References: Message-ID: Stephen Ferg: >It says """When a module named spam is imported, the interpreter >searches for a file named spam.py in the current directory, and then >in the list of directories specified by the environment variable >PYTHONPATH. ... When PYTHONPATH is not set, or when the file is not >found there, the search continues in an installation-dependent default >path; on Unix, this is usually .:/usr/local/lib/python. > >Actually, modules are searched in the list of directories given by the >variable sys.path which is initialized from the directory containing >the input script (or the current directory), PYTHONPATH and the >installation-dependent default.""" > >Is the installation-dependent default path on Windows usually >Lib/site-packages? I guess it's more than that. PythonWin 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32. >>> import sys >>> print sys.path ['','C:\\Python\\Python22\\lib\\site-packages\\Pythonwin', 'C:\\Python\\Python22\\lib\\site-packages\\win32', 'C:\\Python\\Python22\\lib\\site-packages\\win32\\lib', 'C:\\Python\\Python22\\lib\\site-packages', 'C:\\Python\\Python22\\DLLs', 'C:\\Python\\Python22\\lib', 'C:\\Python\\Python22\\lib\\lib-tk', 'C:\\Python\\Python22'] None of these directories qualify for any of the other categories, so these must all be in the installation-dependent default. >If so, then it looks like my original search order was wrong, >and the correct search order (on Windows) is: > >--------------------------------------------------------- > * Python's built-in modules, including modules in the standard >library > * the directory from which your main module was loaded > * in directories in PYTHONPATH > * in the /python23/Libs/site-packages directory >-------------------------------------------------------- > >Is that correct? Well no, I don't think so. The tutorial doesn't say that the modules in the standard library are searched first. It says the current directory is first, which you don't even mention. And the tutorial says sys.path is searched, which may be modified by the program. Why are you trying to rephrase the tutorial, when the tutorial is perfectly clear? >Part of what is confusing me is that Lib/site-packages is pretty >poorly documented. It doesn't have to be, for ordinary users. My guess is the documentation is in this area: http://www.python.org/sigs/distutils-sig/doc/ -- Ren? Pijlman From kelianichols at ssdd.nrl.navy.mil Mon Jan 5 10:59:10 2004 From: kelianichols at ssdd.nrl.navy.mil (Kelia Nichols) Date: Mon, 05 Jan 2004 10:59:10 -0500 Subject: Pyserial question Message-ID: <000d01c3d3a4$db8464d0$17abfa84@Nuvodido> Hello, I am using Pyserial to work with a RS232 device. My question is, how do I write hex to the device or cannot write hex to it pyserial? Kelia Nichols ______________________________________ No trees were killed in the sending of this message. However a large number of electrons were terribly inconvenienced. From tjreedy at udel.edu Fri Jan 23 13:22:44 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 23 Jan 2004 13:22:44 -0500 Subject: Ordered dictionary? References: Message-ID: > Well I too sometimes need the keys in a dictionary to be sorted and your > solutions wouldn't help. The problem is the following. > > I have a number of key value pairs, like names and telephone numbers. > Just more subject to change. Now I want the telephone numbers of everyone > whose name starts with "jan". > > Or I just inserted a name and want to know who is alphabetically next. > Or I want to know who is first or last. A python dict is not very well suited to this, especially for large numbers of key,value pairs. However, if you do pull out sorted lists of keys, use the bisect module to find specific keys. log(n) behavior is fine. A table with a btree index is designed for the things your want to do. There is a btree,py in zope (by Tim Peters, I believe), but I do not know how 'extractable' it is. You could search the archives. Terry J. Reedy From writeson at earthlink.net Fri Jan 23 07:16:06 2004 From: writeson at earthlink.net (Doug Farrell) Date: 23 Jan 2004 04:16:06 -0800 Subject: debugging Message-ID: <88bc63c6.0401230416.7acf904c@posting.google.com> Hi all, Can someone help me out a little with Python? What do people use to debug Python code? I don't understand how to use the built in debugger and I haven't had any luck getting ddd to debug my Python programs. I end up falling back on inserting print statements in my code to figure out what's going on. This works but isn't always the fastest route to a solution. So, I'm just wondering what other people do. Thanks, Doug From sombDELETE at pobox.ru Sat Jan 17 04:10:24 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 17 Jan 2004 12:10:24 +0300 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> <265368cb.0401151529.50c36679@posting.google.com> <4007F50F.E2AF33AD@engcorp.com> <265368cb.0401161604.58099d89@posting.google.com> Message-ID: "Laurent Therond" wrote in message news:265368cb.0401161604.58099d89 at posting.google.com... > Peter, thank you for taking the time to answer. > > I will need some time to digest this information. > > From where I stand, a Python newbie who knows more about Java, this > concept of binary string is puzzling. I wish Python dealt in Unicode > natively, as Java does. It makes things a lot easier to comprehend Python does deal with Unicode natively. You just need to put u character before the string. This of course a violation of the rule "There should be one-- and preferably only one --obvious way to do it." 'a' == u'a'. But remember that Python appeared before Unicode, so strings in Python could not be unicode strings from the beginning . > Having strings be byte arrays, on the other, seems to confuse me. Use unicode strings only. -- Serge. From fumanchu at amor.org Fri Jan 30 14:11:47 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 30 Jan 2004 11:11:47 -0800 Subject: HowTo Search in nested lists Message-ID: Florian Lindner wrote: > >I've two nested lists which are representing a table or matrix. > >Now I found to search for certain values in a certain column. > >For example: column 1, search for 5, return 1, because 5 is > >found in the first column of the second element of t Christopher Koppler replied: > ...let's make a function of it that returns the list(s) > (in case you have more than one list fitting your search > criteria) containing the searched for value. Good answers, Christopher. You might consider combining the several approaches into a single one by creating an iterator; this has the advantage of functioning identically regardless of whether the consumer code wants one match or all matches (without traversing the entire list if only one result is desired). Notice also that the original requirement called for obtaining the index of the column found, not the row. >>> t = [[1,2,3],[4,5,6],[7,8,9],[2,8,5]] >>> >>> def positions(nested_list, value): ... for row in nested_list: ... try: ... yield row.index(value) ... except ValueError: ... pass ... >>> positions(t, 5).next() 1 >>> [x for x in positions(t, 5)] [1, 2] Robert Brewer MIS Amor Ministries fumanchu at amor.org From nuffsaid at phreaker.net Sun Jan 18 14:52:06 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sun, 18 Jan 2004 20:52:06 +0100 Subject: wxwindows question References: <1h6pd1-788.ln1@wintermute.g2ctech> Message-ID: On Sun, 18 Jan 2004 16:13:41 +0100, Lars Heuer wrote: > > Maybe WAX is an interesting project. It tries to build a wrapper ahead > of wxPython to serve a more python-ic way to code python programs: > > See: > http://wiki.wxpython.org/index.cgi/Wax > http://zephyrfalcon.org/labs/dope_on_wax.html > Thanks for the links, Lars. I was not aware of Wax. It looks like a good idea to me. But the following statement from the second link does not sound too promising: "Frankly, I don't have the time to work on this project very much. That's why I only add new features when I need them." Anyway, even if the project will not mature, it might show a way to go with existing GUI toolkits. Write a wrapper which is as close as possible to the original and then subclass the widget classes in the wrapper to make their usage more pythonic. Nuff From __peter__ at web.de Fri Jan 30 10:31:02 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Jan 2004 16:31:02 +0100 Subject: Adding/removing instance members References: Message-ID: Ladv?nszky K?roly wrote: > I understand instance members can be added to an object in a dynamic > manner: > > class Cc: > pass > > oCc=Cc() > oCc.x=10 # oCc now has a new member > > What is the way to remove these instance members? > Is it possible to add a new member whose name is given by a string? You can delete an attribute like so: del c.x Use setattr/getattr/delattr() to set, get or delete attributes known only by their name: >>> class C: pass ... >>> c = C() >>> setattr(c, "x", 123) >>> c.x 123 >>> getattr(c, "x") 123 >>> del c.x >>> c.x Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'x' >>> c.x = 123 >>> delattr(c, "x") >>> c.x Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'x' Peter From timr at probo.com Fri Jan 9 20:53:21 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 09 Jan 2004 17:53:21 -0800 Subject: count objects in a list and random numb gen References: Message-ID: <1emuvvsb1vdj8e50npn9adu46f5lijsufs@4ax.com> Bart Nessux wrote: > >Also, does this bit of code look to be truely random? The code doesn't look random at all, but of course that's not really the question you meant to ask. >def random_number_gen(): > winner = [] > winner.append(random.sample(xrange(100000), 1)) > print winner It depends entirely on your definition of "truly random". There is no single definition of that phrase. However, that specific example provides no benefit over this simpler and more efficient code: def random_number_gen(): print int(random.uniform(0,100000)) which is itself just a shortcut for: def random_number_gen(): print int(random.random()*100000)) What are you using the random numbers for? Tell us what you want to do with them, and we'll suggest the right method. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From brice.vissiere at costes-gestion.net Tue Jan 20 05:46:12 2004 From: brice.vissiere at costes-gestion.net (Brice Vissi?re) Date: 20 Jan 2004 02:46:12 -0800 Subject: Python database Message-ID: Hi python friends, I'm currently working on a data handling tool. For internal storage, I'm looking for a 100% python database. I have some constraints: + multi-platform + relational with built-in query system (SQL preferably) + built-in string functions + reliable + fast I don't care about: + network access + concurracy control + transaction commit/rollback One of the key feature I'm looking for is direct string handling in queries: concatenation, substring extraction, stripping, justifying, ... all we can do with python strings. My first thought was to use Gadfly. I've downloaded and installed it. Now, I'm investigating the documentation and examples to find string capabilities of Gadfly, but at first look, it seems that it will not fit to my needs. My problem would be solved by using a database allowing user function creation, but I don't know whether such a tool exists. So, have you any idea of a db tool I should use ? Thanks in advance. Brice From harry.g.george at boeing.com Mon Jan 19 07:27:27 2004 From: harry.g.george at boeing.com (Harry George) Date: Mon, 19 Jan 2004 12:27:27 GMT Subject: Escaping slashes (double backslash plague) References: <400BFC54.FC6EADF4@engcorp.com> Message-ID: Peter Hansen writes: > Aloysio Figueiredo wrote: > > > > I need to replace every ocurrence of '/' in s by '\/' > > in order to create a file named s. My first attempt > > was: > > > > s = '\/'.join(s.split('/')) > > > > but it doesn't work: > > > > >>> s = 'a/b' > > >>> s = '\/'.join(s.split('/')) > > >>> s > > 'a\\/b' > > >>> repr(s) > > "'a\\\\/b'" > > >>> > > > > '\/'.join() escapes the backslashes and I don't know why. > > It does not, although *you* are not escaping the backslash > yourself, and that is dangerous. Get in the habit of always > escaping your own backslashes, so that if you ever happen > to use a backslash followed by one of the characters which _is_ > a valid escape sequence, you won't get confused. > > '\/' == '\\/' > > but > > '\t' != '\\t' > > The first example shows two ways of writing a string with the blackslash > character followed by a forward slash. The second example shows a TAB > character on the left, but a backslash plus the letter 't', on the right. > > As for your apparent automatic escaping of backslashes: when you show > results in an interactive session by just typing the expression, such as > when you do ">>> s" you will see the repr() of the value, not the actual > content. Use print instead and you'll see the difference: > > >>> print s > > This is all covered pretty well, I think, by the Python tutorials and > such. Have you gone through those? > > -Peter Did someone already mention os.path? Since this is about filenames, that is the best cross-platform colution. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From exarkun at intarweb.us Tue Jan 27 09:21:38 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 27 Jan 2004 09:21:38 -0500 Subject: threads In-Reply-To: References: Message-ID: <20040127142138.GB16734@intarweb.us> On Tue, Jan 27, 2004 at 09:00:38AM -0500, Bart Nessux wrote: > Could someone explain the concept of threads and how I might use them in > Python? I was a math major, not a CS major (theory instead of practice). > Most of my programming knowledge has grown out of system administration > and shell scripting, not professional software development. > > How could I make this script threaded, and why should I, how would it > benefit me? The script already takes up 100% CPU resources, what would > using threads gain for me: > > #!/usr/bin/python #change this to your Python's path > > def cpu_test(): > x = 0 > while x < 999999999: > x = x + 1 > print x > cpu_test() > cpu_test() > > If the above is not suitable for threading, please give me a short > example of something that is. > On a single CPU machine, threads will never improve the performance of a CPU-bound task. On multiple CPU machines, threads may improve performance of CPU-bound tasks, but only in certain very special circumstances. For more details about this, see http://python.org/doc/api/threads.html Threads are useful in ways other than exploiting multiple CPUs, though. They can be used to make blocking APIs appear to be asynchronous, and this is the prime use of them in Python. For example, DB-API 2.0 specifies an interface for working with databases, but every method it specifies blocks. Threads can be used to create a new API wrapped around DB-API which specifies all the same operations, but with an asynchronous interface, allowing any regular DB-API 2.0 module to be used without blocking. This can be useful for working around third-party limitations (it would be pretty bad if one had to rewrite every DB-API module, just to get an asynchronous interface). Aside from this, though, threads are only marginally useful, and can leave to non-deterministic behavior if not used carefully. Think twice before throwing them into your programs. Jp From tomas at fancy.org Thu Jan 15 03:11:54 2004 From: tomas at fancy.org (Tom Plunket) Date: Thu, 15 Jan 2004 00:11:54 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> <1AjNb.8936$1e.894@newsread2.news.pas.earthlink.net> Message-ID: Brandon J. Van Every wrote: > Why are you wasting our time... Why be concerned about why someone else is wasting their time? It's up to the reader to decide to spend time reading posts or not, the author does not make these decisions. So- the person wasting their time, by definition, is the person reading the posts in the first place and claiming that they're a waste... -tom! From pwatson at redlinec.com Fri Jan 23 02:46:14 2004 From: pwatson at redlinec.com (Paul Watson) Date: Fri, 23 Jan 2004 01:46:14 -0600 Subject: performing action on set of charecters References: Message-ID: <4010d131$1_1@themost.net> "jeff" wrote in message news:cdac0350.0401220751.618353a3 at posting.google.com... > hiya, > > Ive a load of binary in a file. Its 3 bit (2^3) and i wanna convert it > to an integer. > > ive tried using theintergar = string.atoi(thebinary, 2), but that > doesnt take it as 3 bit binary > > it has no spaces it it, so im a bit stuck as to how to do this with > python, > > cheers > > greg Will the following do what you want? #! /usr/bin/env python f = file('bits.dat', 'rb') a = f.read() f.close() vals = [] for b in enumerate(a): v = ord(b[1]) if (b[0] % 3) == 0: vals.append((v >> 5) & 0x07) vals.append((v >> 2) & 0x07) carryover = (v << 1) & 0x07 if (b[0] % 3) == 1: vals.append(carryover | ((v >> 7) & 0x01)) vals.append((v >> 4) & 0x07) vals.append((v >> 1) & 0x07) carryover = (v << 2) & 0x04 if (b[0] % 3) == 2: vals.append(carryover | ((v >> 6) & 0x07)) vals.append((v >> 3) & 0x07) vals.append(v & 0x07) print vals From tjreedy at udel.edu Tue Jan 20 12:30:29 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 Jan 2004 12:30:29 -0500 Subject: keynote speaker, PyCon Reminder: Early bird reg deadline 2/1 References: Message-ID: <5MCdnVrfdMM0-JDdRVn-hw@comcast.com> "John Benson" wrote in message news:mailman.541.1074598380.12720.python-list at python.org... > My curiosity has been greatly piqued to see that > > "DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote > speaker is Mitch Kapor of the Open Source Applications Foundation > (http://www.osafoundation.org/). " > > Isn't Kapor the Lotus guy that tried to quash Borlands Quattro Pro because > it offered an alternative Lotus-user-friendly menuing structure? (see > http://lpf.ai.mit.edu/Copyright/copyright.html) > > And who also claimed that "it is my heartfelt belief that many of the > increasing number of recently issued software patents, concerning, for > instance, fundamental techniques and artifacts of user interfaces, should > never have been granted in the first place because of their failure to > qualify as either novel or non-obvious. Some patents appear to preempt > automation of common functions such as footnoting. This to me is like > allowing a patent on the round steering wheel." > (http://www.jamesshuggins.com/h/tek1/software_patent_kapor.htm) > > I'm experiencing some severe cognitive dissonance here. Can anybody help? I am pretty sure the second item (statement) came several years after the first. Sometimes people learn from experience and mistakes. I have. tjr From jsbenson at bensonsystems.com Mon Jan 19 13:27:14 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Mon, 19 Jan 2004 10:27:14 -0800 Subject: keynote speaker, PyCon Reminder: Early bird reg deadline 2/1 Message-ID: <00fb01c3deb9$dcf92f60$210110ac@jsbwxp3> My curiosity has been greatly piqued to see that "DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). " Isn't Kapor the Lotus guy that tried to quash Borlands Quattro Pro because it offered an alternative Lotus-user-friendly menuing structure? (see http://lpf.ai.mit.edu/Copyright/copyright.html) And who also claimed that "it is my heartfelt belief that many of the increasing number of recently issued software patents, concerning, for instance, fundamental techniques and artifacts of user interfaces, should never have been granted in the first place because of their failure to qualify as either novel or non-obvious. Some patents appear to preempt automation of common functions such as footnoting. This to me is like allowing a patent on the round steering wheel." (http://www.jamesshuggins.com/h/tek1/software_patent_kapor.htm) I'm experiencing some severe cognitive dissonance here. Can anybody help? From nid_oizo at yahoo.com_remove_the_ Mon Jan 12 11:01:47 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 12 Jan 2004 11:01:47 -0500 Subject: How to know if a system command doesn't exist? Message-ID: Hi, How can I know if a system command doesn't exist? All the ways I have tried behave like if the system command was existing but returning one. I don't want to sound provocative, but open in Perl returns an error in a command doesn't exist, so I'm sure we could have an exception in the same case for popen in Python? Thx and Regards, Nicolas From jzgoda at gazeta.usun.pl Sat Jan 31 15:05:18 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 31 Jan 2004 20:05:18 +0000 (UTC) Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: Stan Schwartz pisze: > My name is Stan Schwartz, and I'm a University of Pennsylvania > Ph.D. and an independent inventor. I'm submitting two computer > graphics patents to the USPTO during the next several weeks. This sounds like one of these emails, you know them: """ DEAR SIR MY NAME IS ANNE-MARIE ABAHA, I AM THE WIFE OF FORMER PRESIDENT SANI ABAHA... """ -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From mcfletch at rogers.com Fri Jan 23 19:45:49 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 23 Jan 2004 19:45:49 -0500 Subject: Python & Databases ? In-Reply-To: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> References: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> Message-ID: <4011C03D.1050504@rogers.com> Did you try a search for this? http://www.google.ca/search?q=python+database seems to return some fairly relevant documents... Short answer: yes. :) Have fun, Mike Peter Moscatt wrote: >Will Python work with any of the databases like MySQL... ? > >Pete > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From kenfar42 at yahoo.com Fri Jan 9 21:40:55 2004 From: kenfar42 at yahoo.com (Ken) Date: 9 Jan 2004 18:40:55 -0800 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) Some of them. I'm using python for data transformations: some feeds are small and easily handled by python, however the large ones (10 million rows per file) require a bit of thought to be spent on performance. However, this isn't exactly python optimization - more like shifting high-level pieces around in the architecture: merge two files or do a binary lookup (nested-loop-join) one one? etc... To make matters worse we just implemented a metadata-driven transformation engine entirely written in python. It'll work great on the small files, but the large ones... Luckily, the nature of this application lends itself towards distributed processing - so my plan is to: 1. check out psycho for the metadata-driven tool 2. partition the feeds across multiple servers 3. rewrite performance-intensive functions in c But I think I'll get by with just options #1 and #2: we're using python and it's working well - exactly because it is so adaptable. The cost in performance is inconsequential in this case compared to the maintainability. From dd at guv.ethz.ch Sat Jan 31 16:47:47 2004 From: dd at guv.ethz.ch (=?iso-8859-15?Q?David_D=FCrrenmatt?=) Date: Sat, 31 Jan 2004 22:47:47 +0100 Subject: Running External Programs from Within Python References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: On 31 Jan 2004 11:23:42 -0800, Bob=Moore wrote: > Can I run (call? exec? eval?) an external program from inside a Python > program? Try this: import os os.system('notepad.exe') # starts notepad For complex interaction, use win32pipe (Win32 Extensions). dave From jjl at pobox.com Mon Jan 12 18:26:43 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Jan 2004 23:26:43 +0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> Message-ID: <87llocg34c.fsf@pobox.com> Paul Rubin writes: [...] > C++ was motivated by the problems faced by big projects written in C. > I'm talking about stuff like telephone switches with hundreds of > programmers and millions of lines of code. Even with very competent [...] If you're doing a comparative study of C and C++, that's true. But many, many other languages that don't suffer from C++'s absurd baggage also provide that kind of scalability (in terms of function points -- nobody cares about lines of code). The consensus seems to be that the root causes of C++'s baggage are C-compatibility and efficiency, not primarily the demands of large projects. John From deets_noospaam at web.de Fri Jan 2 08:53:42 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Fri, 02 Jan 2004 14:53:42 +0100 Subject: undo and redo ? References: Message-ID: > I'm coding with Tkinter and i wonder whether we could get current OS' > clipboard available, and event more, anyone can inspires me how we can > achieve undo and redo function ? When working with a MVC-approach, the actions you the user can invoke on the model could be created as objects that know how to undo/invert their effects. Then you store a list of these actions and performing undo takes the last action and apply its inverted action to your model. Right from my head: class InsertAction: def __init__(_, index, needle): _.index = index _.needle = needle def do(_, haystack): haystack[index:index] = _.needle def undo(_, haystack): del haystack[_.index : _.index + len(_.needle)] Hope this gives you an idea. You can also have to types of actions - primitive and complex. Performing undo will then undo all primitve actions until the action queue is empty or a complex actions is reached. This allows e.g. in a text-editor to perform undo subsequently inserted characters at once. HTH, Diez From mwh at python.net Thu Jan 15 06:59:50 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 15 Jan 2004 11:59:50 GMT Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <7xhdz08xgy.fsf@ruckus.brouhaha.com> <1073978329.887910@yasure> <87brp7agl7.fsf@pobox.com> <7xvfnfmzy8.fsf@ruckus.brouhaha.com> <878yka2sze.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Not sure what the goals were, but I'm not sure they were to compete > with Netscape and IE. CNRI funding -- "R" for research -- seems to > imply I do remember correctly (one of us should really check the > facts here... oh well, it's USENET ;-). I thought the purpose of grail was a test bed for research into mobile agents, that being what most of the PythonLabs flok were working on at CNRI. I'm probably no better informed than the rest of this thread, though :-) Cheers, mwh -- Our Constitution never promised us a good or efficient government, just a representative one. And that's what we got. -- http://www.advogato.org/person/mrorganic/diary.html?start=109 From user at domain.invalid Mon Jan 26 15:04:16 2004 From: user at domain.invalid (user at domain.invalid) Date: Mon, 26 Jan 2004 20:04:16 GMT Subject: Deleting objects Message-ID: Say I have a database object 'db', that contains table objects, that contain field objects so that I can do things like this: print db.table.field.value() Now, after plundering the database for a while, the db objects heads a tree of lots of data. If I want to "reset" the object so that I get all of my memory back, can I just do: del db or maybe: for t in db.tables: del t and expect that I have cleaned up all of my memory? After writing this out, I see that the answer is clearly yes, but I will post anyway. Thanks Toby From andy47 at halfcooked.com Fri Jan 9 07:59:40 2004 From: andy47 at halfcooked.com (Andy Todd) Date: Fri, 09 Jan 2004 12:59:40 +0000 Subject: [OT] Database reporting software In-Reply-To: References: Message-ID: Steve Horsley wrote: > I have an existing system working on MS Access, and software that > regularly logs events into it (and deletes old events after a year). > > Now need to move to real servers, probably Solaris though possibly > Linux. Modifying the software to update the database (maybe mySQL or > Oracle) contents is easy enough, but how do I produce reports > (statistics and summaries) on the database contents? > > I could contemplate web based or application based report generation, > but are there easy to use draggy-droppy report designing applications > around? Just the names would enable me to look them up. > > I am struggling with OpenOffice.org at the moment, trying to see if it > can do what I'm looking for, but it doesn't seem to be able to do GROUP > BY and SUM() - simple aggregation stuff. > > All suggestions would be very welcome. > > Steve The only product I've used is Crystal reports. There is a cost factor involved but it is pointy clicky, supports 'proper' SQL like summing and group bys and isn't too expensive. The product page is here : http://www.businessobjects.com/products/reporting/crystalreports/default.asp Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From robin at jessikat.fsnet.co.uk Sat Jan 3 17:58:01 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 3 Jan 2004 22:58:01 +0000 Subject: Lists are weird when they are instance members References: Message-ID: <2QeszXA5j09$EwLl@jessikat.fsnet.co.uk> In article , python newbie writes I think you're not grokking that using class A: mylist = [] makes mylist a class attribute ie all instances share the same version of mylist. To get an instance version you need to assign self.mylist. That would normally be done using an __init__method. so class A: def __init__(self): self.mylist = [] then each instance sets up its own empty list at creation time. Hope that helps. -- Robin Becker From james at logicalprogression.net Thu Jan 22 12:12:13 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 22 Jan 2004 17:12:13 +0000 Subject: What is object() In-Reply-To: <20040122154420.6597.qmail@web61110.mail.yahoo.com> References: <20040122154420.6597.qmail@web61110.mail.yahoo.com> Message-ID: <200401221712.13248.james@logicalprogression.net> On Thursday 22 January 2004 3:44 pm, Hameed Khan wrote: > hi, > i was reading library refrence manual. there i found > object() function. they says in library refrence that > "Return a new featureless object. object() is > a base for all new style classes. It has the methods > that are common to all instances of new style > classes." > > My questions are whats the use of this function and > the object returned by it? and what are new style > classes?. > > Thanks, > Hameed Khan Roughly, the purpose of object is that inheriting from it makes a new-style class. For a description of new-style classes see: http://www.python.org/2.2.3/descrintro.html and maybe also: http://users.rcn.com/python/download/Descriptor.htm Also see the ongoing argument about the definition of a new-style class on python-dev under the thread "Hot-To Guide for Descriptors - Nits! :-)" James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From exarkun at intarweb.us Fri Jan 16 14:18:53 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 16 Jan 2004 14:18:53 -0500 Subject: Bug or feature? In-Reply-To: <200401161613.06481.james@logicalprogression.net> References: <200401161613.06481.james@logicalprogression.net> Message-ID: <20040116191853.GA27129@intarweb.us> On Fri, Jan 16, 2004 at 04:13:06PM +0000, James Henderson wrote: > On Friday 16 January 2004 2:44 pm, Alexey Nezhdanov wrote: > > > I know the case where such python behaivoir causes hard-to-catch problems. > > I do not know any case (anybody knows? please give example) where such > > "feature" may be useful. > > > > So I proposing to make a change into python and reverse the order of > > calculations. > > Just for sure: > > === Order used now === > > ## a+=a.Sub(b) > > 1. evaluate value of 'a' > > 2. evaluate value of 'a.Sub(b)' > > 3. evaluate the sum > > 4. store the result into 'a' > > === Proposed order === > > ## a+=a.Sub(b) > > 1. evaluate value of 'a.Sub(b)' > > 2. evaluate value of 'a' > > 3. evaluate the sum > > 4. store the result into 'a' > > -1 > In any language that uses such an operator I would expect: > > a += b > > to be synonymous with: > > a = a + b Of course, it should be noted that, in Python, "a += b" is only sometimes synonymous with "a = a + b". The rest of the time, it's hard to say what it is synonymous with :) > > You are suggesting that it should mean: > > a = b + a > > It is not like Python to attach its own idiosyncratic semantics to operators > already well known from other languages. I think this would catch a lot of > people out. > Definitely. Consider tuple += tuple. It would not only be idiosyncratic, but outright surprising and irrational if using += on (1, 2) and (3, 4) resulted in (3, 4, 1, 2). > Of course, it's probably best to avoid writing code where the order makes a > difference. :) Amen. Write simple code and all those who follow in your footsteps will thank you. Jp From shian5.bbs at wretch.csie.nctu.edu.tw Sat Jan 10 23:26:11 2004 From: shian5.bbs at wretch.csie.nctu.edu.tw (¯u¤ß) Date: 11 Jan 2004 04:26:11 GMT Subject: delete file with zipfile Message-ID: <4ADOiZ$6GG@wretch.csie.nctu.edu.tw> I wrote some scripts to process a zip-file with zipfile I know how to add a file to a zip-file but I couldn't find the way to delete it Anyone know how to remove a file from a zip-file with zipfile? -- ????????????????????????????????????? ?????BBS telnet://wretch.twbbs.org ???? ?? ????????? ????????????????????????????????????? ????????????????????????????????????? ???????????????????218-166-150-104.HINET-IP.hinet.net? From dietrich at zdome.net Fri Jan 23 19:05:25 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Fri, 23 Jan 2004 16:05:25 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> Message-ID: <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> On Jan 23, 2004, at 10:59 AM, Christian Wilcox wrote: > You might find this http://www.artima.com/intv/craft.html artima.com > interview (especially the section "Learning Languages") with Yukihiro > Matsumoto, creator of Ruby, interesting. He discusses how certain > programming languages focus on specific paradigms, which could allow a > programmer to think in ways they may not otherwise. > > Python doesn't necessarily force any specific paradigm, which is one > of it's selling points, IMO. I've been programming a lot of different things lately, and sometimes I do feel constrained by Python. The only way that I can program so I don't feel constrained is to use multiple languages. Sometimes I really just want to curry my functions in Python or Lisp, sometimes I really want to have Python's or Ruby's objects in Lisp or C, sometimes I want to write a macro in languages other than Lisp, and sometimes I even want to be able to do pointer arithmetic in Python. Python's strength is that it encourages paradigms that are relatively concise and easy to read and write, and the paradigms it uses coincide very nicely with many programming projects. But there are many projects which are just not nice to write in Python. Example: I wrote a project in Python which reads some data files and uses them to make a decision (sort of). I got it to about 90% functionality, and realized that the last 10% was extremely difficult to do with Python. After writing one Lisp macro of exactly 13 lines, I rewrote the entire program, incorporating the data into Lisp files which were not only much shorter, but much clearer, easier to read, etc. I just couldn't think of a way to write this program in Python without a lot of code replication. Similarly, most scripting and many other projects I'd never consider doing in anything but Python, except the occasional hardcore text processor which causes physical pain to write in anything but Perl or Ruby. Python seems to take the middle ground. It's build from a procedural standpoint, in an environment where most things are objects and some are functions. It's not what I'd choose as an example of an object oriented language. There are no messages, only function calls, so you can't capture them. The plus side is that methods behave exactly the same as functions, this makes the language simple and the two ideas interchangeable. You can set an object's method to a function. The minus side is that the paradigm of sending a message "to" an object doesn't exist, and anyone coming from Smalltalk or even Objective-C might miss that and feel constrained (I did). But if Python were really object-oriented like that, then it wouldn't have Python's simplicity any more. From bkc at Murkworks.com Fri Jan 23 09:14:19 2004 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 23 Jan 2004 09:14:19 -0500 Subject: Python Consultants? References: <8e198b65.0401221315.6d5cb3fe@posting.google.com> Message-ID: "Dan" wrote in message news:8e198b65.0401221315.6d5cb3fe at posting.google.com... > Here are a pair XML problems that are available: > > #1) Setup to convert these xml files > http://www.gothamanalytics.com/PairTools/geturl?url=http://app.quotemedia.co m/data/getHistory.xml&symbol=SUNW > http://www.gothamanalytics.com/PairTools/geturl/?url=http://app.quotemedia.c om/data/getQuotes.xml?symbols=SUNW > into a vector of open,close,volume information suitable for use with a > numerical Python module. Doing this quickly is a plus. Can you better define "vector". Do you want a Numeric array, or a list or tuple? Do you want a different vector for each of (open, close, volume) (ie, 3 arrays) or do you want the three values stuck into one tuple/list element and that element put into an array/list? What do you mean by "quickly"? You haven't given an indication of the size of the file you wish to process. The URL shown above produces a rather small file. But are you planning to process megabytes of data with multiple symbols over long periods of time? SAX can easily parse those xml files without loading them entirely in memory. What platform are you running on? Maybe it's quicker to use a C extension like libxml2 if you're going to parse extremely large files. You haven't provided enough information about your problem domain. > #2) Expose the Salesforce.com SOAP functionality from salesforce.com > generated WSDL files, here is an example WSDL > http://gothamanalytics.com/Ex/enterprise.wsdl > See sforce.com for more info on the salesforce.com API. A Python > solution is preferred but a work around which uses Java and the > Salesform.com Apache Axis library and an appropriate gateway from > python might also be acceptable. Results from an attempt at using ZSI > to process the WSDL file is appended to this message. I think there are others on this list who are (or will soon) need to work with Salesforce.com. I have been evaluating it and DreamFactory for a few months, but I don't have any clients at the moment that need to use either. If you're just doing "bulk transfer" of data, you might consider a hybrid approach using JyRetic EAI Server http://sourceforge.net/projects/retic Otherwise, continued work on the pywebsvcs-talk list could arrive at a solution in time. In fact, I think I saw a post from you on the list this week. If your business has resources that can be applied to fixing problems in ZSI or SOAPPY that'd be a good way to solve your immediate problem, and "giving back" to the community. -Brad > -- > http://mail.python.org/mailman/listinfo/python-list > From sross at connectmail.carleton.ca Fri Jan 30 21:41:10 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 30 Jan 2004 21:41:10 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: "Daniel Ehrenberg" wrote in message news:711c7390.0401301726.3e38da27 at posting.google.com... [snip example] > Does that illustrate it well? I know the difference between := and = > is annoying, but you'll get used to it, and it allows really cool > things to be done with scopes and inheretance. I think I get the idea. Let's see: P = Object clone do( # saw do() used in iolanguage mail archive allocated = 0 init = method( id := allocated # semi-colons required? allocated += 1 ) howMany = method(return allocated) ) x := P clone y := P clone write("allocated? ", P howMany()) # output ... # allocated? 2 Correct? Thanks for making me aware of this language, it has some interesting ideas. I'm not annoyed by the difference between := and =. I understand the issue(s) they're trying to solve: you don't need to declare local variables, or use self, explicitly. I don't have a problem with that. I imagine it could lead to subtle bugs (if you update a slot when you meant to set a new one), but that is only speculation on my part. I'm not a fan of the parenthesis (which might be expected from a Python user - love that significant whitespace ;). I'm also not a big fan of 'clone', I'd rather see 'new', but I do understand why 'clone' is more apt. Of course, in this language, you could always just say Object new = Object getSlot("clone") P = Object new ... I can appreciate the flexibility of that. From Paul.Moore at atosorigin.com Tue Jan 6 12:09:08 2004 From: Paul.Moore at atosorigin.com (Moore, Paul) Date: Tue, 6 Jan 2004 17:09:08 -0000 Subject: PEP 324: popen5 - New POSIX process module Message-ID: <16E1010E4581B049ABC51D4975CEDB8803060D8E@UKDCX001.uk.int.atosorigin.com> From: Peter Astrand [mailto:astrand at lysator.liu.se] >> The biggest issue, though, is that args as a sequence of program >> arguments is very Unix-specific. This is a big incompatibility between >> Unix and Windows - in Windows, the low-level operation (CreateProcess) >> takes a *command line* which is passed unchanged to the child process. >> The child then parses that command line for itself (often, but not >> always, in the C runtime). In Unix, exec() takes an *argument list*. >> If you have a command line, you have to split it yourself, a task >> which is usually delegated to /bin/sh in the absence of anything else. >> This is hard to handle portably. > Oh, I've never thought of this. It's a major issue. I've been porting process-creation code from Unix to Windows for a long while now, and there simply isn't a good, compatible, answer. > I've found some documentation on this. > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/progs_12.asp > is interesting. It describes how the MS C runtime translates the > commandline to an argv array. Let's call this "Algorithm A". The problem here is that not all programs use the MSVC runtime. Borland C uses a subtly different algorithm, and programs written in other languages often don't use an argv concept at all. Even adding quotes when not necessary can cause certain programs to fail. > When passed a sequence, popen5 should translate this sequence into a > string by using algorithm A backwards. This should definitely be > implemented in popen5. > There are two more cases: > > 1) Should popen5 support a string argument on Windows? > > and > > 2) Should popen5 support a string argument on UNIX? > You seems to have made up your mind about case 1, and even thinks that > this should be "recommended". I'm not that sure. Using a list works most of the time, but can break in subtle, and surprising ways. I have coded "Algorithm A in reverse" a number of times, and *always* managed to construct a program that "broke". With Windows GUI programs (not the key use case for this module, I admit) it's not remotely hard to construct a broken example :-( > What about case 2 ? This could be supported by converting the string to an > sequence using Algorithm A. One large problem though is that Algorithm A > is *not* the same as a typical shell uses. For example, an OS X user might > want to do: > > Popen("ls '/Applications/Internet Explorer'") > > This won't work if we use Algorithm A. > > If we extend Algorithm A to support single quotes as well, this will not > work as expected on Windows: > > Popen("echo 'hello'") > > Sigh. Sigh indeed. It's just not cross-platform no matter how you try. BTW, your echo example won't work in any case on Windows, as "echo" is a shell builtin, and not available as a standalone executable. So on Windows, you'd need Popen("cmd /c echo hello") And don't get me started on how cmd/c's quoting peculiarities can make this even worse :-( > The only drawback with "process" is that it is already in use by > http://starship.python.net/~tmick/#process. Ah. I wasn't aware of that module. I wonder whether Trent would be willing to combine his code and yours somehow, and donate the name? Paul From maarten at remove_this_ws.tn.tudelft.nl Thu Jan 15 08:27:08 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Thu, 15 Jan 2004 14:27:08 +0100 Subject: Newbie: how to write modules without C References: <40069088$0$327$e4fe514c@news.xs4all.nl> Message-ID: > I strongly recommend you read chapter 6, Modules, of the tutorial: > http://www.python.org/doc/current/tut/node8.html This is exactly what I couldn't find before, thanks! -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From pythonguy at Hotpop.com Tue Jan 13 05:49:32 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 13 Jan 2004 02:49:32 -0800 Subject: Python Optimization Message-ID: <84fc4588.0401130249.e6ad2bf@posting.google.com> Interesting article in Kansas State University website on Python internals. Thought I should post it here. http://www.cis.ksu.edu/VirtualHelp/Info/develop/cmu-user.info.Source_Optimization.html -Anand From xpythonist at yahoo.com.br Thu Jan 22 04:50:46 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Thu, 22 Jan 2004 06:50:46 -0300 (ART) Subject: newbie: prefix operator "**" In-Reply-To: <200401211615.09463.james@logicalprogression.net> Message-ID: <20040122095046.3203.qmail@web21506.mail.yahoo.com> The ** operator is also useful when you have a dictionary and want to unpack it to pass as keyword arguments to a function: >>> def f(a,b): ... print a, b ... >>> f(1,'foo') 1 foo >>> f(a=1, b='foo') 1 foo >>> d = {'a':1, 'b':'foo'} >>> f(d) Traceback (most recent call last): File "", line 1, in ? TypeError: f() takes exactly 2 arguments (1 given) >>> f(**d) 1 foo >>> Aloysio --- James Henderson escreveu: > On Wednesday 21 January 2004 3:59 pm, Jeff Epler > wrote: > > On Wed, Jan 21, 2004 at 10:33:49AM -0500, > Christian Jauvin wrote: > > > Hello, > > > > > > I am playing with some classes in the Tkinter > module > > > to learn some GUI basics. > > > > Take a look at the Tutorial, section 4.7.2. The > ** prefix for an > > argument means that it accepts arbitrary keyword > arguments. > > > http://python.org/doc/tut/node6.html#SECTION006720000000000000000 > > > > Example: > > > > def f(**kw): > > print kw > > > > >>> f(a=1, b=2) > > > > {'a': 1, 'b': 2} > > Since Jeff beat me to it with his reply and > reference to the tutorial I'll > just add that ** is also used in a sort of reverse > sense when calling - as > opposed to defining - a function, so that you can > pass a dictionary to a > function and have all the key-value pairs treated as > keyword arguments. This > is called the extended call syntax and might be > useful, for example, if a > function with keyword arguments dictionary wants to > pass these values on to > another function, e.g.: > > def f(**kw): > print kw > > def g(**kw): > f(**kw) # extended call sytax > > g(a=1, b=2) > > With the same result as above. Extended call sytax > is most useful to avoid > the use of the deprecated apply(). See: > > http://www.python.org/doc/current/lib/non-essential-built-in-funcs.html > > under apply() > > and: > > http://www.python.org/doc/current/ref/calls.html > > Finally, as two stars are used for arbitrary > dictionaries single stars are > used for arbitrary sequences. > > James > -- > James Henderson, Logical Progression Ltd. > http://www.logicalprogression.net/ > http://sourceforge.net/projects/mailmanager/ > > > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis! http://br.geocities.yahoo.com/ From goodger at python.org Thu Jan 22 10:05:50 2004 From: goodger at python.org (David Goodger) Date: Thu, 22 Jan 2004 10:05:50 -0500 Subject: PyCon2004 - Where to stay, which airport? In-Reply-To: References: Message-ID: <400FE6CE.30403@python.org> Brad Clements wrote: > I think this year I might be able to make it to my first Python > conference. It'll be my first Python conference too. > Anyway, where should I stay that's cheap but not too yucky? I don't > mind riding the subway. I might come early for sprints or the > Smithsonian. I'll be coaching a sprint on Docutils: . You're welcome to join in! > I couldn't find recommended lodgings on the PyCon wiki. The main wiki page has links: http://www.python.org/cgi-bin/moinmoin/PyConDC2004 > Is DCA the correct airport? Yes, but the others are OK too. See the PyConForCheap link for more about airports. -- David Goodger From dietrich at zdome.net Sun Jan 25 18:34:58 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 25 Jan 2004 15:34:58 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> <4012FEB1.5000106@prescod.net> Message-ID: <1692AB60-4F8F-11D8-BCE5-0003934ACDEC@zdome.net> On Jan 25, 2004, at 7:14 AM, Aahz wrote: > Well, choose_random_assoc() needs to dispatch on functions rather than > values. That will recurse only one level, and only in > choose_random_assoc(). You'll also need to identify tuples in order to > pass in values. Here's a rewrite of Paul's function that shows roughly > what you need to do: > > function random_sword_magic_power(quality): > return choose_random_assoc( > selector = (quality, (poor, medium, good)), > properties = { > (5, 0, 0): glows_in_the_dark, > (3, 3, 0): magically_silent, > (1, 5, 1): (elemental_power, choice([earth, water, air, > fire]), > (0, 2, 4): magical_keen_edge, > (0, 0, 2): ((random_sword_magic_power, medium), > (random_sword_magic_power, medium)), > } > > Quite frankly, though, for this kind of application, I probably would > choose to write a domain-specific language (more precisely, a "smart" > config file format). That would make it easier for someone who wasn't > a > programmer to add functionality. As I said earlier, I don't think the > fact that Lisp makes it easy to directly express this idiom makes up > for > its other faults. Oh, I see. I could write... from random import * def apply(x): x[0](*x[1:]) def apply_random(list): return apply(choose_random(list)) def choose_random(list): total = 0 for probability, result in list: total += probability which = randint(total) for probability, result in list: if which < probability: return result which -= probability raise ValueError, "Probabilities sum to zero." def random_sword_magical_power(quality): which_column = { poor:0, medium:1, good:2 }[quality] table = [ ((5, 0, 0), (glows_in_the_dark,)), ((3, 3, 0), (magically_silent,)), ((1, 5, 1), (elemental_power, choice([earth, water, air, fire]))), ((0, 2, 4), (magical_keen_edge)) ((0, 0, 2), (lambda: random_sword_magical_power(medium) + random_sword_magical_power(medium))) ] table = [ (p[which_column], v) for (p,v) in table ] return apply_random(table) ...am I making this clearer? Hint 1: What language is famous for its built-in function 'apply'? Hint 2: What happens if you remove the commas in the table. You may choose to write a domain-specific language. This was my original idea as well. The early versions of this program had the tables in XML files, and the Python code was short and sweet. However, as I started writing some of the more complicated tables, I needed to write hooks in the XML back into Python, and eventually one of the XML files saw the presence of a few 'lambdas' here and there. I changed the XML files, I refactored the Python code, but XML didn't integrate code well enough with its data, and Python didn't integrate data well enough with its code. The Lisp code that replaced everything is smaller, faster, easier to read, and easier to write. My only point is that Python is not the right tool for every project. I only see two ways to make this read well in Python: either add macros (like Lisp, NOT like C) or add blocks that don't use lambda (like Smalltalk or Ruby). I prefer Python's syntax the way it is. From usenet at mail-2-me.com Tue Jan 27 04:44:48 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: 27 Jan 2004 01:44:48 -0800 Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain References: Message-ID: Thanks for your help, but that does not work. I get an error message which sais it can't reach the domain. But I'm sure did not make an syntax-error, because if I enter my own domain it works. Any other idea? Dirk Tim Golden wrote in message news:... > >Hi! > > > >I'm trying to get the PDC-Computername of a foreign WinNT-domain, but > >I only managed to get the PDC of my own domain with this code: > >pdc=win32net.NetGetAnyDCName() > > If you don't specify any params to that call, win32net will assume > you're looking at your own domain. It can take two params: server & domain. > > If you do this: > > pdc = win32net.NetGetAnyDCName (None, "name_of_other_domain") > > it should work. > > 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 bwm at acm.org Fri Jan 16 12:01:21 2004 From: bwm at acm.org (Bernhard Mulder) Date: Fri, 16 Jan 2004 17:01:21 GMT Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: Here is an example of a server which runs as long as self.running is set: class SimpleXMLRPCServer_with_stop(SimpleXMLRPCServer.SimpleXMLRPCServer): def __init__(self, *args, **kwds): self.running = True SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kwds) def serve_while_running_is_set(self): """Server while running is set.""" while self.running: self.handle_request() Skip Montanaro wrote: > Maxim> is there a way to process actions other than XML-RPC requests > Maxim> using SimpleXMLRPCServer? Is is possible to do something like > > Maxim> server = SimpleXMLRPCServer(('', 8000)) > Maxim> server.register_instance(MyClass()) > Maxim> while(1) > Maxim> if(checkSomeCondidion()): > Maxim> server.serve_once() > Maxim> else: server.stop() > > You should be able to override the serve_forever() method. > > Skip > From jzgoda at gazeta.usun.pl Thu Jan 15 13:12:24 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 15 Jan 2004 18:12:24 +0000 (UTC) Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> Message-ID: ?????? ? pisze: >> (will not mention that it works on AS/400, the best >> minicomputer(!) ever made). > > Why is it the best minicomputer ever made? > I really want to know! Since nobody ever produced any other. Only IBM produced machines that can be called "midrange" (something between microcomputer and "real computer", the famous S/390 mainframe). They still use this terminology. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From news2 at mystrobl.de Tue Jan 20 17:39:32 2004 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Tue, 20 Jan 2004 23:39:32 +0100 Subject: py2exe 0.5.0 (finally) released References: <8a27e309.0401201304.7ee860b0@posting.google.com> Message-ID: <1ebr001fkuq85al2i8c26ejceu8qvedmdb@4ax.com> ny_r_marquez at yahoo.com (R.Marquez): >Maybe I'm missing it, but I don't see how to specify an icon to use >for the exe. Is that funtionality no longer available? icon_resources works for me, like so: setup( windows = ["wxKnife.py", {"script":"wxKnife.py","icon_resources":[(1,"images/app2.ico")]}], console=["installed_updates.py","installed_sw.py"], data_files=[("images",["images/app2.ico",]),] ) -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From mike at odyne.com Mon Jan 19 10:22:36 2004 From: mike at odyne.com (Mike) Date: 19 Jan 2004 07:22:36 -0800 Subject: Printing variable names References: Message-ID: That makes life easy. Problem solved! Thanks all for the help. Mike > > You're lucky, functions "know" their name: > > >>> def func1(): pass > ... > >>> def func2(): pass > ... > >>> for f in [func1, func2]: > ... print f.__name__ > ... > func1 > func2 > > Peter From paul.moore at atosorigin.com Fri Jan 23 09:24:17 2004 From: paul.moore at atosorigin.com (Paul Moore) Date: 23 Jan 2004 06:24:17 -0800 Subject: Is twistedmatrix.com dead? Message-ID: <182bcf76.0401230624.7e468275@posting.google.com> I haven't been able to get through to twistedmatrix.com for a few days now. I know they had a problem a couple of days ago, but is there still a problem, or has something at between me and them simply failed to notice they are back? Thanks, Paul From no.mail at available.net Sun Jan 25 21:32:37 2004 From: no.mail at available.net (Georgy) Date: Mon, 26 Jan 2004 02:32:37 GMT Subject: Mod_python on Windows Troubles References: Message-ID: <9%_Qb.14588$YG.883493@twister.southeast.rr.com> No problem with *.so. My config: Windows XP, Apache 2.0.47 (Win32) mod_python/3.1.2b Python/2.3.2 mod_python.so 3.1.1b (hmm... it reports 3.1.2b but the file's version says 3.1.1b) is 114,688 bytes The error message means probably that your mod_python.so and your %SystemRoot%\system32\python22.dll or python23.dll files are not compatible. Georgy "Josiah Carlson" wrote in message news:bv1par$ctl$2 at news.service.uci.edu... | | > modules/mod_python.so" to httpd.conf, the Apache service refuses to | > start with the following error: "Cannot load C:/Program Files/Apache | > Group/Apache2/modules/mod_python.so into server: The specified module | | While I'm not using Apache or mod_python, I would be willing to bet that | your error is the result of using 'mod_python.so' in Windows. Try | 'mod_python.dll' instead. | | - Josiah From tmartinez at ammsoft.com Tue Jan 27 05:04:15 2004 From: tmartinez at ammsoft.com (Ya) Date: Tue, 27 Jan 2004 11:04:15 +0100 Subject: wxpython and wxlocale References: Message-ID: This is my code: The button of "OK" is not translated. What is wrong ? #I have a mo file named myapp.mo for translate my own dialogs. #its containt #.... #.... #: myapp.py:23 #msgid "Hello World" #msgstr "Bonjour Monde" #... #in this location .\locale\fr\LC_MESSAGES import gettext from wxPython.wx import * import wx import locale import sys, os, time def startapp(self): self.loc = wx.Locale() self.loc.Init(wx.LANGUAGE_FRENCH) gettext.translation("myapp", ".\locale",languages=['fr']).install() #display then message "Bonjour Monde", but the OK button not is translate!!!!! dlg = wxMessageDialog(None, _('Hello World'),'', wxOK | wxICON_INFORMATION) try: dlg.ShowModal() finally: dlg.Destroy() class BoaApp(wxApp): def OnInit(self): wxInitAllImageHandlers() startapp(self) return True def main(): try: demopath= os.path.dirname(__file__) os.chdir(demopath) except: pass application = BoaApp(0) application.MainLoop() if __name__ == '__main__': main() "Jarek Zgoda" escribi? en el mensaje news:bv403p$3ot$1 at atlantis.news.tpi.pl... > Ya pisze: > > > Is there any way of telling python that the text of the dialogues is in a > > specific language? > > And in affirmative case. How is it made? since all the attempts have been > > useless. > > I think that wxLocale has to be used, but I do not become clear. > > loc = wx.Locale() > loc.Init(wx.LANGUAGE_POLISH) > > Et voila, your program uses Polish dialogs. > > -- > Jarek Zgoda > Unregistered Linux User #-1 > http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From mwh at python.net Mon Jan 19 06:23:10 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 19 Jan 2004 11:23:10 GMT Subject: parse binary file in python? References: Message-ID: Andreas R?sdal writes: > On Sun, 18 Jan 2004, "Martin v. L?wis" wrote: > > Andreas R?sdal wrote: > > > I want to parse a binary file in python. Does > > > python have some built in methods for doing this easily? > > > Any links to example code would be nice.. > > > > Depends on the kind of parsing you want to do. Python > > can naturally represent binary files in string objects, > > e.g. > > > > f = open("binaryfile.bin", "rb") # notice the b for binary mode > > data = f.read() > > f.close() > > > > You can then look at the individual bytes by index. > > Thanks. Just wanting to know if I understood your answer correctly; > will the data variable above be an array of binary data, > eg. data[220] == 0, and data[221] == 1 etc? No, it's a string, but you can get what you want by using the `ord' builtin function or the array module or the struct module (or probably various other ways). Cheers, mwh -- To summarise the summary of the summary:- people are a problem. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From aahz at pythoncraft.com Sat Jan 3 22:47:51 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 Jan 2004 22:47:51 -0500 Subject: Creating a capabilities-based restricted execution system References: Message-ID: In article , John Roth wrote: >"Aahz" wrote in message >news:bt7lbp$ovg$1 at panix2.panix.com... >> In article , >> John Roth wrote: >>> >>>Restricted Python was withdrawn because of a number of holes, of which >>>new style classes were the last straw. >> >> RestrictedPython was *not* withdrawn; rexec was withdrawn. This is a >> difficult enough issue to discuss without confusing different modules. See >> http://dev.zope.org/Wikis/DevSite/Projects/SupportPython21/RestrictedPython > >I'm not sure what you're trying to say. The Zope page you reference >says that they were (prior to 2.1) doing things like modifying generated >byte code and reworking the AST. That's fun stuff I'm sure, but it >doesn't have anything to do with "Restricted Execution" as defined in the >Python Library Reference, Chapter 17, which covers Restricted Execution, >RExec and Bastion (which was also withdrawn.) > >If I confused you with a subtle nomenclature difference, sorry. I don't >care what Zope is doing or not doing, except for the fact that it seems >to come up in this discussion. I'm only concerned with what Python is >(or is not) doing. The approach in the Wiki page you pointed to does, >however, seem to be a substantially more bullet-proof approach than >Python's Restricted Execution. Well, I don't care what you do or don't care about, but I do care that if you're going to post in a thread that you actually read what you're responding to and that you post accurate information. If you go back to the post that started this thread, it's quite clear that the reference was specifically to Zope's RestrictedPython. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From max at alcyone.com Tue Jan 13 17:49:49 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 13 Jan 2004 14:49:49 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <4004760D.2607A0@alcyone.com> "Brandon J. Van Every" wrote: > I'll denigrate them all I want. With rare exceptions, they aren't a > value > add to what I want to get done. There's this huge cultural divide > between > hobbyists and commercialists. Right, they're all hobbyists and you're a commercialist. What's your professional experience, again? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ All I know is / I need you in my life -- India Arie From usenet_spam at janc.invalid Fri Jan 9 15:39:07 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 09 Jan 2004 20:39:07 GMT Subject: Looking for help with regular expressions- not Python Specific References: <8d3e714e.0401072114.5bf3fba7@posting.google.com> Message-ID: Joe Francia schreef: > You also may want to check out > Kodos for interactively testing & debugging regexes - > http://kodos.sourceforge.net An alternative to Kodos is Kiki: (uses wxPython while Kodos uses pyQT) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From wweston at att.net Sat Jan 24 12:09:21 2004 From: wweston at att.net (wes weston) Date: Sat, 24 Jan 2004 17:09:21 GMT Subject: Various strings to dates. In-Reply-To: <4GfQb.16187$AA6.14368@fed1read03> References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: <5FxQb.100853$6y6.2012117@bgtnsc05-news.ops.worldnet.att.net> #!/usr/local/bin/python -O #NOTE: add missing MONTHS; DAYS not used import datetime import string dateList = ["Fri, 23 Jan 2004 00:06:15", "Thursday, 22 January 2004 03:15:06", "Thursday, January 22, 2004, 03:15:06", "2004, Thursday, 22 January 03:15:06"] MONTHS = [("JANUARY",1), ("JAN",1), ("FEBRUARY",2), ("FEB",2), #etc ] DAYS = [("Monday",0), ("Mon",0), #........ ("Thursday",3), ("Thur",3) ] #-------------------------------------------------------------------- def GetMonthInt(mstr): #print "mstr=",mstr for t in MONTHS: if t[0].find(mstr) > -1: return t[1] return -1 #-------------------------------------------------------------------- class MyDateTime: def __init__(self,oddstr): tokens = oddstr.split() temp = [] for t in tokens: if t.find(":") > -1: continue if t[-1] == ',': t = t[:-1] temp.append(t) tokens = temp #for t in tokens: # print t year = -1 month = -1 day = -1 for t in tokens: if t[0] in string.digits: x = int(t) if x > 31: year = x else: day = x continue t = t.upper() if t[0] in string.ascii_uppercase: x = GetMonthInt(t) if x <> -1: month = x continue if year > -1 and month > -1 and day > -1: self.Date = datetime.date(year,month,day) else: self.Date = None def Show(self): print self.Date.ctime() #-------------------------------------------------------------------- if __name__ == '__main__': for date in dateList: dt = MyDateTime(date) dt.Show() From max at alcyone.com Thu Jan 22 21:06:25 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Jan 2004 18:06:25 -0800 Subject: I support PEP 326 References: Message-ID: <401081A1.E4C34F00@alcyone.com> Gary Robinson wrote: > I've recently had a couple of cases of needing exactly what it > proposes, and > having to kluge around the fact that it's not there. It's a great > idea. > > If there anywhere else I should be expressing my opinion on this, let > me > know. Seems quite reasonable to me. The only issue I'd take with it is the choice of Min and Max for the names of the singletons; they're a little too close to the functions min and max, which obviously they're both likely to be used with. I would suggest something a little more verbose such as Minimum and Maximum, or if you want to get silly, Infimum and Supremum. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Love is the most subtle form of self-interest. -- Holbrook Jackson From somebody at nowhere.com Sat Jan 10 17:58:23 2004 From: somebody at nowhere.com (Sean Richards) Date: Sun, 11 Jan 2004 11:58:23 +1300 Subject: Emacs python mode question References: Message-ID: <87zncvwgvk.fsf@hugin.valhalla.net> jblazi writes: > gogo-line is on the menu but is not bound to a key. How can I bind it? Put (global-set-key (kbd "M-g") 'goto-line) in your ~/.emacs Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From a.schmolck at gmx.net Fri Jan 9 12:41:29 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 09 Jan 2004 17:41:29 +0000 Subject: how to speedup this code? References: Message-ID: Ognen Duzlevski writes: > Hi all, > > I have rewritten a C program to solve a bioinformatics problem. Portion where most of the time is spent is: > > def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): > global ONEINDELPENALTY,OPENGAPPENALTY > > for ndx1 in range(1,tlen+1): > for ndx2 in range(1,qlen+1): > delmat[ndx1][ndx2] = Min(delmat [ndx1-1][ndx2]+ONEINDELPENALTY, \ > Min(scoremat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY, \ > insertmat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY)) > insertmat[ndx1][ndx2] = Min(insertmat[ndx1][ndx2-1]+ONEINDELPENALTY, \ > Min(scoremat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY, \ > delmat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY)) > scoremat[ndx1][ndx2] = Min(scoremat[ndx1-1][ndx2-1], \ > Min(delmat[ndx1-1][ndx2-1], insertmat[ndx1-1][ndx2-1])) + \ > GetFitnessScore(tseq,ndx1-1,qseq,ndx2-1) You're obviously quite new to python and Numeric (also have a look at numarray, BTW, which is meant to replace Numeric in the not so far future), so you're still thinking in terms of C. In python+Numeric you can often replace C-style for loops with a much more concise and elegant array manipulation (which will be very efficient, unlike for loops in python -- unless you are using psyco, that is). I think you're particular example will fit into this pattern (warning: the code below is just toget you started -- it might be quite wrong, I haven't looked too carefullly at your code and just jotted this down quickly): from Numeric import minimum, array, ... delmat = array( [...] def ... # formatted a bit funny for better visual clarity delmat[1:tlen+1,1:qlen+1] = \ minimum( delmat[1:tlen,1:qlen+1]+ ONEINDELPENALTY, minimum( scoremat[1:tlen,1:qlen+1]+ OPENGAPPENALTY, insertmat[1:tlen,1:qlen+1]+ OPENGAPPENALTY + ONEINDELPENALTY)) [etc.] Be sure you understand the indexing (NB. array[a][b] vs. array[a,b]), the Numeric manual is quite good, so have a look at it (reading some code in scipy or some other project that uses Numeric might also be a good way to speed up the learning process). HTH 'as p.s. Let me also recommend that you don't emulate the C style compile-run-debug-edit approach in python -- I think you'll find that a test-driven development + an interactive shell to try things out (have a look at ipython, BTW) make for much more pleasant scientific computing. From mwh at python.net Wed Jan 7 07:28:32 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 7 Jan 2004 12:28:32 GMT Subject: KeyboardInterrupt and threading References: Message-ID: q2n8byu02 at sneakemail.com (Ivan Nestlerode) writes: > Michael Hudson wrote in message news:... > > On debian, the signal module certainly should be available, and the > > KeyboardInterrupt exception should go to the main thread. Or at > > least, that's what I thought. You're definitely seeing it being > > delivered to an arbitrary thread? > > > > Cheers, > > mwh > > After a closer look, I am not seeing KeyboardInterrupt being delivered > to non-main threads. What I am seeing is that Ctrl-C does not work at > all when non-main threads are CPU intensive. Oh... > I had previously jumped to the conclusion that because Ctrl-C didn't > work and because the non-main thread was sloppy ("except:"), that > Ctrl-C wasn't working because KeyboardInterrupt was going to the > sub-thread. That was an incorrect conclusion. Well, in a way, good, but perhaps not for you... > So I guess the entire problem can be restated as: How do I make > Ctrl-C work properly when the non-main thread is busier than the > main thread? This is hard for me to answer -- it works fine for me. What platform are you on? ISTR Debian, but not versions of anything. I'm somewhat inclined to start blaming libc at this point... As you may well be aware, the combination of threads and signals is a bit of a minefield. Python runs all threads other than the main thread with all signals masked. My understanding is that when a signal is delivered to a process it's delivered to an arbitrary thread that has that signal unmasked -- in Python's case, this should be the main thread. It kind of sounds like in your case the signal is being queued up on a non-main thread, but as the signal is never unblocked, it never gets handled. [...] > I think this is a bug though (I shouldn't have to put hacks into the > main thread to get this to work). Agreed, but I'm not sure they're in Python. > Any thoughts? Upgrade glibc? Cheers, mwh -- ARTHUR: Why are there three of you? LINTILLAS: Why is there only one of you? ARTHUR: Er... Could I have notice of that question? -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From computer.problemen at skynet.be Sat Jan 10 13:27:35 2004 From: computer.problemen at skynet.be (broebel) Date: Sat, 10 Jan 2004 19:27:35 +0100 Subject: solving a small programm Message-ID: <40004254$0$16669$ba620e4c@news.skynet.be> hey, for the real programmers amongst you, this may be really annoying but I've been learning the language for only two days. this is my problem, in this programm,which already works I now have to make a total count of how many coins are used. this program gives the total per coin. It should be a small peace of code (as explained in a tutorial i read, without the answer.)that counts the total of all the coins. I ve been searching for two days and for this kind of programm it really seems kind of long. thanks in advance # Een bedrag gepast betalen met zo min mogelijk euromunten bedrag = input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) for munt in 200, 100, 50, 20, 10, 5, 2, 1 : aantal = 0 while bedrag >= munt : aantal = aantal + 1 bedrag = bedrag - munt if aantal > 0 : print aantal, 'x', munt what i need is: for example the programm gives 68= 50*1 10*1 5*1 2*1 1*1 I need an additional code to get the "5" total of all the coins together. From joe.nguyen at coair.com Thu Jan 8 18:15:04 2004 From: joe.nguyen at coair.com (JuiceMan) Date: 8 Jan 2004 15:15:04 -0800 Subject: Python and SOAP Message-ID: <67ce7525.0401081515.cdde341@posting.google.com> Hi, i've been trying to access the my company's SOAP webservice with no luck. I'm using the httplib library. This is my code: from httplib import HTTP from urllib import quote # Establish SOAP data SOAPdata = '' SOAPdata = '' SOAPdata = SOAPdata + '\n ' SOAPdata = SOAPdata + '\n ' SOAPdata = SOAPdata + '\n XXXXXX' SOAPdata = SOAPdata + '\n XXXXXX' SOAPdata = SOAPdata + '\n XXXXX' SOAPdata = SOAPdata + '\n ' SOAPdata = SOAPdata + '\n ' SOAPdata = SOAPdata + '\n' postdata = quote(SOAPdata) print "\n************************* OUTGOING SOAP ************************************" print postdata # Begin HTTP request req = HTTP("insidecoair5") req.putrequest("POST", "/cowsemployeeservicecenter/cowsemployeeservicecenter.asmx") req.putheader("Accept", "text/xml; charset=utf-8") req.putheader("Content-Type", "text/xml; charset=utf-8") req.putheader("Content-Legth", str(len(postdata))) req.putheader("SOAPAction", "COM.COAIR.WWW.Technology.CoWebServices.COWSEmployeeServiceCenter/checkPassword") req.endheaders() # Send SOAP body req.send(postdata) ec, em, h = req.getreply() print "\n*************************** HTTP RESPONSE **********************************" print ec, em print "\n*************************** HTTP HEADER RESPONSE ***************************" print h # get file-like object from HTTP response # and print received HTML to screen fd = req.getfile() textlines = fd.read() fd.close() print "\n************************** INCOMING SOAP ***********************************" print textlines I get back a faultstring with a "THe root element is missing" error I cant seem to see what im doing wrong. Any help would be greatly appreciated. From mailund at birc.dk Thu Jan 15 09:59:39 2004 From: mailund at birc.dk (Thomas Mailund) Date: Thu, 15 Jan 2004 15:59:39 +0100 Subject: Cyclic garbage collection and segfaults... References: Message-ID: On Thu, 15 Jan 2004 11:15:51 +0000, Michael Hudson wrote: > "Thomas Mailund" writes: > >> Hi group. >> >> I have a problem with some C extensions I am working with and >> hope that some of you can help. > > [snippety] > >> static void >> Simple_dealloc(SimpleObject *self) >> { >> fprintf(stderr,"Simple_dealloc %p\n", self); >> self->ob_type->tp_free((PyObject*)self); /* <= segfault here */ > > Well, you're calling tp_free from a tp_dealloc. That doesn't *sound* > sensible to me. I'm suprised to hear that; the documentation I was working from, , does exactly that. Of course, this is from the section that uses reference counting, not cyclic gc, but later on, when the garbage collector is introduced, the deallocator still calls tp_free, it just calls clear first . If I shouldn't free self in this way, how should I do it? >> Can anyone explain what I'm doing wrong? Or perhaps suggest a better >> solution to my "real" problem, if I'm approaching the problem completely >> wrong :-) > > There are docs on this sort of thing. About the garbage collection? In that case, I thought I *was* following the documentation ;-) If about the general problem with accessing the whole and parts of a C structure from python, if you have any specific references in mind, I would be very grateful if you would post them. I know that I am not the first to have this problem, and that very likely there are general patterns for solving the problem, but my googling didn't find anything (which probably means I wasn't asking the right questions, but never the less...) Yours, /mailund From sidharthk at hotmail.com Thu Jan 29 13:18:27 2004 From: sidharthk at hotmail.com (Sidharth Kuruvila) Date: Thu, 29 Jan 2004 23:48:27 +0530 Subject: conditional expression sought References: Message-ID: since True and False can also evaluate as 1 and 0 you can use the binary operators | and & for or and and respectively >>> class F: ... a = 5 ... def b(self): ... self.a = 4 ... return True ... def a(self): ... self.a = 1 ... return False ... >>> g = F() >>> g.a() & g.b() False >>> g.a 4 "Elaine Jackson" wrote in message news:pRbSb.330334$ts4.37644 at pd7tw3no... > If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, > then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without > evaluating any other B_i. This is such a useful mode of expression that I would > like to be able to use something similar even when there is an i with > bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) > or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious > reasons. Does anybody know a good way to express this? Any help will be mucho > appreciado. > > Peace > > From newsgroups at jhrothjr.com Wed Jan 28 10:18:22 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 28 Jan 2004 10:18:22 -0500 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> <40177f07$0$1730$5a62ac22@freenews.iinet.net.au> Message-ID: <101fkp3nd3ea84c@news.supernews.com> "Derek Fountain" wrote in message news:40177f07$0$1730$5a62ac22 at freenews.iinet.net.au... > > What do you need this for? If you can be more specific, we might be able > > to help you a little better. > > I have a Tcl/Tk script which uses a canvas to graphically represent the data > stored in the program. Whenever the data store is updated, a Tcl trace > automatically triggers to ensure the graphical display is kept consistent > with the data. I was after a simple way to convert the script to Python > Tkinter. Without the eqivalent of Tcl traces I'm probably going to have to > think about it... ;o) There's a facility where you can associate a widget with a variable so that when the variable changes the widget's value changes, and vice versa. I don't offhand remember the details though. You'll need to look at one of the references. The variable has to be a subclass of a special Tkinter class for this to work, though. John Roth From exarkun at intarweb.us Sun Jan 18 14:58:49 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 18 Jan 2004 14:58:49 -0500 Subject: circular dependency between class and its metaclass In-Reply-To: <400AE6A4.4090409@sympatico.ca> References: <400AE6A4.4090409@sympatico.ca> Message-ID: <20040118195849.GA512@intarweb.us> On Sun, Jan 18, 2004 at 03:03:48PM -0500, Stefan Seefeld wrote: > hi there, > > I'v run into a little problem for which I only found an ugly workaround, > so I'd like to know whether people are aware of better ways to achieve > this... > > I'm defining a class 'Class' for which I want to set up a __metaclass__ > 'Type' > which does some work on class variables. In particular, it should apply > a function on all base classes that are themself derived from 'Class'. > > My first try was: > > ==== > > class Class(object): > > class Type(type): > > def __init__(cls, name, bases, dict): > > hierarchy = list(filter(lambda i:issubclass(i, Class), bases)) hierarchy = [i for i in bases if isinstance(i, Type)] > # do something with the hierarchy here > > __metaclass__ = Type > > ==== > > However, this fails because at the point where I want to create the > 'hierarchy' variable 'Class' isn't known yet. (At what point is it actually > injected into the local dict ?) > It is added after the class object is created, which is more or less after the dedent token at the end of the class definition. So, for: class Foo: # A pass # B x = Foo() # C `Foo' is bound between lines B and C. > Then I tried to define 'Type' after 'Class' (instead of inside it): > > ==== > > class Class(object): pass #supress details for clarity > > class Type(type): > ... > > Class.__metaclass__ = Type > > ==== > > But this didn't work at all (even though I don't quite understand why). The __metaclass__ variable must be set before the class is defined, because it is used to determine how the class object will actually be created. Once the class object has already been created, the __metaclass__ variable is meaningless. > [snip last case - workaround] Jp From dwelch91.nospam at comcast.net Fri Jan 2 21:53:21 2004 From: dwelch91.nospam at comcast.net (djw) Date: Sat, 03 Jan 2004 02:53:21 GMT Subject: mysql python Newbie Question In-Reply-To: References: Message-ID: Andrew wrote: > Hi I would like to create a program that accesses mysql from a gui on my > local computer "mysql is on a server" > > but I am fairly new to python and programming GUI's in general > > What I would like this program to do is be able to access my server and > change update add and delete records from my databases without having to > write sql. > > I can create the GUI fairly easily but I do not know how I or what functions > and modules would be needed to do this or how to write them "Forgive me if I > sound to Newb" > > If someone out there could help me out maybe offer advice or even better > some code to build on that would be cool > > Thanks in advance > > Cheers > > Andrew > > Quick google search of "python mysql" yields: http://sourceforge.net/projects/mysql-python Google of "python mysql example" yields: http://www.devshed.com/Server_Side/Python/PythonMySQL/print_html Moral: Google is your friend. -D From francisgavila at yahoo.com Wed Jan 14 04:10:30 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 14 Jan 2004 04:10:30 -0500 Subject: Inserting while itterating References: Message-ID: <100a1uco9n3l21b@corp.supernews.com> Thomas Guettler wrote in message ... >Hi, > >Simple excerise: > >You have a sorted list of integers: >l=[1, 2, 4, 7, 8, 12] > >and you should fill all gaps: > >result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > >How would you code this? > >Constrain: The original list should be changed, >don't create a copy. > > thomas > This a homework problem? >>> L = [1, 2, 4, 7, 8, 12] >>> result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> L.extend([i for i in range(L[0], L[-1]) if i not in L]) >>> L.sort() >>> L == result True -- Francis Avila From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jan 3 13:33:21 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 03 Jan 2004 19:33:21 +0100 Subject: Import problems In-Reply-To: References: Message-ID: <3ff70aef$0$327$e4fe514c@news.xs4all.nl> Psymaster wrote: > I'm working on projects using pygame and I encounter the following > problem: In (almost) every file of my source I have to "include > pygame" because every file uses some function from pygame. Is there > another way to do this? Does it provide overhead to my app? There is no overhead. Modules get imported only once. Any additional imports just return the same module directly. But there should be another way to do this; if all your files depend on pygame, I think the modularization / structure of your program is suboptimal. I think there should only be a few modules that do stuff related to pygame, the rest should import those instead of doing things via pygame themselves. --Irmen From peter at engcorp.com Tue Jan 13 14:34:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jan 2004 14:34:02 -0500 Subject: error at "import anydbm" References: <40042edd$0$24038$626a54ce@news.free.fr> Message-ID: <4004482A.A66C2886@engcorp.com> "C?dric V." wrote: > I am unable to import anydbm without error under Python2.2 or 2.3 (Linux). > > this script: > >#!/usr/bin/env python > >import anydbm > > > >if __name__ == "__main__": > > db = anydbm.open("test", "rwc") > > db["test"] = "ok" > > returns at execution: > > >cedric at dev _test $ python dbm.py > >Traceback (most recent call last): > > File "dbm.py", line 2, in ? > > import anydbm > > File "/usr/lib/python2.3/anydbm.py", line 59, in ? > > _errors.append(_mod.error) > >AttributeError: 'module' object has no attribute 'error' Do you have any modules of your own creation called any of the following? ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] These are the names of the modules anydbm tries to import, and it appears to expect each of them to have an "error" name defined. Most likely your module, with a conflicting name, is being found first and it does not have an "error" attribute. Generally speaking, you should try to avoid using the same names as the standard library modules for your own code. -Peter From jeremy at zope.com Mon Jan 12 11:49:58 2004 From: jeremy at zope.com (Jeremy Hylton) Date: Mon, 12 Jan 2004 11:49:58 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401111712.22a74be7@posting.google.com> References: <9a6d7d9d.0401111712.22a74be7@posting.google.com> Message-ID: <1073926198.6341.424.camel@localhost.localdomain> On Sun, 2004-01-11 at 20:12, Aaron Watters wrote: > > "The standard" ones aren't all that standard. ANSI SQL-92 defines multiple > > isolation levels, and they've been (I think) fairly critiqued as incomplete > > and partly ambiguous; e.g., > > > > A Critique of ANSI SQL Isolation Levels > > Hal Berenson, et al. > > http://citeseer.nj.nec.com/berenson95critique.html > > Some SQL isolation levels are hacks to allow long running transactions, > etcetera. If you keep to the strictest isolation level you get the > classical behaviour which has been studied and elaborated by many very > smart people over the last several decades and which is very well > understood. I think lower isolation levels are more than hacks for long-running transactions. They seem like they're pretty important for achieving good performance. The strictest isolation level is necessary, of course, for some applications, but not all. Here's was PostgreSQL has to say about full serializability. http://www.postgresql.org/docs/current/static/transaction-iso.html > The Serializable mode provides a rigorous guarantee that each > transaction sees a wholly consistent view of the database. However, > the application has to be prepared to retry transactions when > concurrent updates make it impossible to sustain the illusion of > serial execution. Since the cost of redoing complex transactions may > be significant, this mode is recommended only when updating > transactions contain logic sufficiently complex that they may give > wrong answers in Read Committed mode. Most commonly, Serializable mode > is necessary when a transaction executes several successive commands > that must see identical views of the database. Jeremy From michael at foord.net Mon Jan 19 06:50:10 2004 From: michael at foord.net (Fuzzyman) Date: 19 Jan 2004 03:50:10 -0800 Subject: Setting Window Size using Pack Under Tkinter References: <8089854e.0401160134.5674a86c@posting.google.com> <4007de09$0$151$e4fe514c@dreader5.news.xs4all.nl> <4007dedc$0$166$e4fe514c@dreader5.news.xs4all.nl> Message-ID: <8089854e.0401190350.61b3efc@posting.google.com> Short of actually trying it...... (when I get home I *will* try it) Would the following work : from Tkinter import * gui=Tk() Button(gui, text='A button', command=a_function).pack() ####code#### gui.geometry("+%d+%d" %(300, 100)) gui.resizable(0,0) gui.mainloop() ?? If I recall correctly it ought to.... (mixing the pack and geometry methods in the same GUI)... Anyway - thanks. Fuzzy "duikboot" wrote in message news:<4007dedc$0$166$e4fe514c at dreader5.news.xs4all.nl>... > from Tkinter import * > gui=Tk() > > ####code#### > gui.geometry("+%d+%d" %(300, 100)) > gui.resizable(0,0) > gui.mainloop() > > Will work offcourse too.. :-) > > cheers, > > Arjen > > > > "duikboot" schreef in bericht > news:4007de09$0$151$e4fe514c at dreader5.news.xs4all.nl... > > from Tkinter import * > > gui=Tk() > > > > ####code#### > > gui.geometry("+%d+%d" %(300, 100)) > > gui.resizable(0,0) > > > > if __name__=='__main__': > > gui.mainloop() > > > > > > > > > > "Fuzzyman" schreef in bericht > > news:8089854e.0401160134.5674a86c at posting.google.com... > > > I'm having trouble implementing my GUI using Tkinter...... > > > I've been working through the Tkinter tutorials from 'Programming > > > Python' and am generally happy enough with the functionality and feel > > > of the results *but* - I can't see how to set the size of the root > > > window (or any top level window) and to stop it being resized........ > > > > > > Thanks for any help. > > > > > > Fuzzyman > > > > > > > > > -- > > > > > > YAPLP > > > Yet Another Python Links Page > > > http://www.voidspace.org.uk/coollinks/python_links.shtml > > > > > > Python Utils > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > > > > > -- > > > > > > 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.atlantibots.org.uk > > > http://groups.yahoo.com/group/atlantis_talk/ > > > Atlantibots - stomping across the worlds of Atlantis. > > > --- > > > 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 NAIGIMSESRIMAIL at gims.com Tue Jan 27 07:20:35 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Tue, 27 Jan 2004 14:20:35 +0200 Subject: ALERT - GroupShield ticket number OA1719_1075206030_ESRIMAIL_3 w as 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: ciwwy at aol.com Sent: -1211817472,29615281 Subject: Error Attachment Details:- Attachment Name: MailMonitor_report.txt File: MailMonitor_report.txt 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: 1867 bytes Desc: not available URL: From newsgroups at jhrothjr.com Sat Jan 3 12:39:42 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 12:39:42 -0500 Subject: Text-to-HTML processing program References: Message-ID: "phil hunt" wrote in message news:slrnbvcm32.122.philh at cabalamat.cabalamat.org... > Does anyone know of a text-to-HTML processing program, ideally > written in Python because I'll probably be wanting to make small > modifications to it, which is simple and straightforward to use > and which uses a simple markup language (something like Wikipedia > markup would be ideal)? There's an old saying that's attributed to a lot of people: For every hard problem, there is a solution that is simple, obvious and wrong. Markup seems to be one of those problems. Lots of people look at the existing markup languages out there, go "oh, yuck!," and invent a simpler markup language that promptly starts growing until it reaches the state of the languages they originally rejected as too complex. John Roth From JimJJewett at yahoo.com Mon Jan 19 16:58:05 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 19 Jan 2004 13:58:05 -0800 Subject: __init__(self, *args, **kwargs) - why not always? Message-ID: Normally, I expect a subclass to act in a manner consistent with its Base classes. In particular, I don't expect to *lose* any functionality, unless that was the whole point of the subclass. (e.g., a security-restricted version, or an interface implementation that doesn't require a filesystem.) One (common?) exception seems to occur in initialization. I understand stripping out arguments that your subclass explicitly handles or replaces. A subclass intended to restrict access might even "handle" all unknown arguments. But for the general case, is there any reason *not* to pass unhandled initializer arguments to the parent classes? More specifically, is there any reason not to replace: class SubClass(BaseClass): def __init__(self): BaseClass.__init__(self) with: class SubClass(BaseClass): def __init__(self, *args, **kwargs): BaseClass.__init__(self, *args, **kwargs) on a near-global basis? -------- Bug 876421 provides an example surprise in the standard library. http://sourceforge.net/tracker/?func=detail&atid=105470&aid=876421&group_id=5470 SubClass(level=ERROR) throws an exception, even though BaseClass(level=ERROR) works, and level=ERROR was still valid to the subclass, with the same meaning. I expect that variations on verbosity will be a common pass-through argument in many types of code. -------- Yes, I realize that changing BaseClass.__init__(...) to super.__init__(...) may be better still, but that discussion is orthogonal to this question. Yes, I would have preferred that the interpreter add the (possibly modified) *args and **kwargs automatically, but I do realize that it is too late for that change. -- -jJ Take only memories. Leave not even footprints. From quentel.pierre at wanadoo.fr Fri Jan 16 06:40:08 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Fri, 16 Jan 2004 12:40:08 +0100 Subject: Tkinter: disable menu items while running References: Message-ID: Menu widgets have an index, used to get/set their properties There must be more elegant solutions, but this should work : ---------------------- from Tkinter import * root=Tk() def hello(): print "hello !" def toggle(): if submenu.entrycget(0,"state")=="normal": submenu.entryconfig(0,state=DISABLED) submenu.entryconfig(1,label="Speak please") else: submenu.entryconfig(0,state=NORMAL) submenu.entryconfig(1,label="Quiet please") menubar = Menu(root) submenu=Menu(menubar,tearoff=0) submenu2=Menu(submenu,tearoff=0) submenu2.add_command(label="Hello", command=hello) # this cascade will have index 0 in submenu submenu.add_cascade(label="Say",menu=submenu2,state=DISABLED) # these commands will have index 1 and 2 submenu.add_command(label="Speak please",command=toggle) submenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Test",menu=submenu) # display the menu root.config(menu=menubar) root.mainloop() ----------------------Hope this helps, Pierre From kvisco at exoffice.com Mon Jan 26 21:01:03 2004 From: kvisco at exoffice.com (kvisco at exoffice.com) Date: Mon, 26 Jan 2004 21:01:03 -0500 Subject: hello Message-ID: <200401270200.i0R20eZB027664@smtptpa.interwan.gte.com> The message contains Unicode characters and has been sent as a binary attachment. From ptmcg at users.sourceforge.net Wed Jan 14 02:39:21 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Wed, 14 Jan 2004 07:39:21 GMT Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> <2szMb.6443$k4.143679@news1.nokia.com> <3rr900dm9s7th7kgq4muj76d5ocs5uep3b@4ax.com> Message-ID: "Tim Roberts" wrote in message news:3rr900dm9s7th7kgq4muj76d5ocs5uep3b at 4ax.com... > Olaf Meyer wrote: > > > >I just found out another way ;-) Using the locals() has the disadvantage > >that I cannot use more complex variable parameters (e.g. certain values > >of a dictionary). The following works well: > > > >cmd = (executable + " -start " + startTime + " -end " + endTime + > > " -dir " + options.dir) > > Yes, that works, but you should bear in mind that it is slower than the %s > option. The "+" operations are all separate interpreter steps, while the > "%" operation is done in C. > On the relative time scales of concatenating 7 strings compared to forking off a separate process (which I presume is what is to be done with cmd), I'd go for the more readable representation, to aid in long term maintainability. If I have some string concatenation being done in a highly repetitive part of code, then by all means, replace it with one of the half dozen documented optimized alternatives. But if I build a string in order to create a sub-process, or invoke a database query, or make a remote CORBA invocation, etc., then these "optimizations" don't really save much time, and instead distract me/reviewers/testers/maintainers from the important program logic. -- Paul From skip at pobox.com Thu Jan 22 14:15:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 22 Jan 2004 13:15:09 -0600 Subject: shelve slow in python 2.3.3 for windows In-Reply-To: <456v00hma5e5afsmujntins8basrfgotg3@4ax.com> References: <322u00ppo44l8g003dgtcu8lna432to411@4ax.com> <456v00hma5e5afsmujntins8basrfgotg3@4ax.com> Message-ID: <16400.8509.191175.694059@montanaro.dyndns.org> Skip> 'dbhash' and 'bsddb185' are really the same beast. Marco> Now the question is: is it possible to use bsddb185 with python Marco> 2.3.3? Skip> You're barking up the wrong tree. That's not the problem. Marco> So you're telling me that dbhash (namely Marco> /python2.3/DLLs/_bsddp.pyd) on python 2.3.3 for Windows has a Marco> problem? It would seem so. See my most recent post to your bug report. Switching between bsddb.hashopen and bsddb.btopen seems to make a huge difference. Skip From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Jan 3 07:23:18 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 03 Jan 2004 13:23:18 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: <3ff6b436$1$331$e4fe514c@news.xs4all.nl> Gerrit Holl wrote: > Any comments? Are you aware of Jason Orendorff's path module? (haven't tried it myself though) See this thread: http://tinyurl.com/3gq8r (google link) --Irmen From Pieter.Claerhout at Creo.com Tue Jan 13 17:30:03 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 13 Jan 2004 23:30:03 +0100 Subject: Oracle to Mysql (dates) Help please Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D89@cseexch01.cse.creoscitex.com> My mistake, it should indeed be executemany. I guess I'm getting to much used to using PDO (pdo.neurokode.com) to do database stuff... pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Dennis Lee Bieber [mailto:wlfraed at ix.netcom.com] Sent: 13 January 2004 18:49 To: python-list at python.org Subject: Re: Oracle to Mysql (dates) Help please duikboot fed this fish to the penguins on Tuesday 13 January 2004 01:13 am: > > > Could you please explain that? See the reply (Pieter Claerhout) -- though according to my documents, the method is executemany(), not execute_many(). -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < -- http://mail.python.org/mailman/listinfo/python-list From xah at xahlee.org Sun Jan 25 00:31:36 2004 From: xah at xahlee.org (Xah Lee) Date: 24 Jan 2004 21:31:36 -0800 Subject: perl bug File::Basename and Perl's nature Message-ID: <7fe97cc4.0401242131.22acf485@posting.google.com> Just bumped into another irresponsibility in perl. the crime in question this time is the module File::Basename. Reproduction: 1. create a directory containing a file of this name: "cdrom.html". 2. "use File::Basename;", with the line: ($name,$path,$suffix) = fileparse($File::Find::name, ('.html', '.m')); 3. Notice that your cdrom.html will be parsed into "cdr" with suffix "om.html". expletive Perl and Perl slinging morons. Now, if you peruse the "documentation" of "perldoc File::Basename", you'll see that it shouldn't be so. AND, the writting as usuall is fantastic incompetent. To illustrate, i quote: --begin quote fileparse The fileparse() routine divides a file specification into three parts: a leading path, a file name, and a suffix. The path contains everything up to and including the last directory separator in the input file specification. The remainder of the input file specification is then divided into name and suffix based on the optional patterns you specify in @suffixlist. Each element of this list can be a qr-quoted pattern (or a string which is interpreted as a regular expression), and is matched against the end of name. If this succeeds, the matching portion of name is removed and prepended to suffix. By proper use of @suffixlist, you can remove file types or versions for examination. --end quote Note the last sentence: "By proper use of @suffixlist, you can remove file types or versions for examination." Now, this is in sync with the usual verbiages of unix man pages, of mentioning irrevalent things. Why the fuck do i need to know what is version, or examination what?? Not every morons in this world is using unix with its morinic convention of appending things to file names as a versioning system, and not every moron in this world need to "exam" things. The unix irrevalency, inprecision, driveling are paragoned above. Here is a better documentation for the fileparse subroutine. fileparse fileparse divides a file name into 3 parts: directory string, file name, file name suffix. fileparse($filename, @suffixes) returns a array of 3 elements ($name, $dir_path, $suffix). The concocted result of "dir_path$name$suffix" is guaranteed to equal to $filename. The @suffixes is a array of strings, for example ('\.html', '\.txt', '\.png'). These strings are interpreted to be regular expressions, and is matched against the end of $filename. But NOOO, perl morons are too enamored with driveling to write such functional spec, after all, the code is sloppy and they don't REALLY know what the code really does. This is not just one incompetence. Perl is filled with them. This report is on Perl version: This is perl, v5.8.1-RC3 built for darwin-thread-multi-2level (with 1 registered patch, see perl -V for more detail) -- To the rookie programers out there, i advice against learning Perl. (i suggest Python instead) Please see http://xahlee.org/UnixResource_dir/perlr.html Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From carroll at tjc.com Wed Jan 14 18:31:32 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed, 14 Jan 2004 23:31:32 GMT Subject: best book References: Message-ID: On Thu, 15 Jan 2004 03:32:31 +0530, km wrote: >What is the best book to start with python ? i am have been working since 1 yr with Perl. My favorite to start is O'Reilley's "Learning Python." Try to borrow it, rather than buy it, though, or at least buy a used copy. Once you know Python, you won't be using this book for much; you'll be using the online documentation or a reference-type book like (my favorite) "Python in a Nutshell". You'll probably get a bunch of responses, saying "You don't need a book, use the online tutorials," but if you're like me, you like the idea of curling up on the couch or in bed with an honest-to-goodness *book.* If not, there *are* a lot of good tutorials. A good place to start is . From Mike at DeleteThis.Geary.com Fri Jan 23 11:37:53 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 23 Jan 2004 08:37:53 -0800 Subject: debugging References: <88bc63c6.0401230416.7acf904c@posting.google.com> Message-ID: <1012jf28chjio61@corp.supernews.com> Doug Farrell wrote: > Can someone help me out a little with Python? What do people > use to debug Python code? I don't understand how to use the > built in debugger and I haven't had any luck getting ddd to > debug my Python programs. I end up falling back on > inserting print statements in my code to figure out what's > going on. This works but isn't always the fastest route to a > solution. So, I'm just wondering what other people do. What OS are you running? On Windows, PythonWin has a nice interactive debugger. My favorite is Komodo, which is available for Windows, Linux, and Solaris: http://www.activestate.com/Products/Komodo/ Komodo is not free, but the personal edition is pretty cheap, and the commercial edition is well worth the price for commercial development. -Mike From just at xs4all.nl Tue Jan 13 05:13:26 2004 From: just at xs4all.nl (Just) Date: Tue, 13 Jan 2004 11:13:26 +0100 Subject: problems with dict() in python 2.2 References: Message-ID: In article , Olaf Meyer wrote: > I'm trying to build a dictionary using python's dict type, but somehow > it does not work the way I expect it to. Here's the code: > > Python 2.2.1 (#7, Jan 9 2004, 16:59:31) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. > >>> data=dict(red=1) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'red' is an invalid keyword argument for this function > > What am I doing wrong? You're using a 2.3 feature in 2.2. Just From newspost at lolmc.com Sun Jan 25 17:28:30 2004 From: newspost at lolmc.com (Lol McBride) Date: Sun, 25 Jan 2004 22:28:30 +0000 Subject: MySQL insert query problem Message-ID: Hi all, I'm using Python 2.3 and the MySQLDB module on a Mandrake Linux 9.2 system and I'm encountering a problem whentrying to insert a string object intoa varchar field in a database I'm using. The query being sent to the MySQL server by my program is : INSERT INTO analysis (DrawNumber,pool1)VALUES (847, ' (4, 8, 21, 24, 39, 44) ' ) ; But the field pool1 actually contains (4, 8, 21, 24, 39, i.e it is missing the final digits ( 44 ) and the closing bracket.The program writes a number of rows into the database and they all exhibit the same behaviour - could anyone shed some light on this problem? Thanks, Lol McBride From zunbeltz at wm.lc.ehu.es.XXX Fri Jan 9 02:41:29 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 09 Jan 2004 08:41:29 +0100 Subject: __init__, __slot__ and **keywordargs Message-ID: Hi, I'm playing with __slot__ (new class) and the __init__ method of my class. I want the arguments of __init__ to be keywords and that the method initialize all the attributes in __slot__ to None except those in the argument of __init__ (Is this a good practice?). I've the following class class PersonalData(object): __slot__ = ("Firstname", # Firstname of the person. "Surname", # Surname of the person. "Birthdate", # Birthdate of the person. "Nationality" # Nationality of the person. ) def __init__(self,**args): for kwrd, value in args.items(): self.__setattr__(kwrd,args[kwrd] # for arg,value in args.items(): # if arg in self.__slot__: # self.__setattr__(arg,value) # else: # errmsg = str(self.__class__.__name__) # errmsg += "object has not attribute " + arg # raise AttributeError, errmsg def __str__(self): buffer = "" for attr in self.__slot__: if attr in self.__dict__.keys(): buffer += attr + ": " + str(self.__getattribute__(attr)) + "\n" The problem is that the __init__ defined can set attributes that are not in the slot and i want to have an exception when someone tries to do inst = PersonalData(noattribute = "Smith") I've coded the solution in the fragment that is commented, raising and exception manually. Someone knows a more elegant solution and can explain with the first definition didn't raise and exception? Thanks in advance Zunbeltz -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From marco at bubke.de Wed Jan 7 03:30:45 2004 From: marco at bubke.de (Marco Bubke) Date: Wed, 07 Jan 2004 09:30:45 +0100 Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: Michael Hudson wrote: > Ype Kingma writes: > >> Marco Bubke wrote: >> >> > Hi >> > >> > There is the Lock object in the threading module. >> > But there is no medode there I could aquire a scoped >> > lock like: >> > >> > mutex = threading.Lock() >> > my_lock = mutex.scoped_acquire() # maybe scoped_lock() >> > #now this stuff is locked >> > >> > del mylock >> > >> > #the lock is released. >> > >> > def do_domething: >> > my_lock = mutex.scoped_acquire() >> > #now this stuff is locked >> > #the lock is released after its out of scope >> > >> > >> > I have written this my own but I'm not sure there is a drawback >> > because its looks so convinent. So I wonder why its not in >> > the module? >> >> Some reasons: >> - What should happen when an exception happens during the locked stuff? >> - It is possible pass a reference to the lock during the locked stuff, >> so although the lock goes out of local scope, there still might be >> a reference to it. >> - The moment that __del__() is called is not guaranteed. >> >> You can also do it like this: >> >> mutex = threading.Lock() >> mutex.acquire() >> try: >> # now this stuff is locked >> finally: >> mutex.release() # explicit is better than implicit > > This is the way to do it today. There's PEP 310 which, if accepted, > makes this at least shorter to write... (and PEP 310 references a > lengthy discussion about whether using __del__ like this is wise). Thats looks really nice. thx Marco From rick_muller at yahoo.com Sat Jan 17 23:23:02 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 17 Jan 2004 20:23:02 -0800 Subject: Does anyone else not find the fun in programming...? References: Message-ID: <5eb8fb88.0401172023.737e05d6@posting.google.com> chris.lyon at spritenote.co.uk (Chris Lyon) wrote in message news:... > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, > I have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along > canals is fun, Arguing about quite how useless the British Government > is fun but programming ? > > Do I need help ? > > (Actually typing this was quite fun, so perhaps) I never found programming fun until Python. But I find Python's syntax so natural that I can write little toy codes almost effortlessly and try out ideas, which I find incredibly gratifying. Plus, I really like the fact that so many cool things are included in the Python distribution, so I can play around with list comprehensions or XML parsing when the mood strikes. However, I should point out that I'm a scientist, not a computer scientist. I have a feeling that if all I got paid to do, day in and day out, was write code, I might see Python as merely another tool of management's oppression. So I know where you're coming from. R. From just at xs4all.nl Tue Jan 6 03:40:24 2004 From: just at xs4all.nl (Just) Date: Tue, 06 Jan 2004 09:40:24 +0100 Subject: tuple.__hash__() References: Message-ID: In article , "Thomas Guettler" wrote: > Can someone point me to the documentation > of tuples __hash__ method? > > I want to unique a list of tuples. Since > __hash__ returns a 32 bit integer, there > could be a situtation where two different tupples > return the same value. That's a basic propery of hashing in general, no? > >>> t1=(1, 2, 3) > >>> t1.__hash__() > -821448277 > >>> t2=(1, 2, 3) > >>> t2.__hash__() > -821448277 Not sure what your point is here: you're showing that two _equal_ tuples have the same hash value. > Is there a dictionary type which uses __cmp__() like > btrees in the standard library? I don't think so. Just From http Mon Jan 5 16:28:35 2004 From: http (Paul Rubin) Date: 05 Jan 2004 13:28:35 -0800 Subject: local interpreter remote machines References: Message-ID: <7x4qvaxeyk.fsf@ruckus.brouhaha.com> hokieghal99 writes: > This may not be possible, but I thought I'd ask anyway. Could I get > the below code to run on a Python server where other machines would > connect to it (say thru the Web) and get details of *their* system > instead of the system details of the machine that the interpreter is > running on? Any ideas? In general, what you're asking for is called OS fingerprinting. It's an active topic in security research. Figuring out a remote system's OS is the first step towards breaking into it, so there's a slow but growing effort among OS implementers to thwart attempts at fingerprinting. In simple cases, though, you can do stuff like connect to the remote IP address's port 80 and see if you can get any HTTP server headers to examine, and stuff like that. OS's also leave inadvertent fingerprints, like the "randomly generated" TCP sequence numbers which have detectable statistical patterns on some systems. If you can detect such a pattern, that often lets you identify the remote OS. From zanesdad at bellsouth.net Mon Jan 19 06:18:00 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 19 Jan 2004 06:18:00 -0500 Subject: ANN: Munkware 0.3 Message-ID: <20040119111800.GA689@cerberus> Munkware, a transactional and persistent queueing mechanism, is proud to announce version 0.3 for public consumption. One bug fix in this release: - Now checks for proper index on all put_commit() and get_commit() calls. The Sourceforge Project page is located at http://sourceforge.net/projects/munkware/ and the project home page is located at http://munkware.sourceforge.net/ I'm currently working on a quasi-RESTish (web services/HTTP) interface for Munkware rather than going the SOAP route that I had initially thought. I've got a design about 3/4 of the way hammered out, but no code so far on that. I'm planning on (at least as a first stab) using the standard library BaseHTTPServer to run it from. Hopefully, I'll be able to get something present-able in the next couple of weeks. If you have any suggestions, please feel free to email them to me. Jeremy Jones From jcarlson at uci.edu Tue Jan 20 00:15:31 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 19 Jan 2004 21:15:31 -0800 Subject: stack-like file object References: <400be8f3_2@nova.entelchile.net> <20040119183719.ABC4.JCARLSON@uci.edu> Message-ID: <20040119211320.D6B9.JCARLSON@uci.edu> > > While I don't condone the use of files as stacks, the below should work > > for you. It doesn't reduce in size when an object is removed, but as > > long as you don't try to share the stack between processes or threads, > > it should work fine. > > condone > v : excuse, overlook, or make allowances for; be lenient with; > > Jp I was using it in a similar tone as: "I don't condone the robbing of banks, but below is a plan to do so, if one were to want to." - Josiah From gagenellina at softlab.com.ar Fri Jan 2 21:01:56 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 02 Jan 2004 23:01:56 -0300 Subject: Keyboard browsing (was Re: ANN: Python Language Reference) In-Reply-To: References: Message-ID: <5.2.1.1.0.20040102224658.02429820@192.168.0.115> At 2/1/2004 19:19, you wrote: > > Opera can be completely keyboard-driven. And to search, you can type > >/TEXT, just like you would in lynx or any other proper viewing or > >editing tool. > >Really? That's not in my Opera/Linux 6.1. That really cool feature appeared in v7.20. But Ctrl-F = search in page works from prehistoric ages :) Gabriel Genellina Softlab SRL From vidiv at gmx.net Tue Jan 13 14:28:42 2004 From: vidiv at gmx.net (vidiv at gmx.net) Date: Tue, 13 Jan 2004 20:28:42 +0100 (MET) Subject: Terminal Emulation with IBM ES9672 mainframe via multiplexer. Message-ID: <8411.1074022122@www20.gmx.net> Hi All, Sorry for repeating, in the earlier msg i forgot to add a Subject line !! I am a student-newbie to Python-List (for that matter Python language) working on a project for Terminal Emulation. The dumb terminal interacts with an IBM ES9672 mainframe through a 'multiplexer-MUX'. The s/w is currently running in 'C' on a Windows NT environment and the requirement is to introduce Object Oriented concepts and C++ was the obvious choice, but i came across 'Python' (and also Perl, Ruby, ..etc) after i installed RH8 on my PC last month. We are actively canvassing the advantages of GNU s/w and philosophy and would like to simultaneously port it to GNU/Linux platform. I have read some of the documentation in Python. Before using Python as our project language it would be useful to know whether Python has functions, libraries/headers (like C does) capable of handling the foll. : 1] open and close serial ports, 2] set baud rates, 3] check parity bit/byte, 4] stop bits, 5] Hardware handshaking, 6] selection of port,...... Our existing 'C' code is to be ported to the GNU/Linux platform so we are actively looking at an OOP concept. The part for serial port communication in C++ has classes so its easier to write customized programs to do most of the above. Most importantly compatibility issues with the existing Multiplexer and Cisco Routers have to be kept in mind as the company will *not* make any H/W changes. We saw that python has some routines for using existing C code, so we dont have to rewrite everything and can make modules containing functions and use it to operate on files. Does it provide any other serial port communication features ? It would be nice if anyone could throw some light on some of the above issues. Thankyou for your time. Ciao, Vidya. -- +++ GMX - die erste Adresse f?r Mail, Message, More +++ Neu: Preissenkung f?r MMS und FreeMMS! http://www.gmx.net From fortepianissimo at yahoo.com.tw Fri Jan 9 23:50:27 2004 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 9 Jan 2004 20:50:27 -0800 Subject: module for parsing email Received headers? Message-ID: Does anyone know the existence of such module? I bet 90% of the chance that the wheel was invented before. Thanks! From deadlink27 at web.de Thu Jan 29 13:05:31 2004 From: deadlink27 at web.de (Sebastian Stelzer) Date: Thu, 29 Jan 2004 19:05:31 +0100 Subject: Get error "ImportError: No module named _tkinter" Message-ID: Hi, I'am a beginner in Python and I have got a problem with the TKInter module. When I want to start e.g. pysol, I get following output: [output] Traceback (most recent call last): File "/usr/share/games/pysol/src/pysol.py", line 47, in ? from main import main File "/usr/share/games/pysol/src/main.py", line 48, in ? from app import Application File "/usr/share/games/pysol/src/app.py", line 54, in ? from images import Images, SubsampledImages File "/usr/share/games/pysol/src/images.py", line 47, in ? from pysoltk import tkversion, loadImage, copyImage, createImage File "/usr/share/games/pysol/src/pysoltk.py", line 81, in ? exec "from " + m + " import *" File "", line 1, in ? File "/usr/share/games/pysol/src/tk/tkconst.py", line 39, in ? import Tkinter File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter [/output] I'am using Suse Linux 9.0 with Python 2.3.3. Can anybody help me? cu From bkelley at wi.mit.edu Tue Jan 6 07:57:47 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 06 Jan 2004 12:57:47 GMT Subject: Project dream In-Reply-To: References: Message-ID: <3FFAB26F.7030704@wi.mit.edu> Andrew Dalke wrote: > Lonnie Princehouse: > >>I keep thinking that a good graph module would be really handy (as in >>nodes and edges, not plotting) > > > I've wondered about Boost. There's Boost Python of course, > and Boost includes a graph library with many of the features you've > listed. But do the two work well together? I dunno. > > >>with the ability to traverse and manipulate graphs in nice Pythonic ways, > > > And I really don't know if the result will feel Pythonic. I barely > understand how to make the examples work, much less what > needs to be done to get a full melding. > > >>basic graph theory (finding cycles, paths, cliques, etc). I've >>started writing one, but it's nowhere near completion. > > > I have two C extensions for Python which do max clique detection. > See http://starship.python.net/crew/dalke/clique/ . But I haven't > tested them in over 4 years. I have and just last year. They work pretty well but I think that there might be better algorithms. I had them working under python 2.2 but they aren't useful out of the box since there is no driver. I can package it with the one that I have (the graph is represented as a numeric matrix) if anyone is really interested. > > BTW, I've done various bits of graph theory work for molecular > structures. I've found that the nomenclature is different enough > that it's hard for chemistry and graph theory to share each other's > data structures directly. (Eg, we want "atoms", which are > "colored nodes", and "bonds", which are "colored undirected > edges" of low valence (usually 4 or less, rarely above 6, and > never larger than about 13.) This is a bit of a pain, algorithms might want to use node and edge or vertex and edge while chemists want to use atom and bond. > Still, I'll be interested in anything you have, especially > subgraph isomorphism. (There is Brian Kelly's "Frowns" > package which has a Python interface to the VF algorithm > but it needs to convert to VF's data structures before doing > the search, and that apparently takes most of the time.) I have minimized this somewhat, but I expect that it still is going to be slow to keep parallel graph structures (python->C++) (python->boost). I have almost completed a pure-python version of vflib, mainly for the purpose of doing recursive graph searching. It doesn't appear to be much slower than the C++ counterpart and doesn't have the start up time conversion. The vflib package is available seperately from frowns by the way. > > Andrew > dalke at dalkescientific.com > > Brian. From omission9 at invalid.email.info Mon Jan 26 00:03:39 2004 From: omission9 at invalid.email.info (omission9) Date: Mon, 26 Jan 2004 05:03:39 GMT Subject: efficient updating of nested dictionaries In-Reply-To: References: Message-ID: omission9 wrote: > I have a dictionary that looks like this > MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO > > I am having a problem updating this with a simple > MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting > into the inner dicts. > Getting the keys of each and iterating through and updating each one is > terribly slow as the number of keys gets bigger and bigger. > What is the bst way to update my nested dicts? > > > So far I have found this on the internet: def rUpdate(self,targetDict,itemDict): valtab=[] for key,val in itemDict.items(): if type(val)==type({}): newTarget=targetDict.setdefault(key,{}) self.rUpdate(newTarget,val) else: targetDict[key]=val However, this does not seem to handle the fact that each dict has multiple keys. :( So far the modification I have made to make it work right have failed. Any ideas? From msurette at laframboise.net Wed Jan 28 09:33:04 2004 From: msurette at laframboise.net (Michael Surette) Date: Wed, 28 Jan 2004 14:33:04 GMT Subject: pexpect exceptions References: Message-ID: On Wed, 28 Jan 2004 01:21:49 -0800, Manuel de Ferran wrote: > Michael Surette wrote in message news:... >> I have been trying to automate the changing of passwords using python and >> pexpect. I wrote a script as a test and it works, except that it gives me >> an exception when it stops running: >> >> Exception exceptions.OSError: >> (10, 'No child processes') in > > ignored >> >> What is happening and how do I get rid of the exception? >> >> I am running python 2.3.2 under Slackware linux 9.1 and pexpect 0.99. >> Here is the script: >> >> #!/usr/bin/python >> import pexpect >> import sys >> >> if len(sys.argv) != 3: >> print 'usage error!' >> raise SystemExit >> >> name= sys.argv[1] >> passwd= sys.argv[2] >> >> a= pexpect.spawn('passwd %s'%name) >> >> changed= False >> while not changed: >> i= a.expect(['[Nn]ew password:','[Cc]hanged']) >> if i == 0: >> a.sendline(passwd) >> elif i == 1: >> changed= True > > I have the same issue with the following code : > #!/usr/bin/env python > '''This runs "ls -l" on a remote host using SSH. > At the prompts enter hostname, user, and password. > ''' > import pexpect > import getpass > > host = raw_input('Hostname: ') > user = raw_input('User: ') > password = getpass.getpass('Password: ') > > child = pexpect.spawn("ssh -l %s %s /bin/ls -l"%(user, host)) > > child.expect('password:') > child.sendline(password) > > child.expect(pexpect.EOF) > print child.pid,'middle',child.isalive() > > print child.before > > This is a slighty modified version of sshls.py (shipped with > pexpect-examples). I've only added "print > child.pid,'middle',child.isalive()" > and I get the same exception : "exceptions.OSError: (10, 'No child > processes')" > > The weird thing I can't explain is that, I don't get the exception > without ",child.alive()" I have found a solution and an explanation. Adding "a.close(False)" as a last line of my script fixes the problem. The spawn.close() function calls os.pidwait() with your child process pid. In our two cases, that pid is dead and os.pidwait rightfully raises an exception. Calling spawn.close() with a False argument bypasses this call. From cwilcox at etcconnect.com Wed Jan 21 12:48:48 2004 From: cwilcox at etcconnect.com (Christian Wilcox) Date: Wed, 21 Jan 2004 11:48:48 -0600 Subject: Help, *.CHM, etc -> *nix .chm viewer Message-ID: <69A0D4AB81C51447AD6BA387782B8D6401343F78@midl-mail4.etcconnect.com> > I wonder if anyone has written a cross-platform CHM decoder and browser > that has the help browser look & feel. I can't find one, but it seems > that python would be a great language to make such a thing. Maybe > I'll take a crack if it hasn't been done. I like monolithic, > compressed help vs. a big directory full of html. http://xchm.sourceforge.net/ Description from the page: xCHM is a .chm viewer for UNIX (Linux, *BSD, Solaris), written by Razvan Cojocaru. Success stories of xCHM on Mac OS X have also been received, and apparently xCHM even works if compiled under the Cygwin environment in Windows. HTH Christian Wilcox From alert at notification.messagelabs.com Tue Jan 27 09:39:02 2004 From: alert at notification.messagelabs.com (alert at notification.messagelabs.com) Date: 27 Jan 2004 14:39:02 -0000 Subject: WARNING. You sent a potential virus or unauthorised code Message-ID: <20040127143902.21330.qmail@server-20.tower-27.messagelabs.com> For English instructions please scroll down. ISION MailScan hat einen potenziellen Virus oder eine verd?chtige Datenstruktur in einer von Ihnen verschickten oder an Sie gesendeten Nachricht entdeckt. ____________________________________________________________ Einige Informationen zu der infizierten eMail ____________________________________________________________ Zur besseren Identifikation der Nachricht: Der Absender der Nachricht war: python-list at python.org Der Empf?nger der Nachricht war: serg at spiegel.de Der Betreff war: '(empty)' Die Nachricht wurde verschickt am Tue, 27 Jan 2004 14:36:08 +0100 Um die Nachricht genauer zu identifizieren: Scanner 7 (Unpacker) berichtet folgendes: >>> W32/MyDoom.A in '508073_2X_PM4_EMS_MA-OCTET=2DSTREAM__text.exe' Die Originalnachricht ist in den ISION Quarant?ne_Server umgeleitet worden, in mail server server-20.tower-27.messagelabs.com (id 508073_1075214341) und wird dort f?r 30 Tage gespeichert bevor sie endg?ltig gel?scht wird. ____________________________________________________________ Weitere Hilfe ____________________________________________________________ Lesen Sie bitte die haeufig gestellten Fragen ( FAQ) fuer eine solche Situation unter http://www.ision.net/mailscan/faq Hier werden die meisten Ihrer Fragen beantwortet. Wenn Sie weitere Informationen ben?tigen oder glauben, dass es sich um einen falschen Alarm handelt, kontaktieren Sie bitte das ISION Customer Interaction Center unter support at ision.net Sollten Sie mit dem Support in Kontakt treten, geben Sie bitte immer die nachfolgende Virus Identifikationsnummer an: {{{ mail server server-20.tower-27.messagelabs.com (id 508073_1075214341) }}} ______________________________________ Diese Nachricht wurde von ISION MailScan unter Nutzung des MesssageLabs Virus Control Centers auf alle bekannten Viren untersucht. Wenn Sie mehr ?ber diese Dienstleistung erfahren m?chten, besuchen Sie http://www.ision.net/mailscan/faq _________________________________________________________________ *************************ENGLISH********************************* ISION Mailscan discovered a possible virus or unauthorised code (such as a joke program or trojan) in an email sent by you. Please read this whole email carefully. It explains what has happened to your email, which suspected virus has been caught, and what to do if you need help. ____________________________________________________________ Some details about the infected message ____________________________________________________________ To help identify the email: The message was titled '(empty)' The message date was Tue, 27 Jan 2004 14:36:08 +0100 The message identifier was (empty) The message recipients were serg at spiegel.de To help identify the virus: Scanner 7 (Unpacker) reported the following: >>> W32/MyDoom.A in '508073_2X_PM4_EMS_MA-OCTET=2DSTREAM__text.exe' The message was diverted into the virus holding pen on mail server server-20.tower-27.messagelabs.com (id 508073_1075214341) and will be held for 30 days before being destroyed. ____________________________________________________________ What should you do now? ____________________________________________________________ If you sent the email from a corporate network, you should first contact your local Helpdesk or System Administrator for advice. They will be able to help you disinfect your workstation. If you sent the email from a personal or home account, you will need to disinfect your computer yourself. To do this you will need an anti_virus program. We suggest using one of the leading industry anti_virus packages such as McAfee, F_Secure or Cybersoft, which cost ?15_?30 per copy. ____________________________________________________________ Getting more help ____________________________________________________________ You may like to read the Support FAQs at http://www.ision.net/english/mailscan/faq These will answer many of the most common queries. If you believe this message to be a false alarm or you require further assistance, you can email ISION UK Support at:_ support at ision.net.uk or contact ISION Internet by telephone on:_ +44 (0) 208 293 73 00 Please quote the following Virus Pen ID when contacting Support. {{{ mail server server-20.tower-27.messagelabs.com (id 508073_1075214341) }}} ________________________________________________________________________ This email has been scanned for all viruses by the MessageLabs Email Security System. For more information on a proactive email security service working around the clock, around the globe, visit http://www.messagelabs.com ________________________________________________________________________ From swalters_usenet at yahoo.com Sun Jan 11 02:29:47 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 11 Jan 2004 07:29:47 GMT Subject: QOTW? References: Message-ID: |Thus Spake Skip Montanaro On the now historical date of Sat, 10 Jan 2004 07:50:09 -0600| > > QOTW perhaps? > > Sam> I read the benchmark and I think it doesn't measure python in > it's Sam> target area. That's like taking a world-class marathon > runner and Sam> wondering why he doesn't compete well in a > figure-skating event. > > Skip *garsh* I feel flattered. *blush* You know, I sadly spent quite a bit of time debating which simile to use there. I wandered around the house wondering what to put there. Some rejected ideas: "It's like asking Kasparov why he didn't win the weight-lifting competition." "That's like asking a world-class marathon runner why he doesn't compete well in a weight-lifting competition." "That's like asking a world-class weightlifter why they didn't do well in the figure skating competition." (I almost used this one because it conjures images of a burly Russian weight-lifter floundering on ice skates. Very Monty-Python-esque.) I chose the one I did in case I needed to later state that "Both figure skating and marathon running are aerobic sports, but that doesn't mean that the skills involved are the same." . Now, I feel compelled to justify my statement. Let's look closely at the benchmarks and try to figure out if there's a good reason why we fell down where we did. We did poorly at Math, and competitively at I/O. I'm reminded of Antoine de Saint-Exupe'ry saying "A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away." While not part of the Zen of Python, this seems to be an unstated principle of Python's design. It seems to focus on the bare minimum of what's needed for elegant expression of algorithms, and leave any extravagances to importable libraries. Why, then, are integers and longs part of Python itself, and not part of a library? Well, we need such constructs for counters, loops and indexes. Both range and xrange are evidence of this. Were it not for this, I daresay that we'd have at least argued the necessity of keeping these things in the language itself. Floats are a pragmatic convenience, because it's nice to be able to throw around the odd floating point number when you need to. Trig functions are housed in a separate library and notice that we didn't do too shabby there. I/O is one of our strengths, because we understand that most programs are not algorithmically bound, but rather I/O bound. I/O is a big bottle-neck, so we should be damn good at it. The fastest assembly program won't do much good if it's always waiting on the disk-drive. Perhaps our simplicity is the reason we hear so many Lisp'ers vocally complaining. While more pragmatic than Lisp, Python is definitely edging into the "Lambda Calculus Zone" that Lisp'ers have historically been the proud sole-occupants of. After all, until Python, when one wanted a nearly theoretical programming experience, one either went to C/Assembly (Turing Machine Metaphor) or Lisp (Lambda Calculus Metaphor.) Python is being used in so many introductory programming courses for the very reason that it so purely fits the way a programmer thinks, while still managing to be pragmatic. It allows for a natural introduction to some of the hardest concepts: Pointers/Reference, Namespaces, Objects and Legibility. Each of these concepts is difficult to learn if you are first indoctrinated into an environment without them. In my attempts to learn C++, I initially felt like I was beating my head up against a wall trying to learn what an object was and why one would use them. I have since observed that people coming from a strongly functional programming background have the same experience, while those with no functional programming dogma in them find objects quite a natural concept. The same thing is true of the other concepts I mentioned. If you have them, it's easy to work without them. If you don't, you'll flounder trying to pick them up. Think about how easy it is to pick out a C programmer from their Python coding style. The one important concept I didn't mention is message-passing. This is an important, but much less used concept. It is the domain of Smalltalk and Ruby. I've looked some at Ruby, and lurk their Usenet group. From what I can tell, Ruby takes almost the same philosophy as Python, except where we think namespaces are a honking great idea, they think message-passing is a honking great idea. The nice thing about message-passing is that if you have all the other concepts of OO down, message passing seems natural and is not terribly difficult to "fake" when it's the only missing OO primitive. This is why C++, while not a message-based OO language, is used so often in GUI's, an inherently message-based domain. This is also why we have such a nice, broad choice of GUI toolkits under Python despite lacking a message primitive. Well, I've blathered enough on this topic. I hope, at least, that I've said something worthwhile. Though, I doubt I've said anything that hasn't been said better before. Caffeine, Boredom and Usenet are a dangerous mix. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From mnations at airmail.net Tue Jan 27 00:35:06 2004 From: mnations at airmail.net (Marc) Date: 26 Jan 2004 21:35:06 -0800 Subject: Pickling Tkinter widgets - Where does Python stand now? Message-ID: <4378fa6f.0401262135.3e05d217@posting.google.com> Hi all, After some research I've decided that my previous question (Confusing problem between Tkinter.Intvar...) was headed in the wrong direction. Partly because I think I have a greater understanding of what was happening, and partly because pickling Tkinter widgets is an issue that seems to have been touched on over the years but never really acted on. Postings back to '96 have talked about the need to pickle Tk widgets. People have asked about it at various points, and no one has ever really even come up with a workaround (that I could find). So I am wondering a couple of things: Are there any plans in the future to alter Tkinter so that it will be Pickle compliant in the main release? Has anyone ever found a workaround (whether through altering the main Tkinter.py file or other) that will allow pickling of Tk widgets. Thanks, Marc From peter at cendio.se Wed Jan 28 04:40:07 2004 From: peter at cendio.se (Peter Astrand) Date: Wed, 28 Jan 2004 10:40:07 +0100 (CET) Subject: Cross-version extension modules? Message-ID: If I build a extension module with Python 2.2 and then loads it with 2.3, I get: RuntimeWarning: Python C API version mismatch for module _foo: This Python has API version 1012, module _foo has version 1011. How fatal is this? Is it safe to use the module anyway? If not, is it possible to build the module differently, so that it actually is safe to use it with different versions of Python? -- Peter ?strand www.thinlinc.com Cendio www.cendio.se Teknikringen 3 Phone: +46-13-21 46 00 583 30 Link?ping From alessandro at sephiroth.it Sat Jan 17 05:29:36 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Sat, 17 Jan 2004 10:29:36 GMT Subject: dde References: <8EFMb.102403$_P.3808599@news4.tin.it> Message-ID: > That's not an app, that's a file format. no, I mean Flash MX 2004. The app. "Tim Roberts" ha scritto nel messaggio news:udqe00t28lml4kfqpi2f0k3t191e6pqg2u at 4ax.com... > "Alessandro Crugnola *sephiroth*" wrote: > > > >"Tim Roberts" wrote: > >> > >> What DDE app are you trying to control? > > > >macromedia Flash > What app are you trying to > control? I would have guessed that a fancy app like Dreamweaver, for > example, would probably be controllable by COM, which is easy in Python. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From phipps.xue at sap.com Fri Jan 9 04:17:22 2004 From: phipps.xue at sap.com (Phipps Xue) Date: Fri, 9 Jan 2004 17:17:22 +0800 Subject: MozPython: Why my MozPython did not work after installed successfully? Message-ID: Hello Dr. Schilz, I installed MozPython 0.1.0 by your tutorial. But I can not see the output in mozilla when I ran a test.py, there's no error message or item displayed. Is there any possible problem or note? Could you please tell me the way to see how the mozpython runs? Here, I list my environment information below for you to make a diagnosis. OS: Microsoft Windows XP Mozilla: 1.5 installed in 'd:\Program Files\Mozilla' Python: ActivePython 2.3.2 installed in 'd:\Program Files\Active Python' System Environment Variables: - PYTHONPATH: d:\Program Files\Active Python\lib;f:\Projects\Python;' Phipps From mi-mal at o2.pl Mon Jan 12 03:19:27 2004 From: mi-mal at o2.pl (Mimal) Date: Mon, 12 Jan 2004 09:19:27 +0100 Subject: CGI module problem: duplicated output In-Reply-To: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> References: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> Message-ID: > Pardon me for saying so, but I don't believe you. Your script must > actually look like this: Pardon me too, but I know what my script looks like. I'm not such a fool! I've tested this script under Windows NT + Python 2.1 and Windows XP + Python 2.3 with the same result. To prove you, I copied YOUR code and pasted to *.py file. Than I made it executable and run it using console (./cgi.py). This is what it showed: Hello, world! Content-type: text/html Hello, world! Hello, world! Content-type: text/html Hello, world! I know it's very strange. I don't get it and that's why I need help. :-) -- Mimal From wweston at att.net Thu Jan 29 22:02:26 2004 From: wweston at att.net (wes weston) Date: Fri, 30 Jan 2004 03:02:26 GMT Subject: conditional expression sought In-Reply-To: References: Message-ID: <6PjSb.138487$6y6.2697536@bgtnsc05-news.ops.worldnet.att.net> Elaine, The last code line: print "I would have liked this to be B[2] = ",B[2] prints the value of B[2]; the value you don't want. I think what you meant was that you want B[2] to be 0.0 not false. bool(0.0) does equal false. --------------------------------------------------- The code: A.append(bool(randint(0,1))) will always yield an A of [true,true,true] --------------------------------------------------- I didn't know this about python, and I'm not sure I like it: wes at linux:~/amy> python >>> print 1.1 and 2.2 2.2 >>> print 2.2 and 1.1 1.1 >>> print (1.1 and 2.2) 2.2 The order is important. To me, it should be printing true and not either number or the last number. From miki.tebeka at zoran.com Sun Jan 11 02:56:18 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 10 Jan 2004 23:56:18 -0800 Subject: Providing Default Value for User Input References: Message-ID: <4f0a9fdb.0401102356.236040e1@posting.google.com> Hello, > I have just begun learning Python so that I can write a simple script > to make modification of a file used by another Python script easier. > This file is basically a list of regular expressions. What I want to > do is allow the user to select one of these regular expressions to > modify, but I've realized I know of no way to provide a default value > for user input. Which user input? raw_input, Tkinter, wxPython ... > I could choose to show the regular expression the user > has chosen and simply allow the user to retype it and modify it from > there, but that is time consuming and error prone. Does Python support > a way to do this? To do what? I don't understand your question. Maybe an example will help. > If worse comes to worst, is there a way I could > write such code on my own without having to write a C-based module > (I'd like to stick to Python code only since some users will be > running this script on Windows without a C compiler)? If you create a C extension you can distribute just the binary so your users won't need a C compiler. (They might need some required DLL's but you can ship them as well). HTH. Miki From donn at drizzle.com Sun Jan 25 13:27:12 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 25 Jan 2004 18:27:12 -0000 Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> <1074926701.236022@yasure> Message-ID: <1075055229.911425@yasure> Quoth Zoo Keeper : ... | Neither did I mean to imply that I was not sure if I wanted to use | Python/Bethon. I love Python, and I love BeOS. Bethon seems to be the way to | go, altho' I need to learn Bethon. As far as I know, there's no alternative. Just wanted to point out that some limitations and impediments come with this path, compared to C++. On the other hand, Python may actually solve one problem that some people claim is serious defect of BeOS. When Be was alive, the pervasively multithreaded architecture was supposed to be a big advantage, but after they crashed, even Be engineers came out of the woodwork to claim that the concurrency issues posed too difficult of a problem for most developers and were thus responsible for a lot of unreliable software. I loved the thread-per-window architecture myself and never noticed any problem, and at first I figured that might have been because I fastidiously follow a queuing, event I/O model for thread interop in my own application. But Python itself takes some of the teeth out of concurrency problems, because the interpreter doesn't run in parallel. So while your program executes in parallel, your code doesn't - only the library functions are parallel. Donn Cave, donn at drizzle.com From EP at zomething.com Thu Jan 22 00:50:01 2004 From: EP at zomething.com (EP) Date: Wed, 21 Jan 2004 21:50:01 -0800 Subject: a curious IDLE Error In-Reply-To: <400F5ABA.3090608@rogers.com> References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> Message-ID: <5.2.0.9.0.20040121213755.00b7e840@mail.zomething.com> I'm not sure this error is of note, but it was curious to me (a puzzle). Windows 2000, Python 2.3, using IDLE file editor and shell I had a small script which imported string and worked fine until I added a std. input line: raw_input("some prompt") It opened IDLE and died with error: 'tuple' object not callable I closed the IDLE shell, re-ran the module, which opened a new IDLE shell and repeated the same error. Did this many times. I opened a separate instance of Python (IDLE shell) and tried the raw_input function: it ran fine. I ran my module at the Windows command prompt, and it ran fine. I opened a new Python shell from the instance of IDLE editor where my module was open and tried the raw_input(): >>> someFile=raw_input("enter: ") Traceback (most recent call last): File "", line 1, in ? someFile=raw_input("enter: ") TypeError: 'tuple' object is not callable Can anyone point me in the right direction? Eric Apologies for the lack of proper analysis, I am all ears. From thelastmohiccan at yahoo.com Mon Jan 26 11:51:12 2004 From: thelastmohiccan at yahoo.com (lenk) Date: Mon, 26 Jan 2004 18:51:12 +0200 Subject: Zope In-Reply-To: References: Message-ID: Stephen Boulet wrote: > Just wondering, it's not in /etc/init.d/zope* ? > there is no zope path in etc/init.d/.. only /opt/zope/........... From andrew-pythonlist at puzzling.org Thu Jan 8 09:06:24 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 9 Jan 2004 01:06:24 +1100 Subject: Twisted or Medusa or Zope In-Reply-To: <425cc8d1.0401070808.14690325@posting.google.com> References: <425cc8d1.0401070808.14690325@posting.google.com> Message-ID: <20040108140624.GD551@frobozz> On Wed, Jan 07, 2004 at 08:08:55AM -0800, mir nazim wrote: > hi, > i m planning to start writing intranet applications and want ur real "intranet applications" is a very vague term. Can you be more specific? > cool advices for choosing the correct platform. the choice is between > the three: > > 1. Twisted > 2. Medusa > 3. Zope > (i do not know any of the three). > > i want u people to help me choose the correct platform. It depends :) > my questions are: > > 1. which has the least learning curve. Depends on what you're trying to do. Zope is probably easier to write most kinds of web applications in, because that's what it's designed to do, whereas Twisted is probably easier to implement a network protocol in, because that's what it's designed to do. I think this is the wrong question to ask. The three packages you listed above do quite different things, so the important issue isn't which is easier to learn, but which is the right tool for your job. > 2. which is best suited for the purpose for applications like workflow > automation, groupware, and other business related apps. How do you want people/systems to interact with your "workflow automation, groupware, and other business related apps"? A custom network protocol? Remote procedure calls, e.g. XML-RPC? Web pages? Something else? > please also highlight the major diffrences between the three. > also tell if there is a better alternative. Twisted: Paraphrasing http://twistedmatrix.com/ slightly: "Twisted is an event-driven networking framework written in Python and licensed under the LGPL. Twisted supports many different transports, such as TCP, UDP, SSL/TLS, multicast and Unix sockets. Twisted includes a large number of ready-to-use protocol implementations, including HTTP, NNTP, IMAP, SSH, DNS, IRC, FTP. Twisted also includes some applications implemented with these protocols, such as a web server and domain name server." Medusa: http://www.amk.ca/python/code/medusa.html says: "Medusa is a framework for writing asynchronous socket-based servers." It is simpler and lower-level than Twisted. This means it's harder to work with, but perhaps lighter-weight. For new projects, I think Twisted is probably a better choice than Medusa. Zope uses Medusa for its web server. Zope: http://www.zope.org/ says: "Zope is an open source application server for building content managements, intranets, portals, and custom applications." It's a web server with an integrated object database. Notably for you, there are "products" (i.e. modules) for Zope that include Workflow automation engines for document publishing -- I'm thinking of CMF here (http://cmf.zope.org/). Plone (http://www.plone.org), which is built on CMF, is worth looking at if you are interested in the CMF. My guess is that Zope is probably the tool best suited to your problem, but, well, "it depends" :) It's entirely possible that you might want more than one of these tools, too! -Andrew. From nick889 at mail.com Sun Jan 4 00:26:01 2004 From: nick889 at mail.com (Nick) Date: 3 Jan 2004 21:26:01 -0800 Subject: Py2exe?? Error: Nothing to do? References: <86df8ed4.0401031028.6edf2381@posting.google.com> Message-ID: <86df8ed4.0401032126.4031bcc8@posting.google.com> Yes, i did manage to get it to work, thank you. Also, i am kinda new to the whole newgroups thing. I am currently posting from google.com and they say it takes several hours before the groups are updated. Is there anyway to make it so that the newgroups are like update instantly. From swalters_usenet at yahoo.com Mon Jan 5 19:09:02 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Tue, 06 Jan 2004 00:09:02 GMT Subject: Python/C and PYTHONPATH References: Message-ID: |Thus Spake Tero Pihlajakoski On the now historical date of Mon, 05 Jan 2004 22:39:19 +0000| > I'll see if it's actually the C-part that's causing problems, but I worked > it around by adding: > > PyRun_SimpleString("import sys\nsys.path.insert(0,'')"); > > right after the Py_Initialize(). > > Works ok. Guess I'm "allowed" to do that(?) IMLK (In My Limited Knowledge) that seems okay, but it also feels a bit ham-handed. try this snippet: ---untested code--- #include #include /* prototyping may not be neccessary... dunno...*/ extern char *getenv(const char *name); extern char *setenv(const char *name, const char *value, int overwrite); /* comment them out if gcc complains about redeclarations. */ /* append something to pythonpath */ /* returns 0 on failure, 1 on creation of the env variable and 2 on an append oh, and -1 in cases of catastrophic miscompilation */ int myPyPathAppend(char *extrapath) { char *buffer = NULL; /* size to taste... You should do this dynamically to avoid future buffer overrun attacks*/ char eventual_path[1024] = { 0 }; /* take note: after getenv, buffer points to an external constant character buffer. do NOT try to modify it directly. use strcpy(char *dest, char *src) (he says knowingly... is she into photography mate?) */ if( (buffer = getenv("PYTHONPATH")) == NULL ) { /* we're here because PYTHONPATH is not already part of the environment. */ setenv("PYTHONPATH", extrapath, 1); /* the last argument makes sure that we create the env var*/ /* did it go happen .. you should check this more rigorously*/ if( (buffer = getenv("PYTHONPATH")) == NULL) { /* we failed... abend. */ return 0; } else { /* success! cheers! */ return 1; } return -1; /* dead code... should never reach here */ } else { /* PYTHONPATH already exists. append ';', then our new path and update it. */ /* find the "=" in the buffer... from string.h extern char *strstr (__const char *__haystack, __const char *__needle) there's a better way to do this, but I can't recall the function off the top of my head */ buffer = strstr(buffer, "=") + 1; /* +1 because buffer points to the equals. we want the string starting after it. */ /* copy the old PYTHONPATH string */ strcpy(eventual_path, buffer); strcat(eventual_path, ";"); strcat(eventual_path, extrapath); setenv("PYTHONPATH", extrapath, 1); /* the last argument makes sure that we create the env var*/ /* did it go happen .. you should check this more rigorously*/ if( (buffer = getenv("PYTHONPATH")) == NULL) { /* we failed... abend. */ return 0; } else { /* success! cheers! */ return 2; } return -1; /* dead code... should never reach here */ } else { /* PYTHONPATH already exists. append ';', then our new path and update it. */ /* find the "=" in the buffer... from string.h extern char *strstr (__const char *__haystack, __const char *__needle) there's a better way to do this, but I can't recall the function off the top of my head */ buffer = strstr(buffer, "=") + 1; /* +1 because buffer points to the equals. we want the string starting after it. */ /* copy the old PYTHONPATH string */ strcpy(eventual_path, buffer); strcat(eventual_path, ";"); strcat(eventual_path, extrapath); setenv("PYTHONPATH", extrapath, 1); /* the last argument makes sure that we create the env var*/ /* did it go happen .. you should check this more rigorously*/ if( (buffer = getenv("PYTHONPATH")) == NULL) { /* we failed... abend. */ return 0; } else { /* success! cheers! */ return 2; } return -1; /* dead code... should never reach here */ } return -1; /* deader code... should *really* never reach here */ } ---untested code--- I haven't tested, compiled or even read through this code. I'm late for a party and still added comments That means you get punctuation patrol :-P Check the semicolons, check the braces Hey, I hear that in some companies they call this teamwork methodology "extreme-programming" We're buzzword compliant! HTH (Danm... I'm such a code monkey) -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From rkern at ucsd.edu Tue Jan 20 00:35:17 2004 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 20 Jan 2004 05:35:17 GMT Subject: efficent test for array with only one value? In-Reply-To: <25mud1-s1m.ln1@jowls.lairds.org> References: <00ird1-dmd.ln1@jowls.lairds.org> <25mud1-s1m.ln1@jowls.lairds.org> Message-ID: Kyler Laird wrote: > Robert Kern writes: > > >>>>>from Numeric import * >>>>>a = ones((3,5)) >>>>>equal.reduce(a.flat) >> >>1 >> >>>>>a[0,3] = 0 >>>>>equal.reduce(a.flat) >> >>0 >> > >>Ufuncs are wonderful things. > > > Yeah, but they also don't work for this. First, I'm guessing that reduce > will not stop immediately when equal encounters a False. (It doesn't do > "and".) > > Also, it just plain doesn't work. > >>> import Numeric > >>> a = Numeric.zeros((3,5)) > >>> Numeric.equal.reduce(a.flat) > 0 > >>> Numeric.equal.reduce([0,0,0,0,0,0,1]) > 1 Yeah, I'm sorry. I had a brainfart (one of several today, alas). The reduce method is completely the wrong thing to use since it uses the *result* of the last comparison as the first argument for the following comparison. However, alltrue(a.flat == a.flat[0]) will work but won't short-circuit. Fast, though, if the array isn't huge. > --kyler -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nhodgson at bigpond.net.au Fri Jan 16 16:59:30 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 16 Jan 2004 21:59:30 GMT Subject: Retrive unicode keys from the registry References: <1xpzaa8i.fsf@python.net> Message-ID: <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> Thomas Heller: > In the actual use case I have, I'm quite sure that the subkeys are coded > in latin-1: And you are also sure that your locale will always use a latin-1 code page or another code page similar enough to work on your keys. > But, assume that I wanted to provide a patch to Python (or implement in > ctypes) so that QueryValue accepts unicode subkey names (I was > astonished to find out that it does not). How could this be done, > hopefully portable between NT/2000/XP and 98, and assuming unicows.dll > is not installed - so the wide version is not available on 98? This is somewhat unpleasant, requiring runtime conditional code. For the Python standard library, in posixmodule.c, places where there is a need to branch first check that the OS is capable of wide calls with unicode_file_names(), then check if the argument is Unicode and if it is then it calls the wide system API. While the wide APIs do not work on 9x, they are present so the executable will still load. One limitation on the Unicode support in posixmodule is that it doesn't try to detect and use MSLU on Windows 9x/Me. > My understanding is that it's possible to convert any (for a certain > definition of 'any) unicode string in a byte string (because the > encoding for the byte string can be specified). Then you have to choose the encoding and switch the current locale to that encoding as there is no encoding or locale parameter to RegQueryValue. Values with characters from different languages may not be encodable into any non-Unicode encoding. Neil From elainejackson7355 at home.com Sat Jan 31 01:17:18 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 31 Jan 2004 06:17:18 GMT Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: Have you considered " globals()[name] = i " ? "Josiah Carlson" wrote in message news:bvedh2$7h7$1 at news.service.uci.edu... | | >>Fair enough. However, is there anything wrong with modifying globals() | > | > | > No. "globals()['a'] = 3" is exactly the same as "a=3" executed at module | > scope, outside of functions. The purpose is to allow you to set a variable | > whose name you do not know until runtime. An example, as in your | > application, is when the name comes from user input. | | I personally enjoy modifying globals() as it suits my needs. Another | statement that is quite useful is global. | >>> def set_global_k(i): | ... global k | ... k = i | ... | >>> set_global_k(5) | >>> k | 5 | >>> set_global_k(6) | >>> k | 6 | >>> | | Really only useful for when you know the name of the variable before | runtime, but then again, one could always: | >>> def set_global_name(i, name): | ... exec('global %s;%s = i'%(name, name)) | ... | >>> set_global_name(10, 'l') | >>> l | 10 | | | MMM, global manipulation. Now if only there was a python function for | global dominance, though perhaps globals().clear() is sufficient. | Mua-hah-hah. | | - Josiah From stevewilliams at wwc.com Fri Jan 9 22:10:12 2004 From: stevewilliams at wwc.com (Steve Williams) Date: Sat, 10 Jan 2004 03:10:12 GMT Subject: Databases: Which one's right for me? In-Reply-To: <4378fa6f.0401091717.1ae63541@posting.google.com> References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: Marc wrote: > Hi all, > [snip] > Basically I need a db that will travel with my executable script and > faithfully store and edit the data needed in that script. People using > this script will need to be stand alone users. Having a client/server > arrangement is not possible over a network. > > Also, installing some type of db engine outside of Python is also not > possible. [snip] > Or, if there exists > another solution other than the two I mentioned, please throw that out > there because it's almost impossible to completely examine every > possibility out there. All suggestions are helpful. > > Thanks ahead of time, > Marc Firebird 1.5 has a nice stand-alone database capability I use for demos. You don't have to install anything on the target machine, but it's not something that can be packed up in a python exe, as far as I know. You have to have the Firebird database, its dll, config file and message file in the same directory as your Python program, but that's all. Firebird, as a database, is worth a look. I'd spend an hour evaluating it before using ACCESS and DAO. You might run into deployment problems with ACCESS 2, 3, 4, 5, 7, 2000/DAO on Windows 95, Windows 98, Windows NT, Windows XP, service packs 1-5, plus corruption/compaction headaches. But that's just my experience. "You have moved the mouse, please insert the ACCESS installation CD...". If you just want some data persistency, use pickle. From grey at despair.dmiyu.org Tue Jan 20 19:38:12 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 21 Jan 2004 00:38:12 -0000 Subject: regular expression question Message-ID: Ok, this just seems convluted. import re line = 'match this' foo = re.search(r'.*(this)', line) foo.groups()[0] To me there seems there should be a way to return a group without having to get the tuple and then slice it out from there. However foo.group(0) will return the entire string (only one argument given) and groups doesn't seem to do anything significant with any entry I give it. Am I missing something obvious or is this the final solution? -- 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 rhughes at fastmail.fm Thu Jan 1 16:12:43 2004 From: rhughes at fastmail.fm (Rob Hughes) Date: 1 Jan 2004 13:12:43 -0800 Subject: Happy New Year in Python and other languages Message-ID: <809f2610.0401011312.190dfb44@posting.google.com> I saw Vadim Antonov's "Happy New Year in 4 languages" program (http://www.gnu.org/fun/jokes/happy-new-year.cfbC.html) and thought I'd write a similar program using Python. Here it is: #include #define fi int main(void){printf("Happy New Year!\n");return(0);} #/* This code has the same effect in Python, C, C++, and bash. # Written by Rob Hughes , December 2003. true=False if true : then echo -e +"\bHappy New Year!" else : print "Happy New Year!"; fi=0 #*/ fi From seanl at chaosring.org Sat Jan 3 04:44:34 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 01:44:34 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: <7xznd58klr.fsf@ruckus.brouhaha.com> References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Well, I have a dumb question. Have you studied the security failures > of rexec/Bastion and convinced yourself that they don't happen to your > new scheme? If you know of a location where the known shortcomings of rexec are documented, please let me know. So far I've only seen a couple examples and a lot of people saying "it's not secure so let's disable it." My current methodology is to be very careful about adding any privileges beyond what RestrictedPython allows. > You might look at the PyPy architecture doc if you haven't yet. > Making a separate object space for restricted objects may fit PyPy's > design quite naturally. I have looked at PyPy. It's very interesting, but RestrictedPython is already written and in use in Zope. I think I've figured out a way to use my name mangling scheme to make attributes only *writable* by code defined on a class from which an object descends: do writes through a name-mangled method, and have RestrictedPython output self._mangled_setattr(attr, val) for each attempted attribute assignment. This will basically make it impossible to have attributes that are writable from other classes, but I think it's probably a prerequisite for capabilities. Most other languages require attributes to be set via methods anyway, right? From usenet_spam at janc.invalid Mon Jan 26 22:10:00 2004 From: usenet_spam at janc.invalid (JanC) Date: Tue, 27 Jan 2004 03:10:00 GMT Subject: "Lecture Preparation" Discussions on Python References: <1010a26.0401212246.3cac7d06@posting.google.com> <38ec68a6.0401261727.1c0f835e@posting.google.com> Message-ID: afriere at yahoo.co.uk (Asun Friere) schreef: >> While I'm generally interested in such discussions, I won't be >> participating because I hate web boards. I vastly prefer netnews, with >> grudging use of e-mail lists. > > Nice for those who can get it. The (educational) institution where I > work have, in their wisdom, decided not to make netnews available, so > I have to access even this newsgroup via a web board (GoogleGroups). You don't *have* to... Register an account at and you have access to a very good news server. It's a free service from a German government-funded research institute. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From deanm at uniplus.hr Wed Jan 28 10:50:02 2004 From: deanm at uniplus.hr (Dean Marodi) Date: Wed, 28 Jan 2004 16:50:02 +0100 Subject: Crystal Reports Viewer in wxPython Message-ID: Hi! I want to use Crystal Reports Viewer with wxPython. Can anyone help (example)? Thanks, Dean From jjl at pobox.com Tue Jan 13 13:19:25 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 18:19:25 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <87u12z90eq.fsf@pobox.com> "David M. Cook" writes: > In article <40029dad$0$28706$a729d347 at news.telepac.pt>, Bicho Verde wrote: [...] > You could casually pick up enough Python to be useful in a week or so of > evenings. > > Perl is not much harder, It *seems* so when you first learn it... > but has a lot of "gotchas". ... and they never end! Ilya Zakharevich (a "Perl God"): http://www.google.com/groups?threadm=8h8scu%245h2%241%40charm.magnus.acs.ohio-state.edu In article <8f498v$751$1 at charm.magnus.acs.ohio-state.edu>, ilya at math.ohio-state.edu (Ilya Zakharevich) wrote: [...] > Let me reiterate my current opinion on the topic: the reason for my > puzzlement (and your trouble) is the difference between Perl as a > scripting language and Perl as a programming language. Perl is > absolutely fine as a scripting language. Perl is pretty unusable as a > programming language. [...] I'm not sure I'd go quite as far as that, but it's not a million miles from the truth. Why saddle yourself with the costs of Perl when Python demonstrates there are no significant associated benefits? (I'm talking about "programming" not "scripting" here, using Ilya's language, though I'd argue Python is just as good for scripting as Perl) John From paul at prescod.net Thu Jan 29 22:22:46 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 29 Jan 2004 19:22:46 -0800 Subject: Python vs. Io In-Reply-To: <711c7390.0401291301.3f95794@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <4019CE06.7000908@prescod.net> Daniel Ehrenberg wrote: > Io (www.iolanguage.com) is a new programming language that's purely > object-oriented (but with prototypes), has a powerful concurrency > mechanism via actors, and uses an extremely flexible syntax because > all code is a modifiable message tree. I long to live in a world where Python is considered a crufty incumbent legacy language that is forced on unwilling programmers by Pointy Haired Bosses. First, it would mean that Python has vanquished languages that programmers like less. Second, it would mean that the up-and-coming languages are so unbelievably cool and elegant that they make Python look like a lumbering dinosaur. Thanks for reminding me that that that day was once unfathomably far in the future and now seems almost around the corner! But when I look closer at IO it seems to me that the day is not as near as I hope. If you wish to hasten I urge you to: * finish the IO tutorial * distribute windows binaries of IO * make IO compilers to C and Java available * make bindings to popular windowing toolkits * make bindings to Java, .NET, COM, SOAP, XML-RPC etc. * use IO in a production context so that the rest of us can have faith in its stability * implement MySQL and Oracle bindings * publish some books on IO * point me to some documentation on how to launch and kill processes in IO If this were all done tomorrow I might be tempted to jump over to IO but I would be amazed if it were all done even two years from now. Also, an observation: IO's syntactic simplicity looks to me to be both a blessing and a curse. Paul Prescod From eric.brunel at N0SP4M.com Fri Jan 16 10:07:38 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Fri, 16 Jan 2004 16:07:38 +0100 Subject: Tkinter: modal ok in windows, but not in Linux References: Message-ID: klappnase wrote: > DoubleM wrote in message news:... > >>Hi, >> >>I'm running Python2.3.3c1 on Mandrake 9.1 >> >>The following code is designed to bring up a window with a button labeled >>"popup". Clicking on the popup buttons triggers a secondary window with a >>button labeled "ok". The second window is supposed to be modal - it should >>not be possible to reset the focus back to the first window or close the >>first window without first closing the second. The program works just fine >>in Windows XP home, but in Linux I can close the first window while the >>second one is still active. >> >>This seems to be a bug, or am I doing something wrong. I searched google >>for Tkinter Linux modal, but found nothing relevant. >> >>Thanks for your help. >> >>Here's the code, copied and pasted from IDLE. >> >>############################# >>from Tkinter import * >> >>makemodal = 1 >> >>def dialog(): >> win = Toplevel() >> Label(win, text = "Secondary").pack() >> Button(win, text = "Ok", command = win.destroy).pack() >> if makemodal: >> win.focus_set() >> win.grab_set() >> win.wait_window() >> print "dialog exit" >> >>root = Tk() >>Button(root, text = 'popup', command = dialog).pack() >>root.mainloop() >>################################# >> >>Mike >>mmoum-xxxspam.woh.rr.com > > > Hi Mike, > > I guess you should use > > root.wait_window(win) > > instead of > > win.wait_window() It is indeed better, and so is doing a: win.transient(root) to avoid being able to put the main window on top of the dialog. This won't however solve the OP's problem, which is that the main window can still be closed when the second window is running. We've had the same problem, and I finally ended up thinking this problem's is not Python's fault, nor Tkinter's one, nor even tk's one: with X11, the controls on the window frame are actually managed not by the client application (from the X11 server point of view), but by the window manager. If the window manager decides to ignore the grab set on one of your windows and to continue to treat events for the other windows, you're stuck. The only thing you can do is treating the window deletion event to explicitely ignore it via a root.protocol('WM_DELETE_WINDOW', ...). There may be a way of doing it automatically at tk's level, but it would certainly be a big work, not to mention that there may be some window managers that *do* take the grab_set into account, and so where this work would be unnecessary. There are other issues due to the window manager on various platforms; for example, the CDE window manager dtwm used on Sun's apparently can't make a window always stay on top of another. So dialogs on Sun's can always be put behind by clicking on another window of your application, which is really annoying. All of the above is only my analysis of the problem; if anybody can confirm or prove me wrong, I'll be happy to learn something :-). But since tk is just a layer on "native" widgets for all platforms, you may always get behaviour differences across platforms for such things. I suppose other toolkits using the same principles (e.g. wxWindows) may have the same problems. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From dsarrazinNOSPAMPLEASE at cyberus.ca Sun Jan 11 20:18:57 2004 From: dsarrazinNOSPAMPLEASE at cyberus.ca (Denis Sarrazin) Date: Sun, 11 Jan 2004 20:18:57 -0500 Subject: Division oddity References: Message-ID: <7at3005sjtd6clgfm6e7v1gq83ohlrc2td@4ax.com> Try 1.0/2 instead of 1/2. Note that when I do eval("1/2") I get 0 not 0.5 -Denis Le Sun, 11 Jan 2004 23:45:48 +0000, Tim Rowe a ?crit : >If I do from __future__ import division then eval(1/2) gives me 0.5 as >expected. But if I do print input("enter a sum: ") and enter 1/2 as >the sum I get 0 as if I hadn't done the import. I thought input was >supposed to give the same behaviour as an eval on raw input -- why the >difference here? From pinard at iro.umontreal.ca Thu Jan 22 12:03:58 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 22 Jan 2004 12:03:58 -0500 Subject: What is object() In-Reply-To: <20040122154420.6597.qmail@web61110.mail.yahoo.com> References: <20040122154420.6597.qmail@web61110.mail.yahoo.com> Message-ID: <20040122170358.GA19330@alcyon.progiciels-bpi.ca> [Hameed Khan] > and what are new style classes?. http://www.python.org/2.2.3/descrintro.html is a good read on this subject. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From usenet_spam at janc.invalid Sun Jan 25 02:26:47 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 25 Jan 2004 07:26:47 GMT Subject: pyMagick vs PIL References: <8d3e714e.0401242204.38c9c0e@posting.google.com> Message-ID: cappy2112 at yahoo.com (Tony C) schreef: > I've used Image Magick before, and I'm happy with it. > When I searched for Python extensions for Image Magick, I found an > unsupported (an old) version of pyMagick. There's also the PythonMagick bindings for GraphicsMagick: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From cbh at newenglandhomes.net Fri Jan 23 11:27:38 2004 From: cbh at newenglandhomes.net (CB Hamlyn) Date: Fri, 23 Jan 2004 11:27:38 -0500 Subject: File Install Program Using Python? Message-ID: <1012ij4idech2d6@corp.supernews.com> Hello, I'm currently working on a Modification for the PC game Battlefield 1942. I'm a pretty good VBA Programmer with some Foxpro under belt as well. After reading a ton of stuff on-line I'm simply floored by everything Python has to offer. Anyway, I want to create an installation program that takes a folder and all it's sub-folders and copies them from a compressed form into the proper directory. Basically a simplified version InstallSheild or whatever. I assume Python is capable of such a feat and I'm wondering if anyone can spin me around, point me in the right direction and shove me toward my goal. Any help would be appreciated. Thanks CB Hamlyn From crescent_au at yahoo.com Tue Jan 27 21:18:39 2004 From: crescent_au at yahoo.com (Ben) Date: 27 Jan 2004 18:18:39 -0800 Subject: python in dreamweaver Message-ID: Hi all, Is it possible to design my web site in Dreamweaver and add python codes in it later?? Thanx Ben From jcarlson at uci.edu Wed Jan 21 16:17:00 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Jan 2004 13:17:00 -0800 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <40083eac$0$321$e4fe514c@news.xs4all.nl> <40086C6E.8536542C@hotmail.com> <40098f12$0$320$e4fe514c@news.xs4all.nl> <400AB936.BA1D9D73@hotmail.com> <7934d084.0401181805.71029c2f@posting.google.com> <400EE6B5.27C6B694@hotmail.com> Message-ID: <20040121131300.D8E9.JCARLSON@uci.edu> Even easier: Q = Queue.Queue() Q.put(gen) def thread(): a = Q.get() use = a.next() Q.put(a) #do whatever you need Of course you could just as easily use a single lock and a class: class lockedgen: def __init__(self, gen): self.g = gen self.l = threading.Lock() def get(self): self.l.acquire() a = self.g.next() self.l.release() return a generator = lockedgen(gen) def thread(): use = generator.get() #do what you need - Josiah From viruswall at hypovereinsbank.de Thu Jan 29 09:56:04 2004 From: viruswall at hypovereinsbank.de (viruswall at hypovereinsbank.de) Date: Thu, 29 Jan 2004 14:56:04 -0000 Subject: Virus Alert Message-ID: <20040129145604.4A13F56389@mucmvw2.hypovereinsbank.de> The mail message (file: feyz.zip) you sent to oliver.imbusch.extern at hvbsystems.com contained a virus. From linda at gwmail.dtcc.cc.nc.us Thu Jan 29 17:10:53 2004 From: linda at gwmail.dtcc.cc.nc.us (linda at gwmail.dtcc.cc.nc.us) Date: Thu, 29 Jan 2004 17:10:53 -0500 Subject: hello Message-ID: <200401292210.i0TMAqHM079091@mxzilla7.xs4all.nl> The message contains Unicode characters and has been sent as a binary attachment. -------------- next part -------------- A non-text attachment was scrubbed... Name: message.zip Type: application/octet-stream Size: 0 bytes Desc: not available URL: From fahad_faridi at yahoo.com Fri Jan 9 15:41:56 2004 From: fahad_faridi at yahoo.com (fahad) Date: Fri, 09 Jan 2004 20:41:56 -0000 Subject: pycap installation problem Message-ID: Hi, I'm trying to install pycap-0.1.6 using following commnad: python setup.py build --compiler=mingw32 but it throws a lot of errors about missing files some of them is: running build running build_py running build_ext building 'pycap.protocol' extension D:\cygwin\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\Python23 \include -Ic:\Pyth on23\PC -c src/protocol\ip.c -o build\temp.win32-2.3 \Release\src\protocol\ip.o In file included from src/protocol/protocolmodule.h:7, from src/protocol/ip.c:4: src/protocol/arp.h:6:20: libnet.h: No such file or directory In file included from src/protocol/protocolmodule.h:8, from src/protocol/ip.c:4: src/protocol/ethernet.h:5:20: libnet.h: No such file or directory src/protocol/ethernet.h:6:24: sys/socket.h: No such file or directory src/protocol/ethernet.h:7:24: netinet/in.h: No such file or directory src/protocol/ethernet.h:8:23: arpa/inet.h: No such file or directory src/protocol/ethernet.h:30:7: warning: no newline at end of file Any idea? Thanks. From jjl at pobox.com Wed Jan 14 21:37:32 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 02:37:32 +0000 Subject: I come not to bury C++, but to praise it... References: Message-ID: <87wu7uq6mr.fsf@pobox.com> "Andrew Koenig" writes: > "John Benson" wrote in message > news:mailman.337.1074032524.12720.python-list at python.org... > > > I got into Python because I took one look at C++ and saw all the > > handwaving in the introductory O'Reilly book to the effect that > > "everything looks sweet now, but wait until these snazzy little > > features interact..." and then started casting around for another > > road to OOP. > > Perhaps you should cast around for a different C++ book while you're > at it, too -- maybe the one you found isn't well suited to your > particular learning style. Andrew's own "Accelerated C++" is good (written with Barbara Moo). :-) John From usenet at -OBFUSCATION-joefrancia.com Wed Jan 28 16:21:42 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Wed, 28 Jan 2004 21:21:42 GMT Subject: executing an external app In-Reply-To: References: Message-ID: Joseph Krauze wrote: > Hi all, > > I have a simple question which I cannot solve (relatively new to Python). > I want to write a script that executes an application on the go. I looked > into the exec*e() calls but the problem there is that they do not return. > I also looked into execfile() but here the PATH is not taken into account > and I couldn't figure out to pass the file that's executed arguments. > > So, is there a simple way to execute an external app? > i.e. execvpe('cat', 'myFile') - this will not return > > Thanks, > Joseph Look at os.spawn* or os.popen* -- Soraia: http://www.soraia.com From mhammond at skippinet.com.au Mon Jan 26 17:54:57 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 27 Jan 2004 09:54:57 +1100 Subject: -- Pythonic control of Windows GUI application: tabs and listviews In-Reply-To: <4b3b1124.0401251706.6cf67f27@posting.google.com> References: <4b3b1124.0401251706.6cf67f27@posting.google.com> Message-ID: zapazap wrote: > For the "List-View" and "Tab" controls then, I expected to find the > constants > > win32con.LVM_GETCHECK > win32con.TCM_GETITEMCOUNT FYI, A good source of sample code for working with tree-view controls can be found in the SpamBayes project, specifically: http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/Outlook2000/dialogs/FolderSelector.py?view=markup Working with these win32gui structures is a complete PITA (as it needs to be done via the 'struct' module) - I'd like to integrate support for ctypes structures to make this more readable. In fact, I'd love to see ctypes structure support as a standard library module, but that is for another thread in a another forum Mark From none at none.com Wed Jan 14 14:34:48 2004 From: none at none.com (Derek) Date: Wed, 14 Jan 2004 14:34:48 -0500 Subject: Printing to console (No Scroll) References: Message-ID: "Diez B. Roggisch" wrote > > Any alternatives to ncurses? It seems like a overkill for this... > > Maybe you can use sys.stdout.write in conjunction with control- > codes for moving back the cursor to column one. But you'll have > to lookup these for yourself :) I think \r is the control code (at least if you want to go back to the start of the line): import time, sys for second in range(10): time.sleep(1) sys.stdout.write(`10-second` + " seconds \r") sys.stdout.flush() From rmkrauter at yahoo.com Sat Jan 24 23:18:21 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat, 24 Jan 2004 23:18:21 -0500 Subject: Newbie Nested Function Problem In-Reply-To: <9%GQb.77000$Su5.22817@twister.nyroc.rr.com> References: <52d610h685a613ua1tk5k8f11cv1d61q0b@4ax.com> <9%GQb.77000$Su5.22817@twister.nyroc.rr.com> Message-ID: <1075004300.4567.36.camel@vaio> I should have suggested a 'fix' before: change all the "leave"s which are referring to, or defining the function "leave" to "leaver" or something like that. Keep all program's references to the variable "leave" unchanged. Then your program should work. To clarify my previous reply, your problem is this: leave = 'xqz' leave() The leave() call is actually trying to call a string object, which is not callable. So I wasn't quite right in what I told you in the previous post - the leave() call is not trying to call the function xqz(), its trying to call the string xqz. Rich On Sat, 2004-01-24 at 22:47, Brian Samek wrote: > > Okay, ask_number doesn't do what you're saying. It's asking for a number, > > placed into variable number, and if it gets something out of range, prints > > an error message. > > > > And then ends. It doesn't either a) repeat until it gets a valid number > > or b) do anything with the number it gets, like pass it back to the caller > > in a return statement, i.e.: > > > > It does repeat if it doesn't get a valid number. The function calls itself > after printing an error mesage. For some reason the original message > formatted itself differently when I pasted it into my mail program. The > line just before the first else statement should be indented to the same > level as the line before it so it reads: > > def ask_number(): > number = input("Please enter a number.\n") > if number > 500 or number - int(number) != 0 or number < 1: > print "Input positive integers less then 501 only, please." > ask_number() > else: > > > > > return number > > > > > ask_number() > > > > Okay, you invoked ask_number, but didn't even try to get anything from it. > > Normally, this would read something like: > > > > number_in = asknumber() > > > > What do you mean by I "didn't even try to get anything from it." I get a > variable called "number" from it from which the countdown(number) function > counts down. > > > > else: > > > > Um.. it looks like you're inadvertably making this a deeply recursive > > call, probably something you want to stay away from until you have regular > > stuff down pat. > > I don't understand what you're saying. I designed the program as three > functions nested within each other. Are you saying I should be designing it > differently? I made it a series of nested functions because, for example, I > needed to use the "number" variable from ask_number before it was destroyed. > When a function ends, any variables it has created are destroyed. > > Thanks, > > Brian > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tassilo.parseval at rwth-aachen.de Tue Jan 27 02:23:38 2004 From: tassilo.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: 27 Jan 2004 07:23:38 GMT Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> <40136b6d@news.victoria.tc.ca> <7fe97cc4.0401260943.2442ba4e@posting.google.com> <7fe97cc4.0401261904.4880149a@posting.google.com> Message-ID: [ F'up set ] Also sprach Xah Lee: > a correction to my previous post. > > In my previous post i said one of the stupidity of Perl's > File::Basename module is that it requires user to tell it OS type. > This is incorrect. You also said that the suffix list would be required. This is also incorrect. Tassilo -- $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({ pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#; $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval From ANTIGEN_EMAILWA1 at click2learn.com Tue Jan 27 20:32:48 2004 From: ANTIGEN_EMAILWA1 at click2learn.com (ANTIGEN_EMAILWA1) Date: Tue, 27 Jan 2004 17:32:48 -0800 Subject: Antigen found VIRUS= W32/MyDoom-A (Sophos,CA(InoculateIT)) worm Message-ID: <9AD24984FA80A847936D467D79B771190178BC86@emailwa1.corp.click2learn.com> Antigen for Exchange found document.zip->document.txt .pif infected with VIRUS= W32/MyDoom-A (Sophos,CA(InoculateIT)) worm. The message is currently Purged. The message, "test", was sent from python-list at python.org and was discovered in IMC Queues\Inbound located at asymetrix/Bellevue/EMAILWA1. From newsreply at transfertech.de Wed Jan 14 11:14:50 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Wed, 14 Jan 2004 17:14:50 +0100 Subject: PyQT: qt.qApp Message-ID: Hello, in my application I want to subclass qt.QApplication and use this subclass instead of QApplication for my gui. Some of my modules are automatically generated by pyuic and I am not allowed to change their source code. The problem is these modules do "from qt import *" and use an object called 'qApp' which seems to be an instance of qt.QApplication and I want them to use my subclass (exactly its instance) instead of 'qApp'. How can I solve this? Can someone tell me what qt.qApp is and what it is used for? (I'm using PyQT 3.6.) TIA, Axel From deets_noospaam at web.de Wed Jan 14 13:26:13 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 14 Jan 2004 19:26:13 +0100 Subject: Printing to console (No Scroll) References: Message-ID: > How can I print to the console without having it scrolling to a new line > for each print statement? > I want to print a count down in the console, but for each count it scrolls > the screen (of course). Use ncurses. Diez From theller at python.net Fri Jan 16 15:50:53 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 21:50:53 +0100 Subject: Retrive unicode keys from the registry References: Message-ID: <1xpzaa8i.fsf@python.net> "Neil Hodgson" writes: > Thomas Heller: > >> def RegQueryValue(root, subkey): >> if isinstance(subkey, unicode): >> return _winreg.QueryValue(root, subkey.encode("mbcs")) >> return _winreg.QueryValue(root, subkey) >> >> Does this look ok? > > It will fail for keys that can not be encoded in your current code page. > That will not often be a problem but if you want to be safe then access to > the wide version is needed. In the actual use case I have, I'm quite sure that the subkeys are coded in latin-1: # -*- coding: latin-1 -*- LOG_KEYS = [u"DSC-S Cs Gun Emitter [Ah]", u"Ga Gun Beam Defining Aperture [?Ah]"] and in my tests it worked. Even if I wrote this: # -*- coding: latin-1 -*- LOG_KEYS = ["DSC-S Cs Gun Emitter [Ah]", "Ga Gun Beam Defining Aperture [?Ah]"] But, assume that I wanted to provide a patch to Python (or implement in ctypes) so that QueryValue accepts unicode subkey names (I was astonished to find out that it does not). How could this be done, hopefully portable between NT/2000/XP and 98, and assuming unicows.dll is not installed - so the wide version is not available on 98? My understanding is that it's possible to convert any (for a certain definition of 'any) unicode string in a byte string (because the encoding for the byte string can be specified), but that it's impossible to convert a byte string into unicode unless the byte string's encoding is known. Maybe this only shows my un-understanding of unicode... Thanks, Thomas From kylotan at hotmail.com Sat Jan 31 19:50:27 2004 From: kylotan at hotmail.com (Kylotan) Date: 31 Jan 2004 16:50:27 -0800 Subject: pythonwin woes References: Message-ID: <153fa67.0401311650.13fb9088@posting.google.com> Mark Hammond wrote in message news:... > IDLE runs all programs in a new, external Python process, so never sees > this issue. In lots of ways, I like the way Pythonwin does it - keeping > that state around can be very useful - eg, after the program has > terminated, you can still see the objects etc. IDLE keeps the state around after program termination too, so that you can query it from the command line. It just gets rid of it when you execute the next program (or re-execute the current one). -- Ben Sizer From not at all.com Wed Jan 14 05:42:01 2004 From: not at all.com (G.I.L) Date: Wed, 14 Jan 2004 12:42:01 +0200 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> Message-ID: <40051cb3$1@news.012.net.il> Brandon J. Van Every wrote: > "G.I.L" wrote in message > news:40047290$1 at news.012.net.il... >> >> Brandon, why the fuck on Earth couldn't you spend that exact amount >> of time doing what you did BEFORE posting and arguing with the >> entire newsgroup? > > Hey GIL, you're here wasting time of your own free will. Don't look > to me to be the purveyor of your quality discourse. To me this is > just hours between implementing stuff. Partially implementing stuff. > Although actually, there's another agenda. I know *someone* out > there is going through the same shit I have / I am. The posts are > for their benefit, to give them warnings / inklings. Are you applying to be a martyr, St. Brandon? >> It >> was an unbelievable waste of time, since you've managed to convice >> (maybe still wrongfully) all the people that you are completely >> clueless. > > Why, because I turned around a project in 3 weeks while having the > flu half the time? No, because you dumped the project because it was boring. This may kill any credit you may have had with people. > You try to do something big, you put your money on the line to do it, > you fail or don't entirely succeed, you give postmortem, you lay all > your cards out for others to examine... *then* I will worry about > your opinion. You state that you will follow only those who fail after putting their own money on projects? BTW, there seems to be a hint of contradiction, since you normally don't look at success the way other people do ($$$), but whenever you say "failure", it's exactly what other people mean. >> I see your point in many of the issues you raised. But the only >> reason I don't compare myself to you, is that I have a shitload of >> games to prove my point. I've never had a major failure, so I never >> needed to use one to leverage my projects. All the things I learned >> from, were simply bad habits, mostly coding habits. I constantly >> evolve, in small steps, from one success to another. That's how it >> should be. You do the math. > > Those who never taste failure are haughty. ..or just plain cautious. g From peter at engcorp.com Thu Jan 8 10:20:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Jan 2004 10:20:51 -0500 Subject: unicode keys in dicts References: <20040108150835.7242ef01.jiba@tuxfamily.org> Message-ID: <3FFD7553.4EFA8C59@engcorp.com> Jiba wrote: > > is the following behaviour normal : > > >>> d = {"?" : 1} > >>> d["?"] > 1 > >>> d[u"?"] > Traceback (most recent call last): > File "", line 1, in ? > KeyError: u'\xe9' > > it seems that "?" and u"?" are not considered as the same key (in Python > 2.3.3). Though they have the same hash code (returned by hash()). > > And "e" and u"e" (non accentuated characters) are considered as the same > ! Well, "e" and u"e" _are_ the same character, while the unicode that comes from decoding the "?" representation is entirely dependent on which codec you use for the decoding. It is only the same as u"?" when decoded using certain codecs, most likely. ASCII is 7-bit only, so the "?" value is not legal in ASCII, which is likely your default encoding. For example, try "?".decode('iso-8859-1') and you will probably get the unicode value you were expecting. I'm not the best to answer this, but I would at least say that the above behaviour is considered "normal", though it can be surprising to those of us not expert in Unicode issues... -Peter From jane.doe at acme.com Fri Jan 9 18:09:04 2004 From: jane.doe at acme.com (Jane Doe) Date: Sat, 10 Jan 2004 00:09:04 +0100 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> <6AlLb.134$hd.7718@news2.e.nsc.no> <3FFEB6D6.BF92551E@engcorp.com> <+vXesJAXsr$$EwJL@jessikat.fsnet.co.uk> <3FFEBE42.80962511@engcorp.com> Message-ID: On Fri, 09 Jan 2004 09:44:18 -0500, Peter Hansen wrote: >I get at least a temporary "server not found" error when I try that name. http://snakelets.sourceforge.org/ ("We're Sorry. The SourceForge.net Website is currently down for maintenance. We will be back shortly) :-) JD. From noah at noah.org Tue Jan 27 13:50:53 2004 From: noah at noah.org (Noah) Date: 27 Jan 2004 10:50:53 -0800 Subject: raw audio input on Windows Message-ID: I need to record raw 8-bit mono audio from a generic sound card on MS-Windows. I need to do something like this: sound_device = open audio device buffer = sound_device.read ('1 second, 8 bit, mono, 8 KHz') process buffer If possible I would also like to experiment with sampling the raw audio in my own loop. For example, something like this: open audio device while 1: read byte from audio device process byte (I realize that Python is probably not ideal for this sort of DSP, but I figure that it should handle 8KHz mono with no problem). Does anyone have any experience with recording sound using the WIN32 API? Can you point me in the right direction? The OSS stuff in Python looks ideal, but unfortunately that's a UNIX only thing :-( http://www.python.org/doc/current/lib/module-ossaudiodev.html Any hints are appreciated. Yours, Noah From whisper at oz.net Fri Jan 2 00:32:07 2004 From: whisper at oz.net (David LeBlanc) Date: Thu, 1 Jan 2004 21:32:07 -0800 Subject: question: Python or Lua for rejuvenation of old PCs? In-Reply-To: <8oKdneXkV7RcYGmiRVn-hQ@comcast.com> Message-ID: > "John Benson" wrote in message > news:mailman.16.1072987285.12720.python-list at python.org... > > I suppose that my question is best phrased as this: What is a > comfortable > > minimum RAM size that a PC needs to have to comfortably run > modern Python > > for non-memory-intensive applications (i.e. no big database crunching or > > other thrashy stuff). I'm thinking about just polling sensors and > actuating > > control devices over RS-232/RS-485/LAN and doing some chitchat between > the > > nodes over the LAN. Based on the response, I'll draw the line between my > Lua > > machines and my Python machines. > > I did my first useful Python work with old DOS version on a 4 MB machine. > Disk memory size and running RAM memory size are different issues. I have > read that Lua beats Python on minimal disk footprint but have no idea of > running size. On Windows, Python.exe is very small but does > import several > modules, though I believe it could be built to require less. > > Terry J. Reedy python.exe is small - for 2.3.2 it's 21kb, but it immediately pulls in a 953kb python23.dll (which is cleverly "hidden" in c:\winnt\system32) and also draws on a 3.6mb set of dlls in python/32/dll. Lua is 140kb. I have seen discussion of Python being run on small x86 systems with 64mb of ram and a 64mb CF card "disk". I think several of the Linux and BSD distros for the Soekris router widgets will run Python, not to mention another language that starts with "P" ;) Dave LeBlanc Seattle, WA USA From raims at dot.com Wed Jan 7 08:43:21 2004 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 07 Jan 2004 14:43:21 +0100 Subject: Why ' '.some_string is often used ? References: Message-ID: <87u137an7q.fsf@mobile.foo> "St?phane Ninin" writes: > def normalize_whitespace(text): > "Remove redundant whitespace from a string" > return ' '.join(text.split()) > > Is there a reason to do instead of just returning join(text.split()) ? join is a function of string module and it belongs also to string object. So you can't do join() but you have to do str = " " str.join(text.split()) or import string string.join(text.split(), " ") Take a look: http://python.org/doc/current/lib/module-string.html -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From reply.in.the.newsgroup at my.address.is.invalid Sun Jan 18 09:34:30 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 18 Jan 2004 15:34:30 +0100 Subject: Using python for _large_ projects like IDE References: <930ba99a.0401180625.5863acd4@posting.google.com> Message-ID: <916l00d71koc9mkag3s0r7s2n06jair55c@4ax.com> Sridhar R: >I am a little experienced python programmer (2 months). [...] >I am planning (now in design stage) to write an IDE I've never developed an IDE, but it wouldn't be my first attempt to write an app. It's huge and complex. I started with prime numbers, tic-tac-toe, towers of hanoi, traveling sales man, merge sort, and little things like that :-) >Are there any ways to forsee the performance critical parts? Sure, no problem. Post the design please. >Also, any suggestions on reducing memory usage of big applications >written in python? Only the obvious: don't keep more data alive than strictly necessary. -- Ren? Pijlman From amuys at shortech.com.au Sun Jan 18 21:05:29 2004 From: amuys at shortech.com.au (Andrae Muys) Date: 18 Jan 2004 18:05:29 -0800 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <40083eac$0$321$e4fe514c@news.xs4all.nl> <40086C6E.8536542C@hotmail.com> <40098f12$0$320$e4fe514c@news.xs4all.nl> <400AB936.BA1D9D73@hotmail.com> Message-ID: <7934d084.0401181805.71029c2f@posting.google.com> [Subject line changed to allow thread to be found more easily in google-groups] Alan Kennedy wrote in message news:<400AB936.BA1D9D73 at hotmail.com>... > [Alan Kennedy] > >> I believe that the following definition of serialise will correct the > >> problem (IFF I've understood the problem correctly :-) > >> It does look like the following version will work, I was too focused on synchronising the underlying generator, and forgot that my code also needed to be re-entrant. Thanks for catching my mistake. > >> #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > >> import time > >> import thread > >> import threading > >> > >> class serialise: > >> "Wrap a generator in an iterator for thread-safe access" > >> > >> def __init__(self, gen): > >> self.lock = threading.Lock() > >> self.gen = gen > >> > >> def __iter__(self): > >> return self > >> > >> def next(self): > >> self.lock.acquire() > >> try: > >> return self.gen.next() > >> finally: > >> self.lock.release() > > [Ype Kingma] > > Looks like a candidate for inclusion in a standard library to me. > > Well, maybe :-) > > To be honest, I don't have the time to write test cases, docs and > patches. So I think I'll just leave it for people to find in the > Google Groups archives ... > Andrae Muys From jjl at pobox.com Fri Jan 23 11:20:37 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 16:20:37 +0000 Subject: Help and optimization hints, anyone? References: <87d69a6e2j.fsf@pobox.com> Message-ID: <87vfn2bpre.fsf@pobox.com> Kim Petersen writes: > Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee: [...] > > dict is also a bad name -- this is the name of the builtin dictionary > > type, which you've just clobbered (in the local scope). > > Hmmm - isn't it called __dict__ ? No, __dict__ is an attribute of Python objects. It's the dictionary in which most Python objects keep their data: >>> class foo: ... def __init__(self): ... self.blah = "stuff" ... >>> f = foo() >>> f.__dict__ {'blah': 'stuff'} dict is the builtin name for the dictionary type: >>> dict >>> dict({"foo": "bar", "spam": "eggs"}) {'foo': 'bar', 'spam': 'eggs'} >>> dict([("foo", "bar"), ("spam", "eggs")]) {'foo': 'bar', 'spam': 'eggs'} [...] > > Haven't read much further, but it looks like you might be better off > > using attribute access rather than indexing. In 2.2, use properties. > > Earlier, use __setattr__ / __getattr__ (make sure you read the docs). > > this migrated from a regular dict which i had to drop because its > not hashable as mentioned earlier - next step __(get|set)attr__. dicts are deliberately not hashable, because they're mutable. Are you sure you want a dict as a dictionary key (assuming that's what you're doing)? John From amy-g-art at cox.net Fri Jan 23 18:04:06 2004 From: amy-g-art at cox.net (Amy G) Date: Fri, 23 Jan 2004 15:04:06 -0800 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: When I tried to do the make install I get the following error message: warning: install: modules installed to '/usr/lib/python2.2/site-packages/', which is not in Python's module search path (sys.path) -- you'll have to change the search path yourself How do I correct this. Sorry for the newb question. "Michael Spencer" wrote in message news:K4ydna_ey7rvOIzdRVn-jw at comcast.com... > "Amy G" wrote in message > news:PRgQb.16209$AA6.9881 at fed1read03... > > No it won't. Unfortunatly I don't necessarily have a comma delimited date > > string. Thanks for the input though. > > > > The following three date strings is another example of the various date > > formats I will encounter here. > > > > Thursday, 22 January 2004 03:15:06 > > Thursday, January 22, 2004, 03:15:06 > > 2004, Thursday, 22 January 03:15:06 > > > > All of these are essentially the same date... just in various formats. I > > would like to parse through them and get a comparable format so that I can > > display them in chronological order. > > > > > > "wes weston" wrote in message > > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net... > > > Amy, > > > I hope there is a better way but, if you go here: > > > > > > http://www.python.org/doc/current/lib/datetime-date.html > > > > > > The new datetime module may help. This and the time mod > > > should get you where you want to go. > > > > > > list = strdate.split(", ") > > > daystr = list[0] > > > daynum = int(list[1]) > > > monthstr = list[2] > > > year = int(list[3]) > > > #funct to get a month int is needed > > > > > > d = datetime.Date(y,m,d) > > > > > > wes > > > > > > --------------------------------------- > > > > > > Amy G wrote: > > > > I have seen something about this beofore on this forum, but my google > > search > > > > didn't come up with the answer I am looking for. > > > > > > > > I have a list of tuples. Each tuple is in the following format: > > > > > > > > ("data", "moredata", "evenmoredata", "date string") > > > > > > > > The date string is my concern. This is the date stamp from an email. > > > > The problem is that I have a whole bunch of variations when it comes > to > > the > > > > format that the date string is in. For example I could have the > > following > > > > two tuples: > > > > > > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 > > 03:15:06") > > > > > > > > I know there is some way to use the date string from each of these to > > get a > > > > date usable by python, but I cannot figure it out. > > > > I was trying to use time.strptime but have been unsuccesful thus far. > > > > > > > > Any help is appreciated. > > > > > > > > > > > > > > > > > This was asked and answered earlier today > > See: https://moin.conectiva.com.br/DateUtil > > >>> from dateutil.parser import parse > >>> parse("Thursday, 22 January 2004 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> parse("Thursday, January 22, 2004, 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> parse("2004, Thursday, 22 January 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> > > > From mike at odyne.com Sun Jan 18 19:28:18 2004 From: mike at odyne.com (Mike) Date: 18 Jan 2004 16:28:18 -0800 Subject: Printing variable names References: Message-ID: Thanks for the info. That does clear up a few things for me. This is what I'm trying to accomplish: Basically I have a list of pointers to functions (or whaterver it's called in Python). Something like this: commands = [func1, func2, ...funcN] This is in a script that I use to test an embedded system through the comport. I call the script with the command number (func1 etc...), which calls the corresponding function, which sends a command to the embedded system. I'd like to be able to call the script with --help and have it spit out the list of commands (the names func1, func2 etc...). Mike Mark McEahern wrote in message news:... > Mike wrote: > > >mylist = [a, b, c] > > > >I want to print out the names of the variables in mylist (not the > >values of a, b, and c). How do I go about doing this. Thanks. > > > >Mike > > > > > There's no simple answer to this. Consider the fact that you can have > more than one name bound to any given mutable instance. What if: > > a = range(10) > b = a > > mylist = [a] > > what name do you want printed for the first item in mylist--'a' or 'b'? > > One idea is to use a dictionary instead. Then: > > for key, value in mydict.iteritems(): > print '%(key)s = %(value)s' % locals() > > I'm curious what problem you're trying to solve. > > Cheers, > > // m From skip at pobox.com Mon Jan 26 09:37:02 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 26 Jan 2004 08:37:02 -0600 Subject: unittest In-Reply-To: References: Message-ID: <16405.9742.364184.703362@montanaro.dyndns.org> Zunbeltz> class KnowValues(unittest.TestCase): Zunbeltz> KnownRotationMatrices = [ Zunbeltz> ((Rotational3Part([[-1,0,0],[0,1,0],[0,0,-1]])), Zunbeltz> (1, -1, 2, matrix.vector([0,1,0]))) Zunbeltz> ] Zunbeltz> def TestRotationalPartdeterminant(self): Zunbeltz> """ RotationalPart. determinant with known values.""" Zunbeltz> for i in self.KnownRotationMatrices: Zunbeltz> det = i[0].determinant() Zunbeltz> self.assertEqual(det,i[1][0]) Zunbeltz> if __name__ == "__main__": Zunbeltz> unittest.main() Zunbeltz> but when i run this scrip i get the following output ... Try renaming your test case method "test_rotational_partdeterminant". Skip From randall at tnr.cc Fri Jan 2 15:56:43 2004 From: randall at tnr.cc (Randall Smith) Date: Fri, 02 Jan 2004 20:56:43 GMT Subject: how to import a module dynamically Message-ID: How do I import a module when given the module name as input? Between __import__, imp, and rexec, I'm very lost. What I want to do seems so simple, but I don't know the best way to do it. How would I import a module into the current namespace using the equivalent of these 2 methods: import modname and from modname import * where modname is validated input Randall From usenet at -OBFUSCATED-joefrancia.com Thu Jan 8 16:41:31 2004 From: usenet at -OBFUSCATED-joefrancia.com (Joe Francia) Date: Thu, 08 Jan 2004 21:41:31 GMT Subject: Cheetah - Test suite failures In-Reply-To: References: Message-ID: Timo Virkkala wrote: > I tried to install Cheetah (0.9.15) and ran into trouble. When running > the test suite, I get 61 failures and 57 errors. Most of the errors are > "ImportError: No module named temp", with some "TypeError: update() > takes exactly one argument (0 given)". > > The full output of the test suite is at > (URL: http://www.cs.helsinki.fi/u/tjvirkka/out.txt ) > > I'd hate to spend hours debugging this thing, so I thought to ask here > if someone has any ideas what's causing this.. > > -- > Timo Virkkala You also may want to post this question to the Cheetah list: http://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss If you don't want to join yet another mailing lists, you can access the Cheetah list in your newsreader by pointing it to news.gmane.org and subscribing to gmane.comp.python.cheetah. From bwglitch at hotpop.com Wed Jan 14 14:04:26 2004 From: bwglitch at hotpop.com (BW Glitch) Date: Wed, 14 Jan 2004 14:04:26 -0500 Subject: Python used in Freedom Force In-Reply-To: References: Message-ID: Wayne Folta wrote: > I don't know if it's been discussed since the game came out a while ago, > but I was looking through some temp files that were installed with the > game Freedom Force (a very fun game) and the scenarios are programmed in > Python! (This is on the Mac, but I assume it also used Python on the PC.) Yes, it does. > An example of the code is: [snip] Careful with that... I was also surprised. The mods written for FF are also in Python. It feels great that the game I like most uses Python. :D -- Glitch http://andres980.tripod.com/ Sow the seeds of fear and victory is yours. -- Iguanus (G1) From dj00302003 at yahoo.com Thu Jan 22 21:18:51 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 22 Jan 2004 18:18:51 -0800 Subject: Urllib2 upgrade is breaking urlopen() Message-ID: <1d17eeb7.0401221818.7d98672@posting.google.com> We have a lot of simple code using 'urllib', that basically just goes out and opens and read()'s some http url. Very basic, ten line scripts, and they work fine with urllib. We want to use urllib2 for everything, though, but when we do we get: page=urllib2.urlopen("http://www.something.com/whatever.php") ... File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 463, in http_error_302 self.inf_msg + msg, headers, fp) urllib2.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Found These redirect errors just don't happen with urrlib.urlopen(), and I can only find a few posts on deja that even mention this problem. Is there a known workaround? Thanks, J.D. From gsmith at oxfam.org.uk Wed Jan 28 07:29:54 2004 From: gsmith at oxfam.org.uk (NEWS) Date: Wed, 28 Jan 2004 12:29:54 -0000 Subject: Distributing Python programs Message-ID: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net> Can I install Python on a networked server and have any user run Python programs without having to go through the 9Mb client install? What are my options for distributing Python programs to my users? Thankyou to anyone who can help. Graham From tim.golden at iname.com Wed Jan 21 15:20:44 2004 From: tim.golden at iname.com (Tim Golden) Date: Wed, 21 Jan 2004 20:20:44 +0000 (UTC) Subject: CD Insert Notification in WinXP References: Message-ID: "Tim Golden" wrote in message news:mailman.575.1074679049.12720.python-list at python.org... > >Hi, > > > >I'm using Python 2.3 on a Win XP box, and I'm trying to find > >if there's > >a library of some sort that will give you a callback (or something > >comparable) when a new disc is inserted into a CD Rom drive. > >I've done a > >little googling and nothing's come up, so I'm not holding my breath. :) > > > > Initial response, prior to further investigation: > [... snip PyGame suggestion ...] OK. After further investigation, what you want to do is trap the WM_DEVICECHANGED message. From a combination of Googling, the following article: http://www.undu.com/Articles/980221b.htm and MSDN KB Q163503 (HOWTO: Getting Notification of CD-ROM Insertion or Removal) and the oh-so-useful ctypes: http://starship.python.net/crew/theller/ctypes/ and some example by Itamar Shtull-Trauring of using the win32gui I've managed to cobble together the following working example. I'm quite sure it could be improved by someone who knew what he was talking about, but it does work. (At least on my laptop). import win32api, win32con, win32gui from ctypes import * # # Device change events (WM_DEVICECHANGE wParam) # DBT_DEVICEARRIVAL = 0x8000 DBT_DEVICEQUERYREMOVE = 0x8001 DBT_DEVICEQUERYREMOVEFAILED = 0x8002 DBT_DEVICEMOVEPENDING = 0x8003 DBT_DEVICEREMOVECOMPLETE = 0x8004 DBT_DEVICETYPESSPECIFIC = 0x8005 DBT_CONFIGCHANGED = 0x0018 # # type of device in DEV_BROADCAST_HDR # DBT_DEVTYP_OEM = 0x00000000 DBT_DEVTYP_DEVNODE = 0x00000001 DBT_DEVTYP_VOLUME = 0x00000002 DBT_DEVTYPE_PORT = 0x00000003 DBT_DEVTYPE_NET = 0x00000004 # # media types in DBT_DEVTYP_VOLUME # DBTF_MEDIA = 0x0001 DBTF_NET = 0x0002 WORD = c_ushort DWORD = c_ulong class DEV_BROADCAST_HDR (Structure): _fields_ = [ ("dbch_size", DWORD), ("dbch_devicetype", DWORD), ("dbch_reserved", DWORD) ] class DEV_BROADCAST_VOLUME (Structure): _fields_ = [ ("dbcv_size", DWORD), ("dbcv_devicetype", DWORD), ("dbcv_reserved", DWORD), ("dbcv_unitmask", DWORD), ("dbcv_flags", WORD) ] def drive_from_mask (mask): n_drive = 0 while 1: if (mask & (2 ** n_drive)): return n_drive else: n_drive += 1 class Notification: def __init__(self): message_map = { win32con.WM_DEVICECHANGE : self.onDeviceChange } wc = win32gui.WNDCLASS () hinst = wc.hInstance = win32api.GetModuleHandle (None) wc.lpszClassName = "DeviceChangeDemo" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = win32gui.LoadCursor (0, win32con.IDC_ARROW) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map classAtom = win32gui.RegisterClass (wc) style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = win32gui.CreateWindow ( classAtom, "Device Change Demo", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None ) def onDeviceChange (self, hwnd, msg, wparam, lparam): # # WM_DEVICECHANGE: # wParam - type of change: arrival, removal etc. # lParam - what's changed? # if it's a volume then... # lParam - what's changed more exactly # dev_broadcast_hdr = DEV_BROADCAST_HDR.from_address (lparam) if wparam == DBT_DEVICEARRIVAL: print "Something's arrived" if dev_broadcast_hdr.dbch_devicetype == DBT_DEVTYP_VOLUME: print "It's a volume!" dev_broadcast_volume = DEV_BROADCAST_VOLUME.from_address (lparam) if dev_broadcast_volume.dbcv_flags & DBTF_MEDIA: print "with some media" drive_letter = drive_from_mask (dev_broadcast_volume.dbcv_unitmask) print "in drive", chr (ord ("A") + drive_letter) return 1 if __name__=='__main__': w = Notification () win32gui.PumpMessages () TJG From haynesc at rockefeller.edu Thu Jan 22 17:03:36 2004 From: haynesc at rockefeller.edu (Chad Haynes) Date: Thu, 22 Jan 2004 17:03:36 -0500 Subject: wxPython question Message-ID: <5sKcnU3qx-sP1Y3dRTvaKA@news.rockefeller.edu> Is there a way to change the background color of a wxCheckBox in wxPython? Using the SetBackgroundColor function will change the background of any label attached to the checkbox, but I want to change the color of the actual box. I thought about trying to draw a colored box behind the checkbox, but I am putting the checkbox over an image and I havent had much luck drawing on top of the image. Any help would be greatly appreciated! -Chad From alan.gauld at btinternet.com Fri Jan 16 15:12:50 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Jan 2004 20:12:50 GMT Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: <40084500.1044866098@news.blueyonder.co.uk> On Fri, 16 Jan 2004 12:00:27 GMT, Samuel Walters wrote: > http://mitpress.mit.edu/sicp/full-text/book/book.html > > It's the major reason I'm learning scheme. > I just don't stop hearing good things about this book. Yep, and a good companion volume, also online is How To Design Programs http://www.htdp.org/2001-11-21/Book/ Which is a more hands on, day to day type scheme tutor but emphasises all the same principles. It's less math oriented that SICP which might appeal to some. But SICP is definitely the more "life changing" in impact. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From maarten at remove_this_ws.tn.tudelft.nl Tue Jan 20 07:43:02 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Tue, 20 Jan 2004 13:43:02 +0100 Subject: Looking for very simple general purpose tokenizer References: Message-ID: I found a complication with the shlex module. When I execute the following fragment you'll notice that doubles are split. Is there any way to avoid numbers this? source = """ $NAMRUN Lz = 0.15 nu = 1.08E-6 """ import shlex import StringIO buf = StringIO.StringIO(source) toker = shlex.shlex(buf) toker.comments = "" toker.whitespace = " \t\r" print [tok for tok in toker] Output: ['\n', '$', 'NAMRUN', '\n', 'Lz', '=', '0', '.', '15', '\n', 'nu', '=', '1', '.', '08E', '-', '6', '\n'] -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From mhammond at skippinet.com.au Sat Jan 10 17:31:28 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 11 Jan 2004 09:31:28 +1100 Subject: Multithreaded COM server problem... In-Reply-To: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> Message-ID: John Lull wrote: > I'm writing a multithreaded COM server to manage a pool of hardware resources. > All objects are designed to be thread-safe, and I've set sys.coinit_flags to > COINIT_MULTITHREADED before importing pythoncom. Note that this flag is effeectively ignored for the server. Objects are created in the same "apartment" as their creator. This, the code implementing your object need not specify this, but the code *creating* the object must. This is what determines the appartment. COM threading rules are complex, but "Python Programming on Win32" (1/2 by me :) covers these rules in words I would have trouble finding again :) Mark. From rodrigob at elo.utfsm.cl Mon Jan 19 09:41:58 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Mon, 19 Jan 2004 11:41:58 -0300 Subject: stack-like file object Message-ID: <400be8f3_2@nova.entelchile.net> Hi, I need to implement a stack on a file. The idea is to have a big list, and put part of his head on the disk. The model of access to the file is like a stack (read in order only the tail, write only at the tail). How could I create this, knowing that I need to pickle arbritary objects ? (to my eyes the problem is: how to pickle various objects in file and access them as separate) RodrigoB. From nospam at nowhere.hu Mon Jan 12 07:56:29 2004 From: nospam at nowhere.hu (Miklós) Date: Mon, 12 Jan 2004 13:56:29 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: As for AI, I would choose Prolog any time over Lisp. ;) I know either one really but I had more fun with Prolog than with Lisp when playing with them. You know the AI people are divided into two groups: 'the fuzzy' and 'the tidy'. (Dunno these are the orginal phrases in English..) The former ones are people of practice and little theory, the latter ones are people of theory and more theory which works in practice. ;) The former ones like Lisp and the latter ones use Prolog. Lisp is prefered in the USA, Prolog is preferred in Europe and Japan. Anyway, my point is that Python is very neat for doing AI: http://www.cs.berkeley.edu/~russell/aima.html This is the best AI textbook I've seen so far and their textbook code is being put into Python... Help them out.. ;) Best, Mikl?s Bicho Verde wrote in message news:40029dad$0$28706$a729d347 at news.telepac.pt... > I have now free time and money to do what I want :-) > I have some basic skills in programming (C, Pascal, Macromedia > Anyone would help me and give me some hints? > > -BichoVerde From aahz at pythoncraft.com Sat Jan 17 14:09:43 2004 From: aahz at pythoncraft.com (Aahz) Date: 17 Jan 2004 14:09:43 -0500 Subject: Overriding operator delete in a Python extension References: Message-ID: In article , Andrew Wilkinson wrote: > >I've written a C++ Python extension, and as part of it I override the >operator new and operator delete functions to provide memory leak tracking >from within the extension. > >When I use the code as part of a complete C++ program everything works >perfectly, however when I compile it with my Python interface code the >operator delete function is not called - the operator new function is >called as normal however. I assume this is because the function is not >linked correctly, but I'm at a loss for how to make the linker resolve the >references in the .so file. > >Does anyone know a possible solution to my problem? Use Boost.Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From db3l at fitlinxx.com Fri Jan 30 16:53:26 2004 From: db3l at fitlinxx.com (David Bolen) Date: 30 Jan 2004 16:53:26 -0500 Subject: TCP server as a Windows service using Python? References: Message-ID: David Mitchell writes: > I can't see how to let the service accept *either* an incoming TCP client > connection *or* an e.g. "stop service" message. If someone could point me > to some sample code, I'd greatly appreciate it - Google hasn't been > helpful. NT Services generally run a dedicated thread to handle service control messages - normally the application starts up and lets its main thread handle that, and it starts a secondary thread to actually run the application code. It's been a while since I last used it, but if you are using the service support from win32all then I believe it should handle it automatically for you. If you subclass from win32serviceutil.ServiceFramework, then the Svc* control message calls (such as SvcStop) should, I believe, arriving in a different thread from your main execution. (*) Thus, your client side processing only has to wait for the TCP connection. The stop service connection is handled in the service message thread, which the framework will turn into the method call. Now, you do have to figure out how you want to interrupt your TCP client processing when you get such a stop message. The demo with win32all uses an event which it can wait on along with the pipes. You could do the same thing with sockets if you used native Windows operations, but if you're using more portable Python stuff, I'd probably just have a periodic timeout to your select to check a flag, or even have an internal loopback socket that you write to to wake up the select and then it can shut down. -- David (*) If for some reason this isn't the case, you can still architect your service this way - just spin off a new thread at startup to handle your TCP clients. From python-list at cstork.org Wed Jan 21 01:24:32 2004 From: python-list at cstork.org (Christian Stork) Date: Tue, 20 Jan 2004 22:24:32 -0800 Subject: Weaver/Yarn Pattern in Python Message-ID: <20040121062432.GA6158@ics.uci.edu> Hello everybody, I am using Python to prototype a compression algorithm for tree-shaped data, e.g., XML data or abstract syntax trees. I use a variant of the visitor design pattern--called weaver/yarn pattern--in order to traverse the tree that is being compressed or decompressed. I do not know of any other interesting application of the weaver/yarn pattern, but it seems like a very suitable subject of study for different implementation strategies. Essentially, I am asking for input on my design decisions. First, let me give you a simple example of the traditional visitor pattern. The following diagram illustrates a depth-first traversal of a mini tree by a visitor. The basic idea is that the tree accepts a visitor and helps it to do a kind of type-dispatch based on the kind of nodes. Tree data structure (nodes a,b,c of types A,B,C) a:A / \ / \ b:B c:C Nested calls ------------ Call location Call stack main: a.accept(v) A: v.visitA(a) V: b.accept(v) B: v.visitB(b) V: c.accept(v) C: v.visitC(c) class A(Node): def accept(self, visitor): visitor.visitA(self) class B(Node): def accept(self, visitor): visitor.visitB(self) class C(Node): def accept(self, visitor): visitor.visitC(self) class Visitor: "Perform specific tasks while visiting certain nodes" def visitA(self, a): for k in a.kids: k.accept(self) def visitB(self, b): pass def visitC(self, c): pass The advantage of this ping-pong between the tree and visitor v is that v encapsulates related processing instructions. Several different visitors can be maintained independently of each other and without forcing changes to the tree node classes. The tree nodes only need to provide a node.accept(visitor) method. Type-checking can ensure the match between the visitor and the tree data structure. Normally, visitors encapsulate different processing passes, which are run one after the other, each time traversing the whole tree. I have implemented the compression of trees as several (sub)visitors c1..cN even though they could have been implemented as one big visitor. Besides the easy recombinability of visitors this has the added advantage that I can use the same visitors for compression and decompression where this is appropriate. But now I have a problem when decompressing. In order to run one visitor after another the first one expects to traverse the whole tree. But this is impossible in case of a decompressor. It lies in the very nature of the application that the tree is being constructed while the visitors work on it. Conceptually the solution is easy. The decompression subvisitors d1..dM have to process the partially available tree upto the point of traversal where it is available. At each node execution has to iterate over the applicable code of d1..dM in the given order. This necessitates a decomposition of visitors into something that we call yarns and these yarns are weaved by one visitor, which we call the weaver. Thus the name "Weaver/Yarn Pattern" for this variation of the visitor pattern. The following exemplifies my current implementation of the w/y pattern for a recursive descent (ie depth-first traversal) visitor. For each (sub)visitor d1..dM the former d.visitX(x) method is divided into several y.weaveX_...() methods. At entry and exit the weaver invokes y.weaveX_First() and y.weaveX_Last(). Each descent into a child is surrounded by y.weaveX_Before(kidno) and y.weaveX_After(kidno) method calls. class Yarn: # methods replacing visitA(..) def weaveA_First(self, a): pass def weaveA_Before(self, a, kidno): pass def weaveA_After(self, a, kidno): pass def weaveA_Last(self, a): pass # methods replacing visitB(..) def weaveB_First(self, a): pass def weaveB_Last(self, a): pass # methods replacing visitC(..) ... class Weaver: "A special visitor which weaves yarns" def __init__(self, yarns): self.yarns = yarns def visitA(self, a): for y in self.yarns: y.weaveA_First(a) for i, k in enumerate(a.kids): for y in self.yarns: y.weaveA_Before(a, i) k.accept(self) for y in self.yarns: y.weaveA_After(a, i) for y in self.yarns: y.weaveA_First(a) def visitB(self, b): for y in self.yarns: y.weaveA_First(b) for y in self.yarns: y.weaveA_First(b) def visitC(self, b): ... By now it should be obvious that the boilerplate for this approach becomes quite extensive and it would be desirable to reduce it. To mitigate the problem I did three things: - Automatically generate templates for yarn classes. The actual code can be filled in. Disadvantage: No convenient way to deal with changes to the tree data structure. - The node.accept(weaver) methods are changed to call a "generic" weaver.weave(node) method (instead of weaver.visitX(node)), which hackishly constructs all the calls to the yarns by assembling the method names from the __class__.__name__ and one of "First", "Last", "Before", and "After". This solution does pretty much what I want: - Writing selected yarn methods allows me to express with little overhead /what/ code to execute /when/ in the weaving process. - Once the weaver/yarn interaction machinery is set up correctly, the debugger points me to real code in case of bugs. This is an advantage over approaches that create classes at runtime, e.g., use of metaclasses or the "new" module. OTOH, I'm not perfectly happy with this solution since it's totally "hackish". For example, I have to use a function, hand-written specifially for this purpose, in order to "type-check" the correspondence of the tree types and the yarns. Maybe Python is not the right language for an elegant solution and I should look at more rigorously or differently typed languages, but I thought it's worth presenting my case here and asking what other python hackers think. Maybe there is another more pythonic way to do this? I looked into several of python's features, but to no avail. Iterators don't seem to play well with yarns (especially if you try to thread objects thru the yarns to support synthesized/inherited attributes a known from attribute grammars). I also looked at metaclasses in order to reduce the boilerplate but that did pay off either. There are certainly other languages and language concepts, which offer interesting implementation alternatives: - Dylan's generic functions seems to be a a good match for my problem, which allows me to get around the method name mangling in weaver.weave(node). Anybody an idea for a nice emulation of generic functions in python? :) - Lazy evaluation as provided by Haskell (or even Ocaml) seems to make the traveral by several visitors unnecessary, but I'm not yet convinced enough of this approach to start a full reimplementation. - Systems for attribute grammar evaluation seem to address some of my general concerns, but I am afraid that they might constrain me too much. If you're still reading this I'm impressed ;-) and I would be very happy to hear what you think. -Chris -- Chris Stork <> Support eff.org! <> http://www.ics.uci.edu/~cstork/ OpenPGP fingerprint: B08B 602C C806 C492 D069 021E 41F3 8C8D 50F9 CA2F From 9974331 at cvm.qc.ca Wed Jan 14 16:14:43 2004 From: 9974331 at cvm.qc.ca (Askari) Date: 14 Jan 2004 13:14:43 -0800 Subject: CheckButton -- modify "check state" Message-ID: <104c369a.0401141314.5c64a727@posting.google.com> Hi, How do for do a "select()" on a CheckButton in a menu (make with add_checkbutton(....) )? I can modify title, state, etc but not the "check state". :-( Askari From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Jan 19 15:58:41 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 19 Jan 2004 21:58:41 +0100 Subject: interface to win job scheduler portable from win98 .. winXP / cmdline or COM ? References: <400c134c$0$9745$9b622d9e@news.freenet.de> Message-ID: Hi ! The AT command, in NT, W2K or WXP, use the user "system", by default (with some limits). It's better to make an Python's script who do the job scheduler ; it's no difficult. * sorry for my bad english * @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From Tobias.Windeln at gmx.de Fri Jan 9 06:39:48 2004 From: Tobias.Windeln at gmx.de (Tobias Windeln) Date: Fri, 09 Jan 2004 12:39:48 +0100 Subject: Object-based inheritance in Python Message-ID: Hi! I'm looking for suggestions on object-based inheritance in Python. Automatic forwarding (often called delegation) in Python is easy: def __getattr__(self, attr): return getattr(self.delegatee, attr) def __setattr__(self, attr, value): return setattr(self.delegatee, attr, value) Maybe there is a way to hand over self to the delegatee object. So the next call on self in the delegatee object is send to the child object. A small example: class Child: def __init__(self, delegatee): self.__dict__['delegatee'] = delegatee # TODO ... delegation/overriding mechanism .... def m(self): self.m2(self) def m3(self): print("Child") class Delegatee: def m2(self): self.m3(self) def m3(self): print("Child") #_______________________ >>> c = Child(Delegatee()) >>> c.m() Child >>> The call to m2() is forwarded to the Delegatee. The call to m3() in m2() is redirected to Child and the m3() Method in Child is called: ===================================================== m2(child_self) child --------------------> delegatee | <-------------------| m3(child_self) ===================================================== This functionality would be helpfull in Patterns (Decorator, Strategy, etc.) Do you have any suggestions on how to hand over self to the delegatee? Since the first argument of every method in Python is self, the rest of the object-based inheritance works automatically! I usually work with Java, where I implemented this functionality with enormous effort. When I saw Pythons reflective capabilities (__getattr__ etc.) I wondered if this is possible in an generic/easy way. Thanks in advance Tobias From just at xs4all.nl Mon Jan 5 13:01:05 2004 From: just at xs4all.nl (Just) Date: Mon, 05 Jan 2004 19:01:05 +0100 Subject: PRE-PEP: new Path class References: Message-ID: In article , "John Roth" wrote: > > > 4) Should path expose an iterator for listdir(?) > > > > > > I don't see why not, as long as the path is to a > > > directory. > > > > _An_ iterator, sure, but not __iter__. How about path.listdir()? :) > > __iter__ could also iterate over the path elements, so it's ambiguous at > > least. > > I see what you're saying. I'd argue (softly) that iterating over > the directory entries is the natural interpretation, though. It's far too implicit to my taste; for one since it's a folder-only operation (and I don't see much merit in having separate classes for folder and file paths). Would you also be in favor of interating over file-paths meaning iterating over the lines in the file? Just From drfransch at netscape.net Wed Jan 7 03:51:45 2004 From: drfransch at netscape.net (F. Schaefer) Date: 7 Jan 2004 00:51:45 -0800 Subject: Code Objects / Variable Names Message-ID: PROBLEM: How can you know what variables are involved in a code object. It is not possible to execute the code object simply into a dictionary and then watch the defined variables. This is because these code objects only contain conditions, that read out variables. EXAMPLE: For the following (compiled) condition (door == "ajar" and alternator == "off") || time > 25 I need to extract, that the variables 'door', 'alternator' and 'time' are involved. Best Regards, Frank Sch?fer. From banderet at nagra.com Thu Jan 15 11:05:30 2004 From: banderet at nagra.com (Gregoire Banderet) Date: 15 Jan 2004 08:05:30 -0800 Subject: Embedded python (use of modules) on system w/o Python installed Message-ID: Hi there, I try to run a python script from a C program. The script uses the re (regex) module. The resulting executable must run on a system that has no lib and python script module, i.e no re.py How should I write my C program (I'd like to avoid any python file installation on target system) ? Now it is: --------- C prg ---------- #include #define PYTHON_SCRIPT "test.py" int main(int argc, char * argv[]) { FILE *fd = fopen(PYTHON_SCRIPT, "r"); Py_Initialize(); PyRun_SimpleFile(fd, PYTHON_SCRIPT); Py_Finalize(); return 0; } ---------------------------- ---------- test.py ---------- import re p = re.compile('(ab)*') print p.match('ababababab').span() ------------------------------ But when I run pytest on the target system: # ./pytest 'import site' failed; use -v for traceback Traceback (most recent call last): File "test.py", line 1, in ? import re ImportError: No module named re From jcb at iteris.com Fri Jan 16 01:57:55 2004 From: jcb at iteris.com (MetalOne) Date: 15 Jan 2004 22:57:55 -0800 Subject: wxPython worries References: Message-ID: <92c59a2c.0401152257.5b93167b@posting.google.com> I have recently been trying to build some GUIs with wxWindows. The first problem that I ran across involved not being able to send and event from a worker thread to the GUI thread and get the GUI thread to process the event while the user had a menu pulled down. I wrote a bug report and this has since been fixed. Tkinter has issues here also. There is no means for a worker thread to put an event in the GUI thread. The second problem that I have run across is that tab order between controls is the order that controls are added. You can't get tabbing to skip a control. If you dynamically add/remove controls you can't achieve your desired tab order. wxWindows seems like a very impressive work. The demo is certainly impressive. I also suppose I shouldn't rant to much about something that is free. However my first two GUIs hit critical problems, and these were really simple GUIs. Granted, the first problem has been fixed now, and I have not yet written a bug report on the second. Tkinter is also giving me problems. I have been trying to add controls to a canvas and to have a scrollbar that will scroll the controls on the canvas. I think I have it figured out now, but it is damn near impossible to figure out from the documentation. I had to scour the internet looking for solutions. I have also played with displaying video in both wxWindows and Tk. I have raw gray scale data simply as a list of values range 0-255. Using PIL I can easily convert to a format wxWindows and Tk can display. I get around 30 fps with wxWindows and 15 fps with Tk. However, all images wxWindows displays must be full 24-bit color. If the images didn't need to be expanded to (r,g,b) I would expect signifcant speed up. I don't know why Tk is so much slower. wxWindows and Tk are the only toolkits that wrap native Windows controls. The others all emulate controls. I am thinking about trying out another toolkit. FOX, FLTK or GTK. I am having enough trouble convincing people to use Python. I'd never be able to get my work to purchase Qt. They would prefer to do everything in VB6. From tzot at sil-tec.gr Thu Jan 8 12:19:57 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 08 Jan 2004 19:19:57 +0200 Subject: Pre-PEP: Dynamically evaluating default function arguments References: Message-ID: On Wed, 07 Jan 2004 20:58:30 GMT, rumours say that Samuel Walters might have written: >OT: I once worked with a fellow that had just enough knowledge about our >business and systems to suggest wildly bad ideas to "improve" our >applications. On one particular project, he was required at several of >the requirements gathering meetings. He took up a crusade that wasted >much of our time explaining to him that his idea was not only undesirable, >but incredibly unworkable. When the preliminary timeline for the project >was passed around via email so that we could all ask for corrections I >added his idea as a milestone with a projected completion date of "After >the eventual heat death of the universe." The project manager happily >emailed him that his proposal had been accepted and added to the timeline. > He was quite pleased with himself and was much easier to work with since >he had "made a difference." So, perhaps we should invent a new reply for all wild ideas about Python (I've had my share of these :) "Thank you for your contribution; your suggestion has been judged worthy of inclusion in Python 4k. Upload your patch to sf.net as soon as Python 3k final is released." -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From dlmurray at micro-net.com Sun Jan 4 19:58:17 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Sun, 4 Jan 2004 17:58:17 -0700 Subject: Why does this fail? Message-ID: New to Python question, why does this fail? Thanks, Dave ---testcase.py--- import sys, urllib, htmllib def Checkit(URL): try: print "Opening", URL f = urllib.open(URL) f.close() return 1 except: return 0 rtfp = Checkit("http://www.python.org/doc/Summary.html") if rtfp == 1: print "OK" else: print "Fail" python testcase.py From brett at python.org Mon Jan 19 18:03:43 2004 From: brett at python.org (Brett C.) Date: 19 Jan 2004 15:03:43 -0800 Subject: python-dev Summary for 2003-12-01 through 2003-12-31 References: <4001a488$0$317$e4fe514c@news.xs4all.nl> Message-ID: <8ab0589d.0401191503.772166f2@posting.google.com> Irmen de Jong wrote in message news:<4001a488$0$317$e4fe514c at news.xs4all.nl>... > First: thanks Brett, for the summary. And get well soon from your pneumonia. > Thanks. The doctor has cleared me of pneumonia. Now if the funky feeling in my lower back when I bend over would just go away I would be willing to claim I am perfectly healthy. > Brett wrote: > > > ------------------------ > > Compiling 2.4 under .NET > > ------------------------ > > Martin v. L?wis has started sandbox work on an MSI installer and moving > > Python 2.4 over to VC 7. > > MSI? Why, what is wrong with the old installer? > I'm not too fond of MSI installers, I find them slow and large. > Especially when using lots of files. That may be a problem in the > installer script, but almost all MSI installers I encountered were > extremely slow when installing and deinstalling a program that > consists of a lot of files (and Python does). > (I must note that this is much less so with recent versions > than before, because the help files are no longer in seperate > html files but in a single chm file). > I am guessing here, but I think it has to do with maintennance and modernization. The WISE installer was only maintained by Tim Peters and he has been hella (too much time in Berkeley) busy for a while now. Moving over to MSI allows Martin to handle it along with anyone else who has experience with MSI installers (which seems to be more than WISE from the emails on the list). Decentralizing reliance on individuals is important in case someone falls off the face of the earth. The Python 2.3 releases have mostly been handled by people who did not usually handle it. Yes, there were some issues, but now there a bunch more people who know how to deal with a release. Beyond that I don't know since I am an OS X user now and just compile from source. =) -Brett From reply.in.the.newsgroup at my.address.is.invalid Thu Jan 1 09:14:18 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 01 Jan 2004 15:14:18 +0100 Subject: Uploading a file with ftplib References: Message-ID: Michael_Goettsche: >can anybody please tell me how to upload it properly? This is a snippet from one of my scripts, that works fine: ftp = ftplib.FTP(Hostname,Username,Password) ftp.cwd(WorkingDirectory) ftp.storbinary("STOR " + RemoteZipFile, file(LocalZipFile, "rb")) ftp.quit() -- Ren? Pijlman From michele.simionato at poste.it Tue Jan 13 09:41:54 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 Jan 2004 06:41:54 -0800 Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> <4002AE9B.C51448FB@engcorp.com> Message-ID: <95aa1afa.0401130641.50e721fd@posting.google.com> "Frithiof Andreas Jensen" wrote in message news:... > "Peter Hansen" wrote in message > news:4002AE9B.C51448FB at engcorp.com... > > > ...., as it takes me only about twenty seconds to start a > > new test file and that's *without* using a template. > > ....in twenty seconds you can just about write "import unittest" ;-) > > I find that a simple module will need about three to five tests for each > method in each class and probably some test data as well often yielding in > total *more* lines of test code than the module I want to test. > > It is simple, stupid & boring code but still lines that have to be typed and > debugged. > > *That* is tedious work. Always will be. That's why I use "doctest" much more than "unittest". Michele From Scott.Daniels at Acm.Org Tue Jan 20 00:41:38 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 19 Jan 2004 21:41:38 -0800 Subject: efficent test for array with only one value? In-Reply-To: <25mud1-s1m.ln1@jowls.lairds.org> References: <00ird1-dmd.ln1@jowls.lairds.org> <25mud1-s1m.ln1@jowls.lairds.org> Message-ID: <400cca0d$1@nntp0.pdx.net> Kyler Laird wrote: > Robert Kern writes: > ... I'm guessing that reduce > will not stop immediately when equal encounters a False. If the early stop is what you want, how about: if vector: d = {} d[vector[0]] = 0 try: for el in vector: d[el] except KeyError: return False return True -Scott David Daniels Scott.Daniels at Acm.Org From david at no.westcontrol.spam.com Fri Jan 16 07:59:30 2004 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 16 Jan 2004 13:59:30 +0100 Subject: keeping Python code properly indented References: <3064b51d.0401151125.711ade4c@posting.google.com> Message-ID: wrote in message news:3064b51d.0401151125.711ade4c at posting.google.com... > How do you keep Python code properly indented as you modify it? I use > an Emacs-type editor that has a Python mode, so the initial indenting > is easy. If I later want to put a 'for' loop (or an 'if' statement) > around a bunch of code, I find myself going through the body of the > loop, manually re-indenting to keep the nested loops correct. There > should be a better way. > Any decent editor will do the indenting in a couple of keystrokes. And even doing it manually, if your looped code is so many lines that manually "tabbing" each is a a big chore, you should probably break it into smaller functions for clarity. > I think that having a 'for' loop end with a matching 'next' statement, > as done in (for example) Basic, is a safer and clearer way of writing > loops, although some Python programmers consider this a 'feature' > rather than a 'bug'. When programming in Basic, you still have to indent the contents of the loop (manually or otherwise, depending on the editor). Just because the basic interpreter / compiler will work without sensible indentation, does not mean that mismatches between the code structure and the code appearance (especially indentation) is in any way a good thing. From jjl at pobox.com Sun Jan 11 09:22:13 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jan 2004 14:22:13 +0000 Subject: What is best for web application development?? References: Message-ID: <878ykelg4q.fsf@pobox.com> Dave Kuhlman writes: > ketulp_baroda wrote: > > > i am developing a web application and i am really confused on what > > should i use. [...] > You may also want to join the web-sig email list and ask your > question there. Or not: that list is supposed to be for discussion of what new web-related code should go into the standard library, not for questions about choosing a web framework. John From blaktyger at hotmail.com Tue Jan 6 11:53:53 2004 From: blaktyger at hotmail.com (Blaktyger) Date: 6 Jan 2004 08:53:53 -0800 Subject: Downloading files off Interet References: Message-ID: Terry Carroll wrote in message news:... > On 5 Jan 2004 23:32:53 -0800, blaktyger at hotmail.com (Blaktyger) wrote: > > >I would like to download some mp3 files from a web site. There is to > >much of them and I had the idea of writing a script to do it for me. > > > >Code: > >import string > >import urllib > > > >f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") > > > >fic=open('mp3file.mp3','w') > >fic.write(f.read()) > >fic.close() > >f.close() > > > >I ran the program and the file is not playing. > >Can someone help me? > > > A couple possibilities: > > First, are you running on Windows? If so, you want your output file > opened binary: > > fic=open('mp3file.mp3','wb') > > Second, what does your output file look like? See if it's a text error > message. Some sites will check to see whether there is a referring page > from their own web site, and disallow transfer otherwise (or divert to a > different site). If your somemp3site.com site does that, your download > will fail. > > The only way I know around this is to give up using urllib, and use > urllib2 instead, opening a Request rather than the url directly, and > specifying the referring page from which you picked up the URL to the MP3 > page. > > I can give more detail on this, but check the binary open first. > > Also, if the referring page is not the issue, you will probably find it > much simpler to use urlretrieve instead. See > http://www.python.org/doc/current/lib/module-urllib.html . > > Instead of: > > import string > import urllib > f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") > fic=open('mp3file.mp3','w') > fic.write(f.read()) > fic.close() > f.close() > > You just do: > > import urllib > urllib.urlretrieve(""" http://www.somemp3site.com/somemp3.com""") > > That's it. It's almost cheating. > > Unfortunately, there's no urllib2.urlretrieve, so if that referring page > thing is your issue, you can't use urlretrieve. > > Hope this helps. Cheating is fun =) Thanks people! From james at logicalprogression.net Wed Jan 21 16:01:33 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 21:01:33 +0000 Subject: Need help with Python class idioms In-Reply-To: <200401212051.50411.james@logicalprogression.net> References: <200401212051.50411.james@logicalprogression.net> Message-ID: <200401212101.33605.james@logicalprogression.net> [Tad Marko] > > def saveToDB(self, db): > > if self.mandatoryVar1 == None: > > raise Exception, "Mandatory Var 1 not set." > > if self.mandatoryVar2 == None: > > raise Exception, "Mandatory Var 2 not set." P.S. Since you're asking about idiom, it would be more Pythonic to write: if self.mandatoryVar1 is None: using the identity test "is" rather than equality test "==", since there is only one None. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From quentel.pierre at wanadoo.fr Tue Jan 6 16:56:57 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Tue, 6 Jan 2004 22:56:57 +0100 Subject: help needed with class and method confusion References: <20040106102232.19889.00002028@mb-m01.aol.com> Message-ID: If I understand the problem, you have a planet and a number of moons turning around it. So you should define two different classes, Planet and Moon -------------------------------- class Moon: def __init__(self, name): self.name = name class Planet: def __init__(self,names): self.moons = [] for name in names: m=Moon(name) setattr(self, name, m) self.moons.append(m) satellites = ["Io", "Europa", "Ganymeade"] Jupiter = Planet(satellites) ------------------------------- You'd better leave the satellite names outside of the __init__ method of Planet, in case you happen to work on another planet Hope this helps, Pierre From zero.kelvin at web.de Sat Jan 24 05:41:02 2004 From: zero.kelvin at web.de (Tim Adler) Date: Sat, 24 Jan 2004 11:41:02 +0100 Subject: Apache: mod_python Message-ID: Hello everyone! Perhaps this is not the right place to ask, but I cannot find a better one. I'm trying to get Python to run as an Apache module (basically I would like to use ViewCVS). I installed mod_python and added this stuff to the httpd.conf LoadModule python_module libexec/mod_python.so AddHandler python-program .py PythonHandler mod_python.publisher PythonDebug OnStill when I access a given .py file (the one that ViewCVS suggests), I get an 500-error and the Apache states in the error.log that it cannot import a "mod_python.apache".Can somebody help me ?Thx, Tim From martin at v.loewis.de Sun Jan 11 16:18:51 2004 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Jan 2004 22:18:51 +0100 Subject: Python And Internationalization maybe a pre-pep? References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> <40011315.7070000@v.loewis.de> <8EeMb.24302$5V2.36981@attbi_s53> Message-ID: Brian Kelley writes: > def foo(...): > return i"Message" > > You wouldn't have to execute foo directly for the parse tree to notice > that i"Message" was a string that is supposed to be > internationalized. This process gets this string placed in the > internationalization table which I would then use various tools to > modify and translate. But this is the technology today! The xgettext utility (either GNU xgettext, or xgettext.py) extracts internationalized strings from Python code into "internationalization tables". These tables are called "PO files". They get translated, then converted into an efficient internal representation, called "mo files". I'm uncertain how this relates to the internationalization tables you are proposing, but please recognize that a single application may have *multiple* such tables, called "textual domains". To find a translation, you not only need the message id, but you also need the textual domain. > This should tranparent to Gui Widgets and the like so you can place > i"Message" in a list box, it will automatically get internationalized > but when you get the result of the user selected, it still can be used > to dictionary look ups exactly the same as the original i"Message". Using what textual domain? > My current thinking is as follows, I could get most of this effect by > not having a new string type (i"") and just making an > internationalization string type. Then I would just use code analyzer > tools to generate the translation tables as Serge suggested, heck, > they could even use the parse module if I was so inclined. xgettext.py already performs very simple parsing of source files, to extract messages. Why reinvent the wheel? > In either case, I far prefer using internation("This is good") over > the _("This is good") function call. So do call it internation(), or internationalization() or something else. It is just a function: def internation(msg): return gettext.dgettext("some domain", msg) Regards, Martin From llothar at web.de Wed Jan 14 09:38:07 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Jan 2004 06:38:07 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: <6ee58e07.0401140638.672d50a7@posting.google.com> graham__fawcett at hotmail.com (Graham Fawcett) wrote in message news:... > Wilk wrote in message news:<87oet9grqy.fsf at blakie. > If it has to be a one-shot install, I would suggest a Web server > written in Python -- Medusa or Twisted, probably -- that you could > bundle with your Python app. Find a Web app framework that (a) works > on Medusa or Twisted and (b) has the templating features you > require/desire. I would not recommend this. A distribution with an own apache server seems to be the best. It is easy to hide the setup and the customers know that there is a good working technologie behind the scenes. And it can be managed by every normal administrator. This is a very important point for larger customers. I would recommend webware+Fun Form Kit+cheeta together with apache. From noemail at noemail4u.com Fri Jan 9 07:28:27 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 09 Jan 2004 12:28:27 GMT Subject: How to log unittest results? References: Message-ID: <30423f111f634a26f0860b79e915918e@news.teranews.com> On 7 Jan 2004 13:05:59 -0800, ericjnilsen at earthlink.net (EricN) wrote: >I like to use unittest. However, when my QA Manager shows up in my >cube and says "Give me evidence that all your unit tests passed", I >have nothing to provide. I'd like to log the unittest results >(verbose mode) somehow. I'm open: logger module, stdmsg redirect, >whatever. Another way to pacify the QAM would be to show the version control log. If you check your stuff in at each stage, and have comments saying what was fixed (e.g., "passed unittest XYZZY"), that should be sufficient for QA purposes. QA confirms that the process is being followed--not that the code works. Sorry I can't help, but why would your QAM care about this level of detail? Unless your code is looking bad (i.e., high defect density) later, when it's integrated, your personal development process, i.e., using unittest or not, is too low-level of a detail. MicroQAM. Does your QAM also want to see marked up printouts of your code, showing that you performed a code review? Design review? Etc? --dang From noemail at noemail4u.com Wed Jan 14 13:05:52 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Wed, 14 Jan 2004 18:05:52 GMT Subject: id3v2 module References: Message-ID: On Tue, 13 Jan 2004 15:47:21 +0000, Andy Todd wrote: >Dusausoy Bruno wrote: > >> Hi, >> >> I'd like to know if there is a third-party module for reading/writing >> id3v2 informations. >> Thanks > >http://www.nedbatchelder.com/code/modules/id3reader.html Go to sourceforge and search for any of 'pyid3', 'ptommi', or 'eyed3'. I've used a couple to fix my ipod database a few times. Well, not the ipod database itself, but renaming files and fixing tags so that ephpod can rebuild the database. --dang From reply.in.the.newsgroup at my.address.is.invalid Thu Jan 22 04:52:42 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 22 Jan 2004 10:52:42 +0100 Subject: python References: Message-ID: Jess Martin: >every time i try to do a command more than a line long it wont work You must be doing something wrong then :-) Check the documentation: http://www.python.org/doc/current/ref/line-structure.html -- Ren? Pijlman From yin_12180 at yahoo.com Mon Jan 26 11:25:00 2004 From: yin_12180 at yahoo.com (Yin) Date: 26 Jan 2004 08:25:00 -0800 Subject: BaseHTTPServer and class variables Message-ID: <88caaeda.0401260825.4db9a07d@posting.google.com> Hello. I am using the basehttpserver to implement the HTTP protocol to serve a fairly large lexicon that I have loaded as a dictionary in python. Rather than writing a whole server, I would like to reuse the BaseHTTPserver classes. I am interested in finding a way to serve the dict without loading the whole dict into memory everytime an HTTP request is made. The dict lives in local memory when it is loaded and takes a long time to load. Unfortunately with the basehttpserver.httpserver and basehttpserver.requesthandlerclass, I am not finding it easy to define a method to load the dict initially. Any thoughts are appreciated. Ideally, in a do_GET for the requesthandlerclass, it'd be nice to be able to access the dict as a class variable, but this doesn't work for me. Thanks. Yin From http Thu Jan 8 22:48:38 2004 From: http (Paul Rubin) Date: 08 Jan 2004 19:48:38 -0800 Subject: convert a list to a string References: <3FFE1E29.20801@hotmail.com> <7xwu81dcr7.fsf@ruckus.brouhaha.com> <3FFE2084.7010700@hotmail.com> Message-ID: <7x7k01lr3d.fsf@ruckus.brouhaha.com> Bart Nessux writes: > How does randint and sample differ? I was under the impression that > sample was more random. No, they both use the same underlying generator. randint gives you one random number, which is what you want. sample takes a list and selects some elements from it. As I mentioned in another post, the underlying generator is designed to have good statistical properties for doing things like simulations. It's not designed to withstand someone actively trying to predict the next random number based on the previous output stream. If you're using it in an application like a high-stakes online game, where players have significant incentive to predict the output, then you should get your random numbers a different way. Doing that kind of thing properly takes a lot of skill though--it's not something newbies should attempt. From jepler at unpythonic.net Sat Jan 3 08:58:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 3 Jan 2004 07:58:30 -0600 Subject: Python for Embedded Devices? In-Reply-To: References: Message-ID: <20040103135830.GA13723@unpythonic.net> There have been a few projects to bring Python to "small" platforms like handheld computers such as wince and palm. These are typically full implementations of Python with a few omissions from the core language (eg unicode, complex numbers) and a stripped-down set of standard modules. I think this typically requires a meg or two for installation, and I don't know whether these projects are actively maintained. Jeff From mwh at python.net Thu Jan 15 06:18:45 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 15 Jan 2004 11:18:45 GMT Subject: best book References: Message-ID: km writes: > Hi all, > > What is the best book to start with python ? i am have been working > since 1 yr with Perl. I posted this last week: ---------------------------------------------------------------------- Thomas Mang writes: > Hello, > > I have programmed mostly in C++ lately, and I want to start learning > Python now. > > Which books would you recommend to buy? Well, maybe, none. Have you tried the online material? http://www.python.org/topics/learn and in particular http://www.python.org/topics/learn/prog.html > I am both looking for an introduction into the language, as well as > complete guides. For the "complete guide", what I've seen of Python in a Nutshell is pretty good. But I actually don't own any books on Python (well apart from the one I tech reviewed). Cheers, mwh ---------------------------------------------------------------------- -- "Well, the old ones go Mmmmmbbbbzzzzttteeeeeep as they start up and the new ones go whupwhupwhupwhooopwhooooopwhooooooommmmmmmmmm." -- Graham Reed explains subway engines on asr From maney at pobox.com Sun Jan 11 00:07:20 2004 From: maney at pobox.com (Martin Maney) Date: Sun, 11 Jan 2004 05:07:20 +0000 (UTC) Subject: Optimized quoting (was Re: Speed?) References: <5.2.0.9.0.20040102221218.00b7c870@mail.zomething.com> Message-ID: Aahz wrote: > In article , > Michael Hudson wrote: >>aahz at pythoncraft.com (Aahz) writes: >>> "Premature optimization is the root of all evil in programming." >>> --C.A.R. Hoare (often misattributed to Knuth, who was himself quoting Hoare) >> >>Cite? > http://www.haskell.org/pipermail/haskell-cafe/2001-January/001461.html > Anybody have a copy of _Literate Programming_ to check? Surely someone else must have checked this before now. Perhaps the reply went astray, or isn't threaded properly so that I don't see it. Anyway. Yes, Knuth says, in a parenthetical aside on page 276, "But I also knew, and forgot, Hoare's dictum that premature optimization is the root of all evil in programming." Which fails to answer the quite reasonable wish for a cite attributing the phrase, rather than the concept, to Hoare. (a distinction Cally likes to troll in her .sig, as you know.) (I can't believe that I have, by dint of rigorously ignoring all but the most fascinating threads, gotten close enough to the working end of this dynamic work-always-in-progress to feel I might have something to add other than a belated footnote. Maybe if I got up at 2:30 AM every day I could find time to read clp!) -- One lesson I've learned from my years as Linux's hood ornament is that there's something worse: some folks can't be content to just take things too seriously on their own. They're not happy unless they can convince others to go along with their obsession. -- Linus From gerrit at nl.linux.org Sat Jan 10 11:44:02 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 10 Jan 2004 17:44:02 +0100 Subject: xrange() syntactic sugar In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE0106382C@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE0106382C@au3010avexu1.global.avaya.com> Message-ID: <20040110164402.GA17806@nl.linux.org> Delaney, Timothy C (Timothy) wrote: > > for i in 0:8:2: > > pass > > This exact syntax has been suggested and rejected a few times now ... it's been suggested a few times on python-dev as well by various luminaries/ I don't think there's a PEP for it though (there probably should be). There is, by Thomas Wouters: PEP 204: Range Literals 14 Juli 2000, rejected. This would mean [5:1:-1] becomes a literal short for [5, 4, 3, 2]. Is there a theoretical retirement period for PEP rejection? After all, it's possible that the Python community and/or Guido thinks very differently about a subject after 5 years. Not that I want to re-open this PEP, but more as a theoretical question... yours, Gerrit. -- 4. If he satisfy the elders to impose a fine of grain or money, he shall receive the fine that the action produces. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From aahz at pythoncraft.com Thu Jan 29 12:04:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2004 12:04:17 -0500 Subject: number of arguments a function takes References: Message-ID: In article , Elaine Jackson wrote: > >Suppose one of the arguments of a function f_1 is another function >f_2. Can f_1 access the number of arguments taken by f_2? (I'm writing >a little script to automate the construction of logical truth-tables.) In theory, yes (because of Python's introspection capabilities). In practice, you're likely to want to choose a different mechanism that doesn't require that information. If you tell us more about your actual problem, we may be able to point you in a better direction. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From jmdeschamps at cvm.qc.ca Mon Jan 19 15:11:16 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 19 Jan 2004 12:11:16 -0800 Subject: Analysing Word documents (slow) What's wrong with this code please! References: <3d06fae9.0401161351.75e7f5a@posting.google.com> Message-ID: <3d06fae9.0401191211.484e76f2@posting.google.com> Eric Brunel wrote in message news:... > jmdeschamps wrote: > > Anyone has a hint how else to get faster results? > > (This is to find out what was bold in the document, in order to grab > > documents ptoduced in word and generate html (web pages) and xml > > (straight data) versions) > > > > # START ======================== > > import win32com.client > > import tkFileDialog, time > > > > # Launch Word > > MSWord = win32com.client.Dispatch("Word.Application") > > > > myWordDoc = tkFileDialog.askopenfilename() > > > > MSWord.Documents.Open(myWordDoc) > > > > boldRanges=[] #list of bold ranges > > boldStart = -1 > > boldEnd = -1 > > t1= time.clock() > > for i in range(len(MSWord.Documents[0].Content.Text)): > > if MSWord.Documents[0].Range(i,i+1).Bold : # testing for bold > > property > > Vaguely knowing how pythoncom works, you'd really better avoid asking for > MSWord.Documents[0] at each loop step: pythoncom will fetch the COM objects > corresponding to all attributes and methods you ask for dynamically and it may > cost a lot of time. So doing: > > doc = MSWord.Documents[0] > for i in range(len(doc.Content.text)): > if doc.Range(i,i+1).Bold: ... > > may greatly improve performances. > > > ... Thanks, it does! And using builtin Find object also. Jean-Marc From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Tue Jan 20 15:45:46 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 20 Jan 2004 22:45:46 +0200 Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> Message-ID: >>>>> "eddie" == Eddie Corns writes: eddie> Python: because everything's not an object Umm... everything is an object in Python (except "names"). Whether everything has to be shoehorned into classes is another thing. -- Ville Vainio http://tinyurl.com/2prnb From bdesth.tagada at tsoin-tsoin.free.fr Sun Jan 18 10:43:23 2004 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Sun, 18 Jan 2004 16:43:23 +0100 Subject: Best way to do this? In-Reply-To: <100kqbt2spltf3b@corp.supernews.com> References: <100jg9er3qak890@corp.supernews.com> <100kqbt2spltf3b@corp.supernews.com> Message-ID: <400aa4d3$0$24024$626a54ce@news.free.fr> Wil Schultz wrote: (Wil, please don't top-post... corrected) > > William Park wrote: > >> Wil Schultz wrote: >> >>> One of the exercises asks for a program to ask for a password three >>> times. Surprisingly this took me much longer that it probably should >>> have so I am curious if the following is the easiest way this is >>> done. Thanks much! >>> >>> ************************************************* >>> #!/usr/local/bin/python >>> >>> count = 0 >>> password = "null" >>> >>> while count < 3: >>> count = count + 1 >>> password = raw_input("what's the pass: ") >>> if password == "mypass": >>> print "Access Granted" >>> count = 3 >>> else: >>> if count < 3: >>> print "Try Again" >>> else: >>> print "Too Bad" >>> ************************************************* >> >> >> >> For crying out loud, here's 3 times for you... >> password = raw_input("what's the pass: ") >> password = raw_input("what's the pass: ") >> password = raw_input("what's the pass: ") >> Okay, maybe I should have said the program should ask for the password >> up to 3 times, exiting on a) the correct password b) the third incorrect >> password. >> Beware of specs, programmers can have strange interpretations sometimes !-) import sys for i in range(3): if raw_input("what's the pass: ") == "mypass": print "Access granted" sys.exit(0) print "Access denied" sys.exit(1) HTH Bruno From tdelaney at avaya.com Mon Jan 5 16:25:23 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 6 Jan 2004 08:25:23 +1100 Subject: intellectual property agreements and open source . was - Re: Whydoes this fail? [2] Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0106312E@au3010avexu1.global.avaya.com> > From: Dave Murray > > After re-reading this part, I can see that it is an idea that > I like. How > does participating in open source work for someone (me) who > has signed the > customary intellectual property agreement with the > corporation that they > work for? The best thing to do is get an explicit exemption - in writing - either for the project as a whole (in this case Python) or for particular aspects. That way there should be no argument. Tim Delaney From sandskyfly at hotmail.com Wed Jan 21 04:46:12 2004 From: sandskyfly at hotmail.com (Sandy Norton) Date: 21 Jan 2004 01:46:12 -0800 Subject: personal document mgmt system idea References: <87wu7mwu8a.fsf@pobox.com> Message-ID: John J. Lee: > Pybliographer 2 is aiming at these features (but a lot more besides). > Work has been slow for a long while, but several new releases of > pyblio 1 have come out recently, and work is taking place on pyblio 2. > There are design documents on the web at pybliographer.org. Why not > muck in and implement what you want with Pyblio? Thanks for the reference, Pyblio definitely seems interesting and I will be looking into this project closely. cheers. Sandy From aahz at pythoncraft.com Mon Jan 19 00:37:33 2004 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2004 00:37:33 -0500 Subject: Suggested generator to add to threading module. References: <7934d084.0401152058.164a240c@posting.google.com> <7934d084.0401181808.6e698042@posting.google.com> Message-ID: In article <7934d084.0401181808.6e698042 at posting.google.com>, Andrae Muys wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article <7934d084.0401152058.164a240c at posting.google.com>, >> Andrae Muys wrote: >>> >>>Found myself needing serialised access to a shared generator from >>>multiple threads. Came up with the following >>> >>>def serialise(gen): >>> lock = threading.Lock() >>> while 1: >>> lock.acquire() >>> try: >>> next = gen.next() >>> finally: >>> lock.release() >>> yield next >> >> I'm not sure this is generic enough to go in the standard library. >> Usually, I'd recommend that someone wanting this functionality consider >> other options in addition to this (such as using Queue.Queue()). > >I'm curious to know how a Queue.Queue() provides the same >functionality? I have always considered a Queue.Queue() to be an >inter-thread communcation primitive. serialise() (at least the >corrected version discussed later in this thread) is strictly a >synchronisation primitive. Well, yes; Queue.Queue() provides both synchronization *and* data protection. In some ways, it's overkill for this specific problem, but my experience is that there are so many different ways to approach this class of problems and so many ways to screw up threaded applications, it's best to learn one swiss-army knife that can handle almost everything you want to throw at it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From nomail at hursley.ibm.com Wed Jan 28 04:22:00 2004 From: nomail at hursley.ibm.com (Derek Fountain) Date: Wed, 28 Jan 2004 17:22:00 +0800 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Message-ID: <40177f07$0$1730$5a62ac22@freenews.iinet.net.au> > What do you need this for? If you can be more specific, we might be able > to help you a little better. I have a Tcl/Tk script which uses a canvas to graphically represent the data stored in the program. Whenever the data store is updated, a Tcl trace automatically triggers to ensure the graphical display is kept consistent with the data. I was after a simple way to convert the script to Python Tkinter. Without the eqivalent of Tcl traces I'm probably going to have to think about it... ;o) From rleeabc at abcnet.com Thu Jan 8 23:29:46 2004 From: rleeabc at abcnet.com (Ryan Lee) Date: Fri, 9 Jan 2004 04:29:46 -0000 Subject: online literatures Message-ID: I have compiled a list of online literatures, mostly related to computing/mathematics/economics stuff, at http://www.srcf.ucam.org/~dl276/bookmarks.php Comments and additions are welcome! Ry From peter at engcorp.com Fri Jan 16 08:59:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Jan 2004 08:59:18 -0500 Subject: do loop References: <3064b51d.0401160536.5d80fa97@posting.google.com> Message-ID: <4007EE36.35A586CB@engcorp.com> beliavsky at aol.com wrote: > > In a Python 'for' loop, one can change the value of looping variable, > so that > > for i in range(3): > i = i*5 > print i > > is legal code > > In Fortran 90 and 95, the analogous code > > do i=0,2 > i = i*5 > print*,i > end do > > is illegal, because variable 'i' cannot be changed inside the loop. > The constraint of not allowing the loop variable to change within the > body of the loop can prevent errors in logic when the body of the loop > is large. > > Is there a way to write a loop in Python that enforces this > constraint? Should such functionality be added to the language? No, absolutely not. I don't believe this is a common error, and in fact sometimes even in e.g. FORTRAN or BASIC you *wanted* to change the loop variable to affect the sequence. In any case Python's typical approach to such things is to treat the programmer as an adult. Note that in Python you can trust that such a change will not affect the sequence as it would with some other languages, but if you do *want* to change the loop variable, and have it affect the sequence, you can use a while loop instead. -Peter From dialtone#NOSPAM#.despammed at aruba.it Fri Jan 16 14:25:39 2004 From: dialtone#NOSPAM#.despammed at aruba.it (Valentino Volonghi aka Dialtone) Date: Fri, 16 Jan 2004 20:25:39 +0100 Subject: Printing to console (No Scroll) References: Message-ID: <87n08nvgp8.fsf@vercingetorix.caesar.org> "Totte Karlsson" writes: > Any alternatives to ncurses? It seems like a overkill for this... import sys, time nrchars = 0 for i in xrange(10): sys.stdout.write("\b \b"*nrchars) sys.stdout.flush() Str = "%i seconds to go" % (10-i) nrchars = len(Str) sys.stdout.write(Str) sys.stdout.flush() time.sleep(1) print -- Valentino Volonghi, Regia SpA, Milan Linux User #310274, Gentoo Proud User From nid_oizo at yahoo.com_remove_the_ Mon Jan 12 17:13:27 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 12 Jan 2004 17:13:27 -0500 Subject: How to know if a system command doesn't exist? In-Reply-To: <87r7y450l9.fsf@pobox.com> References: <8KzMb.1701$PK6.16708@nnrp1.uunet.ca> <87r7y450l9.fsf@pobox.com> Message-ID: John J. Lee wrote: > Nicolas Fleury writes: > >>Nicolas Fleury wrote: > > [...] > >>> How can I know if a system command doesn't exist? All the ways >>>I have tried behave like if the system command was existing but >>>returning one. I don't want to sound provocative, but open in Perl > > [...] > > Haven't tried popen(), but I assume C's system() (of which os.system() > is a trivial wrapper, on posix-y OSes) is implemented in terms of > popen() (or both are implemented in terms of similar lower-level > stuff). I get different return codes from system() depending on > whether the program exists or not, as expected: It doesn't behave like that on Windows... the return value is 1 weither it's the return value of the command executed of if this command doesn't exist. What would be nice, I think, would be to encapsulate the difference, and raise an exception if the command doesn't exist. That might implies additional code for Windows, but in the end the python code would be more portable. Regards, Nicolas From dw-google.com at botanicus.net Sat Jan 24 15:09:54 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 24 Jan 2004 12:09:54 -0800 Subject: Apache: mod_python References: Message-ID: <99dce321.0401241209.3f304a61@posting.google.com> "Tim Adler" wrote... > Still when I access a given .py file (the one that ViewCVS > suggests), I get an 500-error and the Apache states in the error.log that it > cannot import a "mod_python.apache".Can somebody help me ?Thx, Tim Did you follow the mod_python install instructions to the letter? The above suggests an incomplete install. Failling that, have you manually upgraded Python on the machine? mod_python may be linked against one version of Python, but may have it's package installed in the library directory of another. HTH, David. From __peter__ at web.de Tue Jan 27 10:37:54 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Jan 2004 16:37:54 +0100 Subject: Problem with RE matching backslash References: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> Message-ID: Ladv?nszky K?roly wrote: > What is the correct way to match/search a backslash with regular > expressions? > > print re.match('\\m', '\\m').group(0) raises an error while > print re.search('\\m', '\\m').group(0) yields 'm' > > print re.search('\\m', '\m').group(0) yields 'm' > print re.search('\\m', 'm').group(0) yields 'm' > > Any helpful comment on this would be appreciated, The backslash must be escaped twice: once for the Python string and once for the regular expression: >>> print re.match("\\\\m", "\\m").group(0) \m You can use raw strings to somewhat reduce the number of backslashes (but beware of backslashes at the end of the string literals): >>> print re.match(r"\\m", r"\m").group(0) \m Peter From peter at engcorp.com Tue Jan 13 10:48:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jan 2004 10:48:01 -0500 Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> <4002AE9B.C51448FB@engcorp.com> Message-ID: <40041331.1835CD27@engcorp.com> Frithiof Andreas Jensen wrote: > > "Peter Hansen" wrote in message > news:4002AE9B.C51448FB at engcorp.com... > > > ...., as it takes me only about twenty seconds to start a > > new test file and that's *without* using a template. > > ....in twenty seconds you can just about write "import unittest" ;-) You don't know how fast I type. ;-) import unittest class TestCase(unittest.TestCase): def test01(self): pass if __name__ == '__main__': unittest.main() == 23 seconds... counting launching Scite! I agree with all your other points though. -Peter From rimbalaya at yahoo.com Tue Jan 27 10:00:23 2004 From: rimbalaya at yahoo.com (Rim) Date: 27 Jan 2004 07:00:23 -0800 Subject: print format for binary representation Message-ID: <6f03c4a5.0401270700.713a73aa@posting.google.com> Hi, >>> print '%x' % 54 36 >>> print '%b' % 54 Traceback (most recent call last): File "", line 1, in ? ValueError: unsupported format character 'b' (0x62) at index 1 >>> No formating string for binary? There %x for hex. Would %b make sense for bin? Is this worth a PEP? How do I get 00110110 printed instead of the traceback? Thanks, -Rim From swalters_usenet at yahoo.com Mon Jan 5 18:06:55 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 23:06:55 GMT Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> Message-ID: |Thus Spake Peter Hansen On the now historical date of Mon, 05 Jan 2004 17:43:15 -0500| > Well, *almost* any whitespace. :-) > >>>> import string >>>> string.whitespace > '\t\n\x0b\x0c\r ' > > Of those, only '\t' and ' ' are going to be much help, I think, when > trying to indent. Linefeed, carriage return, vertical tab, and form > feed are most likely not well supported yet. ;-) What exactly *is* a vertical tab? I don't think I've ever seen it on a keyboard or used in the wild. I think I may have seen it on the keybindings for a mainframe terminal I once used, but I didn't really dig too deep because, as far as operating the mainframe was concerned, I was a well trained monkey who could check and restart failed jobs. Inquiring minds want to know. Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From fuf at mageo.cz Thu Jan 29 04:50:50 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Thu, 29 Jan 2004 10:50:50 +0100 Subject: C API: how to tell if x is a new style instance? In-Reply-To: <401821E2.1070106@rogers.com> References: <20040128184040.GD11485@foof.i3.cz> <401821E2.1070106@rogers.com> Message-ID: <20040129095050.GA27902@foof.i3.cz> Mike C. Fletcher wrote: >Well, I don't actually know how to check for the spiritual state of a >new-style class, but here's how to tell if an instance is an instance of >a new-style class: > > * Note that a new-style class is a sub-class of type, while > old-style classes are not > * Check if isinstance( instance.__class__, type ) > * ahh - it helped. thank you! but, so it means that PyType_Check() doesn't work for new style classes' instances? it returns 0 but i understood from the documentation that it should return 1: """ int PyType_Check(PyObject *o) Returns true if the object o is a type object, including instances of types derived from the standard type object. Returns false in all other cases. """ -- fuf (fuf at mageo.cz) From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Jan 30 16:17:20 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 30 Jan 2004 22:17:20 +0100 Subject: Tcp/ip programs in python In-Reply-To: References: Message-ID: <401ac9e0$0$314$e4fe514c@news.xs4all.nl> M.Dikmen wrote: > Do you now a source about socket programming in python? or some source > codes, demo programs? i really need them What do you want to achieve using socket communication? If it is IPC (inter-process-communication) and your other party is also a Python program, consider Pyro: http://pyro.sourceforge.net You don't have to write a single line of gory network/socket code, with a few lines you can call Python objects on other machines. --Irmen From claird at lairds.com Fri Jan 23 13:04:12 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 23 Jan 2004 18:04:12 -0000 Subject: Tkinter color names/codes References: <1012mti57i1nsa5@corp.supernews.com> Message-ID: <1012ogslk3vo456@corp.supernews.com> In article <1012mti57i1nsa5 at corp.supernews.com>, I confused matters with: . . . > >>> import Tkinter > >>> l = Tkinter.Label() > >>> l.winfo_rgb("red") > (65535, 0, 0) . . . Ugh. I'm revealing a bad habit I acquired in my Python childhood. What I *should* have suggested was import Tkinter Tkinter.Tk().winfo_rgb("cyan") The Label() and l chatter was just a distraction, for which I apologize. -- Cameron Laird Business: http://www.Phaseit.net From dortmann at lsil.com Tue Jan 20 15:25:09 2004 From: dortmann at lsil.com (Daniel Ortmann) Date: 20 Jan 2004 14:25:09 -0600 Subject: an example of a singleton design pattern in python? Message-ID: Hello, Does anyone have an example of a singleton design pattern in python? Thanks! -- Daniel Ortmann, LSI Logic, 3425 40th Av NW, Suite 200, Rochester MN 55901 work: Daniel.Ortmann at lsil.com / 507.535.3861 / 63861 int / 8012.3861 gdds home: ortmann at venturecs.net / 507.288.7732, 2414 30Av NW #D, Rochester MN 55901 gpg/pgp public key: http://wwwkeys.us.pgp.net jabber: daniel_ortmann at jabber.org / dortmann at jabber.co.lsil.com From jjl at pobox.com Sat Jan 17 15:29:42 2004 From: jjl at pobox.com (John J. Lee) Date: 17 Jan 2004 20:29:42 +0000 Subject: Python class derived from a C++ base class References: Message-ID: <878yk6tj2h.fsf@pobox.com> devrim at machsim.com (Devrim Erdem) writes: [...] > I would like to allow writing plugins also in python. It is very > comfortable if the plugin developer could derive a python class from > the C++ base class. > > I am not well educated to think an elegant and a robust way to do > this. http://www.boost.org/libs/python/doc/ John From theller at python.net Mon Jan 19 05:05:54 2004 From: theller at python.net (Thomas Heller) Date: Mon, 19 Jan 2004 11:05:54 +0100 Subject: Retrive unicode keys from the registry References: <1xpzaa8i.fsf@python.net> <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> <40086EE5.7020708@v.loewis.de> Message-ID: "Martin v. L?wis" writes: > Neil Hodgson wrote: >> The documentation for RegQueryValue says: >> """ Unicode: Implemented as Unicode and ANSI versions. Note that Unicode >> support on Windows Me/98/95 requires Microsoft Layer for Unicode. """ > > Too bad. Perhaps we should link Python with MSLU? I don't know how to interpret the license that's contained in unicows.exe. REDIST.TXT is this: =============================================== Microsoft Layer for Unicode on Windows 95/98/ME =============================================== In addition to the rights granted in Section 1 of the Agreement ("Agreement"), with respect to UNICOWS.DLL, you have the following non-exclusive, royalty free rights subject to the Distribution Requirements detailed in Section 1 of the Agreement: (1) You may distribute UNICOWS.DLL with the following: Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium, Windows NT4, Windows 2000, Windows XP, and Windows Server 2003. Since we're not distributing windows ;-) I don't know what this means. And LICENSE.TXT contains this: * Distribution Terms. You may reproduce and distribute an unlimited number of copies of the Sample Code and/or Redistributable Code (collectively "Redistributable Components") as described above in object code form, provided that (a) you distribute the Redistributable Components only in conjunction with and as a part of your Application solely for use with a Microsoft Operating System Product; [...] (c) you distribute your Application containing the Redistributable Components pursuant to an End-User License Agreement (which may be "break-the-seal", "click-wrap" or signed), with terms no less protective than those contained herein; (d) you do not permit further redistribution of the Redistributable Components by your end-user customers; (e) you do not use """ Thomas From ma at Bell.com Thu Jan 1 23:17:37 2004 From: ma at Bell.com (xam) Date: Fri, 02 Jan 2004 04:17:37 GMT Subject: botlib Message-ID: I am using botlib (found an old copy @http://web.archive.org/web/20010804124140/http://www.linkwatcher.com/src/bo tlib.py no new ones seem to be posted), particularly the Multibot class to fetch multiple groups of URLs in a loop. I found that my app would occasionally get stuck in a forever loop, and I think this is due to the fact that Multibot waits for all the Unibots to return successfully in a loop, and if a socket gets 'broken' somehow this will get the loop stuck. As this is sort of a general asyncore error-handling issue, could someone offer advice? thanks, max From usenet_spam at janc.invalid Sat Jan 31 00:08:51 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 31 Jan 2004 05:08:51 GMT Subject: easiest transition for a PHP website to move to Python? References: <6ee58e07.0401300555.12c07aa3@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) schreef: > Most important, what can you use ? > If you are independ, this means have your own dedicated or virtual > server, AFAIK Python Baby has his own HostBaby... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From news at badblocks.de Sat Jan 31 14:08:31 2004 From: news at badblocks.de (Walter Haslbeck) Date: Sat, 31 Jan 2004 20:08:31 +0100 Subject: problem with weakref.proxy References: Message-ID: Peter Otten <__peter__ at web.de> wrote: > I'd recommend being lazy and using a WeakValueDictionary instead of building > the machinery on your own. Your code would then look similar to the > following: thanks for the tip, but: [...] > def c_show_all(): > print "all GObs, sorted by priority:" > values = GOb.all.values() > values.sort() [...] I don't want the list to be sorted in the method c_show_all, but when a new instance is created. Sort a list is an expensive operation, and c_show_all will be called on every game frame, but new objects are created much less. Walter From skip at pobox.com Sat Jan 10 17:25:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 16:25:59 -0600 Subject: Emacs python mode question In-Reply-To: References: Message-ID: <16384.31735.520343.772245@montanaro.dyndns.org> jb> gogo-line is on the menu but is not bound to a key. How can I bind jb> it? M-x global-set-key RET should do the job interactively. In your ~/.emacs file use something like: (define-key esc-map [g] 'goto-line) YMMV. I don't use GNU Emacs anymore. Keybindings is one area in which Emacs and XEmacs have diverged. Try C-h f define-key RET. Skip From michele.simionato at poste.it Mon Jan 19 03:02:12 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Jan 2004 00:02:12 -0800 Subject: circular dependency between class and its metaclass References: Message-ID: <95aa1afa.0401190002.4a21f927@posting.google.com> Stefan Seefeld wrote in message news:... > hi there, > > I'v run into a little problem for which I only found an ugly workaround, > so I'd like to know whether people are aware of better ways to achieve this... > > I'm defining a class 'Class' for which I want to set up a __metaclass__ 'Type' > which does some work on class variables. In particular, it should apply > a function on all base classes that are themself derived from 'Class'. > > My first try was: > > ==== > > class Class(object): > > class Type(type): > > def __init__(cls, name, bases, dict): > > hierarchy = list(filter(lambda i:issubclass(i, Class), bases)) > # do something with the hierarchy here > > __metaclass__ = Type If "i" is a subclass of Class, then it is an instance of Type: this means that you can write class Type(type): def __init__(cls, name, bases, dict): hierarchy = [i for i in bases if isinstance(i, Type)] # I like list comprehension... class Class(object): __metaclass__ = Type Is this nice enough for you? Michele Simionato From pinard at iro.umontreal.ca Tue Jan 20 22:15:18 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 20 Jan 2004 22:15:18 -0500 Subject: Pyrex without Python (was Re: calling Pyrex results from C) In-Reply-To: <400DD5DE.90405@prescod.net> References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> Message-ID: <20040121031518.GA23308@alcyon.progiciels-bpi.ca> [Paul Prescod] > Jeff Epler wrote: > >How close to impossible would it be to make Pyrex emit Python-free code > >if there are only 'cdefs'? > It will generate a bunch of Python module crap. You could extract the > pure-C code from the middle of it. Or just provide a module containing many stub routines. > I really don't see much benefit to using Pyrex if even _C_'s standard > memory management is too extravagant for your needs. What exactly > would Pyrex buy you if you can't afford to use its high-level features > like memory management, constructors and OO? The pleasure of Python-like syntax, of course. Maybe the fact that one can build and debug prototypes in Python, with the agenda of later transforming them into C, somehow, without rewriting so much of them, for environments where the whole of Python, for various reasons, is not welcome. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From eurleif at ecritters.biz Thu Jan 22 17:53:04 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 22 Jan 2004 22:53:04 GMT Subject: strtotime? Message-ID: PHP has a very nice strtotime function (http://php.net/strtotime) which converts a date/time in virtually any format into a timestamp. Does Python have a similar function? From rmkrauter at yahoo.com Sat Jan 24 22:25:59 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sat, 24 Jan 2004 22:25:59 -0500 Subject: Newbie Nested Function Problem In-Reply-To: References: Message-ID: <1075001159.4056.3.camel@vaio> Looks like you are setting the variable 'leave' to the user input, and then you are calling the function leave(), but remember that 'leave' has been set to some string. So say you enter 'xqz', and expect it to restart the loop when you get to the leave call --- well, what you are doing is trying to call the function xqz(). Rich On Sat, 2004-01-24 at 21:45, Brian Samek wrote: > I began learning python a few days ago and just wrote the following program. > I have nested three functions together. For some reason, the leave function > works fine when 'y' or 'n' are inputted, but it does not restart itself when > other things are inputted. Why is this? > > Thanks, > > Brian Samek > > # Brian Samek > # Created 01/24/2004 > > # This program counts down from a user-defined integer less than or equal > # to 500. > > print "This program counts down from any number less than or equal to 500" > print > > # ask_number gets the number from the user and then puts it into countdown > > def ask_number(): > number = input("Please enter a number.\n") > if number > 500 or number - int(number) != 0 or number < 1: > print "Input positive integers less then 501 only, please." > ask_number() > else: > # countdown does the actual counting down until 0 > def countdown (number): > if number != 0: > print number > number = number - 1 > countdown (number) > else: > # leave asks the user if he wishes to exit > def leave(): > leave = raw_input ("Type 'y' to start over - type 'n' to > exit. ") > if leave == "y": > ask_number() > elif leave == "n": > return > else: > print "Type either 'y' or 'n' please." > leave() > leave() > countdown (number) > ask_number() > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at visualtrans.de Sat Jan 3 14:14:08 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 3 Jan 2004 20:14:08 +0100 Subject: Py2exe?? Error: Nothing to do? References: <86df8ed4.0401031028.6edf2381@posting.google.com> Message-ID: "Nick" schrieb im Newsbeitrag news:86df8ed4.0401031028.6edf2381 at posting.google.com... | I am trying to turn one of my .py files into an exe and I created a | setup script and everything, but when i do the follwing "python | myscript.py py2exe" I get an error saying Normally you would execute the setup script, not the script you are trying to freeze: "python setup.py py2exe" HTH Vincent Wehren "Error: Nothing to do" I am | using Python 2.3 (not alpha) with the latest binary of py2exe on | windows 98. | | What did i do wrong and how do i fix it, thanks. From python at hitmedia.com Sun Jan 25 16:25:39 2004 From: python at hitmedia.com (Python Baby) Date: Sun, 25 Jan 2004 13:25:39 -0800 Subject: Unique ID for CD or DVD In-Reply-To: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> References: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: <20040125212539.GA76757@mail.hitmedia.com> > Does anyone know of an existing algorithm/module for generating a unique ID > for a given CD or DVD? This would be something akin to CDDB where a CD is > recognized based on its content. There are a few different ways to get a unique ID from an audio CD. Gracenote/CDDB does it one way. FreeDB does it another way. MusicBrainz does it another. Sorry, it's in C not Python, but the author of MusicBrainz wrote us a good tool that we use in our CD store, to generate the unique ID of a CD in the drive. It generates many different fingerprints for the CD in the drive, for you to pick and choose whichever one you want to use: http://hitmedia.com/idgen.tgz (NOTE: that URL won't work forever. I just put it up there right now since you asked.) From martin at v.loewis.de Fri Jan 2 06:39:30 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 02 Jan 2004 12:39:30 +0100 Subject: finding file size In-Reply-To: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: Sean Ross wrote: > My question is this: Is there a reason why file objects could not have a > size method or property? Yes. In Python, file objects belong to the larger category of "file-like objects", and not all file-like objects have the inherent notion of a size. E.g. what would you think sys.stdin.size should return (which actually is a proper file object - not just file-like)? Other examples include the things returned from os.popen or socket.socket. Regards, Martin From tjreedy at udel.edu Mon Jan 26 16:26:50 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jan 2004 16:26:50 -0500 Subject: Zope References: Message-ID: "lenk" wrote in message news:bv2j13$n4oug$1 at ID-216549.news.uni-berlin.de... > Hi > I installed zope in suse 9.0(own package).but i can t find start to > start the server . > /opt/zope/ ... is it a right path ? > > second problem > Can you give an web example for python (forum,gueastbook ...) > links pls:) zope is an independently written and distibuted application written in Python with its own mailing lists. If you do not get the answer you want here, try them instead. tjr From zunbeltz at wm.lc.ehu.es.XXX Thu Jan 15 03:19:14 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 15 Jan 2004 09:19:14 +0100 Subject: More than one python in a linux Message-ID: Hi, I've build and installed python 2.2 and python2.3 in a linux box. Now i want to install some packages (Numeric, wxPython and scipy). I've install Numeric and wxPython for python2.3 without problem (python2.3 setup.py install ... and so on). But when I try python2.2 setup.py install I get the following error (for wxpython) running build_py copying wxPython/__version__.py -> build/lib.linux-i686-2.2/wxPython running build_ext error: invalid Python installation: unable to open /usr/lib/python2.2/config/Makefile (No such file or directory) and (for numeric something similar) Traceback (most recent call last): File "setup.py", line 195, in ? ext_modules = ext_modules File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/core.py", line 138, in setup File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/dist.py", line 893, in run_commands File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/dist.py", line 912, in run_command File "/usr/lib/python2.2/cmd.py", line 112, in ensure_finalized line = self.cmdqueue[0] File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/command/install.py", line 267, in finalize_options File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/sysconfig.py", line 421, in get_config_vars File "/var/tmp/python-2.2.2-build//usr/lib/python2.2/distutils/sysconfig.py", line 326, in _init_posix distutils.errors.DistutilsPlatformError: invalid Python installation: unable to open /usr/lib/python2.2/config/Makefile (No such file or directory) Any idea about what can I do? Thaks in advance Zunbeltz -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From mensanator at aol.compost Thu Jan 15 01:16:50 2004 From: mensanator at aol.compost (Mensanator) Date: 15 Jan 2004 06:16:50 GMT Subject: Python bindings for the Gnu Multiprecision library References: <5eb8fb88.0401130844.6054b2d7@posting.google.com> Message-ID: <20040115011650.10703.00000052@mb-m13.aol.com> >Subject: Python bindings for the Gnu Multiprecision library >From: rick_muller at yahoo.com (Rick Muller) >Date: 1/13/04 10:44 AM Central Standard Time >Message-id: <5eb8fb88.0401130844.6054b2d7 at posting.google.com> > >I just discovered the python bindings for the Gnu Multiprecision >library available at http://gmpy.sf.net. The release notes say that it >only works for Python 2.3, but I successfully got it to work on Python >2.2. Way, way cool. > > >For example, the following is an implementation of the Lucas-Lehmer >test for Mersenne primes: > >def lucas(p): > "Test whether 2^p-1 is a Mersenne prime" > s = 4 > val = pow(2,p)-1 > for i in range(3,p+1): s = (s*s-2)%val > return not s > >Using normal python long integers, this routine is an interesting toy, >but not much else. However, with the gmpy libraries, you can grind >away until your Powerbook G4 burns your lap: > >def lucas_gmp(p): > "Test whether 2^p-1 is a Mersenne prime" > from gmpy import mpz > s = mpz('4') > val = pow(2,p)-1 > for i in range(3,p+1): s = (s*s-2)%val > return not s > >Way to go, Alex and Gustavo (and anyone else involved)! The other day I was reading about Linear Congruence on Mathworld. Naturally, Mathworld tells you how to solve these problems using Mathematica functions. Not having Mathematica, I looked through GMPY to see if it had something I could use instead and sure enough, there it was gmpy.divm(a,b,m): returns x such that b*x == a (mod m) A single function call saved me from having to iterate through 617 trillion numbers. It's a great package. -- Mensanator Ace of Clubs From __peter__ at web.de Sun Jan 25 14:12:17 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Jan 2004 20:12:17 +0100 Subject: xrange not hashable - why not? References: Message-ID: Gerrit Holl wrote: > I was trying to do something like: > > comments = { > xrange(0, 4): "Few", > xrange(4, 10): "Several", > xrange(10, 100): "A lot", > xrange(100, sys.maxint): "Can't count them"} > for (k, v) in comments.items(): > if n in k: > commentaar = v > break [...] > So, should I use one of the alternatives after all? Or does someone have > something better to offer? I think you want bisect(): import bisect ranges = [ (0, "Few"), (4, "Several"), (10, "A lot"), (100, "Can't count them") ] def makelookup(r): bounds = [i[0] for i in r][1:] names = [i[1] for i in r] def find(value): return names[bisect.bisect(bounds, value)] return find lookup = makelookup(ranges) # use it last = "" for i in range(-100, 1000): if last != lookup(i): last = lookup(i) print i, last Note that names needs one more entry than bounds. I "fixed" that by discarding the first bounds item. Peter From fnord at u.washington.edu Sat Jan 3 22:59:07 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 3 Jan 2004 19:59:07 -0800 Subject: Python as a numerical prototyping language. References: <67n0966wsz.fsf@aster.homelinux.net> Message-ID: Johannes.Nix wrote in message news: > > One point about Matlab: The basic Matlab is _expensive_. But in a > commercial environment Matlab with signal processing extensions costs > _tens of thousands of dollars_. If I were founding an engineering > startup, I would avoid Matlab if possible at all. Absolutely. About a year ago, I attempted to answer the question "Can Python replace Matlab?" for my workplace. The conclusion was "Not quite yet", for two reasons. The first was purely human: Matlab is entrenched, and there's always resistance to change (note: lots of people here still swear by Fortran '77). The second reason: there's no unified Python environment that gives you easy access to plotting capability and an interpreter, a la Matlab. Python has the ability to do everything Matlab can (and much more!) but it still requires just enough expertise to find, install, and learn the various scipy and plotting modules that only the early-adopter types are willing to do it. Matlab projects around here have a tendency to start as a few .m scripts, and to eventually mature into some kind of end-user application complete with a simple GUI. This is where Python really outshines Matlab: Tkinter and wxPython are far superior to the GUI library that's built into Matlab, and the OO nature of Python makes these more sophisticated applications much easier to develop and maintain. From gerrit at nl.linux.org Fri Jan 23 07:22:00 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 23 Jan 2004 13:22:00 +0100 Subject: What is object() In-Reply-To: References: <10105gchtsl1a21@news.supernews.com> Message-ID: <20040123122200.GB2914@nl.linux.org> Aahz wrote: > >Unless, of course, you're using the __new__() method. > > "Not much" != "none" ;-) "Not much" >= "none" ;-) Because none is not much ;-) yours, Gerrit. -- 211. If a woman of the free class lose her child by a blow, he shall pay five shekels in money. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From ralph at sluiters.de Tue Jan 6 05:07:45 2004 From: ralph at sluiters.de (Ralph Sluiters) Date: Tue, 6 Jan 2004 11:07:45 +0100 Subject: Problem: 'Threads' in Python? References: Message-ID: > Wouldn't a better approach be to decouple the cache mechanism from the cgi > script? Have a long-running Python process act as a memoizing cache and > delegate requests to the slow function. The cgi scripts then connect to > this cache process (via your favorite IPC mechanism). If the cache process > has a record of the call/request, it returns the previous value immediately, > and updates its cache in the meantime. If it doesn't have a record, then it > blocks the cgi script until it gets a result. The caching can not be decoupled, because the cgi-script gets an folder ID gets only data from this "folder". So if I decouple die processes, I don't know which folders to cache and I can not cache all folders, because the routine is to slow. So I must get the actual folder from cgi and then cache this one as long as the uses is in this folder and pulls data every 2 Minutes and cache another folder, if the uses changes his folder. > How can threading help you if the cgi-process dies after each request unless > you store the value somewhere else? And if you store the value somewhere, > why not have another process manage that storage? If it's possible to > output a complete page before the cgi script terminates (I don't know if the > server blocks until the script terminates), then you could do the cache > updating afterwards. In this case I guess you could use a pickled > dictionary or something as your cache, and you don't need a separate > process. But even here you wouldn't necessarily use threads. The data is to large to store it in the memmory and with this method, as you said, threading wouldn't help, but I store the data in the disk. My code: #Read from file try: oldfile = open(filename,"r") oldresult =string.joinfields(oldfile.readlines(),'\r\n') oldfile.close() except: # Start routine oldresult = get_data(ID) # Get xml data # Print header, so that it is returned via HTTP print string.joinfields(header, '\r\n') print oldresult # *** # Start routine result = get_data(ID) # Get xml data #Save to file newfile = open(filename, "w") newfile.writelines(result) newfile.close() #END At the position *** the rest of the script must be uncoupled, so that the client can proceed with the actual data, but the new data generation for the next time ist stored in a file. Ralph From salgado at freeshell.org Sat Jan 24 20:49:04 2004 From: salgado at freeshell.org (Guilherme Salgado) Date: Sat, 24 Jan 2004 23:49:04 -0200 Subject: trouble w/ unicode file Message-ID: <1074995344.17782.16.camel@maluf.alcatraz> Hi there, I have a python source file encoded in unicode(utf-8) with some iso8859-1 strings. I've encoded this file as utf-8 in the hope that python will understand these strings as unicode () strings whithout the need to use unicode() or u"" on these strings. But this didn't happen. Am I expecting something that really shoudn't happen or we have a bug? This is the test i've made: $cat bar.py #-*- coding: utf-8 -*- x = '????????????' print x, type(x) $python Python 2.3.3 (#2, Jan 4 2004, 12:24:16) [...] >>> import bar ???????????????????????? Thanks in advance, []'s Guilherme Salgado -- This email has been inspected by Hans Blix, who has reported that no weapons of mass destruction were used in its construction. Read his report here: From tchur at optushome.com.au Tue Jan 13 00:02:09 2004 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 13 Jan 2004 16:02:09 +1100 Subject: Accessing "GIS (ESRI shape file)" files from Python ? Message-ID: <200401130502.i0D529119803@mail005.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From dave at pythonapocrypha.com Fri Jan 23 11:40:28 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 23 Jan 2004 09:40:28 -0700 Subject: File Install Program Using Python? References: <1012ij4idech2d6@corp.supernews.com> Message-ID: <01eb01c3e1cf$9c0e0430$6401fea9@YODA> CB Hamlyn wrote: > Hello, I'm currently working on a Modification for the PC game Battlefield > 1942. I'm a pretty good VBA Programmer with some Foxpro under belt as well. > After reading a ton of stuff on-line I'm simply floored by everything Python > has to offer. > > Anyway, I want to create an installation program that takes a folder and all > it's sub-folders and copies them from a compressed form into the proper > directory. Basically a simplified version InstallSheild or whatever. > > I assume Python is capable of such a feat and I'm wondering if anyone can > spin me around, point me in the right direction and shove me toward my goal. It's definitely possible, but are you more interested in doing it for your own educational purposes or for getting the job done? If it's the latter then free installers like InnoSetup and the WinAmp installer will save you a lot of time since they already work well. If you just want to do this to learn more, then look into the ZipFile class in the zipfile module for starters. You can add a lightweight GUI using Mark Hammond's win32 extensions or Venster, and finally convert it into an executable with py2exe or one of the other packagers out there. -Dave From lubowiecka at go2.pl Mon Jan 26 10:28:31 2004 From: lubowiecka at go2.pl (Ringwraith) Date: Mon, 26 Jan 2004 16:28:31 +0100 Subject: python service running on Win Xp, but failing on Win NT Workstation :( Message-ID: Hello! I have implemented a Windows Service in Python. It works on Windows XP properly and logs in Event Viever any 'started' or "stopped" events. The problem appeared when I tried to start it on Windows NT Workstation. The following error entry appeared in Event Viewer while starting it. "The Purge Log Files Service service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion. Timeout (120000 milliseconds) waiting for service to connect. " Any ideas what could caused the problem? I can send the code if necessary. Thank you in advance, Nazgul From zunbeltz at wm.lc.ehu.es.XXX Fri Jan 16 03:31:31 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 16 Jan 2004 09:31:31 +0100 Subject: More than one python in a linux References: Message-ID: cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > You probably don't have the development package for python2.2 > installed (python2.2-dev or python2.2-devel or something). > You are right! I've installed it and it semms that now all goes well. Thanks. Zunbeltz > -- > |>|\/|< > /--------------------------------------------------------------------------\ > |David M. Cooke > |cookedm(at)physics(dot)mcmaster(dot)ca -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From patricklcam at yahoo.com Tue Jan 13 21:07:20 2004 From: patricklcam at yahoo.com (Pat Campbell) Date: 13 Jan 2004 18:07:20 -0800 Subject: Python & Netware Message-ID: <7b4a9738.0401131807.4589ca74@posting.google.com> Hi, Awhile back Jeff Davey posted a query about Python issues with NetWare. Wonder if the issues were solved and if the NetWare port might be made available? Thanks in advance Pat From vsamarsk at oz.net Thu Jan 15 00:56:49 2004 From: vsamarsk at oz.net (vsamarsk at oz.net) Date: Wed, 14 Jan 2004 22:56:49 -0700 (MST) Subject: Where *.pth files should be located in MacPython2.3? Message-ID: <3340.4.63.89.150.1074146209.squirrel@www.oz.net> Does anyone know where do I place my *.pth into Mac Python2.3 to specify access path to my modules? Thanx Vladimir From swalters_usenet at yahoo.com Thu Jan 15 23:47:09 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 16 Jan 2004 04:47:09 GMT Subject: python & mathematical methods of picking numbers at random References: Message-ID: | Bart Nessux said | > I am using method 'a' below to pick 25 names from a pool of 225. A > co-worker is using method 'b' by running it 25 times and throwing out the > winning name (names are associated with numbers) after each run and then > re-counting the list and doing it all over again. > > My boss thinks that 'b' is somehow less fair than 'a', but the only thing > I see wrong with it is that it is really inefficient and ugly as it's > doing manually what 'a' does automatically, other than that I think the > outcome of both methods (25 unique winners from a pool of 225) are the > same. Anyone disagree with that and if so, please demonstrate how 'b' > isn't as fair as 'a' > > count = len(list_of_potential_winners) > > a = random.sample(range(count), 25) > > b = random.sample(range(count), 1) > > Thanks! > Bart I looked at the code for random.sample, and found out that the two methods are probabilistically equivalent. Neither is more or less fair than the other. You can, however, poke fun at your cow-orker for using random.sample(range(count, 1) when random.randint(1,count) would have done the exact same thing with the way he used random.sample. HTH Sam Walters. P.S. The code for sample in random.py is very simple and fairly straightforward. You should take a peek at it. The basic algorithm is to make a list of winners, choose a random number, then if the winner is not already in the list, add them. If the winner is already in the list, retry until a new winner comes up. Repeat until you have the desired number of winners. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From mcfletch at rogers.com Fri Jan 9 15:14:03 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 15:14:03 -0500 Subject: Problem with OpenGL.GLUT In-Reply-To: References: <7447dd2a.0401071402.2c0737e6@posting.google.com> Message-ID: <3FFF0B8B.4050208@rogers.com> Cousin Stanley wrote: >Steven .... > > I'm also having import problems > with a Win98 installation of PyOpenGL for Python 2.3 > from .... > > ... >Using < dependency walker > to examine .... > > /site-packages/OpenGL/GLUT.pyd > >shows .... glut32.dll * Not Found * > > PyOpenGL doesn't include the actual GLUT library, just a wrapper around it (most systems already have GLUT installed these days). You can find a link for GLUT for win32 here: http://pyopengl.sourceforge.net/documentation/installation.html (look for "Win32 binary package" under GLUT 3.7+). >I've done a few searches on Google, >but as yet haven't turned up what >seems to be a compatible version >of this particular missing DLL file .... > >Hopefully, someone here might know >how to resolve this .... > > HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From reneaguirre at yahoo.com Thu Jan 29 16:16:01 2004 From: reneaguirre at yahoo.com (Rene Aguirre) Date: 29 Jan 2004 13:16:01 -0800 Subject: Strange wxChoice.FindString behavior Message-ID: <18e22d94.0401291316.afb3dae@posting.google.com> Hello everybody, I had this problem using the FindString funcion of a wxChoice object on wxPython: * I have Windows 98 * I read a text file edited on a Japanese computer, but only uses 'english' characters. * From the file I loaded some strings in some wxChoice object. * Later when I wanted to find an string using 'FindString' I never got a match, even when I say my string, I printed both strings and look same!, same lenght, same internal coding, so the only way to find my string is by using: ## my own Find string function, choice is a wxChoice object def FindString(choice, thestring): for i in range(choice.GetCount()): txta = choiceDevice.GetString(i) if len(txta) != len(thestring): continue if map(ord, txta) != map(ord, thestring): continue return i #we have a match return -1 #not found So this is my best solution to something I think should not happen. Any comments?. Rene From skip at pobox.com Wed Jan 14 12:02:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 11:02:17 -0600 Subject: passing callback function to c-extension In-Reply-To: References: Message-ID: <16389.30233.978705.485655@montanaro.dyndns.org> Diez> I'm now looking for a way to ensure that the passed object is Diez> actually a callable one Try it and see. If an exception is raised, just return NULL. The appropriate exception stuff will have been set. Alternatively, you can test the value of PyCallable_Check(obj) to see if obj is really callable and do your own error recovery. - and how to throw exceptions. The C API manual is your friend here: http://www.python.org/doc/api/api.html Search for "exception". Skip From mir4uu at yahoo.com Tue Jan 20 11:18:21 2004 From: mir4uu at yahoo.com (mir nazim) Date: 20 Jan 2004 08:18:21 -0800 Subject: Python database References: Message-ID: <425cc8d1.0401200818.39bf1452@posting.google.com> brice.vissiere at costes-gestion.net (Brice Vissi?re) wrote in message news:... > Hi python friends, > > I'm currently working on a data handling tool. > > For internal storage, I'm looking for a 100% python database. > > I have some constraints: > + multi-platform > + relational with built-in query system (SQL preferably) > + built-in string functions > + reliable > + fast > > I don't care about: > + network access > + concurracy control > + transaction commit/rollback > > One of the key feature I'm looking for is direct string handling in > queries: concatenation, substring extraction, stripping, justifying, > ... all we can do with python strings. > > My first thought was to use Gadfly. I've downloaded and installed it. > Now, I'm investigating the documentation and examples to find string > capabilities of Gadfly, but at first look, it seems that it will not > fit to my needs. > > My problem would be solved by using a database allowing user function > creation, but I don't know whether such a tool exists. > > So, have you any idea of a db tool I should use ? > > Thanks in advance. > > Brice Did u try KirbyBase. I do not know about it all features but it is implemented in pure python www.netpromi.com/kirbybase From rroberts at adobe.com Mon Jan 12 12:17:48 2004 From: rroberts at adobe.com (Read Roberts) Date: Mon, 12 Jan 2004 09:17:48 -0800 Subject: Help in unwrapping a PyObject* returned by an embedded Python function In-Reply-To: <200401120930.i0C9UTmq032356@se-126.se.wtb.tue.nl> References: <200401120930.i0C9UTmq032356@se-126.se.wtb.tue.nl> Message-ID: Thank you taking the time to read and reply. In fact, I did try all combinations of in the Python call-back function : return myString return (myString) and, in the C calling function, PyArg_ParseTuple(pyStringResult, "s", myString) PyArg_ParseTuple(pyStringResult, "(s)", myString) Also, the Python documentation (and other working code examples I have) indicate that 'PyArg_ParseTuple', unlike BuildValues, always assumes the arguments are supplied in a argument tuple, even if there is only one argumen. I speculate that an argument list object, as required by PyArg_ParseTuple, is not in fact a simple tuple., and that PyArg_ParseTuple cannot be used to parse a regular tuple. Any idea if this is correct? >In comp.lang.python, you wrote: > >> Why does PyArg_ParseTuple fail to parse a return value which is a tuple? >> >> However, the following does not work: >> from Python callback function: return (myString) >> in calling C function: >> if (!PyArg_ParseTuple(pyStringResult, "s", name)) { >> dbprintf(4, "c: failed to parse return value\n"); >> PyErr_Clear(); >> } >> PyArg_ParseTuple fails, and returns NULL. How come? By the >> documentation, I would think that PyArg_ParseTuple would parse any >> Python tuple object. > >To me "s" looks like you are expecting a string and not a tuple. You can >verify that by seeing what happens if you do 'return "blabla"' instead >of 'return ("blabla",)'. >If that works, I would think that changing the "s" to a tuple (ie >something like "(s)" ) should do the trick. > > > >Albert >-- >Unlike popular belief, the .doc format is not an open publically >available format. -- ----------------------------------------------------------------------------------------- Read K. Roberts rroberts at adobe.com Adobe Systems San Jose TW12 (408)-536-4402 on Weds San Francisco (415) 642-5642 Mon, Tues, Thurs, Fri From H.Duerer at gmx.net Wed Jan 21 11:33:26 2004 From: H.Duerer at gmx.net (Holger Duerer) Date: 21 Jan 2004 16:33:26 +0000 Subject: py2exe error References: Message-ID: <87y8s1qn1l.fsf@Ronaldann.demon.co.uk> >>>>> "Haim" == Haim Ashkenazi writes: Haim> Hi Haim> (complete newbie warning...:) ) Python or internet newbie? Google for 'py2exe "no codec search functions registered"' and click on 'I feel lucky'. Holger From jikosan at myrealbox.com Sun Jan 11 03:37:51 2004 From: jikosan at myrealbox.com (Jikosan) Date: Sun, 11 Jan 2004 08:37:51 GMT Subject: Help with if statement References: Message-ID: Ya, I had mis-read the assignment. The code is fully functional now. If anyone is curious, here it is. import random #import random number generator library import math #import math library file=open('C:\Python\output.txt', 'w') a, b = -1.0, 1.0 #set boundary conditions for N in range(0, 100001, 25): # 100,000 trials at steps of 25 if N == 0: #This corrects for N=0 N = 1 onecheck = 0 for n in range(0,N): #generate (x,y) numbers N times. xrand = random.random() yrand = random.random() x = a * (1.0-(xrand)) + b*(xrand) y = a * (1.0-(yrand)) + b*(yrand) c = math.sqrt(math.pow(x,2.0)+math.pow(y,2.0)) #calculate distance to origin if c < 1: onecheck = onecheck+1 pi = 4.0*(onecheck*math.pow(N,-1)) #This is to calculate P(N), the ratio of points whose #distance is less than 1 to the total number of trials. if pi == 0.0: #This is to prevent 'log 0' errors pi == 1.0 log = str(math.log(N, 10)) file.write(str(math.log(N, 10))) file.write(' ') file.write(str(math.log(pi, 10))) file.write('\n') file.close() From exarkun at intarweb.us Mon Jan 19 23:26:56 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 19 Jan 2004 23:26:56 -0500 Subject: stack-like file object In-Reply-To: <20040119183719.ABC4.JCARLSON@uci.edu> References: <400be8f3_2@nova.entelchile.net> <20040119183719.ABC4.JCARLSON@uci.edu> Message-ID: <20040120042656.GA5184@intarweb.us> On Mon, Jan 19, 2004 at 06:43:14PM -0800, Josiah Carlson wrote: > Rodrigo, > > > I need to implement a stack on a file. > > The idea is to have a big list, and put part of his head on the disk. The > > model of access to the file is like a stack (read in order only the tail, > > write only at the tail). > > How could I create this, knowing that I need to pickle arbritary objects ? > > While I don't condone the use of files as stacks, the below should work > for you. It doesn't reduce in size when an object is removed, but as > long as you don't try to share the stack between processes or threads, > it should work fine. condone v : excuse, overlook, or make allowances for; be lenient with; > [snip - file-based stack implementation] Jp From jsteve17 at tampabay.rr.com Mon Jan 19 09:31:55 2004 From: jsteve17 at tampabay.rr.com (JeffS) Date: Mon, 19 Jan 2004 14:31:55 GMT Subject: Tkinter References: Message-ID: km wrote: > Hi all, > > Is there any good online tutorial which is a good intro for Tkinter > programming in Python ? > > regards, > KM http://www.ferg.org/thinking_in_tkinter/index.html http://www.python.org/doc/life-preserver/index.html http://www.nmt.edu/tcc/help/lang/python/tkinter.html From jjl at pobox.com Sat Jan 3 18:44:01 2004 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2004 23:44:01 +0000 Subject: pickling lambdas? References: <9abf3a27.0401031446.4d73cfb2@posting.google.com> Message-ID: <87oetkppha.fsf@pobox.com> gongli at cutey.com (gong) writes: > i would like to pickle a lambda; according to the library docs in 2.3, > i believe this shouldnt be possible, since a lambda is not a function > defined at the top level of a module (?) Yes. > however, upon google searching for "python lambda pickle" i find 2 > posts, one including gvr, which apparently demonstrate that this was > being attempted and even suggest that it is feasible. has this become [...] No, read it again. What you found was Guido figuring out how to *prevent* people pickling lambdas. Functions are pickled by saving the function name. Lambdas have no function name, so pickle complains if you try to pickle them. John From knoppix at laptop.home.net Sat Jan 10 17:35:19 2004 From: knoppix at laptop.home.net (Knoppix User) Date: Sat, 10 Jan 2004 16:35:19 -0600 Subject: [Newb] Attribute error Message-ID: Hi folks There is obviously something that is escaping me - please help!! I have cut and pasted the relevant portions of text from a script I am writing in my quest to learn the Python. Could someone explain the attribution error to me? See the end of the listing for the error. I have created the Image object(?) as a wx.StaticBitmap, so whazzamatter. Thanks for pointers Steve class GIP(wx.Frame): def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, size = (600, 460)) .... self.Image = wx.StaticBitmap(self, -1, wx.EmptyBitmap(*self.thumbSize), pos = (160,10)) <<<<<<<<<<<<<<<<<<<", line 197, in ? File "/usr/lib/python2.3/site-packages/wxPython/wx.py", line 1951, in __init__ _wxStart(self.OnInit) File "", line 191, in OnInit File "", line 78, in __init__ File "", line 116, in DisplayImg AttributeError: GIP instance has no attribute 'Image' From tchur at optushome.com.au Thu Jan 8 17:10:58 2004 From: tchur at optushome.com.au (Tim Churches) Date: 09 Jan 2004 09:10:58 +1100 Subject: What psyco is goot at [Was: Rookie Speaks] In-Reply-To: References: <3FFC9855.3070901@lawson.com> <3FFC9A22.3020507@lawson.com> Message-ID: <1073599858.1866.66.camel@emilio> On Fri, 2004-01-09 at 05:25, Samuel Walters wrote: > |Thus Spake Jacek Generowicz On the now historical date of Thu, 08 Jan > 2004 11:43:01 +0100| > > > Samuel Walters writes: > > > >> If you'd like to see an example of both the psyco and profile modules > >> in action, let me know and I'll give you some more understandable code > >> that I once wrote to see what types of things psyco is good at > >> optimizing. > > > > I think this is generally interesting, and would be curious to see it, > > if you'd care to share. > > Sure thing. The functions at the top are naive prime enumeration > algorithms. I chose them because they're each of a general "looping" > nature and I understand the complexity and methods of each of them. Some > use lists (and hence linearly indexed) methods and some use dictionary( > and hence are has bound). One of them, sieve_list is commented out because > it has such dog performance that I decided I wasn't interested in > how well it optimized. Out of curiosity I ran your code, and obtained these results: Fri Jan 9 08:30:25 2004 primesprof 23 function calls in 2122.530 CPU seconds ... Fri Jan 9 08:43:24 2004 psycoprimesprof 23 function calls in -3537.828 CPU seconds Does that mean that Armin Rigo has slipped some form of Einsteinian, relativistic compiler into Psyco? I am reminded of the well-known limerick: There once was a lady called Bright, Who could travel faster than light. She went out one day, In a relative way, And came back the previous night. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From swalters_usenet at yahoo.com Thu Jan 8 12:55:04 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Thu, 08 Jan 2004 17:55:04 GMT Subject: Pre-PEP: Dynamically evaluating default function arguments References: Message-ID: |Thus Spake Christos "TZOTZIOY" Georgiou On the now historical date of Thu, 08 Jan 2004 19:19:57 +0200| > So, perhaps we should invent a new reply for all wild ideas about Python > (I've had my share of these :) > > "Thank you for your contribution; your suggestion has been judged worthy > of inclusion in Python 4k. Upload your patch to sf.net as soon as Python > 3k final is released." It might shorten a few discussions. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From jcarlson at nospam.uci.edu Fri Jan 30 15:46:25 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 12:46:25 -0800 Subject: Tcp/ip programs in python In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Fri, Jan 30, 2004 at 06:27:45PM -0000, M.Dikmen wrote: > >>Do you now a source about socket programming in python? or some source >>codes, demo programs? i really need them >> > > > In order of increasing relevance: > > http://www.google.com/ > > http://www.vex.net/parnassus/ > > http://www.twistedmatrix.com/ I always found http://www.python.org/doc/current/lib/module-socket.html to be quite useful for the background and http://www.python.org/doc/current/lib/module-asyncore.html for the actual implementation. - Josiah From robin at jessikat.fsnet.co.uk Wed Jan 21 16:20:53 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 21 Jan 2004 21:20:53 +0000 Subject: Nokia prefers Python Message-ID: This might be the start of a success story. Says Nokia prefers Python! http://www.theregister.co.uk/content/64/35040.html -ringing-ly yrs- Robin Becker From max at alcyone.com Thu Jan 29 21:24:40 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 29 Jan 2004 18:24:40 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <4019C068.9F9DC68F@alcyone.com> Daniel Ehrenberg wrote: > Neither the each function nor the map function were built in (Io has > other mechanisms for that kind of thing, but they are less efficient). > Can anyone show me how to so much as alias "for" to "each" in Python > or allow block syntax at all without hacking the C source code? No, you cannot introduce new special forms (i.e., statement syntax) in Python without modifying the Python interpreter itself. There are two major camps in language design. One says that you should be able to modify the language itself to your will, and the other says that this gets rapidly confusing and you shouldn't. They're simply different camps, and the two camps won't agree. Furthermore, the ability to convert a language from the second camp to the first is not without difficulty; such things usually have to be designed into the language from the scratch, or you end up with a very complicated process of creating hygienic macros. This is a situation where Io is in the first camp and Python is in the second. They simply don't have equivalent goals; Python emphasizes transparency and readability more than customizability and flexibility, whereas Io does the opposite. > Io doesn't use __methods_with_this_annoying_syntax__ because nothing > is supposed to be for internal use only and there are only about three > functions that would cause a problem if overridden. > > For embedding, Io doesn't have to use Py_ALL_CAPS, instead it just > uses IoCamelCase, which looks much better. Interfaces to C are much > more object oriented. These are really stylistic objections, as are the other objections you list below. That's completely fine, of course; you should choose a language that jives with your personal sense of language style. But language designers need to make decisions, and those decisions are necessarily going to eliminate some styles of programming, while emphasizing others. You're in a situation where it sounds like Io jives with your sense of style more than Python. That's perfectly fine, and I know from my own research that Io is a neat little language (though I haven't really used it for anything substantial yet). But you can't expect other languages to bend to your personal will and personal sense of style, particularly when it means necessarily violating someone else's corresponding senses. Io and Python have quite different fundamental approaches to language design, and so it's not surprising that there are going to be irreconcilable differences. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The only completely consistent people are the dead. -- Aldous Huxley From me at here.there.com Wed Jan 14 22:27:14 2004 From: me at here.there.com (Peter Ashford) Date: Thu, 15 Jan 2004 16:27:14 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: paul m wrote: > JanC wrote: > >> >> You think "cross-platform" means "it runs out-of-the-box on all >> possible platforms that ever existed, now exist, and will ever exist"? >> >> Please go searching and come back when you find 1 (one) program which >> fits that definition... :-p >> > > vi might come close... ;-) Never!!! Emacs, on the other hand.... :) From eric.brunel at N0SP4M.com Wed Jan 14 10:36:18 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Wed, 14 Jan 2004 16:36:18 +0100 Subject: passing callback function to c-extension References: Message-ID: Diez B. Roggisch wrote: > Hi, > > I'm currently writing my first c-extension module. First of all: distutils > and the tutorial for embedding/extending rock! Great work, guys. > > However, I didn't find a hint how to pass a python callback function. > Googling didn't turn out much useful stuff, so I'd be glad if someone could > post a hint on how to do this. A Python function is just a regular Python object, so it is represented at C level by a PyObject*. To call it from C, just use one of the PyObject_Call functions - see http://www.python.org/doc/current/api/object.html#l2h-189 HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fowlertrainer at anonym.hu Tue Jan 6 05:30:40 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 6 Jan 2004 11:30:40 +0100 Subject: How to I get the classname of object ? Message-ID: <3910373245.20040106113040@anonym.hu> Hello python-list, Please help me !!! like Delphi's obj.ClassName Thanx -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From mcfletch at rogers.com Wed Jan 14 04:04:31 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 14 Jan 2004 04:04:31 -0500 Subject: Inserting while itterating In-Reply-To: References: Message-ID: <4005061F.3020006@rogers.com> Thomas Guettler wrote: >Hi, > >Simple excerise: > >You have a sorted list of integers: >l=[1, 2, 4, 7, 8, 12] > >and you should fill all gaps: > >result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > Well, here's the simplest one... if l: l[:] = range(l[0],l[-1]) but what you're probably looking for is (untested): for x in range( len(l)-2, -1, -1 ): if l[x+1] != l[x]+1: l[x+1:x+1] = range(l[x]+1,l[x+1]) Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From rmkrauter at yahoo.com Fri Jan 30 13:50:53 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri, 30 Jan 2004 10:50:53 -0800 (PST) Subject: HowTo Search in nested lists Message-ID: <20040130185053.7285.qmail@web40110.mail.yahoo.com> I'm still learning too; this is how I would do it, but there are probably better ways: If you require the data structure to be lists, and the lists are relatively small, this approach is probably ok - it returns a list of tuples of indices where the value is found: Suppose you were trying to find the location of the value 5: a = [1,2,3] b = [4,5,6] c = [7,8,9] t = [a,b,c] >>> [(x,y) for (x,n) in enumerate(t) for y in range(len(n)) if n[y] == 5] [(1,1)] You can replace the 5 in the above expression with whatever you want to search for. If you need to do many look-ups, where you are asking "Does this value occur at any position in my array?", and the lists are very, very large, I would consider a different way using dicts instead of lists; looping through the lists every time you need to check if a value is present is not very efficient. Build up a dict out of the table, using tuples of indices as keys d = {} d[(0,0)] = 1 d[(1,0)] = 2 # etc # build up the "reverse" dict dd = {} for k,v in d.items(): dd.setdefault(v,[]).append(k) (You can just make dd{} directly from original table using some other method, without the intermediate step of making d{}; that step doesn't really provide any benefit to you, other than allowing you to build up dd{} using above snippet.) Then you can look up a table value using tuples of indices as keys to d{}. Also, you can check for membership and/or original index locations of a value by using it as a key to dd{}. The look-up should be much faster than the list comprehension method for very large lists. Rich __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From http Sun Jan 4 10:01:14 2004 From: http (Paul Rubin) Date: 04 Jan 2004 07:01:14 -0800 Subject: Find out username and UID/GID References: Message-ID: <7x65frsqpx.fsf@ruckus.brouhaha.com> Florian Lindner writes: > how can I find out the username and it's UID and GID on a linux system, > using the most recent python version? If possible, without the use of extra > libraries. os.getuid(), os.getgid() From aathan-python-5923 at cloakmail.com Mon Jan 5 22:11:18 2004 From: aathan-python-5923 at cloakmail.com (Andrew Athan) Date: Mon, 5 Jan 2004 22:11:18 -0500 Subject: [SOLVED] RE: Repost: Can't sys.exit() from SIGTERM handler? In-Reply-To: Message-ID: Ok, with Jeff's pointer to SystemExit I was able to solve the problem. Firstly, please ignore the below post which is the result of having missed a try:except: in the main program, thus having a case where as Jeff suggested, a "blanket" exception handler was catching the SystemExit silently. A lesson for other silly pythoners like myself :-) Thanks again! A. PS: All the complexity below was the result of complex interaction between the caught and uncaught exceptions, and my own ambiguous debug logs. -----Original Message----- From: python-list-bounces+aathan-python-5923=cloakmail.com at python.org [mailto:python-list-bounces+aathan-python-5923=cloakmail.com at python.org] On Behalf Of Andrew Athan Sent: Monday, January 05, 2004 9:35 PM To: Jeff Epler Cc: python-list at python.org Subject: RE: Repost: Can't sys.exit() from SIGTERM handler? Yes, but it gets stranger (see below). It seems if I try to catch exceptions from within the SIGTERM handler, they are instead caught by the main program. Perhaps this is because a second signal is raised from within the SIGTERM handler and python doesn't handle nested signals well? --------------------------------------------------------- So #1: But first, the "simple" question: It seems really onerous to have to explicitly trap SystemExit and re-raise everywhere in my program, just so I can make sure that proper exit handlers (atexit(), etc.) are called. What is the idiom to "force" and exit while still "properly" shutting down the interpreter? ---------------------------------------------------------- #2 Now the hard question... It seems my problem is caused by my atexit() handler. It is meant to kill the children, and then os.waitpid() for them to make sure they are dead. I added this because killing the python process was not reliably killing the children (this surprised me since I thought the shell sent the signal to all processes in a process group??!!! perhaps cdparanoia has some incorrect exception handling which causes it not to reliably die on SIGTERM) I attribute my woes to the atexit() handler because when I changed my code to explicitly call the function I register with atexit() (called killChildren()) from within my SIGTERM handler, then the behavior got even weirder. The code I have basically looks something like this (pseudocode) childrenList=[] def sigterm(a,b): killChildren() childrenList=[] sys.exit() def sigchild(a,b): pass def killChildren(): try: os.kill(pid,signal.SIGTERM) os.waitpid(pid,0) pass: pass signal.signal(sigchild,signal.SIGCHILD) signal.signal(sigterm,signal.SIGTERM) childrenList.append(fork(...)) sys.atexit(killChildren) ... while 1: try: foo=read() except Exception,e: print 'Here: %s'%e pass If I send a SIGTERM, then I occasionally get 'Here: [Errno 10] No child processes' printed out!!! Stranger still, if I leave the normal atexit() handler alone by doing this instead: def sigterm(a,b): sys.exit() then *no* exception is printed out and the program keeps running. I *still* don't get anything printed even if I explicitly catch SystemExit within the while 1: loop and print a debug statement. The only conclusion I can draw is that (a) atexit's exception handling is strange and/or (b) if the child is still running when I os.kill() it in in the atexit() handler that occurs after the sys.exit() in, the SIGCHILD that gets raised as a result of the kill() is interfering in some very strange way. HELP! Any comments? Thanks, A. -----Original Message----- From: Jeff Epler [mailto:jepler at unpythonic.net] Sent: Monday, January 05, 2004 8:37 PM To: Andrew Athan Cc: python-list at python.org Subject: Re: Repost: Can't sys.exit() from SIGTERM handler? If I had to guess, I'd bet you had a blanket exception handler somewhere. sys.exit merely raises SystemExit, and if this exception propogates all the way back up, Python treats it specially by exiting instead of printing the exception's traceback. :r term.py import os, signal, time, sys, traceback def sigterm(a, b): print "sigterm" sys.exit() signal.signal(signal.SIGTERM, sigterm) os.system("(sleep 1; kill %s) &" % os.getpid()) print "Sleeping (should be killed)" try: time.sleep(2) except SystemExit: traceback.print_exc() raise print "sleep finished (!?)" :r!python -u term.py Sleeping (should be killed) sigterm Traceback (most recent call last): File "term.py", line 14, in ? time.sleep(2) File "term.py", line 5, in sigterm sys.exit() SystemExit -- http://mail.python.org/mailman/listinfo/python-list From maketo at gronland.freeshell.org Fri Jan 9 10:24:06 2004 From: maketo at gronland.freeshell.org (Ognen Duzlevski) Date: Fri, 9 Jan 2004 15:24:06 +0000 (UTC) Subject: how to speedup this code? References: Message-ID: I forgot to say that I have declared the above matrices as lists of lists or by using the Numeric package as their arrays. Ognen From quentel.pierre at wanadoo.fr Thu Jan 8 15:57:19 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Thu, 8 Jan 2004 21:57:19 +0100 Subject: Strings with null bytes inside sqlite Message-ID: I want to store strings in a sqlite database, but my strings may contain null bytes and sqlite can't handle this. What is the best way to solve the problem (the fastest in execution time and / or the one that produces the least additional bytes) : base64, or is there a better solution ? Thanks, Pierre From mcfletch at rogers.com Tue Jan 6 04:04:01 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 06 Jan 2004 04:04:01 -0500 Subject: tuple.__hash__() In-Reply-To: References: Message-ID: <3FFA7A01.4020005@rogers.com> Just wrote: >In article , > "Thomas Guettler" wrote: > > > >>Can someone point me to the documentation >>of tuples __hash__ method? >> >>I want to unique a list of tuples. Since >>__hash__ returns a 32 bit integer, there >>could be a situtation where two different tupples >>return the same value. >> >> > >That's a basic propery of hashing in general, no? > > Yes, but the OP is probably worried about whether the dictionary class can differentiate between objects which hash equal and equal objects: >>> class x: ... def __hash__( self ): ... return 32 ... >>> a = x() >>> b = x() >>> d = {} >>> d[a] = 1 >>> d[b] = 1 >>> d {<__main__.x instance at 0x0129F828>: 1, <__main__.x instance at 0x01523BA0>: 1} >>> class y: ... def __hash__( self ): ... return 32 ... def __eq__( self, other ): ... if isinstance( other, self.__class__): ... return 1 ... return 0 ... >>> s = y() >>> t = y() >>> d = {} >>> d[s] = 1 >>> d[t] = 1 >>> d {<__main__.y instance at 0x011FCF08>: 1} >>> AFAIK, the dictionary class simply uses the hash to sort into buckets, providing fast indexing, before using equality to check whether the two keys are equal. IOW, hashes are an optimisation for lookup, not an identity as far as the dictionary is concerned, so the impact of key-collisions is pretty low. The type must guarantee that equal values hash equal, but it doesn't have to guarantee that only equal values hash equal. >>Is there a dictionary type which uses __cmp__() like >>btrees in the standard library? >> >> > >I don't think so. > > Hmm, not in the same way (i.e. not for a binary-search lookup), but there does appear to be something going on in the dictionary class that does what the OP is probably looking for wrt comparisons. Happy hashing, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From ptmcg at austin.rr.com Fri Jan 2 10:36:48 2004 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 02 Jan 2004 15:36:48 GMT Subject: Array neighbourhoods References: Message-ID: "Daniel Pryde" wrote in message news:mailman.42.1072799018.8134.python-list at python.org... > Hi again. > > One thing I forgot to include in my post the other day. I was wondering if > anyone knew of any fast algorithms for returning the surrounding neighbours > of an array element, or even the neighbours of a group of array elements. > Try this (requires Python 2.3, since it uses sets). Can't say how fast it is, but it handles all cases I can think of (edge effects, disjoint cells, etc.). Maybe start with this to get going, then make it faster if it needs to be. # matrixNeighbors.py from sets import Set def neighborhoodOf(cells, rows, cols): ret = Set() if type(cells) == tuple: row,col = cells for i in (-1,0,1): for j in (-1,0,1): ret.add( (row+i, col+j) ) # remove original cell ret.remove( cells ) elif type(cells) == list: for cell in cells: for neighbor in neighborhoodOf(cell,rows,cols): ret.add(neighbor) # remove original cells ret -= Set( cells ) # remove all entries in ret with negative values, # or values greater than number of cols/rows for x,y in ret.copy(): if x < 0 or y < 0 or x >= COLS or y >= ROWS: ret.remove( (x,y) ) return list(ret) # define matrix boundaries ROWS = 4 COLS = 6 print neighborhoodOf( (0,0), ROWS, COLS ) print neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS ) print neighborhoodOf( (COLS,ROWS), ROWS, COLS ) print neighborhoodOf( [(0,0),(0,1)], ROWS, COLS ) print neighborhoodOf( neighborhoodOf( (1,1), ROWS, COLS), ROWS, COLS ) print neighborhoodOf( neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS), ROWS, COLS ) print neighborhoodOf( neighborhoodOf( (COLS,ROWS), ROWS, COLS), ROWS, COLS ) From rainerd at eldwood.com Thu Jan 29 12:50:42 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 29 Jan 2004 17:50:42 GMT Subject: isinstance() bug References: Message-ID: Michal Vitecek wrote: > Rainer Deyke wrote: >> Michal Vitecek wrote: >>> it's my belief that if i'm instantiating a class from the same >>> location no matter how i imported its definition, its instances are >>> always of the same class. >> >> Your belief is incorrect. 'package.module.A' and 'module.A' are >> distinct classes. Modifications to one do not show up in the other. >> If 'isinstance' reported that an instance of 'package.module.A' is >> an instance of 'module.A', 'isinstance' would be broken and unusable. > > could you elaborate further why do you consider the current behaviour > to be correct? you've only described how it works currently. i'd be > interested what's the reasoning behind that. 'isinstance' does the only possible correct thing. Even without loading the same file as multiple modules, a module can create many distinct classes with the same name. For example: def create_unique_class(): class C(object): pass return C a_bunch_of_classes = [create_unique_class() for i in range(8)] Treating these separate classes as a single class would be just plain wrong. If there's a problem with the current implementation, it is that it allows modules in packages to be imported as top level modules. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From nem at nowhere.invalid Mon Jan 26 02:56:26 2004 From: nem at nowhere.invalid (Nemesis) Date: 26 Jan 2004 07:56:26 GMT Subject: any news client in Python? References: <2b4c49e0.0401230915.3438810f@posting.google.com> Message-ID: "Nemesis" wrote: >> hello everybody. >> i've been looking around for a decent newsreader (not rss) >> that's written in Python. Strange, but i found none so far, >> i've been to sf.net, freshmeat.net, and even googled that, >> still nothing interesting. > I know two newsreader written in Python at least. > 1) Pyne > 2) XPN Aren't they decent newsreaders? :-D -- Testa di Vieri deviata da De Rosa" ( Bruno Longhi) From sandhya.hariharan at sap.com Tue Jan 13 07:21:27 2004 From: sandhya.hariharan at sap.com (sandhya) Date: Tue, 13 Jan 2004 06:21:27 -0600 Subject: Python Message-ID: How to generate a .pyd file from a c++ file?? plz do respond thanks regards Sandhya From wilkSPAM at OUTflibuste.net Mon Jan 12 09:34:45 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 12 Jan 2004 15:34:45 +0100 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> Message-ID: <87oet9grqy.fsf@blakie.riol> ketulp_baroda at yahoo.com writes: > Wilk wrote in message news:<87wu80559x.fsf at blakie.riol>... >> ketulp_baroda at yahoo.com writes: >> >> > i am developing a web application and i am really confused on what should i use. >> > should i use just python and use the cgi module availabe. >> > Or should i use application like WebWare.Also there is PSP available. >> > I am really confused and need help >> >> It depends of the kind of application you want to do exactly, there are >> many possibilities from cgi to zope... >> >> Look into the archive of the list, you'll find a lot of answer to this >> question. Or describe more what you need. >> >> bye > > > hey thanks for ur reply > i am developing an issue tracking system There is one that you can look at : http://roundup.sf.net I think it can be used in standalone server or cgi. > the primary requirements are > 1)it should be platform independent which i think python will take > care of > 2)it should have customizable gui .I am thinking of using templates > for this like Cheetah. Is there any other better solution to Cheetah? There is no better solution than Cheetah : there is others solutions... > The problem i am facing here is i dont know what to use for > development of the application. I came across many ways to develop web > application in python which I already specified like > i)the cgi module in python > ii)Python Server Pages > iii)Quixote > iv)WebWare > v)Zope etc. > I want to choose such an environment so that i dont have to install > other softwares to run my application.For eg. I think if I develop > using zope then the client also has to install zope to run my software > and i dont want this. When you use one of theses servers, you don't need to install anything else than a classic browser on the client side. On the server side, most of the servers will not need anything else, you can even start without server with the batterie include : BasicHTTPServer (it was somes examples on this list somes days ago). bye -- Wilk - http://flibuste.net From michael at telcopartners.com Fri Jan 23 17:51:31 2004 From: michael at telcopartners.com (Michael Spencer) Date: Fri, 23 Jan 2004 14:51:31 -0800 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: "Amy G" wrote in message news:PRgQb.16209$AA6.9881 at fed1read03... > No it won't. Unfortunatly I don't necessarily have a comma delimited date > string. Thanks for the input though. > > The following three date strings is another example of the various date > formats I will encounter here. > > Thursday, 22 January 2004 03:15:06 > Thursday, January 22, 2004, 03:15:06 > 2004, Thursday, 22 January 03:15:06 > > All of these are essentially the same date... just in various formats. I > would like to parse through them and get a comparable format so that I can > display them in chronological order. > > > "wes weston" wrote in message > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net... > > Amy, > > I hope there is a better way but, if you go here: > > > > http://www.python.org/doc/current/lib/datetime-date.html > > > > The new datetime module may help. This and the time mod > > should get you where you want to go. > > > > list = strdate.split(", ") > > daystr = list[0] > > daynum = int(list[1]) > > monthstr = list[2] > > year = int(list[3]) > > #funct to get a month int is needed > > > > d = datetime.Date(y,m,d) > > > > wes > > > > --------------------------------------- > > > > Amy G wrote: > > > I have seen something about this beofore on this forum, but my google > search > > > didn't come up with the answer I am looking for. > > > > > > I have a list of tuples. Each tuple is in the following format: > > > > > > ("data", "moredata", "evenmoredata", "date string") > > > > > > The date string is my concern. This is the date stamp from an email. > > > The problem is that I have a whole bunch of variations when it comes to > the > > > format that the date string is in. For example I could have the > following > > > two tuples: > > > > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 > 03:15:06") > > > > > > I know there is some way to use the date string from each of these to > get a > > > date usable by python, but I cannot figure it out. > > > I was trying to use time.strptime but have been unsuccesful thus far. > > > > > > Any help is appreciated. > > > > > > > > > > This was asked and answered earlier today See: https://moin.conectiva.com.br/DateUtil >>> from dateutil.parser import parse >>> parse("Thursday, 22 January 2004 03:15:06") datetime.datetime(2004, 1, 22, 3, 15, 6) >>> parse("Thursday, January 22, 2004, 03:15:06") datetime.datetime(2004, 1, 22, 3, 15, 6) >>> parse("2004, Thursday, 22 January 03:15:06") datetime.datetime(2004, 1, 22, 3, 15, 6) >>> From akhavr at kds.com.ua Mon Jan 12 13:05:26 2004 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Mon, 12 Jan 2004 20:05:26 +0200 Subject: script to translate from compiler AST References: Message-ID: Michael, "MH" == Michael Hudson wrote: MH> Andrey Khavryuchenko writes: >> I'm looking for a script to translate from 'compiler' AST to py source MH> google('decompyle') Well, not *that* :) >> and executable code. MH> Um, not sure what you're asking for here. You might be asking for MH> Python2C, but it's probably not what you want... Imagine, I've built an AST that I want to run. I've not found an easy (read library) way to do that, hence the question. Is there a way or I'd better write a proper 'visitor' myself? -- Andrey V Khavryuchenko http://www.kds.com.ua/ Silver Bullet Software Solutions http://www.kds.com.ua/training/ From sidharthk at hotmail.com Fri Jan 30 07:04:30 2004 From: sidharthk at hotmail.com (sid) Date: Fri, 30 Jan 2004 17:34:30 +0530 Subject: pyc file problem References: Message-ID: i doubt there are any good name manglers for python.especialy with it being dynamic. you could encrypt your game files. of course the loader would have to be mangled by hand. if you are keen on this you could look at the tempfile and imp modules. this is not foolproof. people could still step through your code and crack it. just wondering, is it smart to have any of the game's logic on the users machine. i can see a lot of situations other than hacking and cracking the code that could lead to problems. From jacek.generowicz at cern.ch Wed Jan 7 07:44:57 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2004 13:44:57 +0100 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> Message-ID: I always wonder whether I should post concise articles, or wordy ones, covering all possbile assumpitons and misconceptions. It appears that, usually, I get the balance hopelessly wrong :-( Or, maybe, that's just what life is like in a large public forum; whatever you say, there will always be hundreds of people who misunderstand you. Thomas Heller writes: > Jacek Generowicz writes: > > > Yes, but this actually does not work out of the box (on any of the > > GNU/Linux, Mac OS X, and even Windoze installaitions I have tried). You > > get an error message complaining about the absence of HTML > > documentation and setting PYTHONDOCS. So, to rephrase my question ... > > > > Where can I find clear instructions on how to install and configure > > the Python documentation which is necessary to make the following > > work: > > > > >>> help('and') > > > > ? > > Download the HTML archive from > , and unpack this in a > temporary directory. Leave the directory structure intact - in Winzip, > make sure the 'Use Folder Names' checkbox is checked. > > This creates a Python-Docs-2.3.3 subdirectory. Copy everything in this > directory (including subdirectories) into your c:\python23\Doc folder > (normally there is a single Python23.chm file in it), and you're done. Does someone who writes > > GNU/Linux, Mac OS X, and even Windoze ^^^^ ^^^^ really look like someone who is looking for instructions on fixing his Python installation on a M$ operating system ? Jacek Generowicz originally wrote: > Where can I find concise, clear documentation[*] describing what one has > to do in order to enable Python's internal help to be able to provide > descriptions of Python keywords ? > > I am in a situation where I have to give Python novices the ability to > fix this for themselves easily. > > > [*] Failing "concise" and "clear", how about "complete and correct" ? I teach an introductionary course on Python. One of the key messages that I try to convey is that with Python's excellent introspection capabilities, the built-in help, and the Python web site, you have pretty much all the information you need at your fingertips. In the course, I politely refuse to answer any questions which the student can easily answer himself by using the interactive help. The point is that I hope that the studens will go away with the ability to find most things out for themselves. In this context, I would like them to be able to find out for themselves how to fix the keyword documentation, which is why I phrased my original question thus: > Where can I find concise, clear documentation[*] describing what one > has to do in order to enable Python's internal help to be able to > provide descriptions of Python keywords ? Note, I did NOT say "How do I ...", I said "Where do I find [...] documentation ...". I am NOT interested in a recipe posted here. I want to know where to find the official instructions on how it is done, so that I can show newbies how to find the information themselves. "Give a man a fish, and he can eat for a day. Teach a man to fish ...", and all that. If these instructions are, as it seems, absent, then I would appreciate advice on what I can do to make them appear in the appropriate place, and what the appropriate place might be. I recognize my impatience with poor documentation as a pathological flaw in my characer, which is why I am asking for help in finding/creating this documentation here. From harry.g.george at boeing.com Wed Jan 28 03:42:11 2004 From: harry.g.george at boeing.com (Harry George) Date: Wed, 28 Jan 2004 08:42:11 GMT Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) writes: > Hello, > > is there something like "JpGraph" for python ? > For those who don't know this PHP library: It is a high level > drawing library that generates gif files with all kind of charts. > > Or (maybe better) is there a C library doing this. I think i > read about something like this a while ago. To generate jpg's and png's (maybe gif's): binding for plotutils: http://biggles.sourceforge.net/libplot/ binding for gnuplot: http://gnuplot-py.sourceforge.net/ gdchart has a python binding (which I can't bring up right now). Here is gdchart's own page. http://www.fred.net/brv/chart/ Also, some people use "R" for fancy charts, and R has a python binding: http://www.R-project.org/ http://www.omegahat.org/RSPython/index.html -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From virusmaster at kaptech.com Thu Jan 29 06:25:35 2004 From: virusmaster at kaptech.com (virusmaster at kaptech.com) Date: Thu, 29 Jan 2004 11:25:35 GMT Subject: Virus Alert Message-ID: <200401291125.i0TBPZX23432@localhost.localdomain> L'email (contenant le fichier : message.exe) que vous avez envoye le 01/29/2004 11:25:34 a jean-claude.messmer at cg67.fr contient le virus WORM_MIMAIL.R et a ete traite par l'action quarantined. Pour toutes questions, adressez-vous a votre administrateur reseau. ----------------------------------------------------------------------------- The email (with attached file: message.exe) you sent on 01/29/2004 11:25:34 to jean-claude.messmer at cg67.fr contains the virus WORM_MIMAIL.R and the action quarantined had been done. If you have questions, please contact your LAN administrator. Cet email a ete genere automatiquement par un serveur anti-virus. Merci de ne pas repondre a ce message. This email has been automatically generated by an antivirus server. Please do not reply to this message. From bdesth.tagada at tsoin-tsoin.free.fr Tue Jan 13 17:20:15 2004 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Tue, 13 Jan 2004 23:20:15 +0100 Subject: Does anyone else not find the fun in programming...? In-Reply-To: References: Message-ID: <40046a6c$0$19277$626a54ce@news.free.fr> Rony wrote: > Group : comp.lang.python > > (snip) > > Well I agree... > Meeting people, having a drink with them, sex.. is s/fun/boring/ > Programming is just s/a job/fun/ did this help ?-) From rick_muller at yahoo.com Thu Jan 22 14:41:18 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 22 Jan 2004 11:41:18 -0800 Subject: Simple way of turning -DNDEBUG off in distutils Message-ID: <5eb8fb88.0401221141.35549e53@posting.google.com> Is there a simple way of toggling the -DNDEBUG flag in the distutils builds? I just realized that all of my assert statements were being skipped because by default the distutils put in -DNDEBUG. Thanks in advance, Rick From tim.golden at viacom-outdoor.co.uk Wed Jan 21 05:34:31 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Jan 2004 10:34:31 -0000 Subject: personal document mgmt system idea Message-ID: >> In addition, a real (text) search engine might be of help. >I'm using swish-e >> (www.swish-e.org) and are very pleased with it. > >Just downloaded it... looks good. Now if it also had a python api (-; Try this: http://jibe.freeshell.org/bits/SwishE/ 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 usenet at -OBFUSCATED-joefrancia.com Sat Jan 17 20:04:40 2004 From: usenet at -OBFUSCATED-joefrancia.com (Joe Francia) Date: Sun, 18 Jan 2004 01:04:40 GMT Subject: Webbrowser and Mozilla control on linux In-Reply-To: <1d17eeb7.0401171633.170e313a@posting.google.com> References: <1d17eeb7.0401171633.170e313a@posting.google.com> Message-ID: Jay Davis wrote: > I can launch a browser on linux with the webbrowser module > and the .open() method. However, I want to be able also to > control the browser, specifically, I'd like to be able to > go to a URL and invoke the automatic form filler and post > the form, all from within a python script. > > I have google'd around and I see hints that there are remote > controller objects for some browsers, but so far I haven't > found any examples of code that controls the browser; most > examples just open the browser, which I could just as well > do from os.system(). > > If anyone can share some samples, or point me to a good > reference with browser control details, I'd much appreciate > it. Thanks! If all you're trying to do is automatically fill out web forms, you'll probably be better off using ClientForm (and possibly ClientCookie) from this page: http://wwwsearch.sourceforge.net/ From tim.one at comcast.net Tue Jan 20 16:07:37 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 20 Jan 2004 16:07:37 -0500 Subject: New to Python: my impression v. Perl/Ruby In-Reply-To: Message-ID: [Ville Vainio] > Ints are objects in python too: > > >>> a=1 > >>> a.__lshift__(1) > 2 > > Though "sending messages" to int literals is a syntax error. Nope, it's fine. If you write 1.__lshift__(1) it's *parsed* as a float literal ("1.") followed by an identifier ("__lshift__"), and that's not meanignful syntax. You could, e.g., do either of these instead: >>> (1).__lshift__(1) # parenthesize the int 2 >>> 1 .__lshift__(1) # put whitespace between int and dot 2 >>> From aathan-python-5923 at cloakmail.com Mon Jan 5 20:22:28 2004 From: aathan-python-5923 at cloakmail.com (Andrew Athan) Date: Mon, 5 Jan 2004 20:22:28 -0500 Subject: (no subject) Message-ID: I have a python program (snippet below) which does not want to seem to die when I issue a sys.exit() inside the SIGTERM handler. The output below is generated as the result of sending several SIGTERM signals to the process, as a result of seeing that it had not died. I don't think this is relevant, but the application has fork()ed a child process (cdparanoia). The only thing I can think of is that somehow, there is an exception occuring inside sys.exit(), otherwise why am I not seeing the "Did not sys.exit()!?" output? Could it be that exit() is returning but that the output fd's are already closed? Verrry strange...and therefore I'm sure I'm making a brain dead mistake. Thanks in advance, A. -------------------------------------------------------------------------- ****SIGTERM***** ****SIGTERM***** .. ****SIGCHILD***** Ripper output status code: (4314, 15) 4320 /root/postprocess /var/music/ripper/8707620b ****SIGCHILD***** Error JOB_NODISC in job <__main__.JobHandler instance at 0x8204b24> 4321 /bin/setserial /dev/ttyS0 spd_normal ****SIGCHILD***** Killing child processes... -------------------------------------------------------------------------- def sigterm(a,b): print '\n****SIGTERM*****\n' sys.exit() print '\nDid not sys.exit()??!!\n' killChildren() os._exit(1) print '\nDid not os._exit()??!!\n' def killChildren(): global childPIDs print '\n\nKilling child processes...' for pid in childPIDs: try: print 'Terminating %d'%pid os.kill(pid,signal.SIGTERM) os.waitpid(pid,0) except: pass def child_exit(a,b): #childpid, status = os.wait() print '\n****SIGCHILD*****\n' pass From bart_nessux at hotmail.com Thu Jan 15 14:33:18 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 15 Jan 2004 14:33:18 -0500 Subject: python & mathematical methods of picking numbers at random Message-ID: I am using method 'a' below to pick 25 names from a pool of 225. A co-worker is using method 'b' by running it 25 times and throwing out the winning name (names are associated with numbers) after each run and then re-counting the list and doing it all over again. My boss thinks that 'b' is somehow less fair than 'a', but the only thing I see wrong with it is that it is really inefficient and ugly as it's doing manually what 'a' does automatically, other than that I think the outcome of both methods (25 unique winners from a pool of 225) are the same. Anyone disagree with that and if so, please demonstrate how 'b' isn't as fair as 'a' count = len(list_of_potential_winners) a = random.sample(range(count), 25) b = random.sample(range(count), 1) Thanks! Bart From mlh at furu.idi.ntnu.no Mon Jan 26 18:35:12 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 26 Jan 2004 23:35:12 +0000 (UTC) Subject: Pyrex and numarray References: Message-ID: In article , Marco Bubke wrote: [snip] I tried using the set-up with Pyrex, but I'm having trouble referencing some of the symbols. (I actually put all of it inside the cdef extern declaration -- maybe I shouldn't have? I couldn't make it compile otherwise...) I manage to reference some of the symbols (such as maybelong) but others trip me up... If I try to define a variable of type PyArray_Descr gcc crashes, and I'm not sure why. The only thing that isn't a warning is na_wrap.c:43: storage size of `__pyx_v_x' isn't known If I run import_libnumarray(), Python can't find the symbol. (It does find libnumarray.so, though.) The same happens when I try to use NA_InputArray: symbol NA_InputArray: referenced symbol not found Why, oh why? :] -- Magnus Lie Hetland "The mind is not a vessel to be filled, http://hetland.org but a fire to be lighted." [Plutarch] From newsgroups at jhrothjr.com Mon Jan 5 12:36:49 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 5 Jan 2004 12:36:49 -0500 Subject: PRE-PEP: new Path class References: Message-ID: "Just" wrote in message news:just-CC8B2B.17325205012004 at news1.news.xs4all.nl... > In article , > "John Roth" wrote: > > > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > > can be found here: > > > > http://tinyurl.com/2578q > > > > Frankly, I like the idea. It's about time that all of the file > > and directory stuff in the os module got objectified > > properly (or at least with some semblance of OO propriety!) > > > > In the issues section: > > [ snipping those points where I agree with John ] > > > 4) Should path expose an iterator for listdir(?) > > > > I don't see why not, as long as the path is to a > > directory. > > _An_ iterator, sure, but not __iter__. How about path.listdir()? :) > __iter__ could also iterate over the path elements, so it's ambiguous at > least. I see what you're saying. I'd argue (softly) that iterating over the directory entries is the natural interpretation, though. > > 15. Should files and directories be the same > > class. > > > > Probably not. While they share a lot of common > > functionality (which should be spelled out as an > > interface) they also have a lot of dissimilar > > functionality. Separating them also makes it easy > > to create objects for things like symbolic links. > > But what about paths for not-yet-existing files of folders? I don't > think you should actually _hit_ the file system, if all you're doing is > path.join(). I agree here. I haven't looked at any of the candidate implementations yet, so I don't know what they're doing. I'm thinking of a three class structure: the parent class is just the path manipulations; it has two subclasses, one for real files and one for real directories. That way they can not only inherit all of the common path manipulation stuff, but the developer can instantiate a pure path manipulation class as well. There might also be a mixin that encapsulates the stuff that's common to real files and directories like accessing and changing dates and permissions. I'm sure there are use cases that will throw a curve at that structure as well. > > Just From nuffsaid at phreaker.net Sun Jan 18 09:45:17 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sun, 18 Jan 2004 15:45:17 +0100 Subject: wxwindows question References: <1h6pd1-788.ln1@wintermute.g2ctech> Message-ID: On Sun, 18 Jan 2004 00:10:09 -0200, Jorge Godoy wrote: > > Which widgets you missed there? > Tkinter: notebook, tree view, printing framework pyGTK: printing framework wxWindows: a powerful, 'normal' TextControl (not Scintilla) - Notebooks exist in some of the Tkinter extensions, but I found it easier (deployment etc.) to write my own notebook (which is not really good looking but enough for most of my purposes). Nevertheless, a notebook and a tree view widget should be part of vanilla Tkinter IMHO. - The TextControl is a good example for what I do not like in wxWindows: it is *very* easy to use widgets in wxWindows in a standard way; but it is often difficult or impossible to do advanced stuff with these widgets. > > It would be very good if wxPython was more python centric instead of > trying to be more like wxWindows. But I guess that people who > prototype in wxPython and then convert some parts (or all) of their > application to C++ wouldn't like such a change... > > There's "equilibrium" here, and messing with that would be > dangerous :-) Another advantage is that wxWindows is already there > and it works. It would be a shame not to benefit from that. > I agree. Having wrappers for existing libraries and software is an important thing and having *prototyping* in mind, one should not try to make such wrappers as pythonic as possible. (Moreover, this would make the maintenance of the wrappers more complicated.) A native GUI toolkit for Python should be something which is written from scratch (resp. - maybe - a wrapper for a GUI toolkit written in C). > > Since you mentioned CGIs, don't you like using Python for that? > I do! For web applications, I normally use CGIs written in Python resp. ASP.NET (mainly from the Mono project) using Code Behind in C#. I like both, but unfortunately, I have to maintain a lot of old CGIs written in Perl, some ASP stuff etc. Nuff From paul at prescod.net Wed Jan 21 11:23:53 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 21 Jan 2004 08:23:53 -0800 Subject: calling Pyrex results from C In-Reply-To: References: <20040120172733.GA7666@titan.progiciels-bpi.ca> <20040120234855.GV22782@jowls> Message-ID: <400EA799.7080706@prescod.net> Kyler Laird wrote: > > Pyrex: > cdef public image_file_open(char* image_filename): > return(Image.open(image_filename)) > > cdef public image_size(image_PIL): > return(Image.size) > > cdef public char* string(x): > s = str(x) > return(s) > > my C: > void *im, *im_size; > im = image_file_open(input_filename); > im_size = image_size(im); > printf("im=%s\n", string(im)); > printf("im_size=%s\n", string(im_size)); > > The first call to string() succeeds but the second one fails. I > suspect that I've expected too much of Pyrex again. Do I need to > allocate memory, manipulate reference counts or something like > that? First, I'd suggest that "integer" is a perfectly good type in both C and Pyrex so you shouldn't pass around Python objects representing integers. Second, you aren't checking the return codes of your functions and C has no exception handling, tracebacks, etc. image_size is probably returning 0 because it is probably throwing an exception because you are asking for the size attribute of the Image class rather than the image_PIL object. You actually would have gotten a Pyrex error on your console if your function were defined to return "int" or "void" because Pyrex would KNOW that there's no way you are doing exception handling so it would try to compensate by printing exceptions to the console. But I wouldn't depend on that feature because it doesn't help for functions that really should return objects. Better to check your return values. Once I fix the Image/Image_PIL error your code runs okay on my computer. But you are walking on thin ice and may just be lucky. It is simply not possible to work with strings generated at runtime in C without worrying about memory allocation sometime. In this case I have the strong suspicion that the string() function is either creating and destroying a string object and then returning you a pointer to the dead object's internal memory buffer (bad news!) or simply losing a reference to the (still living) string object: still not a good thing. Eyeballing the code I believe the former is the issue. You could check for sure by adding some printf's to the generated code to look at __pyx_v_s->ob_refcnt. Why not let Python do the "print" rather than using "printf". Paul Prescod From matt at pollenation.net Fri Jan 23 05:22:59 2004 From: matt at pollenation.net (Matt Goodall) Date: Fri, 23 Jan 2004 10:22:59 +0000 Subject: cgi concurrency approaches? In-Reply-To: <66s11056aptit3vd2inv3p3r07v95k52ha@4ax.com> References: <7x7jzjgso7.fsf@ruckus.brouhaha.com> <66s11056aptit3vd2inv3p3r07v95k52ha@4ax.com> Message-ID: <1074853378.32488.3.camel@harold> On Fri, 2004-01-23 at 10:04, Rene Pijlman wrote: > Paul Rubin : > >I'm wondering if folks here have favorite lightweight ways of dealing > >with concurrency in cgi's. Take a simple case: > > > >You want to write a cgi that implements a simple counter. The first > >time it's called, it prints "1". The next time, "2", etc. > [...] > >Anyone have some simpler approaches? > > Use mod_python and keep the counter in a Python variable (if the value > needs not be persistent). > http://www.modpython.org/ That will only work if you use Apache 2 in threaded mode. Apache 1 and Apache 2 in forking mode (multiple processes) will have a copy of the counter object per-process. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net Any views expressed are my own and do not necessarily reflect the views of my employer. From tismer at stackless.com Mon Jan 5 21:43:11 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 06 Jan 2004 03:43:11 +0100 Subject: Made a huge change to Stackless. Please test! Message-ID: <3FFA20BF.7070607@stackless.com> Hi friends, for the last two+ weeks, I was hacking on the internals of stackless, in order to make things cleaner, smaller, more natural and more complete. This patch is a quite essential refactoring of the internals, enhancing functionality at the same time. On the other hand, semantics are almost not touched. This finally became a redesign of a lot of the machinery. Especially, frames no longer have f_tstate, and much more important, frames no longer carry informationabout the C state. C state (as C stacks) is now a property of the tasklets. All tasklets now have a c state by default. There are trivial cstates and non-trivial cstates. They are distinguished by the nesting_level. A trivial cstate is a C state with nesting_level == 0. This cstate does not need to be saved, since their context is well-known. It can be replaced by a number of trivial statements, which realize so-called soft switches almost an order of magnitude faster. Non-trivial cstates are those created by C stack switching. Note that exactly these tasklets are not restartable after unpickling! As a major enhancement, the system now keeps track of all tasklets which are using a non-trivial cstate, ensuring that all these tasklets will receive a kill() signal if they do not finish normally before thread termination. Here the check-in message: """ This was by far the largest check-in since months! f_state variables are removed from frames. cstack objects are removed from frames. All cstate is now kept in the tasklets. Tasklets with serious cstate are now killed automatically on thread deallocation. Tasklet soft-switching is now secured against repeated entry from "outside": A version variable is tracked, which makes sure that "main" is always left with the most recent version of initial_stub. Hey, this was two weeks of fulltime work! """ Please, give this code a heavy load of testing! With a few changes, this should be the code base for porting Stackless to Python 2.3.3. 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 here at there.org Sun Jan 4 16:36:26 2004 From: here at there.org (The_Incubator) Date: Sun, 04 Jan 2004 13:36:26 -0800 Subject: Scripting C++ Game AI object using Python Generators In-Reply-To: References: Message-ID: Yeah, Stackless sounds interesting, and it was used in Eve-Online. At this point I'm under the impression that a lot of the specific advantages of stackless have to do with distributed applications, where you can have lots and lots of remotely instantiated Python objects running as separate microthreads, managed by software on your servers, with minimal task-switching overhead. My projects is not online multiplayer, so I'm not sure if Stackless would have advantages for my project above and beyond the generators already in Python, but maybe someone else can shed some light on that? It may be worthwhile for me to get in touch with them regarding my project though. Thanks for the suggestion. Nick Harald Massa wrote: > Nick, > > I am not able to understand your request fully (problem on my side, I'm not > into Game Programming) ... > > but many of your keywords I heard last time in a talk by Chris Tismer, > speaking about http://www.stackless.com/ stacklass Python at Europython in > Charleroi. > > Maybe you should look there and maybe send your request directly to him? I > saw him demonstrating a large game application with microthreads and > generators and whatsoever (I just remember the words :)) ) > > Harald From peter at engcorp.com Wed Jan 28 09:29:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 09:29:01 -0500 Subject: Simple Database Package References: <8089854e.0401280622.4e145267@posting.google.com> Message-ID: <4017C72D.D1F763BD@engcorp.com> Fuzzyman wrote: > > I'm looking to build a simple database application for use on the > desktop (customer contact and feedback database). > > Anyone able to reccomend a simple module / package I can use... ? > I've never done any database work before and am ken to learn - but > most of the ones I've seen seem to rely on a database engine buit into > a server.. I need a simple stand alone engine. Of course I could just > build the functions I need - but that would be a bit of a waste and > not so extendable........ Metakit? http://www.equi4.com/metakit.html and http://www.equi4.com/metakit/python.html -Peter From martin at v.loewis.de Sat Jan 10 10:42:05 2004 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 Jan 2004 16:42:05 +0100 Subject: LC_MONETARY formatting In-Reply-To: References: <3FFF38DE.1050603@v.loewis.de> Message-ID: <40001D4D.20609@v.loewis.de> Colin Fox wrote: > I can't believe that I'm the first person who ever wanted to print a > number as a currency value. Why go to the great lengths of what's provided > in localeconv(), only to leave it up to every single programmer to > re-implement the solution? What a waste of time and effort! As Serge points out, C has strfmon. For Python, better start believing that you are the first person who ever wanted to print a number as a currency value in a locale-dependent way. Feel free to contribute patches if you think this should be provided out of the box. Regards, Martin From paton_lewis at yahoo.com Wed Jan 28 20:16:43 2004 From: paton_lewis at yahoo.com (Paton J. Lewis) Date: Thu, 29 Jan 2004 01:16:43 -0000 Subject: Problems with python23_d.lib built with Visual Studio 7.1 Message-ID: I built the Python 2.3.3 sources with Visual Studio 7.1 (the conversion of the Visual C++ 6 project files appeared to work without a hitch). Everything seems fine except when I try to link my project with the debug Python library, in which case I get unresolved symbols apparently because the Python debug library symbol names have been modified in an unexpected fashion. For example, the calling code asks for symbol __imp__Py_InitModule4 (which exists in python23.lib) but python23_d.lib contains __imp__Py_InitModule4TraceRefs. Has anyone run into this problem before? Thanks, Pat From pln at razzle.Stanford.EDU Sat Jan 17 02:09:05 2004 From: pln at razzle.Stanford.EDU (Patrick L. Nolan) Date: Sat, 17 Jan 2004 07:09:05 +0000 (UTC) Subject: Need to get 8.3 path on Windows Message-ID: Our python script uses popen to run an application on Windows XP. The application chokes if the filename given as a command line argument contains any spaces. It's happy with the 8.3 shortname notation, though. So given a file with a name like c:\Documents and Settings\Joe User\Desktop\My Files\foo.dat I would like to be able to convert this to c:\DOCUME~1\JOEUSE~1\Desktop\MYFILE~1\foo.dat This would be a fairly simple exercise in text manipulation except that the number may not always be 1. If the directory names are not unique in the first 6 characters, there may be ~2 etc. Has this been solved by someone else? -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From lsolis at mu.intecsa-inarsa.es Mon Jan 5 03:23:56 2004 From: lsolis at mu.intecsa-inarsa.es (Luis Solís) Date: Mon, 05 Jan 2004 08:23:56 GMT Subject: explicit variable declaration Message-ID: Hi It is possible to declare some variables as int, long... ? , or something like visual basic option explicit. In some situations could be usefull. Thanks From ark at acm.org Tue Jan 27 10:54:18 2004 From: ark at acm.org (Andrew Koenig) Date: Tue, 27 Jan 2004 15:54:18 GMT Subject: I support PEP 326 References: <10105bn3bsi63c9@news.supernews.com> Message-ID: > The issue is that when Min and None are in a sequence that gets sorted, > you can end up with Minimums and Nones getting interspersed like so: > [Min, None, Min...] If Min and None were two different names for the same object, such behavior would be moot. However, the following anomalies might then appear: >>> None None >>> Min None (after all, if they're the same object, how is the interpreter to know which print name to use?) From guido.schimmels at freenet.de Tue Jan 13 15:14:21 2004 From: guido.schimmels at freenet.de (Guido Schimmels) Date: Tue, 13 Jan 2004 22:14:21 +0200 Subject: id3v2 module References: Message-ID: Am Tue, 13 Jan 2004 10:12:40 +0100 schrieb Dusausoy Bruno: > Hi, > > I'd like to know if there is a third-party module for reading/writing > id3v2 informations. > Thanks http://id3-py.sourceforge.net/ From none at none.com Tue Jan 20 16:20:44 2004 From: none at none.com (Derek) Date: Tue, 20 Jan 2004 16:20:44 -0500 Subject: I come not to bury C++, but to praise it... References: <20040114153516.GA16224@intarweb.us> <400D5B8F.8C597B9E@engcorp.com> Message-ID: "Peter Hansen" wrote: > > > A traceback is also much less nasty than deciphering a > > > 1000-character long compiler error message reported in > > > code that uses a heavily templated library. > > > > Absolutely correct. But remember that ugly > > template-related compiler error messages are a reflection > > of current compiler technology, not a fundamental > > limitation of C++. I suspect future compilers will make > > debugging templates much easier. > > I believe I heard that claim, almost verbatim, sometime > I around the last time was actively using C++, which was > I about a decade ago... Hmmm. As late as 1997 I couldn't get consistent template behavior between BCC, GCC, and MSVC. To this day most compilers are broken in some way or other with respect to templates. Even basic STL containers like std::vector were often improperly implemented or incomplete just a few years ago (try GCC 2.95 or VC6 to see what I mean). I also don't remember typelists, traits, policies, or other modern template techniques being popular a decade ago. My point is that while templates aren't new, their widespread use is. I'm not surprised that compiler vendors are only now looking at ways to improve template-related compiler errors. From pinard at iro.umontreal.ca Tue Jan 20 12:27:33 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 20 Jan 2004 12:27:33 -0500 Subject: calling Pyrex results from C In-Reply-To: References: Message-ID: <20040120172733.GA7666@titan.progiciels-bpi.ca> [Kyler Laird] > I realize that the goal of Pyrex is to create a module that can be > called from Python. Or vice-versa. I found Pyrex useful for calling Python modules from within C programs which were not Python-aware to start with. You may even write wholly Pyrex programs. > I've discovered that as long as everything in the code is cdef-ed, > I can call Pyrex code from my C code. If, however, I so much as > mention anything Pythonish, it segfaults during execution. There is some magic needed to establish Python context, not much. Hoping that it will help, here is a template I use when generating Pyrex main programs. `%(module)s' shall be replaced by the Pyrex module name, as Pyrex needs to initialise itself. When Python calls Pyrex, initialisation occurs automatically at `import' time, but when C initially calls Pyrex, initialisation should be explicitly launched. cdef extern void Py_Initialize() cdef extern void Py_Finalize() cdef extern void init%(module)s() cdef extern int main(int argc, char **argv): cdef int index, status Py_Initialize() init%(module)s() import sys try: arguments = [] for index from 0 <= index < argc: arguments.append(argv[index]) sys.argv = arguments result = main_application() raise SystemExit, result or 0 except SystemExit, result: result = str(result) try: status = int(result) except ValueError: if not result.endswith('\n'): result = result + '\n' sys.stderr.write(result) status = 1 except: import traceback traceback.print_exc() status = 1 Py_Finalize() return status -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From gsmith at oxfam.org.uk Thu Jan 29 11:43:34 2004 From: gsmith at oxfam.org.uk (Graham) Date: Thu, 29 Jan 2004 16:43:34 -0000 Subject: Pausing python programs References: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> Message-ID: <4019374d$0$13349$ed9e5944@reading.news.pipex.net> Thanks Max. Big help. regards From jzgoda at gazeta.usun.pl Sun Jan 25 13:10:57 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 25 Jan 2004 18:10:57 +0000 (UTC) Subject: Unique ID for CD or DVD References: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: Hoang pisze: > Does anyone know of an existing algorithm/module for generating a unique ID > for a given CD or DVD? This would be something akin to CDDB where a CD is > recognized based on its content. I could be wrong, but I think CDDB is just > based on file size or disk size and this alone is not unique enough. If the > solution is in Python, all the better. I'm pretty sure I saw Python interface for freedb. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From jepler at unpythonic.net Wed Jan 28 16:05:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jan 2004 15:05:30 -0600 Subject: Best way to compare a list? In-Reply-To: <7b454334.0401281242.3bd604e6@posting.google.com> References: <7b454334.0401271739.59267018@posting.google.com> <7b454334.0401281242.3bd604e6@posting.google.com> Message-ID: <20040128210530.GX18498@unpythonic.net> What do you mean by a "difference"? For instance, what are the differences between these two lists: [1, 2, 3] [3, 2, 1] For some purposes you might want to consider them equivalent, since they both contain 1, 2 and 3 (one time each) and they contain no other elements. Or you might want to say that they differ at element 0 and at element 2. And for this list, what are the differences? [1, 3, 4] [1, 2, 3, 4] For some purposes, you might say that they differ at indexes 1, 2, and 3. For other purposes, you might want to say that the second list has an extra "2" inserted at position 1, but the lists are otherwise the same. Once you define what you mean by "differences", perhaps we can be more helpful. But once you define exactly what your problem is, the algorithm to solve it should be more apparent to you, too! An answer to the simplest of the questions you may have been asking is this: [a == b for a, b in zip(l1, l2)] this returns a list with True in the positions where corresponding elements of l1 and l2 are equal, and False elsewhere. Jeff From dietrich at zdome.net Sat Jan 24 00:44:15 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Fri, 23 Jan 2004 21:44:15 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: <4011C497.1040302@prescod.net> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> Message-ID: <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Please understand, before you read this, that I think Python is the most elegant language that looks and feels natural. My point is that there are plenty of programming techniques which aren't natural in Python, but are still useful. I feel Python's strength is that it is flexible enough that most patterns that many programmers use day-to-day map very easily and naturally into readable Python code. The problem is that often when you use a pattern that doesn't fit the language you use, it will be difficult to code, harder to maintain, and behave unexpectedly meanwhile. The rest of the post is dedicated to two examples of patterns which don't quite fit into Python, but are used well in some projects written in other languages. On Jan 23, 2004, at 5:04 PM, Paul Prescod wrote: > Dietrich Epp wrote: >> ... >> >> Python seems to take the middle ground. It's build from a procedural >> standpoint, in an environment where most things are objects and some >> are functions. It's not what I'd choose as an example of an object >> oriented language. There are no messages, only function calls, so >> you can't capture them. > > That's certainly not true. Take a look at how the XML-RPC libraries > work. They capture "messages" sent from the program to the proxy > object, reify them as XML "messages" sent across the network and then > turned back into function calls applied to objects. Well, I don't mean that you absolutely can't capture a message, but it's just not something that's natural in Python the way it is in Objective C. In Objective C, I can create an object which doesn't respond to some message "foo". However, if I send "foo" to the object, it gets a chance to respond. In Python, there is no concept of messages. You would have to override the function that gets an object's attribute and create a function for it to return. You can capture function calls, but capturing method calls is a two-step process in Python which requires a little bit of magic to implement. The problem is that I didn't define message. In python, sending the "bar" message to the "foo" object is written as "foo.bar()". But it isn't the same as sending a message, because in Python, it's two steps: get the "bar" property of "foo", and call it. The example of this is at the end of this post. >> The plus side is that methods behave exactly the same as >> functions, this makes the language simple and the two ideas >> interchangeable. You can set an object's method to a function. The >> minus side is that the paradigm of sending a message "to" an object >> doesn't exist, and anyone coming from Smalltalk or even Objective-C >> might miss that and feel constrained (I did). But if Python were >> really object-oriented like that, then it wouldn't have Python's >> simplicity any more. >> > > I would appreciate an example of something you would do by capturing a > message that cannot be done in Python. > > I rather wonder if you've illustrated the downside of flitting from > language to langauge. You may think you're using a language to > capacity without actually doing so. I could be wrong but perhaps even > the tasks you turn to Lisp or Perl for may have easy equivalents in > Python. If I wanted to make this personal, I would accuse you of choosing your patterns to fit the language rather than vice versa. Or perhaps no useful pattern exists which is difficult in Python and easy in a different language? I love Python too, but it's only one of the tools in my box. Of course, you haven't seen my code, nor I yours. My most recent Perl script was about twenty lines of nothing but regular expressions and a couple dictionary operations. That would have been even less readable and writable in Python. My Lisp project related to an RPG and random generation of items. It had lots of code like the following: (defun random-sword-magic-power (quality) (choose-random-assoc quality (poor medium good) ((5 0 0) (glows-in-the-dark)) ((3 3 0) (magically-silent)) ((1 5 1) (elemental-power (select-random '(earth water air fire)))) ((0 2 4) (magical-keen-edge)) ((0 0 2) (append (random-sword-magic-power 'medium) (random-sword-magic-power 'medium))))) The numbers on the left are probabilities relative to the other probabilities in the same column. So, when generating a random 'poor' magic quality of a sword, you have a 5/9 chance of getting 'glow in the dark'. For a 'good' quality, you have a 2/7 chance of getting two 'medium' qualities instead. It is difficult for me to imagine how one would go about making this function more concise, to me it looks downright minimal. The only thing I could see making it smaller would be removing the parentheses, but they would have to be replaced by something else such as commas or tabs. I'm not trying to say that all applications are like my application, and I'm not trying to say that my application can't be written in Python. I'm just saying that using macros, a paradigm that Python doesn't even come close to supporting, makes reading and writing functions like the above a lot easier. You don't even need to know that 'choose-random-assoc' is a macro, you just need to know how to use it. Heck, defun is a macro in Clisp. I challenge anyone to come up with a better way to express the above function in Python. If I think it's better, I'll write "PYTHON RULZ" on my forehead and post a photo on the web. On Jan 23, 2004, at 5:35 PM, Brian Quinlan wrote: > Dietrich wrote: >> Python seems to take the middle ground. It's build from a procedural >> standpoint, in an environment where most things are objects and some >> are functions. > > I'd be interested to know why you don't think that functions are > objects. I > would argue that they are because they have attributes, methods, and > are > bound to variables the same way as other Python objects. I agree that functions are objects in Python. However, not everything in Python is an object. For example, names are not objects. In the above example, "foo.bar()", neither "foo" nor "bar" are objects, but they are references to objects. In some languages, such as C and Lisp, references to objects can be directly manipulated (Lisp has symbols, C has pointers). >> It's not what I'd choose as an example of an object >> oriented language. There are no messages, only function calls, so you >> can't capture them. > > You certainly can capture them. Could you demonstrate the Objective-C > or > Smalltalk syntax for doing so? Maybe it is a lot easier in those > languages. In Objective C: - (void)forwardInvocation:(NSInvocation *)invocation { if ([someOtherObject respondsToSelector:[invocation selector]]) [invocation invokeWithTarget:someOtherObject]; else [self doesNotRecognizeSelector:[invocation selector]]; } In Python: def __getattr__(self, name): try: return super(this_class, self).__getattr__(name) except AttributeError: try: method = super(this_class, self).some_other_object.__getattr(name) if iscallable(method): return method except: pass raise In Python you have to be careful because this won't normally capture just method calls, but all attribute accesses. In a typical Objective-C application you'll probably see a lot of places where the program sends a message to an object only if the object responds to that message. Let's compare. In Objective C: - (void)resetToDefaultSettings { if ([delegate respondsToSelector:@selector(defaultSettingsFor:)]) [self setSettings:[delegate defaultSettingsFor:self]]; else [self setSettings:someFallbackValue]; } In Python, first try: def reset_settings(self): try: self.set_settings(self.delegate.default_settings(self)) except AttributeError: self.set_settings(some_fallback_value) But wait! What if there is an error in self.delegate.default_settings() which raises an AttributeError? It might confuse the hell out of a programmer who might go looking for the bug in reset_settings(), because it's using the fallback value for some odd reason. So we should reimplement it. Python, second try: def reset_settings(self): method = None try: method = self.delegate.default_settings except AttributeError: pass if method: self.set_settings(method(self)) else: self.set_settings(some_fallback_value) If you think this example is contrived, maybe you haven't worked with the paradigms used in Objective-C very much. The example above was used dozens of times in a class that I wrote in Objective-C which draws a grid to the screen, for example, when it asks itself or its delegate what color the grid should be, or the maximum scale allowed. The practice is also used heavily by Apple's Cocoa libraries, which are my favorite UI libraries of all time to program with. From peter at engcorp.com Wed Jan 28 14:03:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 14:03:44 -0500 Subject: Distributing Python programs References: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net> <4017C6EE.E7F1B27@engcorp.com> <4017cd62$0$9388$ed9e5944@reading.news.pipex.net> Message-ID: <40180790.FED25AB8@engcorp.com> Graham wrote: > > "Peter Hansen" wrote in message > > > Yes, we run dozens of machines from a single network installation. > > Depending on what extensions you need to install (e.g. win32all) you may > > need to make some small manual adjustments to get it to work, but > > in essence you can just do a "non-admin" local install, then copy the > > entire directory tree to the network. > > > Peter > Thanks for this info. Will this work with Python for Windows? Yes, this is specifically with Windows 98. > I tried what > you suggested a few days ago but found when I ran a python script it asked > me for a python.dll which I have found not in the directory tree but in my > local system32 directory (I have a local Python installation). > > What is significant about the "non-admin" install and how do you do this? The significance of the "non-admin" install is that it would fix the problem you just described... -Peter From ptkwt at aracnet.com Mon Jan 19 22:58:49 2004 From: ptkwt at aracnet.com (Phil Tomson) Date: 20 Jan 2004 03:58:49 GMT Subject: New to Python: my impression v. Perl/Ruby References: Message-ID: In article , Wayne Folta wrote: >-=-=-=-=-=- > >I've been a long-time Perl programmer, though I've not used a boatload >of packages nor much of the tacky OO. > >A couple of years ago, I decided to look into Python and Ruby. Python >looked OK, but not that different. I did like the indent-as-group idea, >which was different. Ruby looked very cool. It _is_ very cool. >But it was impossible to >get good documentation. It' s not _impossible_. Check out www.ruby-doc.org, for example. >It seemed like a Japanese cult with a few >western initiates. You should see us at the Ruby conferences. We must speak only in haiku until we reach the Master level ;-) > >Well, MacOS X ships with Perl, Python, and Ruby (and PHP, and ...) so I >recently figured I'd try them again. I still find Ruby more intriguing, >but I've settled on Python. Why? > Don't lose the intrigue. ;-) >Well, Perl is an expedient measure that (for me) doesn't scale up and >has that horrible OO syntax. (So I never used it much.) If you're going >to read someone else's Perl, you had better be "in the zone". > >A couple of months ago, I'd written a quick Perl script that would >"unstick" a co-worker's POP email. The problem is the Windows-based POP >server is too stupid to realize a message does not end in CRLF, so it >just appends a period then CRLF thinking it's doing well. But the >period ends up not being alone on a line, so it's not a valid >termination to the message. So their email program hangs waiting for a >proper termination. Sigh. > >A week ago, the script broke because I hadn't properly accounted for >the fact that the user might have hundreds of messages queued up. (I >hadn't used a Perl POP package, which might've handled it, but just >threw it together myself. Yes, that would've made the Perl code more >competitive with the other two solutions.) > >So I decided this might be a nice exercise to try Python. And it went >together very quickly using Python's POP3 package. Then I decided to >try it in Ruby. I think one little portion of the code shows the >difference between the two cultures. > >The problem is that the message is not properly terminated, so you need >to time out and catch that timeout to realize, "hmmm, malformed". In >Python I had: > >M = poplib.POP3 ('172.16.30.1') ; >M.user ('foo') ; >M.pass_ ('bar') > >num_mesgs = len (M.list ()[1]) >bad_mesgs = 0 > >for msg in range (num_mesgs): > try: > M.retr (msg + 1) >... blah blah... > >How do I get it to time out after 5 seconds and how do I catch that? >The online docs are pretty good, but I had to guess that POP3 was built >on the socket package. Looking at socket's docs I found the proper >command and exception. I had to include: > >socket.setdefaulttimeout (5.0) > >before the POP3 commands to set the default socket timeout to 5 >seconds. And > >except socket.timeout: > >is the proper way to catch the timeout. Both of these things are in the >socket documentation. > >Contrast this with Ruby. The Ruby docs are less complete, but they did >mention that POP was subclassed from protocol and you'd have to look at >protocol's source to see how it works. Looking through protocol, I >figured out what to do and it was more elegant. > Um hmmm... A quick google for: Net::Protocol Ruby revealed several hits. Although, I'll admit, I didn't find the Net::Protocol class covered in the Pickaxe book. >The protocol class had a read_timeout, but since Ruby's mantra might be >said to be "Real OO", the POP code had been written such that you could >say > >pop.read_timeout = 5 So what's the problem? > >after the POP open and it set the timeout for that pop connection to 5 >seconds. Almost as if POP passed the read_timeout upstream to socket >automatically. (I don't think Ruby does, but it's coded to look that >way.) Did it or didn't it? You never really say what happened with the Ruby code. > >My experience is limited, but it feels like this example gives a good >feel for the two languages. Python was better documented and things >came together quickly. Ruby ultimately had a more elegant solution, but >was more poorly documented. This echoes the mantras: Python's is >"Batteries Included", while Ruby's might be "Real OO". Ok, so you basically had to read the code and then you got it working, or no? > >On a personal note, I usually prefer an elegant solution, but when the >language goes so far as to consider > >0.step(360, 45) > >to be reasonable, my head hurts. I know there's syntactic sugar so I >don't have to code like that. I know everything's an object. But, >dammit, a constant integer is an integer with constant value and >causing it to iterate is a step too far. Different strokes for different folks, I guess. I remember that one of the first things I saw about Ruby was that even interger literals were objects that can receive messages and thinking how wonderful that was. As you say, you're not forced to do things this way - you can use 'for' for example, but: 10.times do something end is somehow so clear. It's almost zenlike. ;-) Phil From amitgaur at yahoo.com Sat Jan 24 09:56:16 2004 From: amitgaur at yahoo.com (Amit Gaur) Date: Sat, 24 Jan 2004 06:56:16 -0800 (PST) Subject: Changing endian format Message-ID: <20040124145616.34640.qmail@web41306.mail.yahoo.com> Hi newbie to python here, I have a binary file and i need to change the endian format..little to big as well as vice versa..could anyone help me out. thanks --------------------------------- Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Wed Jan 21 01:02:08 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 20 Jan 2004 22:02:08 -0800 Subject: PyTime Object and Application Crashing Message-ID: Ryan Scott wrote: > When I run a query against an access database and the default > date for > my date/time field is 12/30/1899 the application crashes. > Changing this > to a different date like 03/03/2003 works. > The output of the query when returned as a list is as follows: AFAICT all dates on or before that date will crash. You have several options: 1. Cast the date value to a string in your SQL before retrieving values; then parse. 2. Store dates as strings altogether avoiding Access date fields. 3. Access the date value as a float, not a PyTime: # 12/30/1899, the zero-Date for ADO = 693594 zeroHour = datetime.date(1899, 12, 30).toordinal() if value is None: return None else: aDate, aTime = divmod(float(value), 1) aDate = datetime.date.fromordinal(int(aDate) + zeroHour) hour, min = divmod(86400 * aTime, 3600) min, sec = divmod(min, 60) aTime = datetime.time(int(hour), int(min), int(sec)) return datetime.datetime.combine(aDate, aTime) HTH! Robert Brewer MIS Amor Ministries fumanchu at amor.org From usenet at mail-2-me.com Sat Jan 31 15:20:15 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: Sat, 31 Jan 2004 21:20:15 +0100 Subject: Running External Programs from Within Python In-Reply-To: <5a40bf6a.0401311123.4b7f783f@posting.google.com> References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: Bob=Moore wrote: > I'm considering making the transfer from Rexx to Python as a scripting > language, but there's one thing I can do in Rexx that I can't seem to > do in Python: run an external program. > > Suppose I have a Tkinter GUI and I want to just push a button and run > the Windows utility notepad.exe. Or push another button and run one > of my old Rexx programs. > > Basically I want to send a command line to Python and have it run that > command line as if I'm sending it to the Windows command-prompt, an > MS-DOS window, or clicking on an appropriate program icon. > > Can I run (call? exec? eval?) an external program from inside a Python > program? > > I have checked the FAQ and documentation. > > Thanx, > > Bob=Moore Hi Bob! That is very easy: popen() Check the FAQ and documentation again for popen. Regards Dirk From rupole at hotmail.com Wed Jan 14 05:53:17 2004 From: rupole at hotmail.com (Roger Upole) Date: Wed, 14 Jan 2004 02:53:17 -0800 Subject: catching msie NewWindow2 event References: Message-ID: <4004f195_2@127.0.0.1> You have to return the out parameters. Try adding return ppDisp,True to the bottom of OnNewWindow2. Roger "mic" wrote in message news:bu146d$66p$1 at news.atman.pl... > I'm trying to catch the MSIE NewWindow2 event using win32com interface. The > code I use is basically something like below: > > from win32com.client import DispatchWithEvents > > class Events: > Browser = None > def OnNewWindow2(self, ppDisp, Cancel): > #catching the new window and trying to place it onto my own > ppDisp = Events.Browser > #Cancel = True - this doesn't work either (should prevent popup from > opening) > > ie1 = DispatchWithEvents('InternetExplorer.Application', Events) > ie2 = DispatchWithEvents('InternetExplorer.Application', Events) > Events.Browser = ie2 > ie1.Navigate('http://jaak.sav.net/test.html') #url to the html document that > opens its own window > > I know that setting ppDisp value should work (at least I've seen it working > in C# code) but using it this way gives no results. What's more depending on > the url I use the event is triggered or not (other standard events work > okay). I've seen ctypes COM implementation demo that makes similiar things > but it looks so much more complicated than win32com api. Hope somebody has > some insight on that... > > Regards, > > Michal > > From theller at python.net Tue Jan 20 06:16:10 2004 From: theller at python.net (Thomas Heller) Date: Tue, 20 Jan 2004 12:16:10 +0100 Subject: interface to win job scheduler portable from win98 .. winXP / cmdline or COM ? References: Message-ID: Tim Golden writes: >>From: Robert [mailto:k.robert at gmx.de] >> >>I found the os.popen("AT /?") way .... however it works not on Win98 >>and the "Day" you enter at the AT are language dependent. >>(e.g. Mi(ttwoch) in german, We(dnesday) in english Windows versions) >> >>I need a solution work from Win98..WinXP most independent from >>internationalization etc. >> >>is there portable way - or at all a way to manipulate the Win98/ME >>scheduler ? if no simple means, even COM stuff would be ok. any >>pointers? >> > > WMI looks like it covers it, but only NT4 / Win2K / XP. > Oh, sorry, I've just realised: the Win32_ScheduledJob > actually refers to the AT service (despite the name!) > > If you're really looking for something which will work > across every version of Windows, I think you're better > off doing something entirely Python from the start. It > shouldn't be hard (he says, having not tried it himself). > The advantage is: it will work everywhere and you have > complete control over it. The disadvantage is: you have > to create your own interface and deal with whatever > issues the existing mechanisms have already dealt with. I'll second that this is most certainly the easiest solution. There seems to be, however, a COM interface to the Task Scheduler, using all custom interfaces: As usual, the docs aren't that crystal clear, but I get the impression that it's even available in win 95, provided that IE4 is installed. Thomas From jsbenson at bensonsystems.com Mon Jan 19 11:46:52 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Mon, 19 Jan 2004 08:46:52 -0800 Subject: time module question Message-ID: <001401c3deab$d7c2d630$210110ac@jsbwxp3> I display a little date and time (down to the seconds) in my Tkinter GUI using Twisted internet sockets and ask Twisted to call a routine the rerequests itself every second. That routine also updates the clock display, so when I can see the seconds counting up, I know that the main event loop isn't frozen for whatever reason. This is not time module functionality, but event scheduling within Twisted. Tkinter also has this capability of calling a function of your choice at some point in the future. This rather handily replaced an older, more paranoid version in which I logged a "heartbeat" message every so often to convince myself that all was well. Message: 5 Date: Mon, 19 Jan 2004 05:12:39 GMT From: Jeff Seale Subject: time module question To: python-list at python.org Message-ID: How would one go about writing a program which included a clock that updated itself? Right now I'm able to display the time in a text widget in the window but I can't get it to update. From scrutinizer at gmx.at Sat Jan 31 08:07:08 2004 From: scrutinizer at gmx.at (Francesco) Date: Sat, 31 Jan 2004 14:07:08 +0100 Subject: ANN: wxPyAtol Message-ID: <01an10pfhlrt12iijnid8of3qot3o92uki@4ax.com> (sorry, if this is also posted in comp.lang.python.announce, but i couldn't see the message) Hello, I'm happy to announce "wxPyAtol" The original program is written by Miroslav Rajcic and is called Atol Filemanager. It is programmed in C++ using wxWindows http://atol.sourceforge.net/ I have posted the sources to: http://berg.heim.at/anden/421194/wxpyatol.zip A few months ago, i couldn't imagine, that this is possible to do in python + wxpython. But also with the help of win32 extensions, I managed to get the most things work. I know, it is almost not at all "pythonic", but I wanted to keep it so, because it is better to compare to the c++ sources, and maybe later, I will inlude more python style. Maybe someone could help me and give me some pointers: In the source, it is marked with todo. for example to retrieve the imagelist from Windows fileextensions self.m_hImageList = windll.shell32.SHGetFileInfo('.txt', win32file.FILE_ATTRIBUTE_NORMAL, byref(shfileinfo), sizeof(shfileinfo), dwFlags) How can I get this in python? thank you and best regards (and sorry for my bad english) -- Francesco From sombDELETE at pobox.ru Sun Jan 4 19:20:36 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 5 Jan 2004 03:20:36 +0300 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Sean R. Lynch" wrote in message news:mvScnSDrma66AWWiXTWc-g at speakeasy.net... > Serge Orlov wrote: > > "Sean R. Lynch" wrote in message news:srudnTjvU9BOH2qiRVn-uA at speakeasy.net... > > > > Thinking about str.encode I conviced myself that global state shouldn't > > be shared by different security domains so that means codecs.py and > > __builtins__ must be imported into each security domain separately. > > It's pretty easy to do with codecs.py since it's python code. But importing > > __builtins__ more than once is pretty hard since it wasn't designed > > for that. > > Global *mutable* state shouldn't be shared, AFAICT. Right, I missed this simple rule. My mind is still confined by my recent attempt to add security by only translating bytecode without any changes to the interpreter. > I believing making > sure no mutable state is reachable through __builtins__ Are you going to create multiple __builtins__ or you're just going to get rid of any global objects in __builtins__? The first lets you handle str.encode the right way. > and having a new > globals dict for each security domain should be enough. Any modules that > are imported would need to be imported separately for each domain, Can C modules be imported more than once in CPython? > which > should be possible with a modified __import__ builtin. I don't have any > intention of allowing import of unaudited C modules. Agreed. -- Serge. From CGStartup at earthlink.net Sat Jan 31 11:07:49 2004 From: CGStartup at earthlink.net (Stan Schwartz) Date: 31 Jan 2004 08:07:49 -0800 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia Message-ID: <2da21d6c.0401310807.671be3b7@posting.google.com> My name is Stan Schwartz, and I'm a University of Pennsylvania Ph.D. and an independent inventor. I'm submitting two computer graphics patents to the USPTO during the next several weeks. Technologies derived from these patents have application in several different market segments, including still image photomanipulation, movie special effects and post-production, web animation, and video games. I'm developing and marketing one or more of the applications through a startup company. I've produced demo output that clearly demonstrates the viability of my approaches, which I've been showing to potential licensees and investors. This demo output is currently being generated through a loosely connected series of scripts. To be productized the scripts will need to be recoded into standalone "industrial strength" applications that are much faster, bullet-proof, and that have slick GUIs. I'm looking for a lead/senior programmer to participate in and organize the implementation side of the startup and probably one or more junior programmers. Successful candidates for the programming team should have some to many of the following skills/characteristics: Extensible knowledge of/comfort with math, as exemplified by one or more of: Computer vision training/experience - feature location/ extraction, motion estimation, object recognition; Image processing training/experience - you know what a convolution kernel is; you've implemented a morphing algorithm; Linear algebra training/experience - matrix manipulation, familiarity with numeric computation packages, such as Numerical Python, or equivalent; Art/math programming play, mathematical visualization; 3D modeling, especially for character animation, especially if you've hacked/manipulated low-level 3D data representations in a variety of formats; GUI design/building, graphic design training a plus; Analysis of algorithms; C/C++, Linux/Unix a plus; (Note that I did most of the scripting mentioned above in Python through PIL and Numerical Python and would consider doing as much as we can of this in Python.) Startup and/or major fielded product development experience required for the lead/senior programmer, a plus for juniors; Within commuting distance of Philadelphia - we may move and/or outsource, but this is where/how we'll start; Relevant educational background is a plus, but I'm more interested in what you can demonstrate to me that you know, can do, and have done, than what you've formally studied; Intellectual flexibility, creativity, and ability to work and brainstorm collaboratively; Open-ended time commitment - After growing this, I have additional ideas in the queue that could be spun off into future products; and Demonstrable artistic skills and training in figurative painting, sculpture, and/or life-drawing are a plus. We have access to seed capital, and we'd prefer if participants accept some portion of salary as equity in our venture. If you're interested in participating, send me a cover letter and resume at cgstartup at earthlink.net. I'm willing to show you the demo and provide more details about the technology, although first you'll have to sign a non-disclosure agreement. The demo can also be posted temporarily to the web for online viewing, accompanied by an explanatory phone call. For Investors/Licensees: If you're a potential investor in the startup or a representative of a company that is potentially interested in licensing one of the applications and are interested in seeing the demo and hearing a description of the technologies, also under conditions of non-disclosure, please let me know through the means described above. Thanks for your time, Stan From rkern at ucsd.edu Sun Jan 18 18:20:52 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 18 Jan 2004 23:20:52 GMT Subject: Fw: PDF library for reading PDF files In-Reply-To: <100luvhbh3vr75d@corp.supernews.com> References: <100luvhbh3vr75d@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Harald Massa wrote: > >>>I am looking for a library in Python that would read PDF files and I >>>could extract information from the PDF with it. I have searched with >>>google, but only found libraries that can be used to write PDF files. >> >>reportlab has a lib called pagecatcher; it is fully supported with python, >>it is not free. >> >>Harald > > > ReportLab's libraries are great things--but they do not "extract > information from the PDF" in the sense I believe the original > questioner intended. No, but ReportLab (the company) has a product separate from reportlab (the package) called PageCatcher that does exactly what the OP asked for. It is not open source, however, and costs a chunk of change. From NAVMSE-INVESTORS_FS1 at alliedcalifornia.com Fri Jan 30 15:39:48 2004 From: NAVMSE-INVESTORS_FS1 at alliedcalifornia.com (NAV for Microsoft Exchange-INVESTORS_FS1) Date: Fri, 30 Jan 2004 12:39:48 -0800 Subject: Norton AntiVirus detected a virus in a message you sent. The inf ected attachment was deleted. Message-ID: <7B3B51FA0493D311B3720090278D3B9637FA2A@INVESTORS_FS1> Recipient of the infected attachment: Bob Conrad\Inbox Subject of the message: HELLO One or more attachments were deleted Attachment document.zip was Deleted for the following reasons: Virus W32.Novarg.A at mm was found. Virus W32.Novarg.A at mm was found in document.htm .scr. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1871 bytes Desc: not available URL: From guido at python.org Mon Jan 26 11:57:44 2004 From: guido at python.org (Guido van Rossum) Date: Mon, 26 Jan 2004 08:57:44 -0800 Subject: PyCon Reminder: Early bird reg deadline 2/1 Message-ID: <200401261657.i0QGviR22138@c-24-5-183-134.client.comcast.net> Info ---- This is a reminder that the deadline for early bird registration for PyCon DC 2004 is February 1, 2004. Early bird registration is $175; after that, it will be $250 through March 17, then $300 at the door. (Note that a week ago I announced the wrong prices for non-early bird. :-) To register, visit: http://www.pycon.org/dc2004/register/ Plug ---- PyCon is the most important conference in the year for me. It brings together the largest group of Python users and developers imaginable. I come to PyCon for many reasons: to meet with other core Python developers face to face; to hear about the exciting things that users from all over the world are doing with Python; to interact in person with Python users of all types, from newbies to veterans of many years; to hear everybody's feedback on where Python is and where they'd like it to go; and perhaps most of all to continue to encourage this wonderful community by my presence, words and actions to grow, reach out to new users of all kinds, and keep listening to each other. I hope everyone who comes to the conference will return from it with a new or renewed feeling of excitement about Python, whether they are developers, sophisticated users, beginners, or even skeptical passers-by. The Python community includes everyone, from grade schoolers just learning about computer science to renowned scientists interested in using the best tools and business people looking for a secret weapon. I'm looking forward to seeing you all at PyCon! Background ---------- PyCon is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. We're looking for volunteers to help run PyCon. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ --Guido van Rossum (home page: http://www.python.org/~guido/) From prtk3 at yahoo.com Thu Jan 29 00:06:25 2004 From: prtk3 at yahoo.com (PT) Date: 28 Jan 2004 21:06:25 -0800 Subject: mod_speling for python Message-ID: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Hi, I'm not looking to get into a debate about case-sensitive vs. insensitive programming languages, but I was looking for suggestions about how it might be possible to add a hook to the python parser similar to the Apache mod_speling module (links below). So that for example if there is a NameError exception, python walks the globals() and locals() to see if it might be just a minor spelling/capitalization error. I can see how this might be done for ImportErrors, using ihooks or iu, but I don't see how to do it for NameErrors. The python compiler module doesn't seem to be the answer. I know there are drawbacks, disadvantages, this is "evil", etc. I only wanted to know what ways there are to add such a hook if it is possible without altering the C source for python itself. Possible End-User Solution A: Simply add an "import spelling" to a python file to enable spell-checking, sort of like how you use the psyco module (speaking of which, how many times have you misspelled that). Possible End-User Solution B: Create an alternative executable that wraps the python interpreter. This wrapper may or may not have to use its own source code parser, like the unreleased mobius-python project. http://httpd.apache.org/docs/mod/mod_speling.html http://lxr.webperf.org/source.cgi/modules/mappers/mod_speling.c http://www.mcmillan-inc.com/importhooks.html http://www.python.org/doc/current/lib/module-compiler.html http://sourceforge.net/projects/mobiuspython From exarkun at intarweb.us Tue Jan 27 10:10:10 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 27 Jan 2004 10:10:10 -0500 Subject: print format for binary representation In-Reply-To: <6f03c4a5.0401270700.713a73aa@posting.google.com> References: <6f03c4a5.0401270700.713a73aa@posting.google.com> Message-ID: <20040127151009.GA16950@intarweb.us> On Tue, Jan 27, 2004 at 07:00:23AM -0800, Rim wrote: > Hi, > > >>> print '%x' % 54 > 36 > >>> print '%b' % 54 > Traceback (most recent call last): > File "", line 1, in ? > ValueError: unsupported format character 'b' (0x62) at index 1 > >>> > > No formating string for binary? There %x for hex. Would %b make sense > for bin? Is this worth a PEP? > > How do I get 00110110 printed instead of the traceback? Oft requested, oft rejected. Defining binary() is about one line of code. Hex is supported because printf(3) supports it. Here's a version to toy with: binary = lambda i, c = (lambda i, c: i and (c(i >> 1, c) + str(i & 1)) or ''): c(i, c) Jp From donn at drizzle.com Sat Jan 24 01:45:02 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 24 Jan 2004 06:45:02 -0000 Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> Message-ID: <1074926701.236022@yasure> Quoth Zoo Keeper : | No takers, eh? :/ | | I can't be the only python user on BeOS... | | The only thing I can think of is that I am running "bone". Well, at least now we know one thing about your setup. In later versions, a Python class can definitely inherit from BWindow. If you have the 0.5.1 distribution, the programs in "test" do it that way, and they work. Earlier versions, before 0.5.0, can't do this (and neither can older versions of Python.) It is certainly possible to mess up the BeOS libraries while trying to improve them, though, as demonstrated by the 3rd party "Developer Edition". That certainly could be your problem. You're not the only Python user on BeOS, but they are few. Given the level of general interest, I think you'd have better odds posting to comp.sys.be.programmer. As for what I read as your implicit question, will you be sorry you chose to develop your application in Python with a Bethon UI - it depends on the details. The functions available here are numerous but not nearly the whole Be API, and there are whole areas of functionality that it will probably never get into. It's pretty useful for casual stuff, but probably not for real hard core polished applications. Distribution will be a harder, too, than a straight C++ program. Donn Cave, donn at drizzle.com From flemming at bjerke.dk Thu Jan 29 03:41:20 2004 From: flemming at bjerke.dk (flemming at bjerke.dk) Date: 29 Jan 2004 08:41:20 -0000 Subject: I have changed my e-mail address Message-ID: <20040129084120.54659.qmail@dmerhverv.org> Send mail til: flem[SLET DETTE]@bjerke.dk Send mail to: flem[DELETE THIS]@bjerke.dk I close flemming at bjerke.dk. Flemming From sross at connectmail.carleton.ca Tue Jan 6 12:19:00 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 6 Jan 2004 12:19:00 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: "Dan Bishop" wrote in message news:ad052e5c.0401041659.68460bd at posting.google.com... > It's a feature. The advantage of defining x // y as floor(x / y) is > that x % y is always nonnegative. Sorry, but x%y can be negative in Python: >>> x, y = 5, -10 >>> x%y -5 From aahz at pythoncraft.com Mon Jan 5 15:42:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Jan 2004 15:42:02 -0500 Subject: Tkinter and OS X 10.3? References: <7ba1cb43.0312301205.30156acf@posting.google.com> Message-ID: In article , Russell E. Owen wrote: > >You are almost certainly typing python instead of pythonw at the >terminal prompt. This results in exactly the error described. (I'm not >sure why there are two commands instead of python doing whatever extra >magic pythonw does.) I'd guess that pythonw imports more stuff; if you want to run a non-GUI application (say in a cron job), that would be wasteful. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From james at logicalprogression.net Wed Jan 21 14:50:23 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 19:50:23 +0000 Subject: Assignment to slice In-Reply-To: <20040121191546.4975.qmail@web40102.mail.yahoo.com> References: <20040121191546.4975.qmail@web40102.mail.yahoo.com> Message-ID: <200401211950.23340.james@logicalprogression.net> On Wednesday 21 January 2004 7:15 pm, Rich Krauter wrote: > I see your point. However I could be wrong, but I > don't know if what you say is really the case, since > negative indexes are just shorthand for > > actual positive index = i + len(x), > > where i is the negative index, and len(x) >= abs(i). > > e.g. > > x = [1,2,3,4,5] > x[-4] is equivalent to x[-4+len(x)], which is x[1] > x[-4:-2] is equivalent to x[(-4+len(x)):(-2+len(x))], > which is x[1:3] > > I contend that my restriction may still hold even in > the case of negative indices, since negative indices > (which are just convenient shorthand), should map to > positive indices. > > In that case, > x = [1,2,3] > x[-10:-9] = [54] should return an exception too since, > > x[-10:-9] = x[-10+len(x):-9+len(x)] == x[-7:-6], which > is REALLY out of bounds of x. Assignment to x[-4:-3] is not same as assignment to x[-1:0]: >>> x = [1, 2, 3] >>> x[-4:-3] = [56] >>> x [56, 1, 2, 3] >>> x = [1, 2, 3] >>> x[-1:0] = [56] >>> x [1, 2, 56, 3] Although x[-4:-3] and x[-1:0] both evaluate to the same thing (an empty list). I would be interested to hear what anyone else has to say about this. > Instead python will just tack stuff on to the front of > the array. Which, I still believe, is totally > inconsistent. But what do I know? I have about 5 > minutes of python experience. > > I guess I just don't like that behaviour. At least in > perl if I assign something to a list slice: > > @x[2..3] = (4,5); > > the list grows, so that the things I inserted are at > the indices where I think I inserted them. > That is, @x now contains (0,0,4,5). That's another way to do it, I suppose. :) James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From none at none.com Mon Jan 12 09:41:59 2004 From: none at none.com (Derek) Date: Mon, 12 Jan 2004 09:41:59 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: "Bicho Verde" wrote: > I have now free time and money to do what I want :-) > > I have some basic skills in programming (C, Pascal, > Macromedia Actionscript) but don't know exactly what to do > in the world of programming. > > And also I don't know exactly why would I learn Python > rather than C#, C++ or Perl. Basicaly I don't know where > to start, if there is much to do or if it is has it seems > and there is software to everything nowadays and so > doesn't make sense to spend time in learning a programming > language. > > I just have this idea that I would like to contribute > to the curve of accelarated exponential progress > (technological singularity), artificial intelligence and so > on. From that point of view there is much to do... But can > I stand for it and where to start? > > Anyone would help me and give me some hints? I agree in large part with Paul's comments. C# is Microsoft's baby though it's technically an open standard -- don't go there unless you have a reason. Perl is pretty cool but I definitely found it harder to use and less intuitive than Python. I would not dismiss C++ (or even vanilla C) outright. I strongly suggest starting in Python and looking to C and C++ when you have good reason -- that is, when those languages will let you do something that Python is less than than stellar at: large applications, system software, performance-critical applications, embedded programming, etc. I would also add that while Lisp has been a favorite in the AI community, you will find that most AI techniques generalize to most any programming language. I spent a good deal of time in grad school and on my first job doing AI programming in C++. The only time I used Lisp was in introductory classes, mostly to write elegant -- but toy -- programs. From steveb428pleaseremovethis at hotmail.com Sun Jan 18 18:43:25 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Sun, 18 Jan 2004 23:43:25 GMT Subject: Using python for _large_ projects like IDE References: <930ba99a.0401180625.5863acd4@posting.google.com> <22zOb.2835$Zk3.135@newssvr29.news.prodigy.com> Message-ID: Thanks Sam "Samuel Walters" wrote in message news:pan.2004.01.18.22.01.46.670164 at yahoo.com... > | DilbertFan said | > > > If you do write this IDE, please include a compiler warning that catches > > the missing () at the end of a function that doesn't have arguments. I've > > sunk into a dark world of a diabolically mind-destroying hysteria while > > trying to troubleshoot some scripts, and then realizing that a python > > function was not executing because I was calling it without '()'. But > > Python doesn't complain, or give you a message or anything,... it simply > > doesn't execute that function! > > Try PyChecker. It should warn you about such things. > http://pychecker.sourceforge.net/ > > HTH > > Sam Walters. > > -- > Never forget the halloween documents. > http://www.opensource.org/halloween/ > """ Where will Microsoft try to drag you today? > Do you really want to go there?""" > From http Sat Jan 31 17:56:15 2004 From: http (Paul Rubin) Date: 31 Jan 2004 14:56:15 -0800 Subject: OT: why do web BBS's and blogs get so slow? Message-ID: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Lots of times, when a blog (that supports user comments) or a web BBS gets heavily loaded, it slows down horribly, even when it's hosted at an ISP on a fast computer with plenty of net bandwidth. I'm wondering what those programs are doing, that makes them bog down so badly. Anyone know what the main bottlenecks are? I'm just imagining them doing a bunch of really dumb things. I'm asking this on clpy because thinking about the problem naturally made me wonder how I'd write a program like that myself, which of course would mean using Python. FWIW, here's how I'd do it: 1) It would be single threaded web server (asyncore, twistedmatrix) with a select loop talking to a socket, either on port 80 directly, or to a proxy web server running mod_gzip, SSL, and so forth. 2) It might use MySQL for infrequent operations like user info lookup at login time or preference updates, but not for frequent operations like reading and posting messages. User session info and preferences would be in ram during a session, in a python dict indexed by a browser session cookie. 3) The message store would be two files, one for metadata and one for message text. Both of these would be mmap'd into memory. There would be a fixed length of metadata for each message, so getting the metadata for message #N would be a single array lookup. The metadata would contain the location in the text file where the message text is and its length, so getting the text would take just one memcpy. The box would have enough ram to hold all recently active messages in ram almost all the time. Paging to disk is left to the host OS's virtual memory system. From the application's point of view everything is always in ram. Digging up old messages might take some page faults, but doing that should be relatively rare. New messages are always appended to the files, keeping memory and paging behavior fairly localized. There might be a third file for an activity log, which is append-only (serial access). Ideally that would be on a separate disk from the message disk, to reduce head contention. 4) Finding all N messages in an active discussion thread might require chasing N pointers in the metadata file, but that would usually be at most a few thousand small lookups, all in ram, and the thread info would be cached in ram in the application once found. Fancier disk structures could speed this up but probably arn't needed. A site like Slashdot gets maybe 20(?) page views per second at busy times, and around 10,000 new messages a day of maybe 1 kbyte each, a mere 10 MB per day of message text, no problem to keep in ram. I'd like to think that the above scheme could handle Slashdot's traffic level pretty easily on one or two typical current PC's with IDE disks, one PC for the BBS application and the other (if needed) for a proxy server running gzip and caching static pages. Am I being naive and/or missing something important? Slashdot itself uses a tremendous amount of hardware by comparison. From bignose-hates-spam at and-benfinney-does-too.id.au Mon Jan 26 21:23:37 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jan 2004 13:13:37 +1050 Subject: Python on portable storage References: Message-ID: On 27 Jan 2004 12:59:26 +1050, Ben Finney wrote: > Howdy all, > > I'm experimenting with carrying my personal computing environment around > on a keychain USB flash storage device. I have the usual suspects on > there: SSH keys, GPG keys, program configs. > > I'm probably not the first to think that a standalone distribution of > Python would be a useful thing to have in my back pocket. Finding > information on that is proving to be a problem, however. I did find this thread: where the OP asked much the same question; the responses were mostly "boot GNU/Linux and run it that way". This isn't what I'm after; I want to walk up to an existing machine, and, without rebooting or installing any software on the machine, plug in my USB storage device and run Python entirely from that. This will mean having a Python executable that can run under the existing environment, of course. What I'm hoping is that there is information on how to set that up, so that the resulting storage has a self-contained Python environment, assuming the executable will run in the first place. -- \ "I filled my humidifier with wax. Now my room is all shiny." | `\ -- Steven Wright | _o__) | Ben Finney From jepler at unpythonic.net Mon Jan 5 22:10:34 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Jan 2004 21:10:34 -0600 Subject: Python/C and PYTHONPATH In-Reply-To: References: Message-ID: <20040106031034.GE5514@unpythonic.net> On Mon, Jan 05, 2004 at 04:17:52PM +0000, Tero Pihlajakoski wrote: > Jeff Epler wrote: > > You'd need to tell us how you're invoking Python. When the Python > > Take a look at: > http://www.python.org/doc/current/ext/pure-embedding.html. Basically, > it's about same (and I tested with it too, same results: failing) Here's the program I came up with: #include int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); PyRun_SimpleString("import sys; print sys.path, sys.executable"); PySys_SetArgv(argc-1, argv+1); PyRun_SimpleString("import sys; print sys.path, sys.executable"); Py_Finalize(); return 0; } This program demonstrates that the initial sys.path element corresponding to the location of the script is created when PySys_SetArgv() is called: $ ./embed ['/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...] ['', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...] That first element depends on the location of the script, as shown here: $ ./embed /tmp/x ['/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...] ['/tmp', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', ...] I don't know where this is documented---PySys_SetArgv is mentioned in the "api" document, but this side-effect is not: http://www.python.org/doc/current/api/embedding.html#l2h-35 http://www.python.org/doc/current/api/initialization.html#l3h-713 You might want to explore just what PySys_SetArgv and submit a documentation patch on sourceforge, both for the api document and for the ext document. Interestingly, calling PySys_SetArgv multiple times inserts multiple items in sys.path. Jeff From peter at engcorp.com Tue Jan 13 10:50:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Jan 2004 10:50:56 -0500 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Message-ID: <400413E0.5C691A56@engcorp.com> Tim Rowe wrote: > > Well, the documentation for "input()" says "Equivalent to > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/ > equivalent...." I remember reading that too, and just assumed that at this point it was in fact *implemented* that way, as a simple alias. Maybe it should be... -Peter From peter at engcorp.com Mon Jan 19 14:52:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 14:52:59 -0500 Subject: Escaping slashes (double backslash plague) References: Message-ID: <400C359B.58CCB134@engcorp.com> Aloysio Figueiredo wrote: > > I need to replace every ocurrence of '/' in s by '\/' > in order to create a file named s. Harry inspired me to reread your question, but now I think you might be very confused about something. Are you trying to create a file whose name contains a forward slash? And you think that by "escaping" the slash with a backslash, you can do this? If so, give up: it's not possible. File names cannot contain a forward slash, at least on most any operating system which uses slashes as path separators. (*) If this isn't what you're trying to do, please explain more thoroughly what your goal is, because it seems very unnecessary to be putting \/ into a string for any reason (whether as a path or not) ... -Peter (*) Examples to the contrary, while perhaps interesting, notwithstanding... From claird at lairds.com Tue Jan 20 10:32:48 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 20 Jan 2004 15:32:48 -0000 Subject: Fw: PDF library for reading PDF files References: <400BFF7B.95F21050@netsurf.de> <400CF2E3.29506EAE@netsurf.de> Message-ID: <100qih06uo847db@corp.supernews.com> In article <400CF2E3.29506EAE at netsurf.de>, Andreas Lobinger wrote: >Aloha, > >Peter Galfi schrieb: . . . >> having to implement all the decompressions, etc. The "information" I am >> trying to extract from the PDF file is the text, specifically in a way to >> keep the original paragraphs of the text. I have seen so far one shareware . . . >As others wrote here, the simplest solution is to use a external >pdf-2-text programm and postprocess the data. Read comp.text.pdf > >There is no simple and consistent way to extract text from a .pdf >because there are many ways to set text. The optical impression . . . I want to emphasize that final sentence. If you insist on pursuing this, though, refer to . -- Cameron Laird Business: http://www.Phaseit.net From scottdog at nospam.com Wed Jan 21 10:08:37 2004 From: scottdog at nospam.com (Dog@will.hunt) Date: Wed, 21 Jan 2004 07:08:37 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> <20040120135921.1C3F.JCARLSON@uci.edu> <400c5790_1@newsfeed.slurp.net> <20040120150005.1C48.JCARLSON@uci.edu> <400c6146_1@newsfeed.slurp.net> <20040120171127.0606.JCARLSON@uci.edu> Message-ID: <400d3f3f_2@newsfeed.slurp.net> Its my fault for not being clear on this. I know how to change the directory on a command prompt in Windows. I was speaking of the Python prompt (>>>). Once I got that, I tried running the file but got this: 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. >>> python setup.py install File "", line 1 python setup.py install ^ SyntaxError: invalid syntax >>> Hope this clears up my inability to give the correct info! :) "Josiah Carlson" wrote in message news:20040120171127.0606.JCARLSON at uci.edu... > > Here is an example set of interactions I did with my command line: > > Microsoft Windows 2000 [Version 5.00.2195] > (C) Copyright 1985-2000 Microsoft Corp. > > C:\>cd "Documents and Settings" > > C:\Documents and Settings>cd jcarlson > > C:\Documents and Settings\jcarlson>cd Desktop > > C:\Documents and Settings\jcarlson\Desktop>cd .. > > C:\Documents and Settings\jcarlson>cd \ > > C:\>d: > > D:\>c: > > C:\> > > > I hope that is enough of an example for you to figure out what is going > on. As to which path you need to change to, it is wherever you decided > to uncompress Spambayes. > > A few things to note. On Windows 2000/xp: > C:\Documents and Settings\\Desktop is the default location of > your desktop. > c:\Documents and Settings\\My Documents is the default location > of your 'My Documents' folder.. > > > If this isn't enough, then Jeebus help you. > > - Josiah > > > > I think that may be my problem. I am not sure how to change the path to > > where the setup.py file is... > > > > > > That didnt work either and the file assoc. are correct. > > > > > > > > > If you are in windows and your associations are correct, try: > > > > > setup.py install > > > > > > Steps for you to help us help you: > > > 1. Open up a console. > > > 2. Change to the proper path. > > > 3. Run (without the single quotes) > > > 'python setup.py install' > > > if that doesn't work, try > > > 'setup.py install' > > > 4. Copy and paste the output in a message here. > > > > > > - Josiah > > > > > > From turnmeinsideoutandeatme14 at yahoo.com Wed Jan 21 10:23:34 2004 From: turnmeinsideoutandeatme14 at yahoo.com (turnmeinsideoutandeatme14) Date: Wed, 21 Jan 2004 15:23:34 -0000 Subject: My roomate taped me feeling myself Message-ID: I can't believe she taped me and posted it on the internet alot of guys told me they thought it was hot but I might remove it here is the link, let me know what you think http://www.hotpersonalad.com/landing.asp?afl=YYHO From jblazi at hotmail.com Sat Jan 10 17:04:08 2004 From: jblazi at hotmail.com (jblazi) Date: Sat, 10 Jan 2004 23:04:08 +0100 Subject: Emacs python mode question References: Message-ID: On Sat, 10 Jan 2004 15:49:22 -0600, Skip Montanaro wrote: > > jb> If I should like to go to line 345: how can I do that? Typing M-x > jb> goto-line and then 345 is a bit cumbersome. I defines the key > Alt-g jb> to be goto-line, but it does not work. > > Is M-g not bound to goto-line? You can check for keybindings by typing > "C-h w" then entering the name of a command. Thx. gogo-line is on the menu but is not bound to a key. How can I bind it? -- jb ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From tzot at sil-tec.gr Thu Jan 8 13:21:22 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 08 Jan 2004 20:21:22 +0200 Subject: Why " ".some_string is often used ? References: <3FFD70EA.A6AF3CB8@engcorp.com> Message-ID: <0t6rvv8085j2fjc3ocg07m8gugtn3e2sq0@4ax.com> On 08 Jan 2004 16:34:39 +0100, rumours say that Syver Enstad might have written: >I'd also like a reversing method for len > >class MyList(list): > def len(self): > return len(self) You can always use the __len__ attribute in this specific case. And now for the hack value: class MyList(list): import new as _new, __builtin__ def __getattr__(self, attr): try: return self._new.instancemethod( \ getattr(self.__builtin__, attr), \ self, \ None) except AttributeError: raise AttributeError, \ "there is no '%s' builtin" % attr allowing: >>> a=MyList() >>> a.append(12) >>> a.append(24) >>> a.len() 2 >>> a.min() 12 >>> a.max() 24 It works for all builtins that can take a list as a first argument. Of course it should not be taken seriously :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From daniel.dittmar at sap.com Mon Jan 5 07:40:01 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 5 Jan 2004 13:40:01 +0100 Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: Marco Bubke wrote: > This does not look nice to me. There should be something me easily. > Maybe that: > > def do_something() lock(mutex): > #this stuff is locked by the mutex > > So you don't forget to release the lock. You could create a class that locks the mutex in the constructor and unlocks it in the __del__ method. class ScopedLock: def __init__ (self, mutex): self.mutex = mutex mutex.acquire() def __del__ (self): self.mutex.release () use as def do_something(): lock = ScopedLock (mutex) # do something # lock will be automatically released when returning This works only in the current implementation of CPython where local variables are usually (*) deleted when they fall out of scope. (*) usually: unless they are returned or added to another object And I guess with metaclasses, you can achieve something like Java's synchronized methods. Daniel From tjreedy at udel.edu Fri Jan 16 14:54:21 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Jan 2004 14:54:21 -0500 Subject: Bug or feature? References: <3dtid1-594.ln1@beastie.ix.netcom.com><1ljkd1-053.ln1@beastie.ix.netcom.com> Message-ID: "Jp Calderone" wrote in message news:mailman.433.1074267521.12720.python-list at python.org... > On Fri, Jan 16, 2004 at 08:31:32AM +0000, Dennis Lee Bieber wrote: > > Terry Reedy fed this fish to the penguins on Thursday 15 January 2004 > > 15:39 pm: > > > > > > > > and returning a value. I see a little better Guido's reason for having > > > list modification methods return None. While chaining is not too > > > problematical, object returns would allow list expressions mixing > > > implicit and overt effects with possible puzzles similar to the one > > > presented in this thread. > > Now that you mention it... Yeah... Can you imagine trying to figure > > out what something like... >http://python.org/doc/current/ref/evalorder.html > Doesn't seem to be a problem, after all. Not for you, but how about newbie and others who don't read or ignore, misunderstand, or reject what they read? Lets try this example based on OP's real examples. Again, hypothetical, assuming list mutators were to return list. l3 = range(3) l3+l3.reverse() # I believe that this wouldbe [1,2,3,3,2,1] l3 = range(3) tem = l3.reverse() l3 + tem # I believe that this would instead be [3,2,1,3,2,1] I am sure that were such things legal, there would be numerous posts complaining about 'unexpected' outcomes. Hence my comment about their not being legal being good. OP believe that getting a different answer when inserting a tempory in the midst of a side-effect dependent expression is such a problem that we should break code to 'fix' it. I obviously disagree. Terry J. Reedy From rupole at hotmail.com Fri Jan 2 03:36:29 2004 From: rupole at hotmail.com (Roger Upole) Date: Fri, 2 Jan 2004 00:36:29 -0800 Subject: pynettestuser References: Message-ID: <3ff4ff8f_3@127.0.0.1> This probably came out of one of the sample scripts from win32all. Win32netdemo.py creates and deletes a user by that name. Roger "PPeterson" wrote in message news:bt0teu$fvt515 at imsp212.netvigator.com... > Hi, > > I am a newbie to python. python installer created a directory named > pynettestuser in the c:\documents and settings. What is that? Thanks. > > PP > > From haim at babysnakes.org Wed Jan 21 10:39:37 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Wed, 21 Jan 2004 17:39:37 +0200 Subject: py2exe error References: <490316A24CC5D411ACD700B0D078F7F003915DD0@cseexch01.cse.creoscitex.com> Message-ID: Pieter Claerhout wrote: > Change the setup script to: > > from distutils.core import setup > import py2exe > > setup( > options = { 'py2exe': { 'packages': 'encodings' } }, > name = 'default', > version = '0.1.0', > console = ["CLI_Backup.py"], > windows = ["Configurator.py"] > ) > > This will force py2exe to include the encodings package which should solve > your problem thanx, it solved the problem. Bye > > Cheers, > > > pieter > > Creo > pieter claerhout | product support prinergy | tel: +32 2 352 2511 | > pieter.claerhout at creo.com | www.creo.com > > IMAGINE CREATE BELIEVE(tm) > > > -----Original Message----- > From: Haim Ashkenazi [mailto:haim at babysnakes.org] > Sent: 21 January 2004 15:40 > To: python-list at python.org > Subject: py2exe error > > > Hi > > (complete newbie warning...:) ) > > I've written a script that uses pickle to store data to a file. here's the > code that stored the data: > > ------------- > > def put(self, conf): > """ dump the preferences to a file""" > > # TODO: make a backup copy of the prefs !!!! > try: > f = open(self.bacFile, "w") > except: > raise 'BadFileError', "couldn't write file" > > pickle.dump(conf, f) > f.close() > > --------------------------------- > > when running from regular python interperter, it works fine. > > I need this script to run without python installed, so I've created a > stand-alone binary with py2exe. I used the following simple setup.py: > > from distutils.core import setup > import py2exe > > setup(name = 'default', > version = '0.1.0', > console = ["CLI_Backup.py"], > windows = ["Configurator.py"] > ) > ------------------------- > > when running from this binary I get this error: > Traceback (most recent call last): > File "MainFrame.pyc", line 140, in OnSaveMenuEvent > File "MainFrame.pyc", line 174, in dumpPrefs > File "NS_Backup.pyc", line 64, in put > File "pickle.pyc", line 1382, in dump > File "pickle.pyc", line 231, in dump > File "pickle.pyc", line 293, in save > File "pickle.pyc", line 663, in save_dict > File "pickle.pyc", line 677, in _batch_setitems > File "pickle.pyc", line 293, in save > File "pickle.pyc", line 514, in save_unicode > LookupError: no codec search functions registered: can't find encoding > ----------------------------- > > I guess I should add some custom module to the setup.py but I don't know > which (or am I completely off track here...). > > can someone help? > > thanx > -- > Haim > > > From skip at pobox.com Wed Jan 21 19:39:03 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 18:39:03 -0600 Subject: Python and writing a CSV file In-Reply-To: <009501c3e07e$80b62e30$97443d42@homebass1> References: <20040121232549.GA28328@mail.theserver.ath.cx> <009501c3e07e$80b62e30$97443d42@homebass1> Message-ID: <16399.7079.192926.761791@montanaro.dyndns.org> Kevin> I am new to Python and would like to attempt to write to a CSV Kevin> file. I have reviewed the documentation at Kevin> http://www.object-craft.com.au/projects/csv/ for the csv 1.0 Kevin> module but I didn't see any information referring to writing (oe Kevin> creating) a CSV file with this module. Does this module have the Kevin> capability to write a CSV file? Yes, but you should upgrade to 2.3 (if you haven't already) and just use the csv module which comes with it: http://www.python.org/doc/current/lib/module-csv.html Skip From warkid at hotbox.ru Thu Jan 15 03:50:57 2004 From: warkid at hotbox.ru (Kerim Borchaev) Date: Thu, 15 Jan 2004 11:50:57 +0300 Subject: super. could there be a simpler super? Message-ID: <2051345875.20040115115057@hotbox.ru> Hello! Always when I use "super" I create a code duplication because class used as first arg to "super" is always the class where the method containing "super" was defined in: ''' class C: def method(self): super(C, self).method() ''' Obviously the methods like the one below doesn't work "right";-) ''' def super(self): super(self.__class__, self) class C: def method(self): super(self).method() ''' Is it possible that such a "super"(deducing class method declaration context) could appear in Python? (It seems to me that to implement a simple super something should be done during "compilation" of class declaration.) Best regards, Kerim mailto:warkid at hotbox.ru From aahz at pythoncraft.com Sun Jan 4 11:13:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2004 11:13:39 -0500 Subject: Parametrized inheritance References: <2AJJb.725692$HS4.5422608@attbi_s01> Message-ID: In article , Dan Bullok wrote: >Mike C. Fletcher wrote: >> >> You can find more information about these kinds of patterns by searching >> for "Mix-In Class" and/or "Multiple Inheritance". Python 2.2 changed how >> multiple inheritance graphs are constructed in Python, BTW. If you used >> old-style classes the mro would have been [MySub, Sub, Base, MyBase, Base] >> IIRC. > >Well, I thought of doing this, but after looking up resolution order (sec >9.5.1 of the tutorial) I found that resolution is done "depth-first, >left-to-right", In my example, that would have given [MySub, Sub, Base, >MyBase, Base], but, I checked, using mro(), and found that it was indeed >[MySub, Sub, MyBase, Base], just as I needed it. (thanks for the mro() tip >- didn't know about that one). Unless I've gone crosseyed (possible, it's >late), this is NOT depth-first, left-to-right. So is the tutorial out of >date? As Mike said, it's different for new-style classes. See http://www.python.org/2.2.3/descrintro.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From popngen at uclink.berkeley.edu Tue Jan 27 20:29:53 2004 From: popngen at uclink.berkeley.edu (Alfred) Date: 27 Jan 2004 17:29:53 -0800 Subject: Running python automatically in the background Message-ID: <1e4e0378.0401271729.3ea6b5c2@posting.google.com> hi all, i'm trying to figure out if there is some easy way to run a python script in the background _without_ specifying "&" in a linux enivornment. script.py & vs script.py is there an easy way to do this? been looking around but couldn't find any docs to support a possibility. thanks! - al From shoot at the.moon Sun Jan 4 15:46:05 2004 From: shoot at the.moon (Steve Horsley) Date: Sun, 04 Jan 2004 20:46:05 +0000 Subject: Let users execute but not view In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hi! > I have a python script which should be executed my normal users but they > should not be able to view the sourcecode. Setting permissions to x only > does not help, the python interpreter can not read the file. > How can I do that? > Thanks, > Florian I believe that the common thing to do is to remove the .py file but leave the compiled .pyc file, which is rather more difficult to reverse-engineer. Not impossible of course. However, I'm only a newbe and others may know a better way. Steve From exarkun at intarweb.us Tue Jan 27 09:08:36 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 27 Jan 2004 09:08:36 -0500 Subject: How does compare work? In-Reply-To: <20040127131651.GA3495@nl.linux.org> References: <40158680$0$7044$ba620e4c@news.skynet.be> <20040126235704.GD13453@siliconimage.com> <20040127131651.GA3495@nl.linux.org> Message-ID: <20040127140836.GA16734@intarweb.us> On Tue, Jan 27, 2004 at 02:16:51PM +0100, Gerrit Holl wrote: > Inyeol Lee wrote: > > (This unusual definition of comparison was used to simplify the > > definition of operations like sorting and the in and not in operators. > > In the future, the comparison rules for objects of > > different types are likely to change.) > > """ > > When comparing mixed types becomes illegal, does that mean sorting a > sequence of mixed types becomes illegal as well? Or will sort be a > special case? > There was discussion of another operation, "before", which could be used to order different types, but which would not be used by < or >. I forget if the final word on this idea was positive or negative, but I'm sure anyone interested could dig up the relevant thread on python-dev. Jp From aahz at pythoncraft.com Fri Jan 9 16:00:53 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2004 16:00:53 -0500 Subject: Tcl/Tk Support References: Message-ID: In article , Diego Ribeiro de Andrade wrote: > >Yes... I typed import Tkinter too but the output was the same! > >how I do to install support for Tkinter? Can I download the Tkinter.py file >and paste in the include directory of Python2.2? You'll probably have to install a package called something like "tk8.3-dev" (that's what it's called in Debian), download the Python source, and build Python. It's possible that the RPMs for Python already have Tkinter built in, but you'll still need to install Tcl/Tk to make it work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From rays at blue-cove.com Thu Jan 29 16:44:09 2004 From: rays at blue-cove.com (Ray Schumacher) Date: Thu, 29 Jan 2004 13:44:09 -0800 Subject: win32com - .ocx won't Dispatch... In-Reply-To: References: Message-ID: <5.2.0.4.0.20040129132222.00b82e18@blue-cove.com> At 12:12 PM 1/29/2004, Markus Wankus wrote: >Open the gen_py'd file 8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py, and do some searching. You should be able to find an obvious main class related to what you are doing (I'm not sure what the .tlb is), and it will say in the comment or docstring that it is a ".", or whatever. Thanks Markus, The lines are from CoClassBaseClass: ... # This CoClass is known by the name 'EDREUTLX.EDREUtlXCtrl.1' class EDREUtlX(CoClassBaseClass): # A CoClass ... That would be a helpful bit for the docs! So, the util class Dispatches, but all calls (properties and functions) give 'Catastrophic failure' Is this really some sort of types problem with this OCX? "pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None)" Thanks for the help, Ray Test run below, kitchen sink included: C:\projects\CV-Mini>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. >>> from win32com.client import * >>> util = gencache._GetModule('8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5') >>> gencache.GetGeneratedFileName('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA',0,3,5) 'AA34F82-95C9-11D3-8EB6-00C0DF2247Cx0x3x5' >>> gencache.MakeModuleForTypelib('8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5',0 ,3,5) >>> gencache.GetModuleForCLSID('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA') >>> gencache.GetClassForCLSID('8AA34F82-95C9-11D3-8EB6-00C0DF2247CA') >>> gencache.GetModuleForProgID('EDREUTLX.EDREUtlXCtrl.1') >>> gencache.EnsureModule('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}',0,3,5) >>> gencache.EnsureModule('EDREUTLX.EDREUtlXCtrl.1',0,3,5) >>> util = Dispatch("EDREUTLX.EDREUtlXCtrl.1") >>> util >>> gencache.EnsureDispatch(util) >>> >>> util = Dispatch("EDREUTLX.EDREUtlXCtrl.1") >>> util >>> # pop-up, no args ... util.AboutBox() Traceback (most recent call last): File "", line 2, in ? File "C:\Python23\lib\site-packages\win32com\gen_py\8AA34F82-95C9-11D3-8EB6-00 C0DF2247CAx0x3x5.py", line 34, in AboutBox return self._oleobj_.InvokeTypes(-552, LCID, 1, (24, 0), (),) pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None) >>> # a property ... util.Version Traceback (most recent call last): File "", line 2, in ? File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 451, in __getattr__ return self._ApplyTypes_(*args) File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 445, in _ApplyTypes_ return self._get_good_object_(self._oleobj_.InvokeTypes(*((dispid, 0, wFlags , retType, argTypes) + args)), user, resultCLSID) pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None) >>> From cwilcox at etcconnect.com Tue Jan 20 15:44:23 2004 From: cwilcox at etcconnect.com (Christian Wilcox) Date: Tue, 20 Jan 2004 14:44:23 -0600 Subject: an example of a singleton design pattern in python? <- from the python cookbook Message-ID: <69A0D4AB81C51447AD6BA387782B8D6401343F6C@midl-mail4.etcconnect.com> A link to search results from the online python cookbook: http://aspn.activestate.com/ASPN/search?query=singleton&x=0&y=0§ion=PYTHONCKBK&type=Subsection > -----Original Message----- > From: Daniel Ortmann [mailto:dortmann at lsil.com] > Sent: Tuesday, January 20, 2004 2:25 PM > To: python-list at python.org > Subject: an example of a singleton design pattern in python? > > > Hello, > > Does anyone have an example of a singleton design pattern in python? > > Thanks! > > -- > Daniel Ortmann, LSI Logic, 3425 40th Av NW, Suite 200, > Rochester MN 55901 > work: Daniel.Ortmann at lsil.com / 507.535.3861 / 63861 int / > 8012.3861 gdds > home: ortmann at venturecs.net / 507.288.7732, 2414 30Av NW #D, > Rochester MN 55901 > gpg/pgp public key: http://wwwkeys.us.pgp.net > jabber: daniel_ortmann at jabber.org / dortmann at jabber.co.lsil.com > -- > http://mail.python.org/mailman/listinfo/python-list > From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Jan 11 18:40:05 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 12 Jan 2004 00:40:05 +0100 Subject: Search and replace a specific word in a file object. References: <56f42e53.0401111519.2da31b8a@posting.google.com> Message-ID: Hi ! You can try this : def remplacerdansfichiertxt(file, listeremplacement, filout): # remplacement dans un fichier texte (et non binary) import os,os.path,re if os.path.isdir(file): print(file+' is a Directory !') else: data = open(file, "rb").read() if '\0' in data: print('it's a binary file') else: newdata=data for chaine,remplacement in listeremplacement : newdata = re.sub(chaine, remplacement, newdata) if newdata != data: f = open(filout, "wb") f.write(newdata) f.close() print(file,';',chaine,' => ',remplacement,':',filout,' : OK') in the call, the parameter "listeremplacement" is like [('oldVal','newVal'),('aaa','bbbb'),('qwerty','azerty')] @-salutations -- Michel Claveau From spamsucks at Ih8it.com Wed Jan 7 10:04:29 2004 From: spamsucks at Ih8it.com (WTH) Date: Wed, 7 Jan 2004 10:04:29 -0500 Subject: ProtoCiv: porting Freeciv to Python References: <3fec66f1$0$967$a1866201@newsreader.visi.com> <3feddb73$1@news.012.net.il> Message-ID: > > Prototyping != implementing. > > Well, duh! > > g That is a VERY important distinction, and not a 'duh' type of statement. WTH From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 3 08:57:50 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 03 Jan 2004 14:57:50 +0100 Subject: Speed? References: Message-ID: <3fidvvkl6u5iohdocs22sog32bgj4pqkjp@4ax.com> EP: >I previously read some comparisons which did not show Python in a good light >in this regard: i.e. Python is slow compared to Perl, C++, Java. These are usually pure compute benchmarks at the interpreted language level. In practice I find that my Python programs perform somewhat better than Java, probably because Python has many libraries implemented in C, whereas Java has many pure Java libraries. -- Ren? Pijlman From astrand at lysator.liu.se Sun Jan 4 06:02:59 2004 From: astrand at lysator.liu.se (Peter Astrand) Date: Sun, 4 Jan 2004 12:02:59 +0100 (CET) Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: <3FF75AFC.3020204@v.loewis.de> Message-ID: On Sun, 4 Jan 2004, Martin v. Loewis wrote: > > "Fixing popen2" would mean a break old applications; exceptions will > > happen, which apps are not prepared of. > > I find that an acceptable incompatibility, and it will likely break > no existing application. Not true. There are lots or apps out there that uses fallback commands: tries to execute one, and if it doesn't exist, tries another one. (One example is jakarta-gump, see http://cvs.apache.org/viewcvs.cgi/jakarta-gump/python/gump/utils/launcher.py?rev=1.6&view=auto) With the current API, you do this by checking if the return code is 127. No-one is prepared for an exception. The return code stuff is also very problematic, and is another reason why make a new module and not "enhance" the old ones. With the current API (which calls /bin/sh most of the time), some returncodes are overloaded by the shell. The shell uses these return codes: 126: the command was found but is not executable 127: the command was not found 128+n: the command was terminated by signal n This means that it is currently impossible to use these return codes for programs launched via the current API, since you cannot tell the difference between a 127 generated by a successful call to your command, and a 127 generated by the shell. I don't see how this can be solved by "enhancing" the current functions, without breaking old applications. >Applications usually expect that the program > they start actually exists; it is a good thing that they now can > detect the error that the missing/non-executable application. There are lots of other errors as well, not just missing/non-executable programs. > > There is no one flexible enough. The > > case for redirecting only stderr is just one example; this is simple not > > possible with the current API. > > Can you elaborate? What is the specific problem, how does your preexec > function look like, and how is it used with popen5. I can then show you > how it could be used with popen2, if that was enhanced appropriately. Yes, the preexec function feature could possiby be added popen2. This is not the problem. > >>Sounds like a new function on the popen2 module. > > > > > > To support all combinations, 12 different functions are necessary. Who > > will remember what popen2.popen11() means? > > Why is that? Just add a single function, with arguments > stdin/stdout/stderr. No need for 12 functions. Then explain the existing > functions in terms of your new function (if possible). Just like popen5.Popen? Yes, that could be done. We would still have the problem with returncode incompatibilites, exceptions and such. > > With popen5, you can do it *without* using the shell. > > Why is that a good thing? 1) Performance. No need for parsing .bashrc on every call... 2) Security. You can do pipes without having to deal with all the quoting issues. 3) Getting rid of the shells overloading of return codes It's also much more elegant, IMHO. > I think this is the core problem of your approach: You throw away all > past history, and imply that you can do better than all prior > contributors could. Honestly, this is doubtful. In a discussion like this, I think it's important to separate the new API from the new implementation: 1) The new API. If you look at the popen5 implementation and PEP, it's obvious that I haven't throwed away the history. I have tried to take all the good parts from the various existing functions. The documentation contains 140 lines describing how to migrate from the earlier functions. Much of the current API has really never been designed. The API for the functions os.popen, os.system, os.popen2 comes from the old POSIX functions. These were never intended to be flexible, cross-platform on anything like that. So, it's not hard to do better than these. 2) The new implementation. When I wrote popen5, I took some good ideas out of popen2. The rest of the code is written from scratch. >The current code > is so complicated because implementing pipes is complicated. Let's keep the POSIX stuff separated from the Windows stuff. popen2.py does not depend on posixmodule.c on POSIX systems, and popen2.py is not complicated at all. The popen* stuff for Windows (and OS2 etc) in posixmodule.c is complicated because: 1) It's written in low-level C 2) It contains lots of old DOS stuff 3) It tries to launch the program through the shell (which is always a pain). > > Well, I don't see how this could be done easily: The current API is not > > flexible enough, and some things (like cross-process exceptions) breaks > > compatibility. > > I never said it would be easy. However, introducing a new popen module > is a major change, and there must be strong indications that the current > API cannot be enhanced before throwing it away. I wouldn't say that introducing a new module is a "major change". Of course, we don't want to end up writing "popen6" in two years, because we've realized that "popen5" is too limited. That's why we should try to get it exactly right this time. I think it would be more useful it we put our energy into trying to accomplish that. > As for breaking compatibility: This is what the PEP should study in > detail. It is sometimes acceptable to break compatibility, if > applications are likely to be improved by the change. *Any* change > can, in principle, break compatibility. Suppose I had an application > that did > > from popen5 import open > > This application might break if your proposed change is implemented, > as a new module is added. So you can't claim "I will break no programs". Isn't this quite a silly example? -- /Peter ?strand From bkelley at wi.mit.edu Fri Jan 9 08:31:01 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 09 Jan 2004 13:31:01 GMT Subject: How to insert into listbox using wxPython In-Reply-To: References: <3ffda907$0$572$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Andrew wrote: > Hi thanks for your help but I am still having problems basically I am using > a button to connect to a Database and I want to display the data from the > database into the listbox > Here is the code I am using for the button > > self.c = self.db.cursor() > self.c.execute("SELECT * FROM guests;") > self.results = self.c.fetchall() > # Here is where I don't know what to do I want to be able to get the > data from self.results and display it in the listbox > self.listbox.Append('') > self.listbox.Set(['']) It looks as though you are putting nothing in the listbox. Append('') adds a blank and listbox.Set(['']) replaces the listbox with a blank. Try: for x in self.results: self.listbox.Append(x[0]) Brian From quentel.pierre at wanadoo.fr Fri Jan 2 03:58:01 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Fri, 2 Jan 2004 09:58:01 +0100 Subject: Multiple exception syntax Message-ID: Normally in Python there is no need to write parenthesis for a tuple : a,b,c=(1,2,3) (a,b,c)=1,2,3 are the same, and so are : for (x,y) in enumerate(aList) for x,y in enumerate(aList) But with "except" the behaviour is very different with or without parenthesis : - "except x,y" means : if exception x is raised, then y is the instance of the x class holding information about the exception - "except (x,y)" means : if one of the exceptions x or y is raised (or both) So it took me some time to figure out why this code was wrong : ---------------------- 1 import ConfigParser 2 conf=ConfigParser.ConfigParser() 3 conf.read("config.ini") 4 5 try: 6 PORT=conf.get("Server","port") 7 except ConfigParser.NoOptionError,ConfigParser.NoSectionError: 8 PORT=80 9 10 try: 11 language=conf.get("Translation","language") 12 except ConfigParser.NoOptionError,ConfigParser.NoSectionError: 13 language="default" ---------------------- In my config.ini there was a [Server] section but no "port" option, and no [Translation] section. I had this very puzzling traceback : Traceback (most recent call last): File "C:\Pierre\Programmes Python\multipleExceptBug.py", line 11 , in ? language=conf.get("Translation","language") File "C:\Python23\lib\ConfigParser.py", line 505, in get raise NoSectionError(section) AttributeError: NoOptionError instance has no __call__ method My bug was in line 7, where ConfigParser.NoSectionError becomes an instance of the NoOptionError class. With parenthesis on line 7 (and 12) it works all right I find this confusing. It would be clearer for me to have : "except Error1 or Error2 or Error3" Or have I drunk too much lately ? Pierre From __peter__ at web.de Tue Jan 27 04:48:07 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Jan 2004 10:48:07 +0100 Subject: Confusing problem between Tkinter.Intvar() and self declared variable class References: <4378fa6f.0401261709.664ca799@posting.google.com> Message-ID: Marc wrote: > Hi all, > > I was using Tkinter.IntVar() to store values from a large list of > parts that I pulled from a list. This is the code to initialize the > instances: > > def initVariables(self): > self.e = IntVar() > > for part, list in info.masterList.items(): > obj = setattr( self.e, part, IntVar() ) It seems odd to use an IntVar as a container for IntVar instances. obj will always be set to None; just use setattr(). > > That allowed me to save bundles of info without having to create > another large dictionary or list. I was using the variable in entry A Python object is just a dictionary in disguise. > boxes to store the amount of parts ordered: > > Entry( cscGroup.interior(), width=3, textvariable = > getattr(self.e, part), > text=e.get()).grid(row=x, column=2, padx=4 > ) > > However, I ran into problems when I tried to pickle the instances in > order to recall them later. To fix that problem I created my own > simple data class that allowed me to save the data the same way while > also having the ability to pickle it: > > class DataVar: > def __init__(self): > self.data = 0 > self.partName = "" > > def set(self, value): > self.data = value > > def get(self): > return self.data > > But I just discovered another problem. It doesn't appear to hold data > the same way. The information appeared global when it was IntVar(). > Now when I go outside the class that set up the entry boxes, the > information does not appear to be in DataVar. I print out the info the > following way: > > def printValues(self): > for part, list in info.masterList.items(): > e = getattr(self.e, part) > print str(part) + " --->" + str( e.get() ) > > This function is in the same class that initialized the DataVar > variables and also that called the class that setup the window to > enter the amount of parts. When I call that class I pass in the > variable in the following way: > > spares = Spares(self.master, self.e) > > So obviously there's something about Tkinter that causes the info to > be global. But even though the DataVar class is an independent class, > for some reason the information is not being maintained. > > Does anyone have any idea why this is happening and how to fix it? I wasn't able to completely follow the last part of your post, so below is a working version of what I /think/ you are trying to do. The important part is a pickle-enhanced container for IntVars that stores their values instead of the instances. It could easily be enhanced to support, say, StringVar by inspecting the type of the values in the __setstate__() method. import Tkinter as tk import pickle class Namespace: pass class IntVars: """ Every attribute is suposed to be a TKinter.IntVar instance """ def __getstate__(self): d = dict(self.__dict__) for k in d: d[k] = d[k].get() return d def __setstate__(self, d): for k, v in d.iteritems(): iv = tk.IntVar() iv.set(v) setattr(self, k, iv) info = Namespace() info.masterDict = { "bird": 1, "elephant": 2, "crocodile": 3, } FILENAME = "crocodile.pickle" class LoadError(Exception): pass class Main(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid() try: self.loadVariables() except LoadError: self.initVariables() self.saveVariables() self.initControls() def loadVariables(self): try: f = file(FILENAME) except IOError: raise LoadError else: # error handling is *incomplete* try: self.e = pickle.load(f) finally: f.close() def saveVariables(self): f = file(FILENAME, "wb") try: pickle.dump(self.e, f) finally: f.close() def initVariables(self): self.e = IntVars() for part, lst in info.masterDict.iteritems(): iv = tk.IntVar() iv.set(lst) setattr(self.e, part, iv) def initControls(self): interior = self # cscGroup.interior() x = 0 for part, lst in info.masterDict.iteritems(): e = tk.Entry(interior, width=3, textvariable=getattr(self.e, part)) # text=... has no effect e.grid(row=x, column=2, padx=4) x += 1 self.button = tk.Button(self, text="Save values", command=self.saveVariables) self.button.grid(row=x, column=2, padx=4) m = Main() m.mainloop() Peter From reply.in.the.newsgroup at my.address.is.invalid Sat Jan 10 20:49:08 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 11 Jan 2004 02:49:08 +0100 Subject: Writing Files References: Message-ID: <2pa100t1laeuhv0g1m3lafif7me0mg5tt8@4ax.com> Lucas Raab: >What is the best way to go about writing to files?? f.write() http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000 >Whenever I insert a statement to write results to a file there's >nothing in it. There must be something wrong with the statement. -- Ren? Pijlman From msurette at laframboise.net Mon Jan 26 17:07:36 2004 From: msurette at laframboise.net (Michael Surette) Date: Mon, 26 Jan 2004 22:07:36 GMT Subject: pexpect exceptions Message-ID: I have been trying to automate the changing of passwords using python and pexpect. I wrote a script as a test and it works, except that it gives me an exception when it stops running: Exception exceptions.OSError: (10, 'No child processes') in > ignored What is happening and how do I get rid of the exception? I am running python 2.3.2 under Slackware linux 9.1 and pexpect 0.99. Here is the script: #!/usr/bin/python import pexpect import sys if len(sys.argv) != 3: print 'usage error!' raise SystemExit name= sys.argv[1] passwd= sys.argv[2] a= pexpect.spawn('passwd %s'%name) changed= False while not changed: i= a.expect(['[Nn]ew password:','[Cc]hanged']) if i == 0: a.sendline(passwd) elif i == 1: changed= True From Sambo at connection.com Tue Jan 6 19:30:10 2004 From: Sambo at connection.com (Sam) Date: Tue, 06 Jan 2004 16:30:10 -0800 Subject: Finaly found a simple enough task for python, took the plunge, but..... Message-ID: <3FFB5312.1030803@connection.com> Only 2 weeks messing around with it ( thanks to programs like SYNCHRONEX and BITORRENT ), and already trying to create windows ( the paths are just too long for me to want to type them ). After much trial and error I finaly got the following code to open the 'get dir' dialog , but I am getting another blank window titled 'tk' and "NOT RESPONDING" When I kill it (end task), I get reiniit/restart (CTRL+F6) in my shell window What am I doing wrong? Do I need to do anythink to clean up after using the dialogs? ********************************************************************************** import os import sys import tkCommonDialog def me(): dir_name = "" getfileDLG = tkCommonDialog.Dialog() getfileDLG.command = "tk_chooseDirectory" getfileDLG.__init__() dir_name = getfileDLG.show( ) print dir_name ********************************************************************************** The other think is that the dialog does not get focus. Must admit I was little more confortable with the HTML help in Python 2.3 however less informative ( which I only installed a week before 2.3.3) The help server in 2.3.3 just produces blank pages (most of the time) and eventualy locks up. I think it has to do with the loopback, I read about somewhere, but I can't be dialed to my ISP all the time. Thanks, Sam. From sancelot at free.fr Fri Jan 16 02:42:05 2004 From: sancelot at free.fr (stephane ancelot) Date: Fri, 16 Jan 2004 08:42:05 +0100 Subject: wxPython worries In-Reply-To: <92c59a2c.0401152257.5b93167b@posting.google.com> References: <92c59a2c.0401152257.5b93167b@posting.google.com> Message-ID: <200401160842.05418.sancelot@free.fr> Hi, I have recently evaluated wxpython because I am coming from fox (for 3 years) , but fox lacks GUI designer and wxwindows with wxpython and boa-constructor seems to solve the problem Thanks for your advice in wxwindows. If you want informations about fox I can help you. Best Regards steph Le Vendredi 16 Janvier 2004 07:57, MetalOne a ?crit : > I have recently been trying to build some GUIs with wxWindows. The > first problem that I ran across involved not being able to send and > event from a worker thread to the GUI thread and get the GUI thread to > process the event while the user had a menu pulled down. I wrote a > bug report and this has since been fixed. Tkinter has issues here > also. There is no means for a worker thread to put an event in the > GUI thread. > > The second problem that I have run across is that tab order between > controls is the order that controls are added. You can't get tabbing > to skip a control. If you dynamically add/remove controls you can't > achieve your desired tab order. > > wxWindows seems like a very impressive work. The demo is certainly > impressive. I also suppose I shouldn't rant to much about something > that is free. However my first two GUIs hit critical problems, and > these were really simple GUIs. Granted, the first problem has been > fixed now, and I have not yet written a bug report on the second. > > Tkinter is also giving me problems. I have been trying to add > controls to a canvas and to have a scrollbar that will scroll the > controls on the canvas. I think I have it figured out now, but it is > damn near impossible to figure out from the documentation. I had to > scour the internet looking for solutions. > > I have also played with displaying video in both wxWindows and Tk. > I have raw gray scale data simply as a list of values range 0-255. > Using PIL I can easily convert to a format wxWindows and Tk can > display. I get around 30 fps with wxWindows and 15 fps with Tk. > However, all images wxWindows displays must be full 24-bit color. If > the images didn't need to be expanded to (r,g,b) I would expect > signifcant speed up. I don't know why Tk is so much slower. > > wxWindows and Tk are the only toolkits that wrap native Windows > controls. The others all emulate controls. I am thinking about > trying out another toolkit. > FOX, FLTK or GTK. > > I am having enough trouble convincing people to use Python. I'd never > be able to get my work to purchase Qt. They would prefer to do > everything in VB6. From anton at vredegoor.doge.nl Thu Jan 29 04:12:29 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 29 Jan 2004 10:12:29 +0100 Subject: Rookie question about data types (hashtables) References: Message-ID: <4018cf7b$0$132$3a628fcd@reader1.nntp.hccnet.nl> Rainer Deyke" wrote: >> What I would LIKE to have is a hashtable-like structure that lets >> me retrieve multiple values based on a partial key. >Sounds like a sorted list would work best. A binary search (see the bisect >module) lets find all matches in O(log n) time. Probably yes. I'm replying just in case someone would like to have their hash values sorted in alphabetical order too. The code below might be of interest to hobbyist programmers who don't care about practical issues :-) (also not tested beyond what you see) Anton from string import ascii_lowercase as alc def antonian_sorted_unrank(k,base,ndig): res = [] while k > -1 : r,k = divmod(k,int('1'*ndig,base)) k,ndig = k-1,ndig-1 res.append(r) return res def antonian_sorted_rank(seq, base,ndig): res = 0 for x in seq: res = x*int('1'*ndig,base)+res+1 ndig -= 1 return res-1 def word_rank(word,ndig): d = [alc.index(c) for c in word] return antonian_sorted_rank(d,len(alc),ndig) def word_unrank(i,ndig): L = antonian_sorted_unrank(i,len(alc),ndig) return "".join([alc[j] for j in L]) def test(): L = ["a","ab","aa","b","bab","ba"] maxlen = max(map(len,L)) print L def wu(i): return word_unrank(i,maxlen) def wr(w): return word_rank(w,maxlen) H = map(wr,L) print H H.sort() print H R = map(wu,H) print R L.sort() assert L == R if __name__=='__main__': test() From gabriel.leblanc at a2m.com Tue Jan 13 12:50:29 2004 From: gabriel.leblanc at a2m.com (Gabriel Leblanc) Date: 13 Jan 2004 09:50:29 -0800 Subject: System calls over network Message-ID: Hello, I am wondering if there's an easy way to do a system call to a file that resides on the network. Say for example I would like to call the batch file which is located at \\ComputerName\file.bat I tried : >>> import os >>> os.popen("\\ComputerName\file.bat") >>> os.popen("\\\\ComputerName\\file.bat") Of course, I replaced ComputerName and file.bat with the correct paths. Any idea ? Thanks ! From ih8spam at spamtrap.com Thu Jan 15 08:58:33 2004 From: ih8spam at spamtrap.com (WTH) Date: Thu, 15 Jan 2004 08:58:33 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <40051cb3$1@news.012.net.il> <40067838$1@news.012.net.il> Message-ID: <100d70ho5p7c577@corp.supernews.com> > Ok, I'll bite. I just invested 0$ on a 3D shooter. I started working on it, > and the math was too hard. I gave up after 5 minutes. Do I qualify? Why didn't OSS flock to satiate your every desire? Shiftless bunch of bastards that lot... WTH From http Sat Jan 10 04:15:53 2004 From: http (Paul Rubin) Date: 10 Jan 2004 01:15:53 -0800 Subject: need help translating a PHP for statement to python References: Message-ID: <7xk740go52.fsf@ruckus.brouhaha.com> dmm at machinic.net (Davis Marques) writes: > I'm translating some PHP scripts to Python and have hit a roadblock > with a for statement. If someone could explain to me how one should > translate the multiple increment, evaluations, etc. in the first line > I would appreciate it deeply ... > > for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { > $prd = $q * $y_ar[$y] + $car; > $prd -= ($car = intval($prd / 1E7)) * 1E7; > if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7; > } Python is more verbose than PHP when it comes to stuff like that. You have to expand things: x = cx - cy - 1 for y in xrange(cy+1): prd = q * y_ar[y] + car; car = intval(prd / 1E7) prd -= car * 1E7; x_ar[x] -= prd + bar bar = (x_ar[x] < 0) # is this REALLY what you wanted? if bar: x_ar[x] += 1E7; x += 1 You can more closely approximate the two parallel loops with the iterzip function in the new itertools package, but that only works with the latest Python versions. I suspect that your if statement was actually supposed to say if (($bar = ($x_ar[$x] -= $prd + $bar)) < 0) $x_ar[$x] += 1E7; but I don't know what you're really trying to do. From tdelaney at avaya.com Thu Jan 8 22:24:36 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 9 Jan 2004 14:24:36 +1100 Subject: xrange() syntactic sugar Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0106382C@au3010avexu1.global.avaya.com> > From: Christopher T King > > for i in xrange(0,8,2): > pass > > is equivalent to > > for i in 0:8:2: > pass This exact syntax has been suggested and rejected a few times now ... it's been suggested a few times on python-dev as well by various luminaries/ I don't think there's a PEP for it though (there probably should be). > xrange() objects become an acceptable list index, operating as a slice > operator does. Example: > > a[0:8:2] is equivalent to a[xrange(0,8,2)] Urgh! Try instead a[slice(0, 8, 2)} ... xrange is probably going to be gradually phased out - it's anomalous in this day and age of iterators, generators and other much more general constructs. Instead, range is more likely to be optimised once we've got rid of the option to modify other modules directly (i.e. once you can't rebind __builtins__.range it can be optimised in those cases where it's just used in a for: loop - the most common case). Tim Delaney From theller at python.net Thu Jan 15 14:38:41 2004 From: theller at python.net (Thomas Heller) Date: Thu, 15 Jan 2004 20:38:41 +0100 Subject: keeping Python code properly indented References: <3064b51d.0401151125.711ade4c@posting.google.com> Message-ID: beliavsky at aol.com writes: > How do you keep Python code properly indented as you modify it? I use > an Emacs-type editor that has a Python mode, so the initial indenting > is easy. If I later want to put a 'for' loop (or an 'if' statement) > around a bunch of code, I find myself going through the body of the > loop, manually re-indenting to keep the nested loops correct. There > should be a better way. > > I think that having a 'for' loop end with a matching 'next' statement, > as done in (for example) Basic, is a safer and clearer way of writing > loops, although some Python programmers consider this a 'feature' > rather than a 'bug'. In Xemacs with python-mode, I just mark the region and hit 'C-c >' py-shift-region-right or 'C-c <' py-shift-region-left. Thomas From jsbenson at bensonsystems.com Thu Jan 1 15:01:15 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 1 Jan 2004 12:01:15 -0800 Subject: question: Python or Lua for rejuvenation of old PCs? Message-ID: <028e01c3d0a2$037aba80$6401a8c0@jsbwxp3> Hi, I've been experimenting with Lua on my Tandem Himalaya K100 system (a decade-old 4-CPU fault-tolerant server from Tandem/Compaq/HP) because it looked like it was simpler to port than Python. Since I've only got 128 MB per CPU and the system is already loaded with SQL and transaction processing monitor software, it's small footprint was also very attractive. Anyway that's how I got interested in Lua. There has already been some discussion of Lua in this forum. At this stage in my understanding, I'd characterize it as highly idiosyncratic, but very dynamic in the same way Python is: it has reference rather than variable copy semantics and functions are first-class objects. It can do OOP, but data and method packaging are shoehorned into a somewhat complicated Swiss Army Knife table construct. It's indexes are also unity-based and there are no slices as in Python. However, it's sufficiently different that it shouldn't be too hard keeping the two languages separate, unlike, say Spanish and Portuguese. That said, I had a project in the back of my head of putting Python on my old PCs ranging from 4MB up to 128 MB RAM as a last-ditch attempt to avoid facing reality and getting rid of them. However, I'm now beginning to wonder if I would be better served by putting Lua on the low-end PCs instead. I'm thinking of using them as nodes in a distributed, fault-tolerant home monitoring and control system that would be easy to port later to embedded microcontrollers. I suppose that my question is best phrased as this: What is a comfortable minimum RAM size that a PC needs to have to comfortably run modern Python for non-memory-intensive applications (i.e. no big database crunching or other thrashy stuff). I'm thinking about just polling sensors and actuating control devices over RS-232/RS-485/LAN and doing some chitchat between the nodes over the LAN. Based on the response, I'll draw the line between my Lua machines and my Python machines. Thanks in advance for any information you may have. From usenet at -OBFUSCATED-joefrancia.com Sun Jan 25 14:58:49 2004 From: usenet at -OBFUSCATED-joefrancia.com (Joe Francia) Date: Sun, 25 Jan 2004 19:58:49 GMT Subject: Need Python script to search content in the web pages In-Reply-To: References: Message-ID: SA wrote: > Hello > > I need a python script that can enable users of a site to search > through the contents of the website. > > Can anyone help? > > --SA http://www.divmod.org/Lupy/index.html From aahz at pythoncraft.com Thu Jan 29 12:02:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2004 12:02:28 -0500 Subject: Pythonwin - breaking out of infinite loop References: <40193737$0$13350$ed9e5944@reading.news.pipex.net> Message-ID: In article <40193737$0$13350$ed9e5944 at reading.news.pipex.net>, Graham wrote: > >How do I stop a Python program running in PythinWin? I would expect to be >able to use CTR-C or CTRL-break etc. That should work, but there are some oddball cases where Python won't check for the signal. Here's a simple example: while 1: pass -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From latex-bugs at latex-project.org Fri Jan 30 10:24:59 2004 From: latex-bugs at latex-project.org (latex-bugs at latex-project.org) Date: Fri, 30 Jan 2004 16:24:59 +0100 (CET) Subject: hello In-Reply-To: <200401301524.i0UFOSZ4003976@rzdspc1.informatik.uni-hamburg.de> References: <200401301524.i0UFOSZ4003976@rzdspc1.informatik.uni-hamburg.de> Message-ID: <200401301524.i0UFOxYX024254@sun.dante.de> Thank you for your message to latex-bugs at latex-project.org. Sorry, but to prevent SPAM, the latex-bugs email processor will accept only messages produced with the help of latexbug.tex. Please resend your problem report with the contents of latexbug.msg as the body of your message. -- From EP at zomething.com Wed Jan 28 23:30:13 2004 From: EP at zomething.com (EP) Date: Wed, 28 Jan 2004 20:30:13 -0800 Subject: Unique ID for CD or DVD In-Reply-To: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: <5.2.0.9.0.20040128202513.00b7f330@mail.zomething.com> Hoang wrote: >Does anyone know of an existing algorithm/module for generating a unique ID >for a given CD or DVD? This would be something akin to CDDB where a CD is >recognized based on its content. I could be wrong, but I think CDDB is just >based on file size or disk size and this alone is not unique enough. If the >solution is in Python, all the better. > >Hoang Do >http://jotsite.com In case its of interest (ICIOT) I came across this company who is making a business, in part, out of digital fingerprinting music http://www.audiblemagic.com/technology.html This patent might be an interesting read: http://tinyurl.com/2nuev Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at gazeta.usun.pl Wed Jan 21 15:36:47 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 21 Jan 2004 20:36:47 +0000 (UTC) Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <20040120181009.060C.JCARLSON@uci.edu> <20040120182610.060F.JCARLSON@uci.edu> <100rutd6kge1g9f@corp.supernews.com> Message-ID: Michael Geary pisze: > You had it right with os.startfile. That calls the ShellExecute function in > Windows, which is the way you would do it in a native Windows application > written in C. Only if you don't pretend to be "Real-Hardcore-Win32-Hackah". We use CreateProcessEx. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From dave at pythonapocrypha.com Mon Jan 26 15:29:32 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 26 Jan 2004 13:29:32 -0700 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> <16405.30020.406117.575663@montanaro.dyndns.org> Message-ID: <090801c3e44b$1b434760$6401fea9@YODA> Skip wrote: > Pardon me, but I don't want "a regular guy" in this particular position. I > want the god damned smartest, most capable person we can find. The real problem is that these days there's no way the smartest, most capable person would ever run for public office. -Dave From donn at drizzle.com Wed Jan 28 01:07:06 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 28 Jan 2004 06:07:06 -0000 Subject: raw_input - why doesn't prompt go to stderr References: <4016A585.6050109@skynet.be> Message-ID: <1075270024.832201@yasure> Quoth "Terry Reedy" : [... in response to] |> Tell me any advantage in raw_input's prompt is going to stdout instead |> of stderr? | | I don't know the ramification of the distinction, expecially across | platforms, well enough to answer. I can only reiterate my suggestion, | given Python as it is today and will remain for some time, that you print | to 'ofile' with default ofile == sys.stdout but with command line or | interactive redirection. I don't know either, but agree that the cross platform point is probably an issue. If it were strictly a UNIX application, I would indeed expect prompt on stderr - as well as a lot of other stuff that now goes to stdout. But I've heard complaints from the Windows crowd that stderr output is a nuisance there in some way, and for sure you couldn't expect MS to appreciate the virtue of this distinction even if they do somehow observe it. Donn Cave, donn at drizzle.com From nbdy9 at hotmail.com.nospam Fri Jan 16 12:16:37 2004 From: nbdy9 at hotmail.com.nospam (Nick) Date: Fri, 16 Jan 2004 12:16:37 -0500 Subject: What's the best Python freeze tool? Message-ID: I've tried a couple of Python freeze tool. But encountered some bugs. Anyone know what's the most mature Python Freeze tool? Thanks. From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 00:02:30 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 21:02:30 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <40051cb3$1@news.012.net.il> Message-ID: "R. Alan Monroe" wrote in message news:wQlNb.2099$f97.683 at fe3.columbus.rr.com... > In article , "Brandon J. Van Every" wrote: > >> >> It > >> >> was an unbelievable waste of time, since you've managed to convice > >> >> (maybe still wrongfully) all the people that you are completely > >> >> clueless. > >> > > >> > Why, because I turned around a project in 3 weeks while having the > >> > flu half the time? > >> > >> No, because you dumped the project because it was boring. > > > >You're a fool then. What's your school of advice, keep working on things no > >matter how much of a boring waste of time they become? > > "Being able to finish something is a form of expertise." --Brandon Van > Every Cool, I like that. I think I even remember saying it. Keep right on quoting! Of course, finishing *something* doesn't mean finishing *everything*. Only fools do that. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From jepler at unpythonic.net Thu Jan 29 11:26:48 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 29 Jan 2004 10:26:48 -0600 Subject: Get number of iteration In-Reply-To: References: Message-ID: <20040129162648.GD18498@unpythonic.net> You're looking for the "enumerate" builtin function in 2.3. for i, x in enumerate(l): print x print i print "next" You can define a "poor man's" enumerate in 2.2: def enumerate(seq): return zip(range(len(seq)), l) but the enumerate in 2.3 is an iterator, not a sequence. Jeff From peter at engcorp.com Mon Jan 5 15:19:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Jan 2004 15:19:42 -0500 Subject: Using revised tempfile module References: <3fe99ce2$0$4744$61fed72c@news.rcn.com> <878ykx6fss.fsf@pobox.com> Message-ID: <3FF9C6DE.848146AB@engcorp.com> "John J. Lee" wrote: > > "Edward C. Jones" writes: > > > #! /usr/bin/env python > > > > import os, tempfile > > > > # I have written code like this several times. It uses the deprecated > > # function tempfile.mktemp. How do I write this with the new tempfile > > # functions? > > You read the tempfile.mkstemp documentation. Or even just re-read the tempfile.mktemp documentation again, which says Deprecated since release 2.3. Use mkstemp() instead. 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 http Wed Jan 21 22:48:13 2004 From: http (Paul Rubin) Date: 21 Jan 2004 19:48:13 -0800 Subject: Converting a string to integer/float References: <2981adb9.0401211943.e1ae272@posting.google.com> Message-ID: <7x7jzkhcea.fsf@ruckus.brouhaha.com> aprogrammer at fastmail.fm (Ikot) writes: > I am stuck with a problem, might be very trivial, to ask here, but > dont find a way out. I read a string like 12345.678 from a text file, > which will be string for me, but how do I convert it into a float for > my use ? s = '12345.678' x = float(s) From hokiegal99 at hotmail.com Mon Jan 5 18:12:01 2004 From: hokiegal99 at hotmail.com (hokiegal99) Date: Mon, 05 Jan 2004 18:12:01 -0500 Subject: local interpreter remote machines References: <3ff9e4b8$0$318$e4fe514c@news.xs4all.nl> Message-ID: <3FF9EF41.8040804@hotmail.com> Irmen de Jong wrote: > hokieghal99 wrote: > >> This may not be possible, but I thought I'd ask anyway. Could I get >> the below code to run on a Python server where other machines would >> connect to it (say thru the Web) and get details of *their* system >> instead of the system details of the machine that the interpreter is >> running on? Any ideas? > > > If you also have Python running on the other machine, > you can do this very easily with Pyro: http://pyro.sourceforge.net > (no network programming necessary at all). > > Essentially you create an object on the remote machine that contains > a method with the code you want to execute, and you call that object > -using Pyro- as if it was located on your own computer. > > But this only works if you have a supported Python version running > on the remote machine, and that you are allowed to connect to that > machine over the network. > > You can even create some python code on your local machine, and > actually submit that to the other machine, let it deal with it, > and then get the results back. > But only do this if you know that no unauthorised user can do this, > because this is a security risk. > > --Irmen de Jong. Thank you, this is exactly what I was looking for! From jkrauze at ccs.neu.edu Wed Jan 28 16:02:34 2004 From: jkrauze at ccs.neu.edu (Joseph Krauze) Date: Wed, 28 Jan 2004 16:02:34 -0500 Subject: executing an external app Message-ID: Hi all, I have a simple question which I cannot solve (relatively new to Python). I want to write a script that executes an application on the go. I looked into the exec*e() calls but the problem there is that they do not return. I also looked into execfile() but here the PATH is not taken into account and I couldn't figure out to pass the file that's executed arguments. So, is there a simple way to execute an external app? i.e. execvpe('cat', 'myFile') - this will not return Thanks, Joseph From ssnews at softel.co.uk Mon Jan 5 09:03:22 2004 From: ssnews at softel.co.uk (Simon Steele) Date: 5 Jan 2004 06:03:22 -0800 Subject: Embedding Python with Dynamic Loading (win) Message-ID: <5e571368.0401050603.265d469d@posting.google.com> Hi, I'm trying to embed python into my application, and have everything working fine using the static import lib. However, I don't want my application to be dependant on python being installed (it's an optional script interpreter). Therefore I want to be able to dynamically load python instead (which I believe is possible, but I can't find any examples for). It seems, however, that the import lib is imported in python.h using a pragma statement. 1. Is there any suggested way to prevent this import without modifying python.h? 2. Does anyone have a modified python.h which uses LoadLibrary / dlopen that they'd be willing to share to save me from writing my own? 3. Has anyone had any success dynamically loading python and using swig modules in the same process (just to check I'm not insane for trying this)? thanks in advance, Simon. -- Simon Steele Programmers Notepad - http://www.pnotepad.org/ From swalters_usenet at yahoo.com Thu Jan 15 01:06:47 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Thu, 15 Jan 2004 06:06:47 GMT Subject: confusion about Exception Mechanism References: Message-ID: | Zachary said | > Hello, > I'm relatively new at Python, and am slightly confused about how the > try...except mechanism is supposed to work. I am just not sure how it > would be used, as it just seems that it is another sort of loop. Is their > any sort of example I could look at, that has an example of how it is > applied? I haven't really seen any such full example. Thanks, And Sorry > for the newbie Question, Zack When I first encountered exceptions, they were a bit confusing for me too. Exceptions are failsafes that allow a program to sensibly deal with errors. When something goes wrong, Python won't just spit out an error message. First it "raises an exception." You may also hear people call that throwing an exception. A try block allows you to "catch" that exception and deal with it yourself. In a way, it's the program sending out a cry for help. By putting something in a try block, you're saying that you're willing to answer that cry. For instance: (stolen from the tutorial page) import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except ValueError: print "Could not convert data to an integer." except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror) except: print "Unexpected error:", sys.exc_info()[0] raise You put the code you're willing to handle exceptions (errors) for between try and except. The first except (there only needs to be one, there may be multiple) says that if the block of code encounters a "ValueError" problem, that we will print "Could not convert data to an integer." and then keeps moving along in the program. The second except block handles IOError exceptions, and also gets some extra information from those exceptions. It stores this extra information in "errno" and "strerror". It then prints some information about what exactly went wrong and continues running the program. The last except block catches any and every error that wasn't caught before it. It will print an error message, then the statement "raise" falls back on the next line of defense of errors. Since this bit of code may itself be inside a try block, maybe the program will handle it elsewhere. If there's no other try blocks to handle an exception, then, and only then, will Python spit out an error message and stop the program. There's other pieces to this puzzle, but they're all on the tutorial page pointed out elsewhere. Hopefully this will give you some sense of bearing while reading that. HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From candiazoo at comcast.net Fri Jan 2 12:46:51 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 17:46:51 GMT Subject: Problem building on BeOS... References: Message-ID: Thanks for the reply! I checked in my editor (pe) and it indicates just a carriage return at the end of the line (visibles and tab stops on). Mike In message , Uwe Hoffmann wrote: > Zoo Keeper wrote: > > For some reason, the Python preprocessing balks on the "\" line > continuation > > character. Any ideas/thoughts? Is it just that my version of gcc is not > > supported? > > > In file included from > /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:4: > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:234: > stray '\' > > in program > > no knowledge of beos, but maybe your files have the "wrong" line ending > (e.g. \r\n instead of \n or something like that) > From ashleylloyd at hotmail.com Wed Jan 7 05:07:41 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Wed, 07 Jan 2004 10:07:41 +0000 Subject: Newbie: BLOB Fields into Interbase Database Message-ID: Hi, Anyone got any hints as to how to insert BLOB data into an interbase db using kinterbasDB? We've found something about using gvib, but would prefer to use kinterbasDB if possible? TIA Ashley _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From eltronic at juno.com Sun Jan 4 00:21:24 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Sun, 4 Jan 2004 00:21:24 -0500 Subject: Recurring dates module [was: Project dream] Message-ID: <20040104.002126.-3883603.2.eltronic@juno.com> On Sat, 3 Jan 2004 15:40:55 -0800 "Robert Brewer" writes: > > eltronic at juno.com wrote: > > > a timer capable of alarms or starting programs with > > > various ways of specifying the event, weekly monthly > > > don't start until, stop after date, user defined, etc. > > Then I responded: > > I've been needing to write this, as well, for my own apps. Here is > a > > first attempt (*very* alpha); feedback/additions appreciated. > > > > http://www.aminus.org/rbre/python/recur.py > > http://www.aminus.org/rbre/python/test_recur.py > > I updated this today, including time functions in addition > to the date functions and generally "filling in the corners". > I also included > an interval calculation function for e.g., threading.Timer. rats, datetime IIR is only py2.3 unless it already works in py2* or some kind soul has backported it ala sets and some of itertools. I envision a timer prog that wakes up every 45 or so seconds parses an event list and acts on those of the current minute. but something like recur would be needed for up/down counters. I guess all counters can derive their data from one main counter. the thought of starting each alarm in a thread maybe minutes days or months in advance is not going to survive reboots well. on win9x HamsinClock is useable, but not flexible enough for interactive use from other programs. since I have 2/3 of the pseudo code already I may have to at some point try to run with it. defining and parsing the ini format and finding a decent name and lack of funded free time keeps me hitting the snooze on this dream. e please forward all spam to "me" ________________________________________________________________ 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 bmgx_no_sp at mgleesonprop.co.za Tue Jan 6 12:42:26 2004 From: bmgx_no_sp at mgleesonprop.co.za (bmgx) Date: Tue, 06 Jan 2004 19:42:26 +0200 Subject: using cgi form via http and extracting results In-Reply-To: References: <3ff84844.0@news1.mweb.co.za> Message-ID: <3ffaf37b.0@news1.mweb.co.za> How would one "create" post data so that I can skip the html form and access the submission script (in ) directly. This is simple if the script uses GET as mentioned, but unfortunately this is not the case which is the very reason for my dilemma.. Ben Finney wrote: > On Mon, 05 Jan 2004 17:39:30 -0800, Tim Roberts wrote: > >>bmgx wrote: >> >>>1) Make an http connection to the remote script (http://server/script.cgi) >>>2) Fill out the html form (1x TEXT and 2x SELECT input fields) >>>3) Submit the form >>>4) extract the actual returned result. (using regex or something..) >> >>You don't actually need steps 1 and 2 at all. > > > True. > > >>HTTP transactions are all completely separate. > > > True (ignoring cookies for now). > > >>The results of a form submission are just a URL. > > > Usually false. > > The result of most form submissions is an HTTP POST request, which > contains the URL and form content as separate data. > > >>If the form has fields "FromCurrency", "ToCurrency", and "Amount", all >>you have to do is this: >> >>http://www.currencyservice.com?FromCurrency=dollars&ToCurrency=pounds&Amount=15 > > > This is only true if the form action is an HTTP GET request, which is a > rather insecure and ugly way to submit form data, and makes it > impossible to submit many kinds of data. HTTP POST is the recommended > method for submitting data to a CGI script. > > >>You don't have to HAVE the form source in order to submit a request. > > > True. You just need to construct the HTTP POST request correctly. > From isrgish at fusemail.com Mon Jan 5 21:04:39 2004 From: isrgish at fusemail.com (Isr Gish) Date: Mon, 5 Jan 2004 21:04:39 -0500 Subject: Simple way to get the full path of a running script? Message-ID: -----Original Message----- >From: "Hartmut Goebel" Wrote: >> import inspect >> print inspect.getsourcefile( lambda:None ) > >Nice idea! > >Enhancement: when using inspect.getfile() the snippet will work even for >module without sourcefile, too. > These 2 ways will give .py even if .pyc was run. There are 2 more options: 1) sys.argv[0] 2) __file__ Isr Gish From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Jan 11 05:21:21 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 11 Jan 2004 11:21:21 +0100 Subject: delete file with zipfile References: <4ADOiZ$6GG@wretch.csie.nctu.edu.tw> Message-ID: Hi ! Please, I beseech you, I beg you, to look at this URL : http://mclaveau.com/ress/python/zipmci.htm @-salutations -- Michel Claveau site : http://mclaveau.com From http Fri Jan 16 23:52:08 2004 From: http (Paul Rubin) Date: 16 Jan 2004 20:52:08 -0800 Subject: YA string interpolation and printing idea References: <7x3caf5mga.fsf_-_@ruckus.brouhaha.com> <4008B9CE.CC140EF@alcyone.com> Message-ID: <7xwu7r6utj.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > Why in the world would you want that? Printing methods go on the things > that do work of printing, which are file-like objects, not strings. To give a convenient way to do interpolated printing. Practicality beats purity. Another approach I like is to define a unary minus operation on strings, which does interpolation. But that's gone nowhere when I've proposed it in the past. Maybe if type/object unification proceeds far enough, we'll someday be able to define our own operations on builtin objects like strings. > And, on file-like objects, that method is called `write'. 'write' does what it should, which is writes out exactly the characters you give it. Python's print statement does the same plus adds a newline, and people have gotten used to that misbehavior (explicit is better than implicit), so I made an accomodation for that. From aahz at pythoncraft.com Tue Jan 27 20:15:10 2004 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2004 20:15:10 -0500 Subject: threads References: <401706AB.6020703@hotmail.com> Message-ID: In article <401706AB.6020703 at hotmail.com>, Bart Nessux wrote: > >Thank you both for the info on threads in Python it was very helpful to >me, I've written something that I think can benefit from threading... >here is the code, I copied this from a few books and a few Web examples >and modified it to suit my test: > >class trivialthread(threading.Thread): > def url_open(self): > for x in xrange(999999): > f = urllib.urlopen("http://xxx.xxx.xxx") > f.read() > f.close() > print self, x Rename ``url_open()`` to ``run()``. You might want to read the slideshow on my web site, paying particular attention to the examples. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From paul at fxtech.com Fri Jan 23 10:20:42 2004 From: paul at fxtech.com (Paul Miller) Date: Fri, 23 Jan 2004 09:20:42 -0600 Subject: Looking for advice: supporting multiple embedded interpreters In-Reply-To: References: Message-ID: <6.0.1.1.2.20040123091910.062b0450@mail.fxtech.com> >I can't address why it doesn't work in 2.3, but just a question - have >you thought of not using independent interpreter states, but just >tracking the contents of sys.modules and clearing out any new modules >at reload time? That would force even nested imports to be reloaded. >You can find an example of doing this in the unittestgui.py module, >for example, that is part of PyUnit, as it uses this approach to >ensure that all modules under test are reloaded at the start of >execution of a test suite. At first I thought this would work, but then I remembered that I have other instances of interpreters and pointers to modules, objects, and functions pointing into them. One of my issues is I do not want to affect other loaded modules, and if I blow away the global module table, then I would mess up all the other instances of scripts that I want to leave alone. From webmaster at beyond-thoughts.com Fri Jan 9 14:05:32 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 09 Jan 2004 20:05:32 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <3FFEFB7C.6030802@beyond-thoughts.com> Gerrit Holl wrote: > John Roth wrote: > >>I'm adding a thread for comments on Gerrit Holl's pre-pep, which [...] > Shall I submit this as an official PEP? Or shall I first fill in more > open issues and perhaps give the possibility to change "closed" issues? > I think there are still a lot of issues. I think letting settle things down at first is wiser. And then present a PEP where many (even better all) contributors agree. (I didn't like the result of PEP308 very much ...) In additions there are still good points in the older discussions and existing modules that should be integrated (You linked in the prePEP). Moreover I'd like to extend the pre-PEP (and PEP): "PEP xxx: new path module" Because there is more than just the Path-Class: BaseClasses, Exceptions, Helper-Functions ... Christoph Becker-Freyseng From bart_nessux at hotmail.com Thu Jan 8 22:21:13 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 08 Jan 2004 22:21:13 -0500 Subject: convert a list to a string Message-ID: <3FFE1E29.20801@hotmail.com> number = random.sample(range(count), 1) This makes 'number' into a one entry list (I don't know why as 'count' is an integer). Is there an easy way to convert 'number' back to an int? TIA From aahz at pythoncraft.com Fri Jan 2 14:11:52 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2004 14:11:52 -0500 Subject: Conditional except: blocks References: Message-ID: In article , Robert Brewer wrote: > >I don't have a quesiton or problem, I just figured some of you would >enjoy the somewhat bizarre logic of the snippet I just wrote for a CGI >request dispatcher: > >try: > return nextHandler(args) >except (None, Exception)[self.trapErrors], exc: > if page =3D=3D u'-Error': > raise exc > else: > return self.handle_error(exc, scriptWithPath) > >If self.trapErrors is True, all exceptions (which subclass Exception) >get trapped, otherwise, no exceptions are trapped. Spiffy. :) That's pretty sick. If you really need to do that, here's a more Pythonic approach: # This goes at beginning of program # or maybe at class/instance initialization if trapErrors: exceptTuple = (Exception,) else: exceptTuple = (None,) # some time later try: return nextHandler(args) except exceptTuple, exc: # Handle exception -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From claird at lairds.com Wed Jan 28 08:10:39 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Jan 2004 13:10:39 -0000 Subject: Running python automatically in the background References: <1e4e0378.0401271729.3ea6b5c2@posting.google.com> Message-ID: <101fd6fcehs156a@corp.supernews.com> In article , Ben Finney wrote: >On 27 Jan 2004 17:29:53 -0800, Alfred wrote: >> i'm trying to figure out if there is some easy way to run a python >> script in the background _without_ specifying "&" in a linux >> enivornment. >> >> script.py & > >That's how you tell any POSIX-compatible shell (like bash) to execute a >command as a background job. Why is that not acceptable? > >> been looking around but couldn't find any docs to support a >> possibility. > >Perhaps if you explain what it is you're trying to achieve, we can offer >a better solution. . . . I'll speculate Alfred has an interest in what & does. It does this, roughly: it forks a copy of the current process, disconnects stdin, and transfers control to the child. So, yes, it's possible to write a Python program that begins in the foreground and, after a while, programmatically "back- grounds" itself. Is that the goal? -- Cameron Laird Business: http://www.Phaseit.net From johng2001 at rediffmail.com Thu Jan 15 06:52:08 2004 From: johng2001 at rediffmail.com (John) Date: 15 Jan 2004 03:52:08 -0800 Subject: Best Python IDE Code Completion! Message-ID: Hi, Could you give your opinions on the best code completion in Python IDEs. My only complaint with PythonWin has been that the code completion support is incomplete. The interactive mode has better behavior than the editor. Tried to fix it but could not. Boa is not too different. At least when I last checked (a few months ago) Komodo and Visual Python were not very different either. Wing IDE seems converse. The editor auto list members is great but has no calltips. The interactive window has no completion at all. I have not checked PythonWorks and Black Adder in a while but their web sites do not seem to brag much in this direction. Python has great introspective capabilities and we have a great open contributing community. What technical difficulties keep us from having REAL code completion like MS, Borland and several Java IDEs (All of which have been funded at one time or the other if not entirely - perhaps this is the reason?) For me, code completion is a very important part of the coding experience and I really miss it in Python in it's full effect. From michele.simionato at poste.it Tue Jan 13 07:24:40 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 Jan 2004 04:24:40 -0800 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: <95aa1afa.0401130424.49749912@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Frithiof Andreas Jensen wrote: > > > >That, in my opinion, is wrong: Fortran is successful because it was there > >first! > > Which brings up the obvious question: why isn't Lisp successful? But it is successful! Look at people working on AI, theory of programming languages, etc: they will (presumably) know Lisp. OTOH, look at people working on number crunching: they will (presumably) know Fortran. It turns out that the number of people working on numerical analysis (or using numerical tools) is much larger than the number of people working on abstract things, so you will have more people knowing Fortran than people knowing Lisp. But this fact alone does not mean that one language is more successfull than the other in its application niche. You could compare Python and Perl (or Ruby) and say that one is more successful than the other, but Lisp and Fortran have different audiences and you cannot estimate their success just as number of users. Just my 2 eurocents, Michele From http Fri Jan 9 17:39:27 2004 From: http (Paul Rubin) Date: 09 Jan 2004 14:39:27 -0800 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <7xsmio4uhs.fsf@ruckus.brouhaha.com> Peter Hansen writes: > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) Yes, absolutely. > Algorithmic improvements that you would make regardless of implementation > language do not qualify, and wasting time optimizing a script that you > run once a year so it takes ten seconds instead of fifteen also does not > qualify because you certainly didn't need to do it... Sometimes I'll take the time to implement a fancy algorithm in Python where in a faster language I could use brute force and still be fast enough. I'd count that as an optimization. From csgcsg39 at hotmail.com Wed Jan 28 04:58:07 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Wed, 28 Jan 2004 09:58:07 -0000 Subject: Problem connecting to https using ZSI (openssl problem) - python2.3 References: Message-ID: Hi, Your best bet would be to ask this question in the python webservices mailing list (see link below) Colin http://sourceforge.net/mailarchive/forum.php?forum_id=1729 "Adil Hasan" wrote in message news:Pine.GSO.4.58.0401271908190.25634 at flora01.slac.stanford.edu... > > Hello, > I'm having problems trying to use ZSI to connect to a https url. > I give the command and I get prompted for my X509 cert pass-phrase, but > the program dies with an openssl error. > > Here's my code: > > from ZSI import * > u='' > n='https://shahzad.fnal.gov/edg-voms-admin/uscms/services/VOMSAdmin' > b = Binding(url=u,ns=n, ssl=1, \ > host='shahzad.fnal.gov',port=8080, \ > cert_file='/home/hasan/.globus/usercert.pem', \ > key_file='/home/hasan/.globus/userkey.pem') > b.listCAs() > > The traceback I get is: > Enter PEM pass phrase: > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 28, in __call__ > requesttypecode=TC.Any(self.name, aslist=1)) > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 131, in RPC > self.Send(url, opname, obj, **kw) > File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", > line 184, in Send > self.h.connect() > File "/usr/local/python2.3/lib/python2.3/httplib.py", line 961, in > connect > ssl = socket.ssl(sock, self.key_file, self.cert_file) > File "/usr/local/python2.3/lib/python2.3/socket.py", line 73, in ssl > return _realssl(sock, keyfile, certfile) > socket.sslerror: (1, 'error:140770FC:SSL > routines:SSL23_GET_SERVER_HELLO:unknown protocol') > > Any ideas about this? Does anyone know how to solve this problem? I have > seen one post here with a similar problem, but haven't seen any > resolution. > > Help! > > thanks, adil From dwelch91.nospam at comcast.net Sun Jan 18 12:19:21 2004 From: dwelch91.nospam at comcast.net (djw) Date: Sun, 18 Jan 2004 17:19:21 GMT Subject: Using python for _large_ projects like IDE In-Reply-To: <930ba99a.0401180625.5863acd4@posting.google.com> References: <930ba99a.0401180625.5863acd4@posting.google.com> Message-ID: I would take a look at Eric. Its written in Python, is fully featured and is plenty fast. In fact, there are plenty of IDEs written in Python or fo Python, why would you want to create yet another one? Also, as a beginning Python programmer, I fear you may be getting in over your head (I'm a 2+ year Python and 10+ year C/C++ developer and would be hesitant to tackle an IDE). Anyway, Eric is here: http://www.die-offenbachs.de/detlev/eric3.html -Don Sridhar R wrote: > Hi, > > I am a little experienced python programmer (2 months). I am somewhat > experienced in C/C++. I am planning (now in design stage) to write an > IDE in python. The IDE will not be a simple one. I had an idea of > writing the IDE in C/C++, as it is a big project, bcoz of the > following > > 1. if python is used, then the memory required for running the IDE > will be high. > 2. if pure python is used, the IDE will be slower. > > I'm not sure whether they are true. > > Then I thought of using python for 90% of the code and using C for > other performance critical part. But the problem is in identifying > the performance critical code. People suggest to start with pure > python and then _recode_ the performance critical code after profiling > the original code. But I fear whether there will be a conflit in say > data structures. Not yet expert in extending/embedding python. > Are there any ways to forsee the performance critical parts? > > Also, any suggestions on reducing memory usage of big applications > written in python? From gerrit at nl.linux.org Thu Jan 29 11:05:12 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 29 Jan 2004 17:05:12 +0100 Subject: C API: how to tell if x is a new style instance? In-Reply-To: <401821E2.1070106@rogers.com> References: <20040128184040.GD11485@foof.i3.cz> <401821E2.1070106@rogers.com> Message-ID: <20040129160512.GA31855@nl.linux.org> Mike C. Fletcher wrote: > Well, I don't actually know how to check for the spiritual state of a > new-style class, but here's how to tell if an instance is an instance of > a new-style class: > > * Note that a new-style class is a sub-class of type, while > old-style classes are not I think you mean instance here? >>> issubclass(int, type) False >>> isinstance(int, type) True yours, Gerrit. -- 2. If any one bring an accusation against a man, and the accused go to the river and leap into the river, if he sink in the river his accuser shall take possession of his house. But if the river prove that the accused is not guilty, and he escape unhurt, then he who had brought the accusation shall be put to death, while he who leaped into the river shall take possession of the house that had belonged to his accuser. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From timr at probo.com Wed Jan 14 02:33:41 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 13 Jan 2004 23:33:41 -0800 Subject: dde References: <8EFMb.102403$_P.3808599@news4.tin.it> Message-ID: "Alessandro Crugnola *sephiroth*" wrote: > >Hi all >I would like to send dde messages to an application, but i don't know which messages it supports. >Is possible to do in some way or I absolutely need the api specifications? You need specs and/or examples. One of the biggest shortcomings of DDE is that it is there is no way to ask an application what operations it supports. Worse, there is no particular standard for the format of DDE messages, so even if you know the function you want to perform, you can't guess what the message and its parameters should be. What DDE app are you trying to control? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bkelley at wi.mit.edu Fri Jan 9 23:19:38 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Sat, 10 Jan 2004 04:19:38 GMT Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: <3FFF26A1.943DEA84@engcorp.com> References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) Yes and No :) I find that optimizing algorithms is a lot more beneficial than optimizing code. Let me give a small example. I have written a chemoinformatics engine (http://frowns.sourceforge.net/) and one of it's features is substructure searching. That is finding if a graph is embedded in another graph. This is an NP-Complete problem. A company recently compared their technique in terms of speed and correctness to frowns. According to them, frowns was 99% percent correct but 1000x slower. (Why they were marketing their system which was built over 5+ man years against mine which was built over 3 months I never will understand) Now, 1000x is a *lot* slower. However, when used in practice in a database setting, my system has a quick mechanism that can reject false matches very quickly. This is standard practice for chemistry databases by the way. All of a sudden the 1000x difference becomes almost meaningless. For a given search across 300000+ compounds, my system takes 1.2 seconds and their's takes 25 minutes. Using my prefiltering scheme their system takes 0.7 seconds. Now my code didn't change at all, only the way it was used changed. I could, of course, generate an example that takes me much longer but the average case is a whole lot better. My system is free though, so my users tend not to mind (or quite honestly, expect) as much :) Brian From usenet_spam at janc.invalid Thu Jan 15 23:49:45 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 16 Jan 2004 04:49:45 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: Peter Ashford schreef: >> vi might come close... ;-) > > Never!!! > > Emacs, on the other hand.... :) vi can't lose that competition. You can always implement vi in emacs if you want an editor, but you can't implement emacs in vi if you need an OS. ;) BTW: I don't care about vi vs. emacs, I use SciTE. :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jensthiede at webgear.co.za Fri Jan 9 15:47:13 2004 From: jensthiede at webgear.co.za (Jens Thiede) Date: 9 Jan 2004 12:47:13 -0800 Subject: Variable Scope 2 -- Thanks for 1. Message-ID: I found the querk in my code: a = [1, 2, 3]; b = a; b.append(4); b == [1, 2, 3, 4]; # As it should. a == [1, 2, 3, 4]; # - Why? One would think that b is a referance to a - however I know it's not. Without changing a thing from above, the following is true: b = []; b.append(5); a == [1, 2, 3, 4]; b == [5]; How do I avoid accedentaly modifying variables, is this a bug? If not why not? Jens Thiede. By the way, living in South Africa, where we have 11 national languages is nice although - as a result - the World does not know what to think of us. :) From ich at jan-kesten.de Sun Jan 18 07:36:31 2004 From: ich at jan-kesten.de (Jan Kesten) Date: Sun, 18 Jan 2004 13:36:31 +0100 Subject: Some kind of mail->html converter for python? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello out there :-) Is was looking around for a tool like mhonarc[1], but implemented in python (musn't be such powerful). Somebody know such a tool? My problem is to archive an entire mailing list on a webpage, but I don't have a shell account there, so I can't install a perl program like mhonarc quite easy. So I thought about putting a cgi ~ there, that can do the job when called. 1. Getting new mail from a pop3 account - no problem at all, poplib works really fine here. 2. Updating the archive - here I found nothing. So I like to ask first before I start programming at my own :-) Any hints? Cheers, Jan -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFACn3PvvmCkIIgH8QRAkxvAKCmb9UCydkGGIx+u3KgMk5wX3iLRACeKbOq g4gZiDaTQ6AQKO1IHGGOWyc= =aMvH -----END PGP SIGNATURE----- From perry at stsci.edu Mon Jan 19 17:13:40 2004 From: perry at stsci.edu (Perry Greenfield) Date: Mon, 19 Jan 2004 17:13:40 -0500 Subject: [Numpy-discussion] Status of Numeric In-Reply-To: <400C3EF3.8090005@ee.byu.edu> Message-ID: Travis Oliphant writes: > > Numarray is making great progress and is quite usable for many > purposes. An idea that was championed by some is that the Numeric code > base would stay static and be replaced entirely by Numarray. > > However, Numeric is currently used in a large installed base. In > particular SciPy uses Numeric as its core array. While no doubt > numarray arrays will be supported in the future, the speed of the less > bulky Numeric arrays and the typical case that we encounter in SciPy of > many, small arrays will make it difficult for people to abandon Numeric > entirely with it's comparatively light-weight arrays. > I'd like to ask if the numarray option couldn't at least be considered. In particular with regard to speed, we'd like to know what the necessary threshold is. For many ufuncs, numarray is within a factor of 3 or so of Numeric for small arrays. Is this good enough or not? What would be good enough? It would probably be difficult to make it as fast in all cases, but how close does it have to be? A factor of 2? 1.5? We haven't gotten very much feedback on specific numbers in this regard. Are there other aspects of numarray performance that are a problem? What specifically? We don't have the resources to optimize everything in case it might affect someone. We need to know that it is particular problem with users to give it some priority (and know what the necessary threshold is for acceptable performance). Perhaps the two (Numeric and numarray) may need to coexist for a while, but we would like to isolate the issues that make that necessary. That hasn't really happened yet. Travis, do you have any specific nummarray speed issues that have arisen from your benchmarking or use that we can look at? Perry Greenfield From webmaster at beyond-thoughts.com Thu Jan 8 19:43:15 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 09 Jan 2004 01:43:15 +0100 Subject: PRE-PEP: new Path class; (UPDATE) isValid, exists In-Reply-To: References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> Message-ID: <3FFDF923.8020605@beyond-thoughts.com> I think the implementation should be changed for the "NormalFSPath". def exists(self): try: os.stat(str(self)) return True except OSError, exc: # Couldn't stat so what's up if exc.errno == errno.ENOENT: # it simply doesn't exist return False return None # the path is invalid def isValid(self, raiseExc=False): if self.exists() is None: if raiseExc: raise InvalidPath else: return False else: return True Christoph Becker-Freyseng From aahz at pythoncraft.com Thu Jan 22 09:26:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Jan 2004 09:26:28 -0500 Subject: "Lecture Preparation" Discussions on Python References: <1010a26.0401212246.3cac7d06@posting.google.com> Message-ID: In article <1010a26.0401212246.3cac7d06 at posting.google.com>, Amir Michail wrote: > >We are planning to have "lecture preparation" discussions in comp3141 >at UNSW, where anyone can participate -- not only students taking the >subject. > >There is a heavy python component in this class and I was wondering >whether anyone is interested in participating in these discussions. >We are looking for both python beginners and experts. While I'm generally interested in such discussions, I won't be participating because I hate web boards. I vastly prefer netnews, with grudging use of e-mail lists. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat Jan 31 00:26:48 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 31 Jan 2004 06:26:48 +0100 Subject: python in dreamweaver References: Message-ID: Hi ! >>> It would be significantly more Pythonic to have a template similar to the following... Yes, but there are the visual aspect of DM... MCI From dw-google.com at botanicus.net Fri Jan 2 01:46:12 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 1 Jan 2004 22:46:12 -0800 Subject: finding file size References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: <99dce321.0401012246.712dd2fb@posting.google.com> "Sean Ross" wrote... > My question is this: Is there a reason why file objects could not have a > size method or property? So that you could then just ask the file how big it > is using fd.size or fd.size(). I'm just curious, because, well, it seems to > have obvious utility, and the way to find it is less than obvious (at least, > it was to me). Hey! 1) Using 'fd' as a name for a file object is a bad idea - you can get fds from os.open. If you insist on C-ish names, how about 'fp' instead? :) 2) There's nothing to stop the file object from having a size method, except that file-like objects then have more to implement. How about something like: py> class SizedFile(file): ... def __len__(self): ... oldpos = self.tell() ... self.seek(0, 2) ... length = self.tell() ... self.seek(oldpos) ... return length ... py> bleh = SizedFile("/etc/passwd") py> len(bleh) 1520 py> len([ x for x in bleh ]) 33 As I wrote this I realised it's wrong - size() would be better, since the length of the sequence is not the number of bytes. Maybe it is in binary mode? Dunno, me sleepy, goodnight.. David. > > Thanks, > Sean From martin at v.loewis.de Sat Jan 3 16:09:01 2004 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Jan 2004 22:09:01 +0100 Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: Michael Hudson writes: > That makes sense. I also guess that as shared libraries are mmaped > into the applications address space they won't use physical memory > until referenced anyway. But relocations probably mess with that. That's what PIC (position-independent code) is for: The code itself has no relocations, only centralized tables at the beginning of the shared library (PLT: procedure linkage table, GOT: global offset table) have relocations; they are tiny compared to the entire image. On Windows, each DLL has a "preferred load address"; if the library is loaded to this address, no relocations are needed (except in the import stubs). On OSX, the infamous "optimizing system" process invoked during software installation precomputes the addresses of all symbols, and puts updated code segments on disk which then can be mapped without relocation. Regards, Martin From __peter__ at web.de Fri Jan 2 04:48:52 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jan 2004 10:48:52 +0100 Subject: Multiple exception syntax References: Message-ID: Pierre Quentel wrote: > I find this confusing. It would be clearer for me to have : > > "except Error1 or Error2 or Error3" I see the ambiguity, but I find the above confusing, too, because it looks like a boolean expression, which it is not. I'd rather change the syntax to clearly separate the tuple of exception classes from the target: "except" [expression ["to" target]] ":" suite "to" is currently a comma. Don't expect that to happen, though. By the way, I don't recall having seen expression containing exception *instances*, and only learned that this is possible when I looked up the try statement in the reference. Is this for string exceptions or has it an application in newer code? > Or have I drunk too much lately ? Obviously, if you have to ask :-) Peter From msurette at laframboise.net Wed Jan 28 10:14:26 2004 From: msurette at laframboise.net (Michael Surette) Date: Wed, 28 Jan 2004 15:14:26 GMT Subject: Running python automatically in the background References: <1e4e0378.0401271729.3ea6b5c2@posting.google.com> Message-ID: On Tue, 27 Jan 2004 17:29:53 -0800, Alfred wrote: > hi all, > > i'm trying to figure out if there is some easy way to run a python > script in the background _without_ specifying "&" in a linux > enivornment. > > script.py & > > vs > > script.py > > is there an easy way to do this? > > been looking around but couldn't find any docs to support a > possibility. > > thanks! > > - al I forget where I first found this snippet, but it's probably what you want. PID= os.fork() if PID != 0: sys.exit() From daniels at dsl-only.net Thu Jan 1 17:31:01 2004 From: daniels at dsl-only.net (sdd) Date: Thu, 01 Jan 2004 14:31:01 -0800 Subject: 'inverting' a dict In-Reply-To: <3ff3848f_1@dns.sd54.bc.ca> References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> <3ff3848f_1@dns.sd54.bc.ca> Message-ID: <3ff4ab5b$1@nntp0.pdx.net> Bob van der Poel wrote: > This is sort of off topic for the thread, but I've got a similar > problem. In this case I have a dict like: > > { 'key1': 'value1', 'key2': value2} > > and I sometimes need to find the key for the value. All values/keys are > unique. I just use a loop: > > for a in dict: > if dict[a]== targ: > return a > return None For a few hunts, I'd do: for key,value in dictionary.iteritems(): if value == target: return key return None Of course, if it probed a lot between changes, it's better to reversedictionary = dict([(v,k) for k,v in dictionary.items()]) -Scott David Daniels Scott.Daniels at Acm.Org From jepler at unpythonic.net Sun Jan 18 22:18:16 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Jan 2004 21:18:16 -0600 Subject: How to hide user's input In-Reply-To: References: Message-ID: <20040119031816.GA21465@unpythonic.net> see the getpass module for one way to do this... Jeff From aaron at reportlab.com Tue Jan 6 09:31:54 2004 From: aaron at reportlab.com (Aaron Watters) Date: 6 Jan 2004 06:31:54 -0800 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0401051026.775d9ef3@posting.google.com> Message-ID: <9a6d7d9d.0401060631.45d2454c@posting.google.com> aaron at reportlab.com (Aaron Watters) wrote in message news:<9a6d7d9d.0401051026.775d9ef3 at posting.google.com>... > Basically I hadn't considered > the possibility that a program might open two direct connections > to a database within the same minute... whoops I meant "second" not "minute". This may not happen very often because only one direct connection is permissable at any given moment (but many indirect connections are okay). -- Aaron Watters === TO INFINITY AND BEYOND From jjl at pobox.com Tue Jan 13 12:44:36 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 17:44:36 +0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <7xhdz08xgy.fsf@ruckus.brouhaha.com> <1073978329.887910@yasure> Message-ID: <87brp7agl7.fsf@pobox.com> "Donn Cave" writes: > Quoth Paul Rubin : > ... > | The one attempt I know of to write a substantial Python application > | competitive with similar applications written in C was the Grail web > | browser, and AFAIK that was a complete failure. However, for small to > | medium sized projects which don't have to run fast, Python is great. [...] > But at any rate, I thought we were talking about huge projects > involving many programmers, and I don't think Grail was of that > sort at all. Right. Wasn't it a research project? In any case, hardly a large-scale programming effort along the lines of Mozilla! > I don't know what kind of programmer resources were > allocated to it, No obvious attribution other than "CNRI" in the tarball, but I think mostly Guido. :-) > but I bet it was actually a smashing success in > those terms. As for its size, I'd have to look, I have the code > around somewhere, but I'd guess it was smaller than Mailman or Zope. > Small enough that one programmer could become pretty thoroughly > acquainted with the whole thing. john[0]$ find /usr/local/src/python/grail-0.6 -name '*.py' | xargs /home/john/bin/pycount.py lines code doc comment blank file [...] 34808 25255 2801 2356 4396 total pycount reports 108756 code lines for Zope 2.6.3 (watch out: for some reason pycount spits out more than one total line with Zope, which you then have to add up -- maybe I'm doing something wrong there...). Given typical reported ratios of Python to C++ lines of code, that's a lot of code (not to mention all the Zope Python code outside of that package -- plone, for example; there's a fair amount of C code there, too, of course). Alex Martelli claimed a C++/Python lines of code per function point ratio of 5 or 6 in a post in this group -- if you believe that's a fair rule of thumb, then on that basis you'd expect 550-650 kLoC for a mythical Zope-in-C++ . In reality, since Zope takes advantage of Python's features, you'd expect to have to write many more lines of C++ than that, following Greenspun's tenth law. Who can be sure what the biggest Python code is, though? See Paul Graham's article on his web store-builder (implemented in Lisp) for one motivation for keeping it a secret (a motivation of the order of several tens of millions of dollars, IIRC ;-). http://www.paulgraham.com/avg.html (pycount reports 21730 code lines for mailman 2.1.4, BTW) John From rune.froysa at usit.uio.no Wed Jan 14 02:35:17 2004 From: rune.froysa at usit.uio.no (Rune Froysa) Date: 14 Jan 2004 08:35:17 +0100 Subject: Unicode and exception strings References: Message-ID: Terry Carroll writes: > On 12 Jan 2004 08:41:43 +0100, Rune Froysa > wrote: > > >Terry Carroll writes: > > > >> On 09 Jan 2004 13:18:39 +0100, Rune Froysa > >> wrote: > >> > >> >Assuming an exception like: > >> > > >> > x = ValueError(u'\xf8') > >> > > >> >AFAIK the common way to get a string representation of the exception > >> >as a message is to simply cast it to a string: str(x). This will > >> >result in an "UnicodeError: ASCII encoding error: ordinal not in > >> >range(128)". ... > >>> x = ValueError(u'\xf8') > >>> x.args[0] > u'\xf8' I was aware of the args variable in Exception, though I could not find any documentation for its usage, thus I wanted to rely on its internal __str__ method, rather than constructing the message myself. But, after a quick look at Python/exceptions.c, it seems that this is a feasable way :-) > The only thing is, what to do with it once you get there. I don't think > 0xF8 is a valid unicode encoding on its own. IIRC, it's part of a > multibyte character. Python gives me this, so I think it is correct: >>> unicode('?', 'latin-1') u'\xf8' For my usage, "u'\xf8'.encode('latin-1', 'replace')" is sufficient. > Is this helping any, or am I just flailing around? It does, thanks a lot for your help. Regards, Rune Fr?ysa From syver-en+usenet at online.no Thu Jan 8 10:34:39 2004 From: syver-en+usenet at online.no (Syver Enstad) Date: 08 Jan 2004 16:34:39 +0100 Subject: Why " ".some_string is often used ? References: <3FFD70EA.A6AF3CB8@engcorp.com> Message-ID: Peter Hansen writes: > John Roth wrote: > > > > And I agree, it's not entirely obvious why it's a string > > method rather than a list method, since it operates on > > a list, not on a string. The only explanation that makes > > sense is that, as a list method, it would fail if the list > > contained something other than a string. That's still > > not very friendly, though. > > One could about as easily argue (and I believe several have done > this quite well in the past, better than I anyway) that you are > actually operating on the *string*, not the list. You are in > effect asking the string to act as a joiner for the elements in the > list, not asking the list to join itself using the specified > string. > > At least, if you look at it that way, it might be easier to swallow. Can't we have both. This is called a reversing method (Beck, Smalltalk Best Practice Patterns) because it allows you to send several messages to the same object instead of switching between different instances, allowing the code to be more regular. class MyList(list): def join(self, aString): return aString.join(self) Like this: lst = ['one', 'two', 'three'] print lst print lst.join('\n') I'd also like a reversing method for len class MyList(list): def len(self): return len(self) Often when I program against an instance I intuitively start each line of code by writing the variable name and then a dot and then the operation. The lack of a reversing method for len and join means that my concentration is broken a tiny fraction of a second when I have to remember to use another object or the global scope to find the operation that I am after. Not a showstopper by any definition, but irritating nonetheless. -- Syver Enstad From jcarlson at nospam.uci.edu Wed Jan 28 16:54:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 28 Jan 2004 13:54:19 -0800 Subject: FRE: PEP 326 is D-E-A-D (was Re: How does compare work?) In-Reply-To: References: Message-ID: Batista, Facundo wrote: > Aahz wrote: > > #- >Even then, what about PEP 326, which presumes to define highest and > #- >lowest objects that can be compared with anything? > #- > #- What about it? ;-) > #- > #- (Guido just posted a Pronouncement rejecting it.) > > Can't find it at http://www.python.org/doc/essays/pepparade.html > > I'm looking in the wrong place? > > Thanks. > > . Facundo All old, new, accepted, rejected, etc., PEPs are listed at http://python.org/peps/ - Josiah From a.schmolck at gmx.net Mon Jan 5 11:50:59 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 05 Jan 2004 16:50:59 +0000 Subject: selecting a random item from a set References: <3FF20AA3.7080603@v.loewis.de> Message-ID: Jp Calderone writes: > > choice(dict(1:"gets this", 2:"gets that", "three":"gets the key")) > > > > This is as broken in the current choice implementation as in the one I > proposed. I don't think it makes any difference to the question at hand. The current implementation will always return values and complain if it unsuccesfully tries a value between 0 and len(dict). I'd argue this is very much preferable to always "succeeding" and sometimes returning a key and sometimes returning a value. 'as From jsbenson at bensonsystems.com Tue Jan 13 21:05:33 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 13 Jan 2004 18:05:33 -0800 Subject: I come not to bury C++, but to praise it... Message-ID: <001701c3da42$e54050c0$8d09500a@jsbwxp3> Thanks for the considerate (and temperate) responses to my C++ post. I know that language advocacy is particularly flame-prone, and find the responses informative. Who knows? I might even change my mind about C++! But I suppose that that's one of the dangers of participating in a dialogue. I normally try to avoid posts based on sprintf("All the cool guys use %s because %s\n", Myfavoritelanguages, Mylimitedexperience) but I most definitely fell into that trap this time around. From ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca Thu Jan 22 02:59:55 2004 From: ConfuseYourSpamBot-parzp at ConfuseYourSpamBot.shaw.ca (Parzival) Date: Thu, 22 Jan 2004 07:59:55 GMT Subject: Nokia prefers Python References: Message-ID: <%pLPb.214668$X%5.181901@pd7tw2no> Robin Becker wrote: > This might be the start of a success story. Says Nokia prefers Python! The referenced article quotes in part: ------------------------------------------------------------------------ "In order to get the best feedback into the viability of such technology concept tools, initial evaluation will be restricted within Forum Nokia to a limited group comprised of professional developers familiar with Nokia platforms and implementations." What this means, a Nokia spokesperson tells us, is that the company won't simply fling it at the company's 1.3 million developers, but offer a more controlled access program. ------------------------------------------------------------------------- With 1.3 million developers, Nokia should REALLY raise the Python profile. Guido may have to move again. Aside: The number of developers per cell phone sold must be pretty high, eh? With so many developers wielding that powerful Python metaobject protocol and all, its likely each cellphone user could program his or her own custom class doing their own custom things, like planning the night's menu during the drive home from work, in that /special/ way... -- (-: Stop, smile, and enjoy your breathing :-) -- Parzival -- Reply-to is confuggled: parzp (@) shaw (.) ca From sdeibel at wingide.com Sun Jan 18 11:06:06 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Sun, 18 Jan 2004 11:06:06 -0500 (EST) Subject: Python Success Stories (was Re: Python used in Freedom Force) In-Reply-To: Message-ID: On Sun, 18 Jan 2004, Alan James Salmoni wrote: > Irmen de Jong wrote in message news:<4006911e$0$327$e4fe514c at news.xs4all.nl>... > > Roberto Amorim wrote: > > > > > Not only Freedom Force, but also Severance: Blade of Darkness (3rd-person > > > action medieval game) and Bridge Commander (Star Trek TNG simulator). > > > > And also Cyan's URU:Ages Beyond Myst. > > I discovered some Python dlls and files in the game directory... > > > > --Irmen > > Perhaps all this stuff could be put onto the "Python Success Stories" > part of the python.org website? It's not public, but if the language > is clearly being used... Hi, I'm the guy that started this collection and am continuously accepting Python Success Stories to add to the current set. In addition to being available online, some of the stories were published in a booklet from O'Reilly, and I'm hoping they'll do future volumes as they did for the Perl Success Stories. There's information on writing a story here: http://pythonology.org/successguide/ I can take outlines or whole stories and can answer any questions you might have. BTW, if you want to "franchise" the content to your own Python-oriented website, you can do that as described here: http://pythonology.org/success&help=1 (but please *do* cache rather than re-fetching the story from us on every page load! ;-) It would be great to get a fresh batch of stories going. I've been less than aggressive in soliciting new ones lately but would like to get this effort moving again. Thanks! Stephan Deibel -- Wing IDE for Python Archaeopteryx Software, Inc Take Flight! www.wingide.com From tzot at sil-tec.gr Thu Jan 1 07:50:28 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 14:50:28 +0200 Subject: RELEASED: allout-vim 031229 References: Message-ID: <0t27vvkch12dcjq88q6m6hsv4jae8suqkg@4ax.com> On Wed, 31 Dec 2003 11:25:45 -0500, rumours say that Fran?ois Pinard might have written: >I sometimes use French words that just happen to be English words >as well, once done the obvious morphological changes! The word >"synoptique" has been part of my early youth: even in elementary school, >teachers were bringing us into writing "plans synoptiques" to summarise >our learning. [and Samuel] >> I tried googling for the term and some variations, and only turned >> up religious sites. I wasn't familiar with the format or the >> terminology. Looking up synoptic in the dictionary didn't shed much >> light on the situation. Trivia of the day: Usually, words common in two languages are derived from other, older languages --like Latin, or in this case, Greek. And most Unix users will be familiar with the composite noun "synopsis" (hint: man pages), parsed as "syn" (I believe "con" as prefix in Latin) and "opsis" ("view"), which means "that which can be viewed at a glance". "Etymology", that's another nice word :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jjl at pobox.com Fri Jan 9 15:20:58 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jan 2004 20:20:58 +0000 Subject: silent saveas ? References: Message-ID: <87wu80q3f9.fsf@pobox.com> Mei writes: [...] > I'm having difficulties to save the web browser in silent. when I try to > use > > WebBrowser1.ExecWB OLECMDID_SAVEAS, OLECMDEXECOPT_DONTPROMPTUSER, > "c:\blank.html", "c:\blank.html" > > The save window keep prompting up. How can I keep the save window in > silent? Please help me, Thanks a lot 1. This is a Python newsgroup, and your question doesn't relate to Python AFAICT. 2. You can't -- the behaviour you report is a bug in IE (at least, was in 5.0). John From noemail at noemail4u.com Mon Jan 12 07:34:28 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 12 Jan 2004 12:34:28 GMT Subject: Debugging Python References: Message-ID: <240ea7d5b9e090c1832dcfd41d455412@news.teranews.com> On Fri, 09 Jan 2004 09:06:33 -0500, "Mike C. Fletcher" wrote: ... >BTW, the Agile Programmer types have been known to suggest that >debuggers are entirely unnecessary, as everything should be caught by >more and more fine-grained unit-tests. Seems like a nice way to go, IMO. ... I think many PSP types would also agree with that statement, but would also suggest that design and code review would also supplement. --dang From bkelley at wi.mit.edu Thu Jan 8 14:03:12 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 08 Jan 2004 14:03:12 -0500 Subject: How to insert into listbox using wxPython In-Reply-To: References: Message-ID: <3ffda907$0$572$b45e6eb0@senator-bedfellow.mit.edu> Andrew wrote: > Hi I just started learning wxPython > > I wanted to know how I could do this in wxPython > > > self.listbox.delete(0, END) > for item in self.results: > self.listbox.insert(END, item) > > > I don't know but I think the insert and delete things here are specific of > Tkinter which I have been studying for the last little while > # make a list box with default choices box = wxListBox(self, -1, choices=['a','b','c']) # append a new entry box.Append('d') # reset the listbox to something else box.Set(['1','2','3']) # delete the second entry selection box.Delete(1) # get the index of currently selected entry print box.GetSelection() # get the string that is selected print box.GetStringSelection() # make a callback for when an entry is selected def listboxhandler(evt): box = evt.GetEventObject() print box.GetSelection(), "selected index" print box.GetStringSelection(), "selected item" EVT_LISTBOX(box, box.GetId(), listboxhandler) full little program ########################################################### from wxPython.wx import * class T(wxFrame): def __init__(self, parent, id, title): print "calling init" wxFrame.__init__(self, parent, id, title) self.mainsizer = self.sizer = wxBoxSizer(wxVERTICAL) # make a list box with default choices box = wxListBox(self, -1, choices=['a','b','c']) # append a new entry box.Append('d') # reset the listbox to something else box.Set(['1','2','3']) box.Delete(0) print box.GetSelections() self.sizer.Add(box, 0, wxEXPAND) self.SetSizer(self.sizer) def listboxhandler(evt): box = evt.GetEventObject() print box.GetSelection(), "selected index" print box.GetStringSelection(), "selected item" EVT_LISTBOX(box, box.GetId(), listboxhandler) app = wxPySimpleApp() foo = T(None, -1, "hello") print foo foo.Show() app.MainLoop() > Anyhelp would be cool > > From fumanchu at amor.org Sun Jan 25 21:21:12 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 25 Jan 2004 18:21:12 -0800 Subject: Mod_python on Windows Troubles Message-ID: Josiah Carlson wrote: > > modules/mod_python.so" to httpd.conf, the Apache service refuses to > > start with the following error: "Cannot load C:/Program Files/Apache > > Group/Apache2/modules/mod_python.so into server: The > specified module > > While I'm not using Apache or mod_python, I would be willing > to bet that > your error is the result of using 'mod_python.so' in Windows. Try > 'mod_python.dll' instead. I don't think so. I *am* using Apache2 on Windows, and it's ".so", for sure. Sounds to me (from the error message) that mod_python.so didn't get installed as it should have. I'm not a mod_python installation expert, so can't recommend anything further. FuManChu From aahz at pythoncraft.com Fri Jan 30 21:01:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2004 21:01:41 -0500 Subject: Get error "ImportError: No module named _tkinter" References: Message-ID: In article , Sebastian Stelzer wrote: >Aahz wrote: >> In article , >> Sebastian Stelzer wrote: >>> >>> import _tkinter # If this fails your Python may not be configured for >>> Tk >>>ImportError: No module named _tkinter >>> >>>I'am using Suse Linux 9.0 with Python 2.3.3. >> >> You need to install Tck/Tk devel package, then rebuild Python. > >I did it and I' got the same error. >Can you tell it more exactly please? Did you ``make distclean`` before rebuilding? If yes, then you're beyond my competence; hopefully someone else will pick the ball. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From worker at webmail.co.za Thu Jan 29 08:26:26 2004 From: worker at webmail.co.za (eugene) Date: 29 Jan 2004 05:26:26 -0800 Subject: crc-16 Message-ID: I looked for a crc-16(crc 16) function to use but couln't find one that worked: This one is working .. def crc16(s): crcValue=0x0000 crc16tab = (0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040) for ch in s: tmp=crcValue^(ord(ch)) crcValue=(crcValue>> 8)^crc16tab[(tmp & 0xff)] return crcValue From kkto at csis.hku.hk Sat Jan 17 23:07:42 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sun, 18 Jan 2004 12:07:42 +0800 Subject: yield References: Message-ID: <7iy8s5lx0x.fsf@enark.csis.hku.hk> >>>>> "km" == km writes: km> Hi all, i didnt understand the purpose of 'yield' keyword and the km> concept of 'generators' in python. can someone explain me with a km> small example how generators differ from normal function calls? Normally, when you define a function and call it, the code within the function gets executed, until the function returns, and at that point the function disappear altogether. For example: >>> def f(): ... a = 1 ... while a < 32: ... print 'Hello, ' + str(a) ... return a ... a *= 2 ... >>> f() Hello, 1 1 Here we define f, and at the time of definition the statements of the function won't be executed. Instead it is executed when the function is called. Once the function returns, the function disappear completely, with all the context in the function: all the statements after the return statement (a*=2 here) won't be executed, and the "other iterations" of the loop will no longer execute. Here, after printing 'Hello, 1', the function stops, returning a value 1 to the caller (which is printed by the Python interpretor). When a function contains the "yield" keyword, the story is somewhat different. If we simply replace the "return" keyword with the "yield" keyword in the above example we get this: >>> def f(): ... a = 1 ... while a < 32: ... print 'Hello, ' + str(a) ... yield a ... a *= 2 ... >>> f() In other words, the statements within the function will not be invoked even when we call f()! Instead, calling f() returns you an object, which is said to be a "generator" object. The basic method of this object is "next". For example: >>> g = f() >>> g.next() Hello, 1 1 So, the effect of f().next() in the function using "yield" is exactly the same as f() in the function using "return". The difference in the current version is that we still have an object g, so... we can call next() again! >>> g.next() Hello, 2 2 >>> g.next() Hello, 4 4 >>> g.next() Hello, 8 8 >>> g.next() Hello, 16 16 >>> g.next() Traceback (most recent call last): File "", line 1, in ? StopIteration In other words, after the function f yields, the function and the execution context has not disappear. Instead it is still stored within the generator object, waiting for you to call next() again. At that point the function continues its execution. If during the execution the function yields another value, g.next() returns the value of that value and f is stopped again. If during the execution the function returns, g.next() throws an exception StopIteration (and will do that again if you call g.next() again). This is a powerful construct: this is the only Python construct that let you easily "remember" the dynamic execution structure. (Most other language lacks that facility so it is impossible to remember the dynamic execution structure, short of packaging all the information you want in structure.) In the above example, after the first execution of next(), the g object remembers (in its "frame object", which can be located by g.gi_frame) what local variables are defined and what values they hold, which line the function is currently executing at, and what global variables are currently visible: >>> g = f() >>> g.next() Hello, 1 1 >>> dir(g.gi_frame) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] >>> g.gi_frame.f_locals {'a': 1} >>> g.gi_frame.f_lineno 5 >>> g.gi_frame.f_globals {'__builtins__': , '__name__': '__main__', '__doc__': None, 'g': , 'f': } The simplest way to use the construct, and also by far the most common use of it, is to use it as an "iterator", i.e., to repeatedly call it in a loop until it finishes throw a StopIteration exception. E.g., >>> for i in f(): ... print i * 3 + 7 ... Hello, 1 10 Hello, 2 13 Hello, 4 19 Hello, 8 31 Hello, 16 55 Here the "for" loop will call the next() method of the generator returned by f() repeatedly, each time getting the returned value into the variable i and execute the "body" of the for loop (which prints the value i*3+7). Similar things happen in list-comprehensions: >>> [i * 3 + 7 for i in f()] Hello, 1 Hello, 2 Hello, 4 Hello, 8 Hello, 16 [10, 13, 19, 31, 55] Note that, apart from printing the 'Hello, n' messages, both of the above have the end-effect that f() is the list [1, 2, 4, 8, 16]. So you can treat a generator as a "lazy" list that (1) an element will be generated "on-the-fly" when next() is called, and thus may be affected by the changes in the environment like the global variables, and may in reverse affect the environment like printing message and changing the global variables; and (2) after producing the element, the element itself will not be kept by the generator. Regards, Isaac. From ramen at lackingtalent.com Sun Jan 18 14:42:58 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sun, 18 Jan 2004 19:42:58 -0000 Subject: Does anyone else not find the fun in programming...? References: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> <400a7a92$0$205$edfadb0f@dread12.news.tele.dk> Message-ID: In article <400a7a92$0$205$edfadb0f at dread12.news.tele.dk>, Max M wrote: > Dave Benjamin wrote: > >> In article <4004f5ac$0$69931$edfadb0f at dread12.news.tele.dk>, Max M wrote: > >> What Python libraries do you use to do algorithmic composition? I played >> around with Snack (for Tcl) awhile back but couldn't get decent realtime >> performance so I gave up on the idea for the time being. I'm very interested >> to hear what sort of techniques you use. > > First of I don't use realtime... I figured... =) > I create lists of notes:: > > class Note: > > def __init__(self, time=0, pitch=64, velocity=64, duration=96): > self.time = time > self.pitch = pitch > self.velocity = velocity > self.duration = duration > > def __str__(self): > r = [] > a = r.append > a('time %s' % self.time) > a('pitch %s' % self.pitch) > a('velocity %s' % self.velocity) > a('duration %s' % self.duration) > return '\n'.join(r) > > That are then converted into midi files by a very simple wrapper layer. > > This simple structure makes it extremely simple to create > transformations on a list of notes. I considder each list a "part" like > you see it in Cubase/Logic. > > The idea is then to create a personal library of transformations and > generators that expres your own musical style. I also have a few > routines for repeating/extending/sequencing these parts. So, a data-flow style more or less... that seems to be a useful model for music software. Have you ever played around with Max? > I import these midi files into software like Cubase, or Reason or Orion. > Where they drive either hardware or software synths. > > I like to fiddle around with the sounds manually by twiddleling the knobs. > > But I don't change the mnusic manually in the sequencer software. Rather > i change the software and genereate a new midi file, that I reload. > > It is a bit like writing code generators. And it is completely flexible, > creative and fun due to the ease of Python. Yeah, makes perfect sense to me. Do you have any Python-generated songs available? Sounds really cool. The thing I was working on was a probabilistic beat generator, based on statistics of when a certain drum would hit in a beat for a selection of hip hop songs. I was trying to capture the "feel" rather than the exact sequence of sounds. I still have the (tcl) source laying around here somewhere. It worked pretty well on Linux (I could actually get it to beat-match) but in Windows the performance was terrible. Which is probably because I'd have to be out of my mind to think I could get realtime performance out of Tcl. ;) Thanks, Max... -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From ralph at sluiters.de Mon Jan 5 14:58:04 2004 From: ralph at sluiters.de (Ralph Sluiters) Date: Mon, 5 Jan 2004 20:58:04 +0100 Subject: Problem: 'Threads' in Python? Message-ID: Hi, i've got a small problem with my python-script. It is a cgi-script, which is called regulary (e.g. every 5 minutes) and returns a xml-data-structure. This script calls a very slow function, with a duration of 10-40 seconds. To avoid delays, i inserted a cache for the data. So, if the script is called, it returns the last caculated data-structure and then the function is called again and the new data is stored in the cache. (There is no problem to use older but faster data) My problem is, that the client (A Java program (or browser, command line)) waits, until the whole script has ended and so the cache is worthless. How can I tell the client/browser/... that after the last print line there is no more data and it can proceed? Or how can I tell the python script, that everything after the return of the data (the retieval of the new data and the storage in a file) can be done in an other thread or in the background? Greetings Ralph From tjreedy at udel.edu Sun Jan 25 21:13:50 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 Jan 2004 21:13:50 -0500 Subject: [OPINION] - does language really matter if they alldothe samething? References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com><028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net><4011C497.1040302@prescod.net><58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: "Dietrich Epp" wrote in message news:D3AD8358-4F90-11D8-BCE5-0003934ACDEC at zdome.net... > > On Jan 24, 2004, at 9:30 AM, Terry Reedy wrote: > > > I slightly prefer my Python version, but I suspect you will not, so you > > remain safe. > > You prefer infinite recursion? Given that my incomplete, you-fill-in-the-blanks, "Maybe something like" this, Python code, translated directly from your Lisp code, would not even compile, and that we were talking about the relative convenience and aethestics of equivalent code in different languages, this response strikes me as a bit odd. Oh well. As I understood your lisp version of random_sword_magic_power(quality), recursive calls are only needed when quality = good, while the two recursive calls then made would only be made with quality = medium, hence the recursion would (should) stop one level down. To make this happen with the Python version, add a first statement "something like" double = (quality == good) and (random_sword_magic_power(medium) + random_sword_magic_power(medium)) or None and substitute double for the double call in the argument list for choose-random-assoc(). I assume that in your code, the same recursion base-casing is hidden within the no-source-given choose-random-assoc macro, by how it rewrites the text of its 'arguments'. I suspect that if choose-random-assoc were an ordinarily lisp function, including in CL, with arguments evaluated before the call, then random_sword_magic_power() would have to explicitly conditionalize its recursive call, just as in other languages. If so, then one very much does have to know that c-r-a is a macro in order to use it efficiently and not write a redundant base-case check. Terry J. Reedy From ark at acm.org Fri Jan 23 00:55:25 2004 From: ark at acm.org (Andrew Koenig) Date: Fri, 23 Jan 2004 05:55:25 GMT Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> Message-ID: > I suppose you could special-case min() and max() to return the > appropriate singletons if called with no arguments. > > There's something very nice about that. There's also something very > ugly about it. I'm having a hard time deciding which is stronger :-) I'm afraid it's not right, because calling min() with no arguments should return Max and calling max() with no arguments should return Min. This behavior is correct because it preserves the intuitive property that if s1 and s2 are (possibly empty) sequences, min(min(s1),min(s2)) should be equal to min(s1+s2), and similarly for max. If you like, Max is the identity element for min and Min is the identity element for max. From jblazi at hotmail.com Sun Jan 11 05:14:57 2004 From: jblazi at hotmail.com (jblazi) Date: Sun, 11 Jan 2004 11:14:57 +0100 Subject: Emacs python mode question References: Message-ID: On Sat, 10 Jan 2004 16:25:59 -0600, Skip Montanaro wrote: > (define-key esc-map [g] 'goto-line) For one reason or the other, this does not work. (I tried several such options before posting.) When I do this (and save .emacs and restart Emacs of course) I get the message Set face default (M-g d) ... in the command line buffer. jb ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From peter at engcorp.com Tue Jan 20 11:39:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jan 2004 11:39:04 -0500 Subject: SystemError while execing bad code References: Message-ID: <400D59A8.ADF3C2F3@engcorp.com> Gerrit Holl wrote: > > I found a cool way to trigger a SystemError: > > >>> exec CodeType(0,0,0,0,"",(),(),(),"","",0,"") > XXX lineno: 0, opcode: 0 > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/", line 0, in > File "/usr/lib/python2.2/site-packages/", line 0, in > SystemError: unknown opcode > > The documentation says: > You should report this to the author or maintainer of your Python > interpreter. Be sure to report the version of the Python interpreter > (sys.version; it is also printed at the start of an interactive Python > session), the exact error message (the exception's associated value) and > if possible the source of the program that triggered the error. > > Although it probably shouldn't be taken literally in this case... > ...or should it :-)? > > Hmm, and this actually *hangs*: > >>> exec CodeType(0,0,0,0,"",(),(),(),"","",2**31-1,"") > XXX lineno: 2147483647, opcode: 0 > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/", line 2147483647, in > > ... > > But I guess this is a case of "so don't do it" :-)? I once experimented, briefly, with doing "genetic programming" (evolving programs to solve problems) using Python bytecode. In effect, this meant that random sequences of bytes were being executed as though they were valid compiled Python programs. The interpreter crashed rapidly and frequently. I quickly concluded that the interpreter is designed to be safe in executing bytecode that is generated by a proper Python compiler, and that the compiler did not generate random bytecodes most of the time. Had to abandon that idea, though in principle it's still very cool. -Peter From !!!salvatore.didio at wanadoo.fr Sat Jan 24 10:42:29 2004 From: !!!salvatore.didio at wanadoo.fr (Salvatore) Date: Sat, 24 Jan 2004 16:42:29 +0100 Subject: Tkinter Base Window In-Reply-To: <401257c4$0$26116$afc38c87@news.optusnet.com.au> References: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Message-ID: Peter Moscatt wrote: > Ok.... I am pretty new to Python (as you may have gathered from previous > posts). So now it time for another one of my ridiculous questions.... :-) > > When using 'Tkinter', what is used as the base window to work from, meaning > what widget do I use to place all other widgets onto to create a custom > dialog ? > > Pete > Here you can find what you search and more ;-) http://www.pythonware.com/library/tkinter/introduction/ Regards Salvatore From carroll at tjc.com Tue Jan 13 20:32:36 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed, 14 Jan 2004 01:32:36 GMT Subject: Unicode and exception strings References: Message-ID: On 12 Jan 2004 08:41:43 +0100, Rune Froysa wrote: >Terry Carroll writes: > >> On 09 Jan 2004 13:18:39 +0100, Rune Froysa >> wrote: >> >> >Assuming an exception like: >> > >> > x = ValueError(u'\xf8') >> > >> >AFAIK the common way to get a string representation of the exception >> >as a message is to simply cast it to a string: str(x). This will >> >result in an "UnicodeError: ASCII encoding error: ordinal not in >> >range(128)". >> > >> >The common way to fix this is with something like >> >u'\xf8'.encode("ascii", 'replace'). However I can't find any way to >> >tell ValueErrors __str__ method which encoding to use. >> >> Rune, I'm not understanding what your problem is. >> >> Is there any reason you're not using, for example, just repr(u'\xf8')? > >The problem is that I have little control over the message string that >is passed to ValueError(). All my program knows is that it has caught >one such error, and that its message string is in unicode format. I >need to access the message string (for logging etc.). > >> _display_text = _display_text + "%s\n" % line.decode('utf-8')) > >This does not work, as I'm unable to get at the 'line', which is >stored internally in the ValueError class (and generated by its __str_ >method). You should be able to get at it via x.args[0]: >>> x = ValueError(u'\xf8') >>> x.args[0] u'\xf8' The only thing is, what to do with it once you get there. I don't think 0xF8 is a valid unicode encoding on its own. IIRC, it's part of a multibyte character. You can try to extract it as above, and then decode it with the codecs module, but if it's only the first byte, it won't decode correctly: >>> import codecs >>> d = codecs.getdecoder('utf-8') >>> x.args[0] u'\xf8' >>> d.decode(x.args[0]) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'decode' >>> But, still, if all you want is to have *something* to print out explaining the exception, you can use repr(): >>> repr(x.args[0]) "u'\\xf8'" >>> Is this helping any, or am I just flailing around? From adonisv at REMOVETHISearthlink.net Mon Jan 12 10:51:55 2004 From: adonisv at REMOVETHISearthlink.net (Adonis) Date: Mon, 12 Jan 2004 15:51:55 GMT Subject: Moving widgets in Tkinter References: Message-ID: Thanks a million, works like a charm! Just another problem arose *grumble*, trying to get it to work with multiple frames, almost there but no cigar. Adonis From max at alcyone.com Sun Jan 18 21:21:49 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 18 Jan 2004 18:21:49 -0800 Subject: Python Text Adventure Authoring System References: <100mf8ial58jf57@corp.supernews.com> Message-ID: <400B3F3D.408DD1A4@alcyone.com> Francis Avila wrote: > I don't want to stop you, but I warn you that developing a system like > this > is far more complex than you think. Also, it's a pretty mature field in terms of existing technology. There are dozens of authoring systems, including half a dozen or so major ones: http://www.alcyone.com/max/links/if.html#Authoring__authoring_systems -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Do we really want to go to Mars / Do we really want to try -- Cassandra Wilson From claird at lairds.com Thu Jan 15 15:23:10 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 15 Jan 2004 20:23:10 -0000 Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> Message-ID: <100dtle1tldg730@corp.supernews.com> In article , Jarek Zgoda wrote: >?????? ? pisze: > >>> (will not mention that it works on AS/400, the best >>> minicomputer(!) ever made). >> >> Why is it the best minicomputer ever made? >> I really want to know! > >Since nobody ever produced any other. Only IBM produced machines that >can be called "midrange" (something between microcomputer and "real >computer", the famous S/390 mainframe). They still use this terminology. . . . Sneaky, Jarek; but there were a LOT of "minicomputer" manufacturers, including DEC, Data General, HP, Prime, ... -- Cameron Laird Business: http://www.Phaseit.net From hans at zephyrfalcon.org Tue Jan 13 20:09:36 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 13 Jan 2004 20:09:36 -0500 Subject: Does anyone else not find the fun in programming...? In-Reply-To: <20040113210157.GD6601@unpythonic.net> References: <20040113210157.GD6601@unpythonic.net> Message-ID: <400496D0.1020301@zephyrfalcon.org> Jeff Epler wrote: >>>>assert "programming" is "fun" > > AssertionError # I'm going home Try: assert "programming is fun" :-) -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From jcarlson at nospam.uci.edu Fri Jan 30 15:04:45 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 12:04:45 -0800 Subject: Safe to modify globals(), or not? In-Reply-To: References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: >>Fair enough. However, is there anything wrong with modifying globals() > > > No. "globals()['a'] = 3" is exactly the same as "a=3" executed at module > scope, outside of functions. The purpose is to allow you to set a variable > whose name you do not know until runtime. An example, as in your > application, is when the name comes from user input. I personally enjoy modifying globals() as it suits my needs. Another statement that is quite useful is global. >>> def set_global_k(i): ... global k ... k = i ... >>> set_global_k(5) >>> k 5 >>> set_global_k(6) >>> k 6 >>> Really only useful for when you know the name of the variable before runtime, but then again, one could always: >>> def set_global_name(i, name): ... exec('global %s;%s = i'%(name, name)) ... >>> set_global_name(10, 'l') >>> l 10 MMM, global manipulation. Now if only there was a python function for global dominance, though perhaps globals().clear() is sufficient. Mua-hah-hah. - Josiah From eric.brunel at N0SP4M.com Thu Jan 8 11:01:22 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Thu, 08 Jan 2004 17:01:22 +0100 Subject: Calling a function dynamically References: <924a9f9c.0401080742.39eba581@posting.google.com> Message-ID: Paradox wrote: > I would like to call a function whose name I supply at runtime. > Something like this but it didn't work > > functionName = 'run' > instance = ClassDef() > args = [1, 2] > > #want the dynamic equivalant of > #instance.run(*args) > > #This didn't work cause there was no __call__ attribute. Why? > value = instance.__call__[functionName](*args) The "function" is in fact a method on the instance, that is handled like a regular attribute. So using getattr should do what you want: value = getattr(instance, functionName)(*args) __call__ is for a completely different purpose, which is to define instances that behave like functions: >>> class Spammer: ... def __call__(self): ... print 'spam' ... >>> o = Spammer() >>> o() spam HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From glenfant at NOSPAM.bigfoot.com Thu Jan 29 11:24:26 2004 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Thu, 29 Jan 2004 17:24:26 +0100 Subject: regexp upward compatibility bug ? References: Message-ID: "Jeff Epler" a ?crit dans le message de news:mailman.984.1075389591.12720.python-list at python.org... > The problem is the use of '-' in the character groups, like > r'[\w-]' > [...] > > Jeff > Jeff, Many thanks for the time you spent for my enlightenments. I fixed the stuff with your help. -- Gilles From emile at fenx.com Sun Jan 4 11:26:30 2004 From: emile at fenx.com (Emile van Sebille) Date: Sun, 4 Jan 2004 08:26:30 -0800 Subject: how to make a code object a function References: Message-ID: Diez B. Roggisch: > Just out of curiosity - is there a way to know the name of a code object you > know nothing about except that it will become a function definition? I > guess I could go for some AST-stuff looking for a "def foo" statement, so I > know I will end up having defined foo when exec'ing the code object. > I'm not quit sure what you're asking, but does sets help? >>> ns = locals().keys() >>> testing = 1 >>> print sets.Set(locals().keys()) - sets.Set(ns) Set(['testing']) Emile van Sebille emile at fenx.com From dkuhlman at rexx.com Mon Jan 19 16:28:44 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 19 Jan 2004 13:28:44 -0800 Subject: Simple question from Python newb... What am I doing wrong? For x, y, z in aTuple: References: Message-ID: Amy G wrote: > I have a whole bunch of tuples that look something like this, > > aTuple = ('1074545869.6580.msg', 't_bryan_pw at gmcc.ab.ca', 'Your > one stop prescriptions') > > now that I have this I try > > for x, y, z in aTuple: > do something with x > do something with y > do something with z > > But I am getting the error that there are too many values to > unpack. If I do... The "for" statement processes each item in a sequence object. The first object in your sequence object (aTuple) is a string. The string has more that three characters. So, that string cannot be unpacked into your three variables x, y, and z. In contrast, consider the following: >>> value = (('aa', 'bb', 'cc'), ('dd', 'ee', 'ff')) >>> for x, y, z in value: print 'x:', x print 'y:', y print 'z:', z x: aa y: bb z: cc x: dd y: ee z: ff >>> In this example, the first item in the tuple is itself a tuple with three items. Therefore, it can be unpacked into the variables x, y, and z. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From seanl at chaosring.org Sat Jan 3 03:58:41 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 00:58:41 -0800 Subject: Creating a capabilities-based restricted execution system Message-ID: I've been playing around with Zope's RestrictedPython, and I think I'm on the way to making the modifications necessary to create a capabilities-based restricted execution system. The idea is to strip out any part of RestrictedPython that's not necessary for doing capabilities and do all security using just capabilities. The basic idea behind capabilities is that you don't give any piece of code you don't trust a reference to something you don't want it to have access to. You use proxies instead (E calls them "facets"). In order to be able to allow untrusted code to create proxy objects, I needed to be able to store a reference to the proxied object in a private attribute. To create private attributes, I'm using "name mangling," where names beginning with X_ within a class definition get changed to __, where the UUID is the same for that class. The UUIDs don't need to be secure because it's not actually possible to create your own name starting with an underscore in RestrictedPython; they just need to be unique across all compiler invocations. The nice thing about using this name mangling is that it's only done at compile time and doesn't affect runtime performance. An interesting side effect is that code defined on a class can access private attributes on all descendants of that class, but only ones that are defined by other code on that class, so this isn't a security issue. I was thinking I needed read-only attributes to be able to avoid untrusted code's being able to sabotage the revoke method on a proxy object, but I'm thinking that just keeping around a reference to the revoke method in the original code may be enough. Does anyone think I'm going in completely the wrong direction here? Am I missing anything obvious? From phil at riverbankcomputing.co.uk Sat Jan 17 08:09:38 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 17 Jan 2004 13:09:38 +0000 Subject: ANN: PyQt v3.10 Released Message-ID: <200401171309.38718.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v3.10 available from http://www.riverbankcomputing.co.uk/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt. Like Qt, PyQt is available under the GPL (for UNIX, Linux and MacOS/X), a commercial license (for Windows, UNIX, Linux and MacOS/X) and a free educational license (for Windows). PyQt is implemented as a set of 9 extension modules containing 300 classes and over 5,750 functions and methods. PyQt also includes bindings to QScintilla, the port to Qt of the Scintilla editor component. PyQt can be used either as a rapid prototyping tool, or as an alternative to C++ for developing large Qt applications. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. Third party tools are also available - such as eric3, a comprehensive IDE (including an editor, debugger, class browser, integration with Qt Designer, re-factoring tools, unit testing tools and integration with source code control systems). eric3 is written entirely using PyQt and is available from http://ww.die-offenbachs.de/detlev/eric3.html. From mwilson at the-wire.com Sun Jan 4 20:20:22 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 04 Jan 2004 20:20:22 -0500 Subject: Why does this fail? References: Message-ID: In article , "Dave Murray" wrote: >New to Python question, why does this fail? > >---testcase.py--- >import sys, urllib, htmllib >def Checkit(URL): > try: > print "Opening", URL > f = urllib.open(URL) > f.close() > return 1 > except: Here, try except Exception, details print "Exception:", details > return 0 > >rtfp = Checkit("http://www.python.org/doc/Summary.html") >if rtfp == 1: > print "OK" >else: > print "Fail" Then you'll see Opening http://www.python.org/doc/Summary.html Exception: 'module' object has no attribute 'open' Fail You probably mean urlopen . Regards. Mel. From ketulp_baroda at yahoo.com Wed Jan 14 04:13:56 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 14 Jan 2004 01:13:56 -0800 Subject: what is best for web development?? References: <87wu80559x.fsf@blakie.riol> <87oet9grqy.fsf@blakie.riol> Message-ID: hi the application should work with Apache or IIS web server. From jolsen at mail2world.com Wed Jan 28 08:01:51 2004 From: jolsen at mail2world.com (Jesper Olsen) Date: 28 Jan 2004 05:01:51 -0800 Subject: newsgroup lib Message-ID: <6b17fa95.0401280501.4be454cb@posting.google.com> Is there a python module for accessing newsgroup articles? Something similar to urllib for downloading web pages... Cheers Jesper From vdebaere at lilly.csoft.net Sun Jan 18 12:59:49 2004 From: vdebaere at lilly.csoft.net (Vincent De Baere) Date: Sun, 18 Jan 2004 18:59:49 +0100 Subject: xml.dom.minidom childnodes In-Reply-To: <1074448002.18656.33.camel@dev.internal> References: <400abcab$0$780$ba620e4c@news.skynet.be> <1074448002.18656.33.camel@dev.internal> Message-ID: <400AC995.2080102@lilly.csoft.net> Mark McEahern wrote: >On Sun, 2004-01-18 at 11:04, Vincent De Baere wrote: > > >>As you can see in the xml file, there is a newline after the (root) >>documentelement. I guess that's why I need to use menurootchildren[1] >>instead of menurootchildren[0] to access the first child. >> >> > >Why not use getElementsByTagName and punt on the whole variable >whitespace as childNodes business? > > That seems to be the solution indeed! Thank you! Vincent From bart_nessux at hotmail.com Thu Jan 22 17:41:13 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 22 Jan 2004 17:41:13 -0500 Subject: HDD Stress Test with Python Message-ID: A bit off topic, but here goes: Does this look like a reasonable hard drive stress-test? I run it repeatedly for a few days on our new PowerMac G5's (they come with Python 2.3 installed!!!) which we've had drive problems with. Two 80GB SATA Maxtor drives replaced already. Only been in use for a few days. Apple is replacing them with Seagate drives, not that that matters. Here's the script: def dd_test(): import os import time print print "DDing first partition to second partition... please wait." fp = os.popen("/bin/dd if=/dev/disk0s3 of=/dev/disk0s5", "r") fp fp.close() print "DD has completed." print print "Formatting first partition UFS" print fp1 = os.popen("/sbin/newfs /dev/disk0s3", "r") fp1 fp1.close() print print "Formatting second partition UFS" print fp2 = os.popen("/sbin/newfs /dev/disk0s5", "r") fp2 fp2.close() print "Sleeping 60 seconds before starting again..." print time.sleep(60) dd_test() dd_test() # Make two equal sized partitions on Mac internal HDD. # Unmount the internal HDD, boot from firewire drive # and run script. # Used 'pdisk /dev/disk0 -dump' to get info about drive. # Used 'newfs /dev/disk0s3' to format a partition UFS. From rmkrauter at yahoo.com Mon Jan 26 21:32:28 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon, 26 Jan 2004 21:32:28 -0500 Subject: efficient updating of nested dictionaries In-Reply-To: References: Message-ID: <1075170748.4050.4.camel@vaio> Oh crap. Sorry about the html emails. I've been meaning to turn that off. Thanks for reminding me. Rich From donn at drizzle.com Sun Jan 25 13:38:31 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 25 Jan 2004 18:38:31 -0000 Subject: any news client in Python? References: <2b4c49e0.0401230915.3438810f@posting.google.com> <4de76ee2.0401241125.45e77f9e@posting.google.com> Message-ID: <1075055910.305663@yasure> Quoth davidb at mcs.st-and.ac.uk (David Boddie): ... | I wrote my own newsreader for a minority platform, too: | | http://www-solar.mcs.st-and.ac.uk/~davidb/Software/Python/NewsRead/ | | There are probably others lurking in FTP archives. | | I have to admit that my own attempt isn't exactly the best example you | could hope for. My excuse is that I had to create my own widget set at | the same time as writing the application. If I still had to use it, I | would probably rewrite it, or at least refactor it severely. That's my story too, but the way I deal with it is to present my BeOS newsreader and IMAP email reader as a demo application for the widget set, hence a built-in excuse for its lameness. I never even got around to the "add group" interface you show there. A really good newsreader is a lot of work (and of course its users are by definition the USENET crowd, not people you want to have to deal with!) But it wasn't much of an issue, because each BeOS user tended to write his own newsreader for some reason - much easier to tolerate the defects of your own software, I suppose. Donn Cave, donn at drizzle.com From bh at intevation.de Tue Jan 13 12:40:59 2004 From: bh at intevation.de (Bernhard Herzog) Date: Tue, 13 Jan 2004 18:40:59 +0100 Subject: Design Question References: <73b00f0c.0401130928.595842c0@posting.google.com> Message-ID: <6qfzejoifo.fsf@salmakis.intevation.de> ferrell at diablotech.com (Robert Ferrell) writes: > My question is about how to architect a class hierarchy where some > methods are nearly identical between a superclass and a subclass, but > differ slightly. For example: > > class Sup(object): > def __init__(self): > self.specialFlag = False > def aMeth(self): > > > > > class Sub(Sup): > def __init__(self): > self.specialFlag = True A commonly used alternative would be class Sup(object): def aMeth(self): self.specialMethod() def specialMethod(self): pass class Sub(Sup): def specialMethod(self): Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From sross at connectmail.carleton.ca Fri Jan 9 12:14:26 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 9 Jan 2004 12:14:26 -0500 Subject: how to speedup this code? References: Message-ID: "Ognen Duzlevski" wrote in message news:btmgtp$grr$1 at chessie.cirr.com... > Hi all, > > I have rewritten a C program to solve a bioinformatics problem. Portion where most of the time is spent is: > > def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): > global ONEINDELPENALTY,OPENGAPPENALTY > > for ndx1 in range(1,tlen+1): > for ndx2 in range(1,qlen+1): > delmat[ndx1][ndx2] = Min(delmat[ndx1-1][ndx2]+ONEINDELPENALTY, \ > Min(scoremat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY, \ > insertmat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY)) > insertmat[ndx1][ndx2] = Min(insertmat[ndx1][ndx2-1]+ONEINDELPENALTY, \ > Min(scoremat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY, \ > delmat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY)) > scoremat[ndx1][ndx2] = Min(scoremat[ndx1-1][ndx2-1], \ > Min(delmat[ndx1-1][ndx2-1], insertmat[ndx1-1][ndx2-1])) + \ > GetFitnessScore(tseq,ndx1-1,qseq,ndx2-1) > > def Min(a,b): > if a< b: > return a > else: > return b > > In C this is not a big deal, delmat, scoremat and insertmat are int matrices dynamically allocated and the > loop-inside-a-loop is pretty fast. However, on python (2.3) it is very slow. So for comparison, my C version takes 8 > seconds to execute and the python version takes around 730 seconds. I have narrowed down through visual observation > (print before and print after entry into the above nested loop) that most of the time is spent in there. I have also > tried the Numeric package with their arrays. It speeded things up somewhat but not considerably. > > Any suggestions? > > Thank you, > Ognen Hi. There is a builtin min() function, so using that should speed things up a little. Also, you calculate "OPENGAPPENALTY+ONEINDELPENALTY" 4 times inside the loop. Outside the loop, store the value of this sum in a variable, say P(?). You also calculate ndx-1 and ndx2-1 5 and 7 times, respectively, so you may want to store those values in temp. variables - say prerow, and precol. range(1,qlen+1) is evaluated tlen times - if qlen does not change, then storing this result would be a good idea, using, say, 'columns'. There are other things, though perhaps not speed related: You have three near indentical operations that could be refactored into a function: def calculate_score(m, n, o, row, col, p0, p1, p2): # you can choose a more appropriate function name m_val = m[row][col]+p0 n_val = n[row][col]+p1 o_val = o[row][col]+p2 return min(m_val, min(n_val, o_val)) This may actually slow things down, so you may not want to use this function. So, if you use these suggestions, you'll end up with something like this [untested]: def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): global ONEINDELPENALTY,OPENGAPPENALTY OIP = ONEINDELPENALTY P = OPENGAPPENALTY+ONEINDELPENALTY s,i,d = scoremat,insertmat,delmat columns = range(1,qlen+1) for row in range(1,tlen+1): prerow = row - 1 for col in columns: precol = col - 1 FSP = GetFitnessScore(tseq,prerow,qseq,precol) delmat[row][col] = calculate_score(d,s,i,prerow,col,OIP,P,P) insertmat[row][col] = calculate_score(i,s,d,row,precol,OIP,P,P) scoremat[row][col] = calculate_score(s,d,i,prerow,precol,0,0,FSP) OK, so, HTH Sean From tzot at sil-tec.gr Mon Jan 19 04:29:59 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 19 Jan 2004 11:29:59 +0200 Subject: YA string interpolation and printing idea References: <7x3caf5mga.fsf_-_@ruckus.brouhaha.com> <4008B9CE.CC140EF@alcyone.com> <7xwu7r6utj.fsf@ruckus.brouhaha.com> Message-ID: On 16 Jan 2004 20:52:08 -0800, rumours say that Paul Rubin might have written: >Maybe if type/object >unification proceeds far enough, we'll someday be able to define our >own operations on builtin objects like strings. I'd like that too, and I believe Ruby does it; however, ISTR that Guido has specifically said that this won't be allowed, since you can always subclass the base types. He's the boss :) I've also seen a hackish patch (by MWH? can't be sure) that allowed one to substitute their own classes for the base types (so that integer or string constants would be instances of the derived subclasses). Don't know if that would help you in your code. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jjhuang at cm.nctu.edu.tw Mon Jan 5 22:16:57 2004 From: jjhuang at cm.nctu.edu.tw (Chun-Chieh Huang) Date: Tue, 06 Jan 2004 11:16:57 +0800 Subject: Embedding python problem, related to PyObject_Print. Message-ID: Dear all, I carefully lookup PyObject_Print in the API manual, but I can't find the resolution. And the problem is described below: I embed python into C++ code as follows: // First register function objects pModule = PyImport_ImportModule("merge"); pDict = PyModule_GetDict(pModule); pFunc = PyObject_GetAttrString(pModule, "TopoCreator"); PyObject *theArg = PyString_FromString("FOSS"); theTopoDesigner = PyObject_CallFunctionObjArgs(pFunc, theArg); addPiconet_Topo = PyObject_GetAttrString(theTopoDesigner,"addPiconet"); // Create PyObject *tmpList = PyList_New(maxNumber); // setting values of tmpList PyObject_Print(tmpList, stdout, 0); pValue = PyObject_CallFunctionObjArgs(addPiconet_Topo, tmpList); The problem is that if I comment out the line "PyObject_Print," I'll get an error message: "TypeError: addPiconet() takes exactly 2 arguments (3 given)" But if I add back the PyObject_Print line, it works as expected. However, I don't need PyObject_Print when the system is finished; I use it for debugging purpose. The "addPiconet" method takes a list as an argument, which is declared as: def addPiconet(self, aList): Blah blah blah I really don't know how to solve it. How can I make it work without PyObject_Print? Any suggestion? Thanks in advance. Albert -- Chun-Chieh Huang, aka Albert E-mail: jjhuang AT cm.nctu.edu.tw ??? Department of Computer Science National Tsing Hua University MIME/ASCII/PDF/PostScript are welcome! HsinChu, Taiwan NO MS WORD DOC FILE, PLEASE! From cygnus at cprogrammer.org Wed Jan 21 18:25:49 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Wed, 21 Jan 2004 18:25:49 -0500 Subject: Need help with Python class idioms In-Reply-To: References: Message-ID: <20040121232549.GA28328@mail.theserver.ath.cx> # ... what if mandatoryVar1 was set to False? To all who have responded to me as such: of course, how one treats the variable in a boolean context depends on what its semantically "false" value is. You do the math; I just provided a syntax alternative. :) -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From jjl at pobox.com Tue Jan 13 13:07:47 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 18:07:47 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <877jzwg1v2.fsf@pobox.com> <95aa1afa.0401130628.7992e9e1@posting.google.com> Message-ID: <87y8sb90y4.fsf@pobox.com> michele.simionato at poste.it (Michele Simionato) writes: > jjl at pobox.com (John J. Lee) wrote in message news:<877jzwg1v2.fsf at pobox.com>.. > > Eiffel: Design by contract. The book to read is Meyer's "Object- > > Oriented Software Construction". Full of interesting stuff, if you can > > stand his self-importance ;-) > > I couldn't! :-)) I admit I have nowhere near finished it either, but more due to my slowness and the book's vastness than the manner of discourse. The irritation he inspires *is* productive, as Michael Hudson says. John From Rici.Yu at noaa.gov Wed Jan 14 10:43:47 2004 From: Rici.Yu at noaa.gov (Rici.Yu) Date: Wed, 14 Jan 2004 10:43:47 -0500 Subject: Interrupt an extension module function Message-ID: <400563B3.64870BD@noaa.gov> Hi all, It seems that python does not interrupt a C-extension module function when a user types CTRL-C. I am not sure this is the expected behavior as this is first time I came across this problem. If it is, what do I have to do to let the user interrupt a long-running extension function? Thanks. -Rici From jcarlson at uci.edu Wed Jan 21 11:48:09 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Jan 2004 08:48:09 -0800 Subject: Interfacing with Voice modem References: Message-ID: <20040121084657.FB37.JCARLSON@uci.edu> > A callcenter-like app that we are writing in Python will need recording > functionality for voice conversations. I am thinking of doing this through > a voice modem. > > Any suggestions on how to interface with a voice modem from Python? 1. Get the C source for doing it. 2. Wrap it up for python calls with SWIG. 3. Cross your fingers. - Josiah From kirk at strauser.com Thu Jan 22 10:05:38 2004 From: kirk at strauser.com (Kirk Strauser) Date: Thu, 22 Jan 2004 15:05:38 GMT Subject: Secure Voting software References: <20040121174434.28446.00000428@mb-m15.aol.com> <7xvfn4lq9m.fsf@ruckus.brouhaha.com> <87zncgy544.fsf@strauser.com> Message-ID: <87y8s0yql4.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-01-22T04:36:55Z, Ben Finney writes: > Security is much more than just cryptography. I wasn't implying otherwise. However, being exposed to the level of engineering required to get that one small part of the system right is humbling. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD4DBQFAD+Xq5sRg+Y0CpvERAv3iAKCHyQEMaKj8a8CJQorrEsHj6DPZ+ACVF5uv ZTfsNz29lr8FBE1vUSyZ4A== =ePzg -----END PGP SIGNATURE----- From shaleh at speakeasy.net Mon Jan 5 20:43:23 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Mon, 5 Jan 2004 17:43:23 -0800 Subject: indendation question In-Reply-To: <3FF9E883.BC8AB864@engcorp.com> References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> Message-ID: <200401051743.23650.shaleh@speakeasy.net> On Monday 05 January 2004 14:43, Peter Hansen wrote: > > Well the "official" standard can be seen in the python files distributed > > with python -- 4 spaces. > > > > That said, Python will use any whitespace you want as long as you are > > consistent. 3 spaces, a tab, whatever. > > Well, *almost* any whitespace. :-) > > >>> import string > >>> string.whitespace > > '\t\n\x0b\x0c\r ' > > Of those, only '\t' and ' ' are going to be much help, I think, when trying > to indent. Linefeed, carriage return, vertical tab, and form feed are > most likely not well supported yet. ;-) > > -Peter (-: Point taken, I must remember to be more careful when wearing my teaching hat. Thanks. From ih8spam at spamtrap.com Wed Jan 14 10:42:41 2004 From: ih8spam at spamtrap.com (WTH) Date: Wed, 14 Jan 2004 10:42:41 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: <100aonoarjllhb2@corp.supernews.com> Sadly, Brandon doesn't 'realize' this at all, he apparently believes that if the OSS movement does not do what he hoped it would that it's basically *crap*. This is the crux of every problem Brandon has with educated adults. If something doesn't work out his way, or if people don't give him what he wants (this week's wants that is), or he doesn't finish yet another hair brained project, the problem is always somewhere other than himself. He's the unluckiest genius-design crack-developer of games ever... WTH "Bent C Dalager" wrote in message news:bu3iv2$n2u$4 at tyfon.itea.ntnu.no... > In article <4004EC9E.1E2E2893 at alcyone.com>, > Erik Max Francis wrote: > > > >If you're saying that you've come to the realization that volunteer > >programers on a project with which you only have a passing interest > >won't follow your orders and do whatever you say, I'd say pointing that > >out is less like "denigration" and more like "common goddamn sense." > > It is, never the less, worth pointing out. It would seem that Brandon > entered the scene with an idea that OSS developers might be incredibly > useful to him for some reason or other. Other game developers might > very well have the same idea. When Brandon finds out that this is not > the case and describes in some detail why OSS won't do the job for > him, than this can certainly be useful for other game developers to > learn so that don't have to spend 6 months figuring out the exact same > thing themselves. > > The conclusion may seem obvious to _you_ but this is no guarantee that > everyone else also possesses this knowledge. OSS is being hailed as > the second coming, and it comes as no surprise therefore that some > people might be deluded into thinking they could harness this power to > cure cancer overnight or land a man on Mars by 2005. > > Cheers > Bent D > -- > Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd > powered by emacs From crap at crud.com Sat Jan 10 14:30:51 2004 From: crap at crud.com (Moosebumps) Date: Sat, 10 Jan 2004 19:30:51 GMT Subject: Setting up test for XML-RPC References: Message-ID: > MB> But the second question still stands. I am running both the client > MB> and server on my own machine now (Windows 2000). Would I just need > MB> Python and web server if they were different machines? I would like > MB> to avoid installing a bunch of software on the 20 machines if > MB> possible. > > You should be able to build a server and a client with just the standard > Python distribution. Really? That would be awesome. But I don't see how that works... what do you enter for the URL? (right now it is just http://localhost, but obviously I would need to specify 20 different machines for my system. They are just bare Windows XP Pro machines with a default installation. They're "Windows Server" machines, I don't think. If performance is an issue (it will be if you are > passing large chunks of data back and forth), there are some things you can > do to speed it up: > > * Install Fredrik Lundh's sgmlop module. > > * Marshal or pickle your data first, then base64 encode them before > passing them to or fro. This greatly reduces the number of XML tags > on-the-wire, and thus the encode/decode time and data size. > Obviously, this only works if you are talking Python-to-Python. > > * Tweak things to gzip-encode the traffic between server and client. > > * Use the xmlrpclib.MultiCall class to bundle logical multiple calls > into a single physical XML-RPC call. Thanks for these suggestions. MB From nospam at nopes Sat Jan 3 11:34:36 2004 From: nospam at nopes (Steve) Date: Sun, 04 Jan 2004 03:34:36 +1100 Subject: End of file? In-Reply-To: References: <3ff665fb$1@clarion.carno.net.au> Message-ID: <3ff6eefc$1@clarion.carno.net.au> Rene Pijlman wrote: > Steve: > >>I'm having trouble finding out if output from a pipe has finished (i.e. >>I can't find tell if there's a EOF in output.readlines()). How do I do >>this? Because readlines() can return empty lines and I can't simply >>check if the line is empty. > > > You don't get an EOF from readlines(). > > "readlines([sizehint]) > > Read until EOF using readline() and return a list containing the lines > thus read." > > http://www.python.org/doc/current/lib/bltin-file-objects.html > Thanks :) From skip at pobox.com Sun Jan 25 16:34:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 25 Jan 2004 15:34:22 -0600 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <64cff82f.0401251143.328388bd@posting.google.com> References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: <16404.13918.738120.967955@montanaro.dyndns.org> malcolmny> Why you can't get something for nothing malcolmny> Jack Schofield Jan 22 2004 ... malcolmny> If you are really going to do these things, you need to hire malcolmny> several reliable programmers with kernel-level skills" Of course, this is only necessary if your company wants to go it completely alone. The fact that Linux is Open Source doesn't mean you can't delegate the function of finding "several reliable programmers with kernel-level skills" to Linux vendors like Red Hat. malcolmny> "Indeed, the whole progress of commercial computing has been malcolmny> from expensive hand-written, bug-ridden, company-specific malcolmny> programs to cheaper but more powerful off-the-shelf malcolmny> packages. From that point of view, open source is a malcolmny> throwback." I fail to see the author's logic here. In what way does he think that Open Source software can't be treated as "cheaper but more powerful off-the-shelf software"? It's just not off a vendor's proprietary shelf. Does Jack Schofield perhaps work for SCO? Skip From bignose-hates-spam at and-benfinney-does-too.id.au Wed Jan 21 23:33:43 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 15:23:43 +1050 Subject: python References: Message-ID: On Thu, 22 Jan 2004 14:17:20 +1030, Jess Martin wrote: > i need help. > im just learning to program Congratulations; hopefully you'll have a lot of fun. Python is a great language to be your first. > every time i try to do a command more than a line long it wont work As you'll read in the above URL on "How To Ask Questions The Smart Way", you'll need to tell us a litle more about what's going on for someone to be able to help you. Please read the document for more guidelines. -- \ "If you go parachuting, and your parachute doesn't open, and | `\ you friends are all watching you fall, I think a funny gag | _o__) would be to pretend you were swimming." -- Jack Handey | Ben Finney From jsbenson at bensonsystems.com Fri Jan 2 02:17:16 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 1 Jan 2004 23:17:16 -0800 Subject: undo/redo, windows clipboard Message-ID: <035f01c3d100$73f90290$6401a8c0@jsbwxp3> With respect to: Message: 13 Date: Thu, 1 Jan 2004 18:38:47 -0800 (PST) From: black Subject: undo and redo ? To: python-list at python.org Message-ID: <20040102023847.78427.qmail at web21326.mail.yahoo.com> Content-Type: text/plain; charset="us-ascii" I'm coding with Tkinter and i wonder whether we could get current OS' clipboard available, and event more, anyone can inspires me how we can achieve undo and redo function ? (end quote) I don't know about undo/redo, but I have sent stuff out of Python via the clipboard. What works for me (courtesy of Mark Hammond) is: import win32clipboard, win32con win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText('your string here') win32clipboard.CloseClipboard() I found out that if I didn't empty the clipboard before adding to it, the new data sometimes ended up in the Microsoft Office clipboard, sometimes not. Now it just shows up each and every time in the plain old Windows clipboard. From jjl at pobox.com Mon Jan 19 08:24:54 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Jan 2004 13:24:54 +0000 Subject: secure unpickle? References: Message-ID: <8765f8xe8p.fsf@pobox.com> "Yun Mao" writes: > Hi, I'm looking for a way in unpickling, or equivalent, such that can only > unpickle (or is limited to) simple data structure, such as number, string, > list, tuples. marshal The docs have similar warnings, though. What's are you trying to do? I'm amazed that WAYTTD isn't a standard USENET acronym by now... John From newsgroups at jhrothjr.com Tue Jan 20 16:36:23 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jan 2004 16:36:23 -0500 Subject: an example of a singleton design pattern in python? References: <645r00hicslg2qn55sncentdk8alnbevab@4ax.com> Message-ID: <100r7t75eqsj436@news.supernews.com> "Rene Pijlman" wrote in message news:645r00hicslg2qn55sncentdk8alnbevab at 4ax.com... > Daniel Ortmann: > >Does anyone have an example of a singleton design pattern in python? > > http://aspn.activestate.com/ASPN/search?query=singleton§ion=PYTHONCKBK&type=Subsection The "cannonical" singleton for new style classes is in: http://www.python.org/2.2.3/descrintro.html See the section on overriding the __new__() method. John Roth > > -- > Ren? Pijlman From whiteywidow at yahoo.com Tue Jan 20 21:28:35 2004 From: whiteywidow at yahoo.com (rt lange) Date: Wed, 21 Jan 2004 02:28:35 GMT Subject: Jython and SciTE Message-ID: I'm trying to get my jython scripts running and compiling on SciTE. This is what I have in my python.properties file: command.name.1.*.py=Go Jython command.1.*.py=jython $(FileNameExt) command.1.subsystem.*.py=1 command.name.2.*.py=Jython -> jar command.2.*.py=jythonc --core --jar $(FileName).jar $(FileNameExt) command.2.subsystem.*.py=1 I keep getting this output: >jython DiceRoll.py >The system cannot find the file specified. It works fine from the command line (PATH is set correctly). From thitucad6tim at jetable.org Wed Jan 28 02:30:18 2004 From: thitucad6tim at jetable.org (Nicolas Lehuen) Date: Wed, 28 Jan 2004 08:30:18 +0100 Subject: Python 2.3.3 : Win32 build vs Cygwin build performance ? References: <4016a71d$0$15004$afc38c87@news.easynet.fr> <4016d8a3$0$19263$626a54ce@news.free.fr> Message-ID: <40176510$0$19279$626a54ce@news.free.fr> One of my test machine was a 2,4 Ghz P4 (without hyperthreading), the other an Athlon XP 2500+, both with 512 Mb of RAM and running under Windows XP. In fact if I directly launch the test\pystones.py script, I dot get marginally better results using the Win32 build : E:\Documents and Settings\Nico>python E:\Python23\Lib\test\pystone.py Pystone(1.1) time for 50000 passes = 1.36434 This machine benchmarks at 36647.7 pystones/second $ python /lib/python2.3/test/pystone.py Pystone(1.1) time for 50000 passes = 1.492 This machine benchmarks at 33512.1 pystones/second So there must be something weird in the hotshot scripts... The cygwin build being slightly slower than the pure Win32 build is something that feels much more sensible. Regards, Nicolas "Paul M" a ?crit dans le message de news: bv74fr$1sdl$1 at netnews.upenn.edu... > Nicolas Lehuen wrote: > > > I have reproduced this on another machine. I tried playing with the > > optimizer options (-O, -OO) and the result is the same : on pystone, Cygwin > > 1.5.6-1 + Python 2.3.3-1 is nearly twice as better as the standard Python > > 2.3.3 distribution for Win32... > > > > I have checked that both distribution are psyco-free. Does anyone have an > > idea of what is going on there ? Better compilation optimisation settings ? > > GCC 3.3.1 producing faster code than MSVC 6 (allright, I can imagine that, > > but twice faster ???) ? > > > > Regards > > Nicolas > > > > I get results opposite yours (though with an oddity in the CPU seconds > reported on the Win32 build -- see below). > > I'm also using Cygwin 1.5.6-1 + 2.3.3-1 and the stock Python 2.3.3 > distribution for Win32. > > Here's my cygwin results: > > $ time python /usr/lib/python2.3/hotshot/stones.py > Pystone(1.1) time for 50000 passes = 2.813 > This machine benchmarks at 17774.6 pystones/second > 850004 function calls in 5.825 CPU seconds > > Ordered by: internal time, call count > > ncalls tottime percall cumtime percall filename:lineno(function) > 50000 2.148 0.000 2.207 0.000 pystone.py:184(Proc6) > 50002 1.102 0.000 1.102 0.000 pystone.py:45(__init__) > 1 0.662 0.662 5.825 5.825 pystone.py:79(Proc0) > 50000 0.435 0.000 4.188 0.000 pystone.py:133(Proc1) > 50000 0.340 0.000 0.340 0.000 pystone.py:208(Proc8) > 150000 0.182 0.000 0.182 0.000 pystone.py:203(Proc7) > 150000 0.181 0.000 0.181 0.000 pystone.py:221(Func1) > 50000 0.170 0.000 0.226 0.000 pystone.py:229(Func2) > 50000 0.163 0.000 1.265 0.000 pystone.py:53(copy) > 50000 0.152 0.000 0.214 0.000 pystone.py:160(Proc3) > 50000 0.103 0.000 0.103 0.000 pystone.py:149(Proc2) > 50000 0.072 0.000 0.072 0.000 pystone.py:177(Proc5) > 50000 0.059 0.000 0.059 0.000 pystone.py:246(Func3) > 50000 0.056 0.000 0.056 0.000 pystone.py:170(Proc4) > 1 0.000 0.000 5.825 5.825 pystone.py:67(pystones) > 0 0.000 0.000 profile:0(profiler) > > > > real 0m35.403s > user 0m34.827s > sys 0m0.233s > > > And my Win 32 results: > > C:\Documents and Settings\pmagwene>python c:\Python23\Lib\hotshot\stones.py > Pystone(1.1) time for 50000 passes = 2.44903 > This machine benchmarks at 20416.3 pystones/second > 850004 function calls in 6559.446 CPU seconds > > Ordered by: internal time, call count > > ncalls tottime percall cumtime percall filename:lineno(function) > 1 1689.491 1689.491 6559.412 6559.412 pystone.py:79(Proc0) > 50000 987.212 0.020 2610.494 0.052 pystone.py:133(Proc1) > 50000 775.010 0.016 775.010 0.016 pystone.py:208(Proc8) > 50000 416.668 0.008 637.938 0.013 pystone.py:53(copy) > 150000 409.522 0.003 409.522 0.003 pystone.py:221(Func1) > 50000 406.804 0.008 535.380 0.011 pystone.py:229(Func2) > 150000 396.484 0.003 396.484 0.003 pystone.py:203(Proc7) > 50000 310.752 0.006 445.215 0.009 pystone.py:160(Proc3) > 50000 290.596 0.006 410.274 0.008 pystone.py:184(Proc6) > 50000 239.539 0.005 239.539 0.005 pystone.py:149(Proc2) > 50002 221.310 0.004 221.310 0.004 pystone.py:45(__init__) > 50000 150.247 0.003 150.247 0.003 pystone.py:170(Proc4) > 50000 146.099 0.003 146.099 0.003 pystone.py:177(Proc5) > 50000 119.678 0.002 119.678 0.002 pystone.py:246(Func3) > 1 0.033 0.033 6559.446 6559.446 pystone.py:67(pystones) > 0 0.000 0.000 profile:0(profiler) > > > > The Pystone time and machine benchmark shows that my Win32 build is > faster, though I don't understand the CPU seconds readout -- the pystone > benchmark did not last 1.5 hrs! > > Maybe it's something odd about my setup? -- dual Xeons (hyperthreading > enabled), 2.5 GB ram, WinXP... > > --Paul From gerrit at nl.linux.org Sat Jan 3 11:50:41 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 3 Jan 2004 17:50:41 +0100 Subject: Filename type (Was: Re: finding file size) In-Reply-To: References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> Message-ID: <20040103165041.GA31412@nl.linux.org> Peter Otten wrote: > http://mail.python.org/pipermail/python-list/2002-June/108425.html > > http://members.rogers.com/mcfletch/programming/filepath.py > > has an implementation of your proposal by Mike C. Fletcher. I think both > filename class and os.path functions can peacefully coexist. Thanks for the links. (I think they don't, by the way) yours, Gerrit. -- 19. If he hold the slaves in his house, and they are caught there, he shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From nomail at nospam.net Fri Jan 9 06:57:58 2004 From: nomail at nospam.net (Olaf Meyer) Date: Fri, 09 Jan 2004 11:57:58 GMT Subject: Python 2.3.3 compilation problems an HP-UX Message-ID: I'm having some problems compiling Python 2.3.3 on HP-UX (B.11.00). I've tried sevral different options for the configure script (e.g. enabling/disabling gcc, aCC) but I always get the same problem during the final linking stage. Several PyThread_* symbols are undefined (for details see the output below). In order to get DCOracle2 support working I've also set the LDFLAGS environment variable to "-lpthread -lcl" (as mentioned in the README.HP-HX file). I would really appreciate any advice! Here's the output of the final stage of my build process: rm -f libpython2.3.a ar cr libpython2.3.a Modules/getbuildinfo.o ar cr libpython2.3.a Parser/acceler.o Parser/grammar1.o Parser/listnode.o Parser/node.o Parser/parser.o Parser/parsetok.o Parser/bitset.o Parser/metagrammar.o Parser/firstsets.o Parser/grammar.o Parser/pgen.o Parser/myreadline.o Parser/tokenizer.o ar cr libpython2.3.a Objects/abstract.o Objects/boolobject.o Objects/bufferobject.o Objects/cellobject.o Objects/classobject.o Objects/cobject.o Objects/complexobject.o Objects/descrobject.o Objects/enumobject.o Objects/fileobject.o Objects/floatobject.o Objects/frameobject.o Objects/funcobject.o Objects/intobject.o Objects/iterobject.o Objects/listobject.o Objects/longobject.o Objects/dictobject.o Objects/methodobject.o Objects/moduleobject.o Objects/object.o Objects/obmalloc.o Objects/rangeobject.o Objects/sliceobject.o Objects/stringobject.o Objects/structseq.o Objects/tupleobject.o Objects/typeobject.o Objects/weakrefobject.o Objects/unicodeobject.o Objects/unicodectype.o ar cr libpython2.3.a Python/bltinmodule.o Python/exceptions.o Python/ceval.o Python/compile.o Python/codecs.o Python/errors.o Python/frozen.o Python/frozenmain.o Python/future.o Python/getargs.o Python/getcompiler.o Python/getcopyright.o Python/getmtime.o Python/getplatform.o Python/getversion.o Python/graminit.o Python/import.o Python/importdl.o Python/marshal.o Python/modsupport.o Python/mystrtoul.o Python/mysnprintf.o Python/pyfpe.o Python/pystate.o Python/pythonrun.o Python/structmember.o Python/symtable.o Python/sysmodule.o Python/traceback.o Python/getopt.o Python/dynload_hpux.o Python/thread.o ar cr libpython2.3.a Modules/config.o Modules/getpath.o Modules/main.o Modules/gcmodule.o ar cr libpython2.3.a Modules/threadmodule.o Modules/signalmodule.o Modules/posixmodule.o Modules/errnomodule.o Modules/_sre.o Modules/_codecsmodule.o Modules/zipimport.o Modules/symtablemodule.o Modules/xxsubtype.o ranlib libpython2.3.a c++ -lpthread -lcl -Wl,-E -Wl,+s -o python \ Modules/python.o \ libpython2.3.a -lnsl -lrt -ldld -lm collect2: ld returned 1 exit status /usr/ccs/bin/ld: Unsatisfied symbols: PyThread_acquire_lock (first referenced in libpython2.3.a(main.o)) (code) PyThread_exit_thread (first referenced in libpython2.3.a(main.o)) (code) PyThread_allocate_lock (first referenced in libpython2.3.a(main.o)) (code) PyThread_free_lock (first referenced in libpython2.3.a(main.o)) (code) PyThread_start_new_thread (first referenced in libpython2.3.a(main.o)) (code) PyThread_release_lock (first referenced in libpython2.3.a(main.o)) (code) PyThread_get_thread_ident (first referenced in libpython2.3.a(main.o)) (code) PyThread__init_thread (first referenced in libpython2.3.a(main.o)) (code) *** Error exit code 1 Thanks, Olaf From missive at frontiernet.net Thu Jan 8 23:25:55 2004 From: missive at frontiernet.net (Lee Harr) Date: Fri, 09 Jan 2004 04:25:55 GMT Subject: Lua: further investigation and comparisons with Python and Forth References: Message-ID: > Before reading about Open Firmware, I had assumed that Forth had completely > dropped out of sight. Anyone else aware of counterexamples? > $ uname -a FreeBSD 4.9-STABLE FreeBSD 4.9-STABLE #1: Sat Dec 27 11:23:38 EST 2003 $ cd /usr/src $ find . -name "*forth*" ./share/examples/bootforth ./sys/boot/common/interp_forth.c ./sys/boot/forth From peter at engcorp.com Wed Jan 28 09:24:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 09:24:48 -0500 Subject: package similar to XML::Simple References: Message-ID: <4017C630.5A6DD35@engcorp.com> Paulo Pinto wrote: > > does anyone know of a Python package that > is able to load XML like the XML::Simple > Perl package does? > > For those that don't know it, this package > maps the XML file to a dictionary. A simple dictionary is insufficient to represent XML in general, so perhaps you're talking about a subset of XML, maybe with no attributes, and where the order of the child elements doesn't matter? Or something else? Or do you really mean something like a multiply-nested dictionary, perhaps with lists as well? > Of course I can build such a package myself > but it would be better if it already exists :) We were able to build something similar by stripping down Fredrik Lundh's elementtree until we had little more than the calls to the expat parser (i.e. we used his source as a tutorial on using expat :-), so if this is something like the XML-subset I mention above, you could do it in an hour or so from scratch if you knew Python well. -Peter From austin at smartobject.biz Tue Jan 6 10:42:46 2004 From: austin at smartobject.biz (Jess Austin) Date: 6 Jan 2004 07:42:46 -0800 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module References: Message-ID: Martin, you seem to be quite fond of popen2. "Martin v. Loewis" wrote in message news:... > So enhance them, instead of replacing them. and... > I find that an acceptable incompatibility, and it will likely break > no existing application. Applications usually expect that the program and... > Why is that? Just add a single function, with arguments > stdin/stdout/stderr. No need for 12 functions. Then explain the existing > functions in terms of your new function (if possible). and... > You really should work with the existing code base. Ignoring it is a > guarantee that your PEP will be rejected. (Studying it, and then > providing educated comments about it, might get you through) But you're not quite so fond of the people who are using popen2. Dumping a bunch of interface changes on them at this late date will not make users happy. They worked to get their code functioning with what you admit is not a perfect module. Now you suggest breaking all that installed code the next time a new version comes out? As someone who has used popen2 and who looks forward to using this new "process" module, I value user happiness. This seems to be one of the many situations in which happiness is highly correlated with choice. If I have some old code that works as well as I need it to work with popen2, I choose to leave it the hell alone, and I appreciate it not getting broken behind my back. If I'm writing something new, and I find the interface offered by "process" more logical, I will choose to use that. Further, I will appreciate not having to reacquaint myself with the numerological arcana of popen2, if only to know what to ignore while using the new function. If I have code I could never get to work properly with popen2 and suddenly "process" becomes available, I will be only too happy to modify it for use with the new module. If I'm an utter newbie who is thinking about processes for the first time in my life, it doesn't matter where the gurus point me so long as they point me to something that makes sense. I admit that I haven't looked at this proposed package at all yet; I've only read the PEP. It's quite possible that it doesn't fulfill all my hopes and dreams, that it won't contribute to my choice and my happiness. I note with some trepidation that plans for the Windows platform aren't fully fleshed out. But you haven't offered criticism of the implementation, your objection is that "it's not called popen2". I suspect that few people will give that objection much weight, whether they have used popen2 or not. "Martin v. Loewis" continues... > I never said it would be easy. However, introducing a new popen module > is a major change, and there must be strong indications that the current > API cannot be enhanced before throwing it away. > > There should be one-- and preferably only one --obvious way to do it. > > As for breaking compatibility: This is what the PEP should study in > detail. It is sometimes acceptable to break compatibility, if I think that the PEP contains the "strong indications" you require. While it's nice to have "one way" that we can tell newbies, it isn't mandatory that there be only one way we've ever done it. That would inhibit progress. I support functioning code, and progress in the directions that users choose. +1. later, Jess From peter at engcorp.com Wed Jan 14 11:16:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Jan 2004 11:16:48 -0500 Subject: I come not to bury C++, but to praise it... References: <40055560.7A0DCD0D@engcorp.com> <100aoq8efq3nt1e@corp.supernews.com> Message-ID: <40056B70.3E04217B@engcorp.com> Cameron Laird wrote: > > I was still fussing with cfront in the early '90s. > Its era *had* passed by then, though. And I actually went looking for it again as recently as two years ago, considering the possibility of using it to allow the use of C++ code for a small embedded processor which did not have an available C++ compiler. I actually don't remember precisely why we didn't try it out, and I assume we simply got distracted by having to make things work and forgot to continue the search. Can it be used as a front-end for such chips, where at best there are two or three C compilers on the market? -Peter From mmoum at woh.rr.com Fri Jan 2 19:21:55 2004 From: mmoum at woh.rr.com (DoubleM) Date: Sat, 03 Jan 2004 00:21:55 GMT Subject: Python 2.3.3 compilation problem References: Message-ID: Zdenda wrote: > Hi, i have RH9 and i need python 2.3. I executed tgz file and typed > ./configue. Then i type make. It is without problem. When I type make > install ... ... > ... > Compiling /usr/local/lib/python2.3/xml/sax/handler.py ... > Compiling /usr/local/lib/python2.3/xml/sax/saxutils.py ... > Compiling /usr/local/lib/python2.3/xml/sax/xmlreader.py ... > Compiling /usr/local/lib/python2.3/xmllib.py ... > Compiling /usr/local/lib/python2.3/xmlrpclib.py ... > Compiling /usr/local/lib/python2.3/zipfile.py ... > make: *** [libinstall] Error 1 > > Have somebody any idea where is error? > Thanks I had the same problem on Mandrake. There seem to be some minor syntax incompatibilities in zipfile.py, and others. Try make -i install, and all should be fine. Mike From vidiv at gmx.net Sun Jan 25 00:10:54 2004 From: vidiv at gmx.net (vidiv at gmx.net) Date: Sun, 25 Jan 2004 06:10:54 +0100 (MET) Subject: Terminal Emulation with IBM ES9672 mainframe via multiplexer. References: Message-ID: <32215.1075007454@www3.gmx.net> > >I am a student-newbie to Python-List (for that matter Python language) > >working on a project for Terminal Emulation. The dumb terminal interacts > >with an > >IBM ES9672 mainframe through a 'multiplexer-MUX'. > >The s/w is currently running in 'C' on a Windows NT environment and the > >requirement is to introduce Object Oriented concepts and C++ was the > obvious > >choice, but i came across 'Python' (and also Perl, Ruby, ..etc) after i > >installed RH8 on my PC last month. We are actively canvassing the > advantages > >of GNU > >s/w and philosophy and would like to simultaneously port it to GNU/Linux > >platform. > > > >I have read some of the documentation in Python. > >Before using Python as our project language it would be useful to know > >whether Python has functions, libraries/headers (like C does) capable of > >handling > >the foll. : > > > >1] open and close serial ports, > >2] set baud rates, > >3] check parity bit/byte, > >4] stop bits, > >5] Hardware handshaking, > >6] selection of port,...... > > > >Our existing 'C' code is to be ported to the GNU/Linux platform so we are > >actively looking at an OOP concept. The part for serial port > communication > >in > >C++ has classes so its easier to write customized programs to do most of > the > >above. > > > >Most importantly compatibility issues with the existing Multiplexer and > >Cisco Routers have to be kept in mind as the company will *not* make any > H/W > >changes. > > > >We saw that python has some routines for using existing C code, so we > dont > >have to rewrite everything and can make modules containing functions and > use > >it to operate on files. > >Does it provide any other serial port communication features ? > >It would be nice if anyone could throw some light on some of the above > >issues. > . > . > . > Yes, Python can do all this. > > Although perhaps not as well as other approaches. I don't understand > your description. You have something that "works", now, and you want > ... well, I'm not sure what you want. Is the software you're looking > to change the terminal emulator, or the MUX? I think it's the former. +++++++ yes, the goal is to rewrite the existing customised Terminal Emulator using C++, as OOP is very efficient. Is it better to script an existing application with Python/Ruby that rewriting 3000+ lines of C code into C++ ?? ++++++++ > What's the relation of the new software and the software it's > replacing? Are they supposed to have the same design? Would it be > easier for you to do object-oriented analysis and design, then imple- > ment in C (while C isn't a particularly inviting language for OO, it > *is* possible to use it)? Is the terminal emulator connecting to a > mainframe, or routers, or both? Is it enough for you just to exhibit > one of the many free-software terminal emulators available? When *I* > work in this area, I certainly start with as much re-use as possible. > Is the point of this to construct working software, or learn OO, or > port to Linux, or ...? Or all of the above? ++++++ Almost.... but here is more...... Currently the 'C'-program executable's are given to the clients and it connects geographically scattered Terminals/PCs and/or Printers and behaves like a dumb terminal emulator (when client uses a dialup to access our Mux) and the I/O data is captured, sent to (& received from) a Multiplexer (Mux)----------> on to the CUTS (Connect Unisys Terminal Emulator using U100 protocol) and ---------> on to the SNA for IBM Mainframe in another city. Our existing program is limited to sending, receiving data till the Mux. It has 3000+ lines of C-code in a 'single' file and needs to be modularized. The exchange of data between a central site host and down lines must be seamless despite different technologies, platforms, environments and so the language used to program it must have adequate runtime libraries and routines for a smooth transition. Even though Python has many modules for various functions, i need more info about the foll.:: 1] If our platform is Gnu/Linux and client uses Windows 98/95 then how can the application be ported so as to be accessible by him without any compatibility issues. 2] Does python have windows enabled runtime libraries and routines to glue some program components. 3] Currently client uses DOS terminal mode so will they need a Windows terminal version of Python interpreter to be installed to run the application or can it be integrated using some tools (which ones?)? It would help to get more information or a pointer to the right direction and hence i posted a message. Regarding using existing free-software terminal emulators available there are a lot of things to be considered. Thanks for your time. -Vidya. -- vidiv AT gmx DOT net +++ GMX - die erste Adresse f?r Mail, Message, More +++ Bis 31.1.: TopMail + Digicam f?r nur 29 EUR http://www.gmx.net/topmail From josecarlos at siadv.com Sun Jan 25 08:31:08 2004 From: josecarlos at siadv.com (José Carlos) Date: Sun, 25 Jan 2004 14:31:08 +0100 Subject: compress string of data Message-ID: Hi. How i could compress string of data?. I heart that it?s possible to make with librep, but i?dont know the way to do it. if somebody know any way to do it or any web where explain it i would thank the help. Regards. Jos? Carlos ADV www.siadv.com From roy at panix.com Mon Jan 12 20:02:25 2004 From: roy at panix.com (Roy Smith) Date: Mon, 12 Jan 2004 20:02:25 -0500 Subject: Python is far from a top performer according to benchmarktest... References: Message-ID: Robin Becker wrote: > -Common blocks are an invention of the Devil-ly yrs- There's no evil you can commit in FORTRAN with common blocks that you can't do just as well in C with globals and pointers. From dwelch at localhost.localdomain Thu Jan 8 18:01:13 2004 From: dwelch at localhost.localdomain (d) Date: Thu, 08 Jan 2004 23:01:13 GMT Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> Message-ID: Rene Pijlman wrote: > broebel: >>first problem is the fact that I started out with a little program who was >>part of a course but the problem is when I launch the program. I don't >>have the time to see the result because the screen closes immediately. >>Can anyone explain what's happening. > > The program started, did what it had to do and then terminated :-) > > "1 How do I run a Python program under Windows?" > http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-under-windows > Worked fine for me on Linux... made two suggested changes: 1) use raw_input(), not input(), 2) check user input for errors. Sorry, I don't know how to say "Enter a number between 0 and 500" in whatever language this is in (German?) #!/usr/bin/env python while 1: bedrag = raw_input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) try: bedrag = int( bedrag ) except ValueError: print "Enter a number between 0 and 500" else: if bedrag < 0 or bedrag > 500: print "Enter a number between 0 and 500" else: break for munt in 200, 100, 50, 20, 10, 5, 2, 1 : aantal = 0 while bedrag >= munt : aantal = aantal + 1 bedrag = bedrag - munt if aantal > 0 : print aantal, 'x', munt -- /d/ From mark at mceahern.com Wed Jan 14 23:01:46 2004 From: mark at mceahern.com (Mark McEahern) Date: Wed, 14 Jan 2004 22:01:46 -0600 Subject: Deleting objects In-Reply-To: References: Message-ID: <1074139306.26201.19.camel@dev.internal> On Wed, 2004-01-14 at 17:23, user at domain.invalid wrote: > Say I have an object (foo), that contains an > array (bar) of references to other objects. > > Now I want to puff some of the objects from the > array so that I remove the array element, and > destroy the oject. > but when I do: > > del foo.bar[0] > > Python says: > object doesn't support item deletion It'd be helpful if you supplied the code in question. Then again, we wouldn't be able to let our imagination wander with what puff might mean. Anyway, is this the sort of thing you're talking about? #!/usr/bin/env python class Foo: def __init__(self): self.bar = [] def __str__(self): return '%s' % (str(self.bar),) l = range(10) foo = Foo() foo.bar.append(l) del foo.bar[0] print 'foo = %s' % (str(foo),) print 'l = %s' % (l,) Cheers, // m From roman.yakovenko at actimize.com Mon Jan 12 03:06:38 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Mon, 12 Jan 2004 10:06:38 +0200 Subject: __slots__, setattr, __metaclass__ Message-ID: <2CD84621099A814598AE3EFEFB5C1421046D2D@exchange.adrembi.com> Hi. I have small problem and I don't know solution. The problem: every class imported from some module X should not allow to be modified ( modified == adding or deleting new class attributes ). Small explanation about what I am doing: I has complex dll written in Managed C++ for C#. I am using "Python for .NET" and python unittest module to test my dll. I find myself often make a mistake in attributes names. I'd like to protect my self from those errors. In subject I listed available options, but I don't know which one to pick and how to use it in my situation. As you can guess I can't to modify Managed C++ sources. Thanks. Roman. From bdelmee at advalvas.REMOVEME.be Thu Jan 8 17:41:15 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Thu, 08 Jan 2004 23:41:15 +0100 Subject: Looking for help with regular expressions- not Python Specific In-Reply-To: References: <8d3e714e.0401072114.5bf3fba7@posting.google.com> Message-ID: <3ffddc8b$0$1110$6c56d894@feed0.news.be.easynet.net> You might find the redemo.py script real handy when investigating regexes. It should live in the Tools subdirectory of your python install (and requires tkinter). From bug-gswin-bounces at ghostscript.com Thu Jan 29 16:31:57 2004 From: bug-gswin-bounces at ghostscript.com (bug-gswin-bounces at ghostscript.com) Date: Thu, 29 Jan 2004 13:31:57 -0800 Subject: Your message to bug-gswin awaits moderator approval Message-ID: Your mail to 'bug-gswin' with the subject Rcypwodky Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list 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://www.ghostscript.com/mailman/confirm/bug-gswin/5f6df4615a4eb2c1cee1818df208649184a3bbee From eppstein at ics.uci.edu Thu Jan 22 15:09:16 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 22 Jan 2004 12:09:16 -0800 Subject: What is object() References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > > i was reading library refrence manual. there i found > >object() function. they says in library refrence that > > "Return a new featureless object. object() is > >a base for all new style classes. It has the methods > >that are common to all instances of new style > >classes." > > There's not much use for an instance of object. Don't worry about it. It can be useful when you want something that is guaranteed to be different from all other objects and has no other purpose than existing and being different. Beyond that somewhat specialized use, object exists to be subclassed, not instantiated directly. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From sross at connectmail.carleton.ca Fri Jan 30 12:00:52 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 30 Jan 2004 12:00:52 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: Hi. I took a look at Io because of your post, and I have a question: Are there prototype(?) _and_ instance methods/slots? In other words, is there a shared state mechanism between instances of a prototype? If so, could you show an example. Thanks, Sean From michael at foord.net Thu Jan 29 03:18:44 2004 From: michael at foord.net (Fuzzyman) Date: 29 Jan 2004 00:18:44 -0800 Subject: Webhosting with Python References: <8089854e.0401280834.6fd4f972@posting.google.com> Message-ID: <8089854e.0401290018.4b07ffbf@posting.google.com> "val" wrote in message news:... > Sorry, > i didn't find any mention of Python. > Can you please point me in right direction? > val > val at vtek dot com > It's definitely got python on - I was pointed to this host from another list that had python on the list.... I can't see it advertised by Xennos - but I have scripts up and running - e.g. http://www.voidspace.xennos.com/cgi-bin/cginews.py One of the error messages I got told me it was Python 2.2........ Fuzzy > "Kevin Ballard" wrote in message > news:bv8pch$2lhu$1 at bigboote.WPI.EDU... > > On 2004-01-28 11:34:43 -0500, michael at foord.net (Fuzzyman) said: > > > > > I've recently starting using a very cheap web hoster who has python > > > 2.2 installed.... almost free hosting (but not quite)..... > > > > > > Thought some of you guys might be interested.......... > > > > > > http://www.xennos.com > > > > > > Fuzzyman > > > > How do you plan to make money off of this? From paul at fxtech.com Tue Jan 27 11:56:47 2004 From: paul at fxtech.com (paul at fxtech.com) Date: Tue, 27 Jan 2004 11:56:47 -0500 (EST) Subject: os.path.split: processing paths from one OS on another In-Reply-To: References: <401691D7.8050607@holmes.nl> Message-ID: <8161.195.173.15.12.1075222607.squirrel@webmail.pair.com> > Windows itself is happy using forward slashes as a directory separator, > so your client can use them throughout. It's only the Windows shell > that requires backslash rather than forward slash. Which is a wonderful reason to use cygwin! From candiazoo at comcast.net Fri Jan 2 14:24:20 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 19:24:20 GMT Subject: Problem building on BeOS... References: Message-ID: Belay that. In message , Zoo Keeper wrote: > O.K! After some tips from you folks, I found that the problem ONLY occurs > with > line continuation in "extern" statements. Works fine for DEFINEs... > > Mike > > In message , Zoo Keeper wrote: > > For some reason, the Python preprocessing balks on the "\" line > continuation > > character. Any ideas/thoughts? Is it just that my version of gcc is not > > supported? > > > > I don't "need" numeric in my current project, but it is a nice package to > > have! > > Apps that do not need to be compiled install and run fine. Actually, > > SQLite > > built and installed fine... > > > > Thanks, in advance. > > > > Mike > > > > Python 2.2.2 (#13, Dec 6 2002, 00:42:47) > > [GCC 2.9-beos-991026] on beos5 > > > > $ python setup.py build > > running build > > running build_py > > not copying Lib/ArrayPrinter.py (output up-to-date) > > not copying Lib/LinearAlgebra.py (output up-to-date) > > not copying Lib/MLab.py (output up-to-date) > > not copying Lib/Matrix.py (output up-to-date) > > not copying Lib/Numeric.py (output up-to-date) > > not copying Lib/Precision.py (output up-to-date) > > not copying Lib/RandomArray.py (output up-to-date) > > not copying Lib/UserArray.py (output up-to-date) > > not copying Lib/numeric_version.py (output up-to-date) > > not copying Packages/FFT/Lib/FFT.py (output up-to-date) > > not copying Packages/FFT/Lib/__init__.py (output up-to-date) > > not copying Packages/MA/Lib/MA.py (output up-to-date) > > not copying Packages/MA/Lib/MA_version.py (output up-to-date) > > not copying Packages/MA/Lib/__init__.py (output up-to-date) > > not copying Packages/RNG/Lib/Statistics.py (output up-to-date) > > not copying Packages/RNG/Lib/__init__.py (output up-to-date) > > running build_ext > > building '_numpy' extension > > gcc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include > > -I/boot/home/config/include/python2.2 -c Src/_numpymodule.c -o > > build/temp.beos-5.0.4-BePC-2.2/_numpymodule.o > > In file included from > > /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:4: > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:234: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:239: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:241: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:244: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:247: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:251: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:253: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:255: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:257: stray > > '\' > > in program > > In file included from > > /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:6: > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:101: stray > > '\' > > in program > > /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:103: stray > > '\' > > in program > > error: command 'gcc' failed with exit status 1 > > $ > > > > From ptmcg at users.sourceforge.net Thu Jan 8 22:43:29 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Fri, 09 Jan 2004 03:43:29 GMT Subject: ANN: pyparsing 1.0.4 released Message-ID: pyparsing version 1.0.4 is available at http://sourceforge.net/projects/pyparsing/. Version 1.0.4 contains: - more performance improvements (another 30-40% reduction) - positional token expressions (StringStart, StringEnd, LineStart, LineEnd) - commaDelimitedList convenience built-in - more example scripts (HTTP server log parser, comma separated list parser) - fixed typo in setup.py - minor API change: delimitedList no longer groups the results, this is now the responsibility of the caller (using Group(delimitedList(expr))) From exarkun at intarweb.us Mon Jan 19 08:40:51 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 19 Jan 2004 08:40:51 -0500 Subject: overwrite private method... (of wxColumnSorterMixin class) In-Reply-To: References: Message-ID: <20040119134051.GA2764@intarweb.us> On Mon, Jan 19, 2004 at 05:00:03AM -0800, Zachary wrote: > > "Florian Preknya" wrote in message > news:bugj2p$vqj$1 at nebula.dnttm.ro... > > Is there a posibility to overwrite a private method (one that starts with > > __ ) ? I read that they are just formely private, they are prefixed with > the > > class name to have an obtured visibility, so maybe it's a trick here... > > > > More details... > > I use wxPython, more specifically the wxColumnSorterMixin class. I want to > > overwrite the __OnColClick event handler to behave on my way: I want the > > sorting feature will affect only some columns, not all columns and that > > event handler is the key. The problem is that the event chain is skiped in > > the __OnColClick method, so I cannot receive the event anymore. So, my > idea > > was to overwrite the __OnColClick method in the mixin subclass. Is this > > possible? Or, are they other solutions for this ? > > > > Thanks, > > Florian. > > > > > What you read is true, so far as I know. It is possible to override them, > as Python doesn't have a notion of encapsulation, again, as far as I know. > You can probably get away with this. > Encapsulation is not the same thing as data hiding or private attributes/methods. Python does not have private attributes or methods, so this is possible. Python *does* support the concept of encapsulation, but that is mostly unrelated to the question at hand. class CustomColumnSorter(wxColumnSorterMixin): def _wxColumnSorterMixin__OnColClick(...): ... Assuming wxColumnSorterMixin is subclassable, this will work. It may not be, though. There is also probably a better way to achieve the results you're looking for. Perhaps by specifying a callback in some other way, such as binding a handler to an event. Jp From jarrodhroberson at yahoo.com Mon Jan 12 00:08:55 2004 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 11 Jan 2004 21:08:55 -0800 Subject: Python installation breaks Outlook Express References: Message-ID: M. Laymon wrote in message news:... > I just installed Python 2.3.3 under Windows XP professional. After I > did, my wife tried to access her email using Outlook Express and got > the error messages: > > Your server has unexpectedly terminated the connection. Possible > causes for > this include server problems, network problems, or a long period of > inactivity. > Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net', > Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F > > Your server has unexpectedly terminated the connection. Possible > causes for this > include server problems, network problems, or a long period of > inactivity. > Account: 'incoming.verizon.net', Server: 'incoming.verizon.net', > Protocol: POP3, > Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F > > (No comments about Outlook, please.I have tried to get her to use a > different email program, but she likes Outlook.) I checked the > settings, then recreated her account in Outlook, but nothing worked. > My Mozilla Thunderbird email client worked fine. > > Since the only thing I had done recently was to install Python. I > used system restore to go back to the point before installing Python. > After I did, Outlook started working again. Has anyone else seen this > behavior ? > > Thanks. > > M. Laymon This has nothing to do with Python and posting the same question over and over will not get a different answer. From dman at dman13.dyndns.org Tue Jan 6 18:50:02 2004 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Tue, 06 Jan 2004 23:50:02 GMT Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> Message-ID: <92urc1-92u.ln1@dman13.dyndns.org> On 06 Jan 2004 23:52:30 +0200, Ville Vainio wrote: > Paul Rubin writes: >> There's been proposals around to add an assignment-expression operator >> like in C, so you could say something like > It's funny, but I find the first version much more readable than the > second one. Especially if I consciously forget the "do lots of stuff > in condition part of while" indoctrination from C. >> but that's the subject of holy war around here too many times ;-). Don't >> hold your breath waiting for it. > > Probably true. Instead of ":=", I wouldn't mind getting rid of > expressions/statements difference as a whole. Uh-oh. Don't go there. If there was no difference, then you would be able to perform assignment, even define a class, in the condition of a while. I don't think you want that based on what you said above. (I certainly don't want to have to read code with such complexity!) -D -- For society, it's probably a good thing that engineers value function over appearance. For example, you wouldn't want engineers to build nuclear power plants that only _look_ like they would keep all the radiation inside. (Scott Adams - The Dilbert principle) www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From HAALrvanderhWEG at xs4all.nl Thu Jan 22 09:39:47 2004 From: HAALrvanderhWEG at xs4all.nl (Rik van der Helm) Date: Thu, 22 Jan 2004 15:39:47 +0100 Subject: newbie,cgi,os.system,cdrecord Message-ID: <400fe08c$0$326$e4fe514c@news.xs4all.nl> Hello, I am trying to make a backupscript in python, which I want to manage via a webform (cgi). In my script I use os.system to execute the following shellscript: "cdrecord -s -dev=0,1,0 -blank=fast -speed=2 fs=8m file.tgz" When I execute the pythonscript in the shell, it gets executed well and I get some output from cdrecord. Which I don't understand because I put cdrecord at silent (-s !) I thought. When I execute the pythonscript in a webbrowser via cgi, cdrecord also gets executed well but I get an 'Internal Server Error' of Python and in '/var/log/httpd/error_log' it says: "malformed header from script. Bad header=Cdrecord 1.11a19 etc....." I think I understand what is going wrong. Apache tries to print the output of cdrecord and finds something wrong and stops executing the script. Is this correct ? If this is correct how do I get cdrecord stop making output texts ? All suggestions are welcome Thanks, Rik From qual at tiscali.de Fri Jan 2 12:31:28 2004 From: qual at tiscali.de (Uwe Hoffmann) Date: Fri, 02 Jan 2004 18:31:28 +0100 Subject: Problem building on BeOS... In-Reply-To: References: Message-ID: Zoo Keeper wrote: > For some reason, the Python preprocessing balks on the "\" line continuation > character. Any ideas/thoughts? Is it just that my version of gcc is not > supported? > In file included from /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:4: > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:234: stray '\' > in program no knowledge of beos, but maybe your files have the "wrong" line ending (e.g. \r\n instead of \n or something like that) From cookedm+news at physics.mcmaster.ca Mon Jan 12 10:27:38 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 12 Jan 2004 10:27:38 -0500 Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> Message-ID: At some point, Erik Max Francis wrote: > Olaf Meyer wrote: > >> Especially if you have a lot of variable input it makes it hard to >> match >> the variables to the proper fields. From other scripting languanges >> I'm >> used to something like: >> >> $cmd = "$executable -start $startTime -end $endTime -dir $directory" >> >> This makes it very easy to see how the string is actually built. You >> dont't have to worry where which variables go. >> >> Is there a similar way to do this in python? > > Sure: > > cmd = "%(executable)s -start %(startTime)s -end %(endTime)s -dir > %(directory)s" % locals() > > There are also more expansive solutions such as YAPTU or EmPy. > > Note, however, that what you are trying to do (presuming you're passing > this to os.system or something similar) is potentially a serious > security risk. If the values of the strings you are constructing the > command line are not fully trustworthy, they can be easily manipulated > to make your program execute arbitrary shell commands. In which case he's probably better off with his original format (almost): cmd = '"$executable" -start "$startTime" -end "$endTime" -dir "$directory"' os.environ['executable'] = 'blah' os.environ['startTime'] = '12' os.environ['endTime'] = '18' os.environ['directory'] = './' os.system(cmd) This way, the shell handles all the quoting. You can do del os.environ['executable'] afterwards to clean up. I got this technique from http://freshmeat.net/articles/view/337/ For the quoting, compare: >>> os.environ['string'] = "`uname` $TERM" >>> os.system('echo "$string"') `uname` $PATH (this is what we want: don't run arbitrary commands or expand environment variables given in a user string) with >>> string = "`uname` $TERM" >>> os.system('echo "%s"' % string) Linux xterm (whoops, security leak) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From jjl at pobox.com Sat Jan 24 10:25:24 2004 From: jjl at pobox.com (John J. Lee) Date: 24 Jan 2004 15:25:24 +0000 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: <871xpp1i8r.fsf@pobox.com> Ganesan R writes: > > Is that all that people mean, though, when they talk about Perl's > > superiority for text mangling? Is there more to it? -- [...] > The perl "built-in" idioms for text processing is not only a syntactic > convenience, there are real performance advantages. For example a simple > perl loop like > > while (<>) { } > > is nearly 6 times slower in python (8 time slower with Python 2.2) using [...] Did you try 'for line in file:'? ISTR Tim Peters optimized that (or was that fileinput?), precisely because of every hacker and their dog running this as a benchmark. John From jcarlson at nospam.uci.edu Fri Jan 23 14:48:52 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 23 Jan 2004 11:48:52 -0800 Subject: I support PEP 326 In-Reply-To: References: <401081A1.E4C34F00@alcyone.com> Message-ID: Mel Wilson wrote: > In article , > Josiah Carlson wrote: > >>>Or, expressing the idea that they're the ends of a number line: >>> >>>PosInf, NegInf >>>PosInfinity, NegInfinity >>>PositiveInfinity, NegativeInfinity > > > Highest and Lowest? > > Regards. Mel. That was a suggestion, as was High and Low. I removed potential locations because it detracts from the main focus of the PEP, the existance of the objects. - Josiah From tjreedy at udel.edu Mon Jan 26 16:55:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Jan 2004 16:55:06 -0500 Subject: raw_input - why doesn't prompt go to stderr References: Message-ID: "Helmut Jarausch" wrote in message news:bv2smu$leh$1 at nets3.rz.RWTH-Aachen.DE... > when using an interactive Python script, I'd like the prompt given by > raw_input to go to stderr since stdout is redirected to a file. This is not the usual behavior, so I presume that you or the code author (if not the same) have done some non-standard redirection. > How can I change this If you wrote or have access to the code, write your own (two-line?) version of raw_input(prompt) using stderror.write(prompt) and return stdin.read(). Or leave stdout alone and use print >> ofile or ofile.write() for the other stuff. Ofile can easily be selectable as either stdout or something else. If you don't have the source, make suggestions to the owner/author. > (and suggest making this the default behaviour) You just did, but part of the definition of 'interactive' is stdout to the screen or other humanly immediately readable output device ;-) Terry J. Reedy From godoy at ieee.org Thu Jan 1 08:41:10 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 01 Jan 2004 11:41:10 -0200 Subject: Graph in wxPython References: Message-ID: On Thursday 01 January 2004 01:31 Oh Kyu Yoon wrote in : > Does anyone know how to implement plots from scipy, chaco, etc > into wxPython widget? Hi. I'm doing some research on the same subject and I found out that Matplotlib seems to be very interesting. Go to http://matplotlib.sourceforge.net/ and take a look by yourself. Be seeing you, -- Godoy. From tzot at sil-tec.gr Thu Jan 8 12:12:51 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 08 Jan 2004 19:12:51 +0200 Subject: Code Objects / Variable Names References: Message-ID: On 7 Jan 2004 00:51:45 -0800, rumours say that drfransch at netscape.net (F. Schaefer) might have written: >For the following (compiled) condition > > (door == "ajar" and alternator == "off") || time > 25 > > I need to extract, that the variables 'door', 'alternator' and 'time' > are involved. I believe that the solution that Francis and Andrew proposed is the most suitable for your case. There is another one, however, that *might* be useful sometime: use the eval(your_code, globals, locals) form, and catch the NameError exceptions. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From grey at despair.dmiyu.org Tue Jan 20 21:02:01 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 21 Jan 2004 02:02:01 -0000 Subject: regular expression question References: Message-ID: On 2004-01-21, Ben Finney wrote: > On Wed, 21 Jan 2004 00:38:12 -0000, Steve Lamb wrote: >> import re line = 'match this' foo = re.search(r'.*(this)', line) >> foo.groups()[0] > >>> import re line = 'match this' foo = re.search( r'.*(this)', line ) > >>> foo.groups() > ('this',) > >>> foo.group(0) > 'match this' > >>> foo.group(1) > 'this' > Read more on the methods available from a MatchObject: Fsck. Of course the groups are numbered from 1 but if one goes by the tuple returned they are numbered from 0. That was my mistake. Thanks for pointing it out to me. :P -- 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 james at logicalprogression.net Wed Jan 21 11:27:55 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 16:27:55 +0000 Subject: problems iterating over a files lines In-Reply-To: <2835a96b.0401210800.4b89d878@posting.google.com> References: <2835a96b.0401210800.4b89d878@posting.google.com> Message-ID: <200401211627.55109.james@logicalprogression.net> On Wednesday 21 January 2004 4:00 pm, Jesse Noller wrote: > I am a relative newbie to python and I am having issues trying to > iterate over the lines of a file. > > I have a text file - foo.bar inside of this file are lines of text: > > x-3411342 > y-1324123 > w-2314121 > > Each with a trailing \n to designate the end of the line. > > I am trying to read this file into python - which is simply in and of > itself, however: > > file = open("foo.bar", "rb") > while 1: > lines = file.open().split('\n'): > if not lines: > break > for lines in lines: > key = line > get.key(key) > results = [key, get.up, get.down] > file.close() > > Appends an extra "blank" line to the list of lines, which causes the > program to crash - secondly, I've looked at about 20 examples, and all > of them (including this one) suffer from the problem of looping over > the lines for the number of lines. > > What I want to do is open the contents of the file - read the line and > set a variable - key, and for each line in the file, I want to do > something with that key - but only once. So I want to read in a line, > set to a variable, do something, print, and then do it for the next > line. First I take it: > lines = file.open().split('\n'): should have been: > lines = file.read().split('\n'): If you used file.read().splitlines() instead you would avoid the extra blank line. A much better way to iterate line-by-line through the list is simply: for line in file("foo.bar", "rb"): # do something to line (I'm using the built-in file() function - strictly type - which is the new name for open().) I don't know where your "get" comes from so I can't help you with the rest. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From whiteywidow at yahoo.com Wed Jan 21 14:54:07 2004 From: whiteywidow at yahoo.com (rt lange) Date: 21 Jan 2004 11:54:07 -0800 Subject: Jython and SciTE Message-ID: I'm trying to get SciTE to run and compile my jython scripts. This is what I have in my python.properties file: command.name.1.*.py=Go Jython command.1.*.py=jython $(FileNameExt) command.1.subsystem.*.py=1 command.name.2.*.py=Jython -> jar command.2.*.py=jythonc --core --jar $(FileName).jar $(FileNameExt) command.2.subsystem.*.py=1 I keep getting as output: >jython DiceRoll.py >The system cannot find the file specified. >jythonc --core --jar DiceRoll.jar DiceRoll.py >The system cannot find the file specified. It works fine from the command line (PATH is set correctly.) From http Sun Jan 18 18:08:03 2004 From: http (Paul Rubin) Date: 18 Jan 2004 15:08:03 -0800 Subject: re question - finiding matching () References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: <7xr7xwyhws.fsf@ruckus.brouhaha.com> miki.tebeka at zoran.com (Miki Tebeka) writes: > I'd like to find all of the sub strings in the form "add(.*)" > The catch is that I might have () in the string (e.g. "add((2 * 2), 100)"), You can't do that with classic regexps. You need a parser, not a scanner. From http Thu Jan 8 23:15:40 2004 From: http (Paul Rubin) Date: 08 Jan 2004 20:15:40 -0800 Subject: Lua: further investigation and comparisons with Python and Forth References: Message-ID: <7xr7y9g3kj.fsf@ruckus.brouhaha.com> "John Benson" writes: > Before reading about Open Firmware, I had assumed that Forth had completely > dropped out of sight. Anyone else aware of counterexamples? There's still a very active comp.lang.forth newsgroup filled with dedicated Forth users. From reply.in.the.newsgroup at my.address.is.invalid Fri Jan 9 19:12:53 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 10 Jan 2004 01:12:53 +0100 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> <026e01c3d702$970ec5a0$6401fea9@YODA> Message-ID: Mike C. Fletcher: >I am often found optimising. By an unoptimized or by an optimizing coworker? :-) -- Ren? Pijlman From jepler at unpythonic.net Mon Jan 26 16:04:10 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 26 Jan 2004 15:04:10 -0600 Subject: Deleting objects In-Reply-To: References: Message-ID: <20040126210410.GA22799@unpythonic.net> On Mon, Jan 26, 2004 at 08:04:16PM +0000, user at domain.invalid wrote: [Can I execute] > for t in db.tables: > del t > > and expect that I have cleaned up all of my > memory? The above code clearly doesn't "free" anything, because there are still references to each of the values 't' has at deletion---namely, the entry in db.tables! Jeff From km at mrna.tn.nic.in Sat Jan 17 13:15:10 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 17 Jan 2004 23:45:10 +0530 Subject: yield In-Reply-To: <20040117165920.GA31881@nl.linux.org> References: <20040117170808.GA21486@mrna.tn.nic.in> <20040117165920.GA31881@nl.linux.org> Message-ID: <20040117181510.GA21559@mrna.tn.nic.in> Hi gerrit, i ran the snippet but i am sorry, i couldnt get what u were saying. kindly enlighten, regards, KM --------------------------------------------------------------------- On Sat, Jan 17, 2004 at 05:59:21PM +0100, Gerrit Holl wrote: > > i didnt understand the purpose of 'yield' keyword and the concept of 'generators' in python. can someone explain me with a small example how generators differ from normal function calls? > > kindly enlighten > > You can see 'yield' as a continuable function: > > def f(): > yield time.time() > yield time.time() > yield time.time() > > now f() will return a generator, with a .next() method. Try: > g = f() > g.next() > g.next() > g.next() > > on the interactive prompt, and see what happens... > > yours, > Gerrit. > > -- > Mozilla _is_ the web: it grows faster than you can download it. > 1011001 1101111 1110101 1110010 1110011 0101100 > 1000111 1100101 1110010 1110010 1101001 1110100 -- From ramen at lackingtalent.com Sat Jan 10 13:34:01 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 10 Jan 2004 18:34:01 -0000 Subject: need help translating a PHP for statement to python References: Message-ID: In article , Eli Pollak wrote: > Haha ... you must be originally a perl coder. Who else writes attricious > code like this > if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) I know, I know! C programmers! Right? -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Jan 11 18:02:16 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 12 Jan 2004 00:02:16 +0100 Subject: ANN: Snakelets 1.21 (simple-to-use web app server with dynamic pages) Message-ID: <4001d5f9$0$328$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.21 is available, which contains some important fixes since the last version. --- WHAT IS IT --- Snakelets is a Python web application server, mainly for educational purposes (but it works fine, mind you). This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). It is possible to run Snakelets off a CD (read-only mode). Snakelet's focus is on understanding the way dynamic web sites are created (the code is very compact and easy to understand), and make this process as easy as possible, while still providing a rich and powerful server environment. It's released under the open-source MIT Software license. --- DOWNLOAD --- You can download from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). To start, you can edit the vhost config file (see docs, not required) and then run the serv.py script, or the monitor.py script if you want to start it as a daemon (on Unix). --- FIXES --- Important changes since 1.20: * virtual host config has been disabled by default, Snakelets will use the old webapp loading method without vhosts. * fixed some issues related to virtual hosts: external port (when running behind a forwarding proxy), url retrieval methods, better config check, manage menu. * fixed bug in '/'-related forwarding on Windows * fixed some socket connection problems * it's possible again to reload a web application * example webapps now have a proper index.html/index.y start location * fixed package name clash in test webapp: snakelets is now tsnakelets * mp3 streaming possibilities are now complete (by album/year/etc) Enjoy, --Irmen de Jong. From sdfATexpertuneDOTcom Mon Jan 19 14:43:57 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Mon, 19 Jan 2004 19:43:57 -0000 Subject: HowTo distinguish between File and Directory Message-ID: On Win32, is there a function in the standard modules that can take a pathname and return whether it refers to a File or a Directory? Scott From mark at mceahern.com Thu Jan 29 13:51:07 2004 From: mark at mceahern.com (Mark McEahern) Date: Thu, 29 Jan 2004 12:51:07 -0600 Subject: conditional expression sought In-Reply-To: References: Message-ID: <4019561B.8040501@mceahern.com> Elaine Jackson wrote: >If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, >then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without >evaluating any other B_i. This is such a useful mode of expression that I would >like to be able to use something similar even when there is an i with >bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) >or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious >reasons. Does anybody know a good way to express this? Any help will be mucho >appreciado. > Why not write a unit test that demonstrates the behavior you want? It'll then likely be obvious to someone both what your problem is and what a likely solution is. Cheers, // m From mark at mceahern.com Wed Jan 14 23:19:42 2004 From: mark at mceahern.com (Mark McEahern) Date: Wed, 14 Jan 2004 22:19:42 -0600 Subject: Inserting while itterating In-Reply-To: References: Message-ID: <1074140382.26201.26.camel@dev.internal> On Wed, 2004-01-14 at 02:43, Thomas Guettler wrote: > Hi, > > Simple excerise: > > You have a sorted list of integers: > l=[1, 2, 4, 7, 8, 12] > > and you should fill all gaps: > > result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > How would you code this? > > Constrain: The original list should be changed, > don't create a copy. In the spirt of unit testing... #!/usr/bin/env python import unittest def fillGaps(seq): expectedLength = seq[-1] - seq[0] + 1 i = 1 while i < expectedLength: if seq[i] - seq[i-1] > 1: seq.insert(i, seq[i-1] + 1) i += 1 class test(unittest.TestCase): def test(self): l = [1, 2, 4, 7, 8, 12] fillGaps(l) self.assertEquals(l, range(1, 13)) unittest.main() From jacek.generowicz at cern.ch Tue Jan 13 04:18:14 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2004 10:18:14 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Samuel Walters writes: > because there seem to be many more introductory tutorials and a lot of > advice that one should learn Scheme, then move to Common Lisp. Careful. If you were to make such a suggestion on comp.lang.lisp, then you'd be likely to be told that learning Scheme first will cause you irreversible brain damage. Of course, now that He Whose Name Must Not Be Mentioned is no longer posting there, the words which will be used to point this out will probably be less colourful. :-) From jcarlson at uci.edu Wed Jan 21 11:53:02 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Jan 2004 08:53:02 -0800 Subject: Dailing modem. References: Message-ID: <20040121084921.FB3A.JCARLSON@uci.edu> > I need to dail a modem from python and disconnect it again. Is there a pythonic way of doing this? Life is just too short for fiddling with the complexity of TAPI via COM. But if you do have a TAPI-way of doing this, please share. > > Help will be welcomed greatly! Herman, You can actually open up a file called 'COM1' or 'COM2' (or any other com ports) and do writes to them without any win32 extensions (reads are another matter entirely). There are tricks so that you're not trying to open the port with both Python and some other app, but as long as your secondary application doesn't have a hold, you can send both 'ATDT \r\n' and '+++ATH\r\n', for desired "dial then hangup" behavior. - Josiah From mhammond at skippinet.com.au Mon Jan 12 00:48:27 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 12 Jan 2004 16:48:27 +1100 Subject: Multithreaded COM server problem... In-Reply-To: References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> Message-ID: John Lull wrote: > Mark Hammond wrote (with possible deletions): > > >>John Lull wrote: >> >> >>>I'm writing a multithreaded COM server to manage a pool of hardware resources. >>>All objects are designed to be thread-safe, and I've set sys.coinit_flags to >>>COINIT_MULTITHREADED before importing pythoncom. >> >>Note that this flag is effeectively ignored for the server. Objects are >>created in the same "apartment" as their creator. This, the code >>implementing your object need not specify this, but the code *creating* >>the object must. This is what determines the appartment. >> >>COM threading rules are complex, but "Python Programming on Win32" (1/2 >>by me :) covers these rules in words I would have trouble finding again :) > > > It covers threading rules for in-process servers pretty thoroughly. > > Unfortunately, this one has to be a local server since it's providing shared > access to a pool of hardware devices from multiple distributed clients. I've > carefully reviewed chapters 5 & 12, and appendix D, and wasn't able to find > anything addressing threading models in the local server in detail. If I've > missed something, I'd be grateful for any additional hints. The problem is that your client code is not running a message loop. If you change the loop of your client test code to something like: for i in range(delay)*10: time.sleep(0.1) pythoncom.PumpWaitingMessages() It works as you expect. A better choice would probably be win32event.MsgWaitForMultipleObjects, but that depends on what your app really does. Mark. From andy at wild-flower.co.uk Fri Jan 23 12:10:45 2004 From: andy at wild-flower.co.uk (andy) Date: Fri, 23 Jan 2004 17:10:45 +0000 Subject: closing database connections In-Reply-To: <71fd0ae5.0401230838.309e9b02@posting.google.com> References: <71fd0ae5.0401230838.309e9b02@posting.google.com> Message-ID: <200401231710.45091.andy@wild-flower.co.uk> I seem to remember reading somewhere that as client connections are a finite (and often scarce) resource, it's not the client but the server that will suffer when you do this. hth, -andyj From james.kew at btinternet.com Sat Jan 3 07:45:31 2004 From: james.kew at btinternet.com (James Kew) Date: Sat, 3 Jan 2004 12:45:31 -0000 Subject: Starting a script interactively? References: <37d5fe8f.0401021305.349a440@posting.google.com> Message-ID: "Al Kabaila" wrote: > David Klaffenbach wrote: > > Is there a way from within a python script to cause the interpreter to > > be in interactive mode after the script finishes? > > In Linux OS, add first line in myscript.py as follows: > #! //python > and make sure that myscript.py is executable. I don't know if this works > under dos, but there should be some equivalent. There is, for NT-class systems -- add .py to PATHEXT -- but I think the Python installer does this automatically. (The ActiveState installer certainly does.) But that only answers the question "how do I make a script executable". The OP wants to know how to have a script drop to the Python interpreter, rather than back to the shell, when the script completes. Under Windows, you could achieve this behaviour for _all_ Python scripts by tweaking the "open" action of the .py file association to add the -i flag. But I think the OP wants to do it only for _some_ scripts, and from _within_ the script -- nothing comes to mind for this. James From usenet at -OBFUSCATION-joefrancia.com Wed Jan 14 22:44:18 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Thu, 15 Jan 2004 03:44:18 GMT Subject: wxPython worries In-Reply-To: <87eku2rnha.fsf@pobox.com> References: <9d1c4d6d.0401141221.22c587f5@posting.google.com> <87eku2rnha.fsf@pobox.com> Message-ID: John J. Lee wrote: > I'll make my usual comment, which is that nobody has yet contradicted > me (unusual on USENET ;-) that Qt is the most well-designed Python GUI > framework. (Qt Designer is very good, too.) I'll second that, and go as far as to say it's a very good GUI framework no matter how you speak to it. > And, strangely, the PyQt commercial license is far cheaper than (C++) > Qt. $400 for former (Blackadder, from theKompany.com), $2500-odd for > the latter! $400 is for preofessional use. For personal use, it's $80, but you lose the right to distribute your apps (but maybe not if you release them under the GPL - I should look into that). > I believe Blackadder comes with Python-specific docs for PyQt, but > they're actually completely redundant, IMHO -- it's trivial to > translate the C++ docs to Python code, using the list of exceptions > distributed with PyQt. You do get a copy of the docs with your BA purchase. The Kompany also sells the PyQt docs separately for $20 for a one-time purchase, or $70 for a yearly subscription; that is, all updates for one year are included. Another BTW: their FAQ page still says > Blackadder is in beta, but I think somebody here mentioned the final > version was actually released some while back (PyQt itself has been > stable for years, of course). It is indeed stable. The one thing I don't like about BlackAdder is BlackAdder itself, the editor portion. It's not terrible - it just doesn't behave quite like I expect a dedicated Python editor to behave. I usually create my GUI in the Qt Designer, and then edit the Python stuff in Eric (Linux) or SciTE (win32). From sebb at linuxcult.com Wed Jan 7 09:08:59 2004 From: sebb at linuxcult.com (sebb) Date: 7 Jan 2004 06:08:59 -0800 Subject: Getting strange characters in the command prompt References: <56f42e53.0401061704.523f394@posting.google.com> <3FFB908F.9010208@v.loewis.de> Message-ID: <56f42e53.0401070608.47f82423@posting.google.com> Thanks a lot From LittleDanEhren at yahoo.com Tue Jan 6 17:52:21 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 6 Jan 2004 14:52:21 -0800 Subject: Pre-PEP: Dynamically evaluating default function arguments Message-ID: <711c7390.0401061452.3ee3789f@posting.google.com> One of the most common bugs that people have on the Python Tutor list are caused by the fact the default arguments for functions are evaluated only once, not when the function is called. The solution to this is usually to use the following idiom: def write_stuff(stuff=None): """Function to write its argument. Defaults to whatever is in the variable "things" """ if stuff is None: stuff = things print stuff However, it would be much more intuitive and concise if the following could be done instead, but with the guarantee that changes in the variable 'things' will be noticed: def write_stuff(stuff=things): print stuff This would instead print whatever is in things when the function is defined. The goal of this pre-PEP is to make it so that the default arguments are evaluated dynamically instead of when the function is created. As this is a pre-PEP, the details have not been finalized yet. One of the first details is whether or not the default argument should be checked to make sure it exists before the function is called. I think it would make the most sense if things were evaluated when the function was defined but the result was not saved and was reevaluated whenever the function is called. This might not be the best way to do it, though, and it might be better to treat it just like a regular equals sign. As with any additional dynamic properties added, there is the possibility of some errors to go uncaught and some. Here is an example of some hypothetical (but unlikely) code that would cause an error as a result of this change: >>> x = 5 >>> def return_something(stuff=x): return stuff >>> return_something() 5 >>> x += 1 >>> return_something() #dynamic now 6 >>> del x >>> return_something() Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined To me, this seems like the logical behavior, but there is still the possiblility of some programs being broken. A way to preserve backwards compatability could be to store the initial evaluation of the default and use it to fall back on if the variable needed isn't around anymore, but this seems overly complicated. Daniel Ehrenberg From glenfant at bigfoot.com Fri Jan 16 09:10:21 2004 From: glenfant at bigfoot.com (Gilles Lenfant) Date: Fri, 16 Jan 2004 14:10:21 -0000 Subject: Making GIF/PNG barcodes Message-ID: Hi, I know that with reportlab + rlbarcode + renderPM + PIL, I could achieve this, but this seems some overkill to me. Is there a solution that requires only PIL ? Google didn't help, or misused it ! Many thanks for any pointer. -- Gilles From swalters_usenet at yahoo.com Mon Jan 5 11:32:06 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 16:32:06 GMT Subject: RELEASED: allout-vim 031229 References: <87d69yqsos.fsf@pobox.com> Message-ID: |Thus Spake John J. Lee On the now historical date of Mon, 05 Jan 2004 16:13:55 +0000| > Of course, you don't always get the whole truth from dictionaries. I > remember my sister and I laughing at the translation in our school French > textbook of "zut" as "bother". "Bother" must be the mildest swearword (if > you can call it that) in the English language -- comically so. We were of > the opinion that a word that's so clearly designed to be spat must be at > least two notches up in vulgarity. :-) Obligatory: Mon a?roglisseur est rempli d'anguilles. (shamelessly stolen from http://www-2.cs.cmu.edu/~sprite/mhifoe.html ) -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From webmaster at beyond-thoughts.com Thu Jan 15 16:42:47 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Thu, 15 Jan 2004 22:42:47 +0100 Subject: PEP for new modules (I read PEP 2) Message-ID: <40070957.9040202@beyond-thoughts.com> Hello, recently there was a lot discussion about a new Path-class. So Gerrit Holl started to write a pre-PEP http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html We tried to summarize the good ideas and suggestions. Some are still missing and concepts of already existing modules have to be added/thought over. Furthermore it turns out that not a new class is needed but a module. The pre-PEP is already quite big --- Gerrit Holl figured out that are bigger ones [1] but I think (and Gerrit Holl agrees) that we should write the PEP a bit different. In PEP 002 about adding a module to the standard library it isn't clear (at least I didn't get it) what exactly should be in the pre-PEP for a new module. There's another difference because the Path module does not exist right now. However I think it's not wrong first to figure out how a good Path-module should look like and then start implementing and continue discussion. I think it would be a good idea to start with a dummy implementation that has docstrings. Then we could build the documentation for the module automatically and it wouldn't be neccessary to put everything into the pre-PEP. I'd like to keep in the prePEP: Abstract, Motivation, a shortened Specification (mostly global structure, definitions, ...), Rationale (especially this one seems important to me), BDFL Pronouncement, References, Copyright. So basically I want to relocate the real Specification, because the more specific it gets the more it looks like a documentation and the prePEP grows and grows ... Is this a valid option for a PEP? Better suggestions? Thank You, Christoph Becker-Freyseng [1] Some statistics about number of words in different peps: $ wc -w *.txt | sort -rn | head -20 | nl 1 6356 pep-0253.txt # subtyping built-in types 2 5273 pep-0100.txt # python unicode integration 3 4985 pep-0307.txt # extension to pickle protocol 4 4985 pep-0249.txt # python database api spec 5 4694 pep-0258.txt # docutils design spec 6 4604 pep-0252.txt # types/classes 7 4551 pep-0101.txt # python releases 8 4457 pep-0287.txt # reST 9 4144 pep-0209.txt # multidim. arrays 10 3968 pep-0225.txt # elementwise operators 11 3916 pep-0302.txt # new import hooks 12 3882 pep-xxxx.txt From gerrit at nl.linux.org Wed Jan 28 16:21:46 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 28 Jan 2004 22:21:46 +0100 Subject: comparing booleans Message-ID: <20040128212146.GA7186@nl.linux.org> Hi, is it proper to compare booleans? It is possible, of course, because they're compatible with numbers, but booleans aren't truly numbers. I'm tempted to write: return cmp(self.extends, other.extends) instead of if self.extends and not other.extends: return 1 else: return -1 # I've already verified self.extends != other.extends ...but somehow comparing Booleans doesn't feel right... Is my feeling correct? (Hmm, makes me wonder, for booleans, are != and ^ equal?) Gerrit. -- 174. If she bear no sons to her second husband, the sons of her first husband shall have the dowry. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From grisha at apache.org Thu Jan 22 19:14:15 2004 From: grisha at apache.org (Gregory (Grisha) Trubetskoy) Date: Thu, 22 Jan 2004 19:14:15 -0500 Subject: [ANNOUNCE] Mod_python 2.7.10 Message-ID: <20040122190718.D6531@onyx.ispol.com> The Apache Software Foundation and The Apache HTTP Server Project are pleased to announce the release of version 2.7.10 of mod_python. This release addresses a vulnerability in mod_python 2.7.9 whereby a specific query string processed by mod_python would cause the httpd process to crash. The previously released version 2.7.9 was supposed to correct this issue, but is still vulnerable. There are no other changes or improvements from the previous version in this release. If you are currently using mod_python 2.7.9 or earlier, it is highly recommended that you upgrade to 2.7.10 as soon as possible. If you are using mod_python 3.0.4, no action is necessary. Mod_python is available for download from: http://httpd.apache.org/modules/python-download.cgi For more information about mod_python visit http://www.modpython.org/ Regards, Grisha Trubetskoy From LittleDanEhren at yahoo.com Tue Jan 6 21:21:49 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 6 Jan 2004 18:21:49 -0800 Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> <92urc1-92u.ln1@dman13.dyndns.org> Message-ID: <711c7390.0401061821.22e24288@posting.google.com> > Uh-oh. Don't go there. If there was no difference, then you would be > able to perform assignment, even define a class, in the condition of a > while. I don't think you want that based on what you said above. (I > certainly don't want to have to read code with such complexity!) > > -D I was able to create an simple text pager (like Unix's more) in some nested list comprehensions. Just because I can do that doesn't mean that real programs will be made like that. IMHO the difference between statements and expressions doesn't really make sense, and it is one of the few advantages Lisp/Scheme (and almost Lua) has over Python. Daniel Ehrenberg From chris.lyon at spritenote.co.uk Wed Jan 7 07:30:34 2004 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 7 Jan 2004 04:30:34 -0800 Subject: urllib urllib2 what is the difference ? Message-ID: Could somebody please explain the difference between these two modules and explain why they are both required, and if there will ever be a unification of them? From andymac at bullseye.apana.org.au Sat Jan 24 17:37:18 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 25 Jan 2004 09:37:18 +1100 (EST) Subject: fcntl O_NDELAY constant not found in python 2.3 on linux In-Reply-To: <20040123190541.31213.qmail@web21206.mail.yahoo.com> References: <20040123190541.31213.qmail@web21206.mail.yahoo.com> Message-ID: <20040125093412.G78742@bullseye.apana.org.au> On Fri, 23 Jan 2004, Ryan Grow wrote: > import os, fcntl, FCNTL > > file = open("/tmp/testfd.txt", 'w') > fd = file.fileno() > fl = fcntl.fcntl(fd, FCNTL.F_GETFL) fl = fcntl.fcntl(fd, fcntl.F_GETFL) ^^^^^ > fcntl.fcntl(fd, FCNTL.F_SETFL, fl | FCNTL.O_NDELAY) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) ^^^^^ ^^ > print "Made it!" All the symbols in FCNTL are available either in fcntl or os. -- 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 sandskyfly at hotmail.com Wed Jan 21 05:01:29 2004 From: sandskyfly at hotmail.com (Sandy Norton) Date: 21 Jan 2004 02:01:29 -0800 Subject: personal document mgmt system idea References: <100ql5oc1rctc09@news.supernews.com> Message-ID: John Roth wrote : > I wouldn't put the individual files in a data base - that's what > file systems are for. The exception is small files (and by the > time you say ".doc" in MS Word, it's now longer a small > file) where you can save substantial space by consolidating > them. There seems to be consensus that I shouldn't store files in the database. This makes sense as filesystems seem to be optimized for, um, files (-; As I want to get away from deeply nested directories, I'm going to test two approaches: 1. store everything in a single folder and hash each file name to give a unique id 2. create a directory structure based upon a calendar year and store the daily downloads automatically. I can finally use some code I'd written before for something like this purpose: from pprint import pprint import os import calendar class Calendirs: months = { 1 : 'January', 2 : 'February', 3 : 'March', 4 : 'April', 5 : 'May', 6 : 'June', 7 : 'July', 8 : 'August', 9 : 'September', 10 : 'October', 11 : 'November', 12 : 'December' } wkdays = { 0 : 'Monday', 1 : 'Tuesday', 2 : 'Wednesday', 3 : 'Thursday', 4 : 'Friday', 5 : 'Saturday', 6 : 'Sunday' } def __init__(self, year): self.year = year def calendir(self): '''returns list of calendar matrices''' mc = calendar.monthcalendar cal = [(self.year, m) for m in range(1,13)] return [mc(y,m) for (y, m) in cal] def yearList(self): res=[] weekday = calendar.weekday m = 0 for month in self.calendir(): lst = [] m += 1 for week in month: for day in week: if day: day_str = Calendirs.wkdays[weekday(self.year, m, day)] lst.append( (str(m)+'.'+Calendirs.months[m], str(day)+'.'+day_str) ) res.append(lst) return res def make(self): for month in self.yearList(): for m, day in month: path = os.path.join(str(self.year), m, day) os.makedirs(path) Calendirs(2004).make() I don't know which method will perform better or be more usable... testing testing testing. regards, Sandy From usenet at -OBFUSCATION-joefrancia.com Tue Jan 6 14:52:14 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Tue, 06 Jan 2004 19:52:14 GMT Subject: using cgi form via http and extracting results In-Reply-To: <3ffb0dde.0@news1.mweb.co.za> References: <3ff84844.0@news1.mweb.co.za> <3ffaf37b.0@news1.mweb.co.za> <3ffb0dde.0@news1.mweb.co.za> Message-ID: bmgx wrote: > Ok it's done right.. > > import urllib > a = urllib.urlopen("http://www.suckerservice.com/convert.cgi", > "Amount=1&From=EUR&To=USD") > b = a.readlines() > c = open("tempresult.html","w") > > i = 0 > d = "********* local copy ******\n\n" > while i < len(b): > d = d + b[i] > i = i + 1 > > c.write(d) > c.close() > a.close() > Instead of constructing the data string by hand, you can pass a dictionary or list of 2-item tuples to urllib.urlencode() and get a properly formatted string: my_data = urllib.urlencode({'Amount':1,'From':'EUR','To':'USD'}) # or... my_data = urllib.urlencode([('Amount',1),('From','EUR'),('To','USD')]) a = urllib.urlopen('http://www.suckerservice.com/convert.cgi', my_data) From jepler at unpythonic.net Fri Jan 9 16:43:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 9 Jan 2004 15:43:43 -0600 Subject: Python is far from a top performer according to benchmark test... In-Reply-To: References: Message-ID: <20040109214343.GE2810@unpythonic.net> numarray is probably the perfect example of getting extremely good performance from a few simple constructs coded in C. (numarray-0.8 is less then 50k lines of C code, including comments and blank lines, so it's also very simple given the amount of "bang" it provides) All your important logic is in Python, you're in no way stuck worrying about buffer lengths, when to call free(), and all those other things that drive me crazy when I try to write in C. If I had to execute my Python programs without executing any code written in "C" behind the scenes, well, I'd be stuck. Of course, the situation is about the same for any language you care to name, and if not then substitute "machine code". Jeff From amy-g-art at cox.net Mon Jan 19 16:15:22 2004 From: amy-g-art at cox.net (Amy G) Date: Mon, 19 Jan 2004 13:15:22 -0800 Subject: Simple question from Python newb... What am I doing wrong? For x, y, z in aTuple: Message-ID: I have a whole bunch of tuples that look something like this, aTuple = ('1074545869.6580.msg', 't_bryan_pw at gmcc.ab.ca', 'Your one stop prescriptions') now that I have this I try for x, y, z in aTuple: do something with x do something with y do something with z But I am getting the error that there are too many values to unpack. If I do... for x in aTuple: print x It prints the items from the tuple each on its own line. How can I unpack these three string values into three different string variables like my first for loop? Thanks in advance for answering what is probably a simple question. From adalke at mindspring.com Thu Jan 15 02:44:38 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 15 Jan 2004 07:44:38 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> <23891c90.0401140223.344b22af@posting.google.com> <100bbb6kj9m03a4@corp.supernews.com> <1AjNb.8936$1e.894@newsread2.news.pas.earthlink.net> Message-ID: Me: > > But if you blabber it to everyone in the manner you have > > then when you do need someone else's help you're less likely to > > get it. Brandon J. Van Every: > Hello, *what* planet are you on? You think there's some crowd of people out > there just waiting to be useful to me? There isn't. That's what I've just > taken 6 months to determine. I'm on planet Earth, while you're on planet BJVE singing "I'm in my own world, you can't come in. I'm having a party, with make-believe friends." Reread what I said: "when you do need someone else's help." That's in the future. Unless you never plan to do anything more than what you did in the last six months? I also used the singular "someone" without saying one whit about a "crowd of people." Me: > > It's made even worse when you make claims related to your > > profession (like "Even 12 years ago, "Computer Graphics: Principles > > and Practice" didn't teach texture mapping. > It didn't. I have my copy still, and there is no discussion of texture > mapping algorithms in it. It was considered "an advanced subject." Then you don't own the second edition, which came out a year before that "12 years ago" comment you made. Had you said 14 years ago then things would be different. A slight timing error perhaps, but properly you should have used the publication date of your book. Besides, you made the explicit claim that DOOM introduced texture mapping to the world when by the time it came out you could buy off-the-shelf SGI boxes with hardware texture maps as part of GL, and of course Wolf3D had texture maps for the walls. > Whatever dude. I could care less about such chronologies. Indeed, since they show your claims of expertise in the field to be overblown it's no wonder you prefer to ignore it. > So, why are you here then? Why are you wasting our > time, talking about the finer points of my personal history? Hmmm, you're the one who started wasting our time to talk about your personal history. But that would be another detail of your history you probably don't care about. > You are here out of a need to remind myself and others of my knowledge or > lack thereof? Wow, what an important job. Hats off to you. Actually, I'm here on a perhaps misguided hope that you will see that the style in which you say and do things affects how people work with you. An engaging and even thoughtful commentary tends to get the best side of people, while one which is spiteful and demeaning gets the worst, and with consequences that may in this era of Google affect you for years to come. That last is of course an extreme but as it is you appear to be approaching persona non grata in this forum which makes it less likely that anyone will help you out in future endeavors. Andrew dalke at dalkescientific.com From knoppix at laptop.home.net Sun Jan 11 17:36:27 2004 From: knoppix at laptop.home.net (Knoppix User) Date: Sun, 11 Jan 2004 16:36:27 -0600 Subject: [Newb] Still not able to solve class attribution References: Message-ID: On Sun, 11 Jan 2004 18:36:22 +0100, Peter Otten wrote: > Just an idea: how about moving the following statement up immediately after > the wx.Frame.__init__(...). The DisplayImg() method *could* be called in > the code you abbreviate with the above four dots. Thanks for the idea Peter. No go. I did think of that earlier, and checked a printout very carefully to make sure about that. Anyway, I did move it up to be the first method after __init__, just to check again. :-( Steve From cliechti at gmx.net Sat Jan 31 14:05:43 2004 From: cliechti at gmx.net (Chris Liechti) Date: Sat, 31 Jan 2004 19:05:43 +0000 (UTC) Subject: Simple web proxy - help needed References: Message-ID: forshtat at hotmail.com (Ziv Forshtat) wrote in news:c335e460.0401310918.49361638 at posting.google.com: > The problem is that at > least on my winxp machine all of these servers only seem to work with > some sites but consistently generate exceptions with others. I keep > getting "connection reset by peer" and "software caused connection > abort"... > Perahps someone has already encountered this problem and solved it?? i have a TCP forwarder program that had similar exceptions. since i chenged it back from sock.sendall(data) to while data: n = sock.send(data) data = data[n:] it's running stable again. maybe look for sendall's in the sources. chris -- Chris From rays at blue-cove.com Sat Jan 31 16:19:17 2004 From: rays at blue-cove.com (RayS) Date: Sat, 31 Jan 2004 13:19:17 -0800 Subject: Running External Programs from Within Python In-Reply-To: References: <5a40bf6a.0401311123.4b7f783f@posting.google.com> <5a40bf6a.0401311123.4b7f783f@posting.google.com> Message-ID: <5.2.1.1.2.20040131131243.09424ec0@216.122.242.54> Hi Dirk, >That is very easy: popen() >Check the FAQ and documentation again for popen. That reminds me, I was asked if you can open a bi-directional pipe to control an external console program on Windows. A guy has compiled FORTRAN (~4,000 lines of 1980's spaghetti) and wants to add a modern GUI and a front end method to check data. Can you both send commands to, and read STDOUT from, a remote console app? Ray From graham at rockcons.co.uk Sun Jan 4 13:18:27 2004 From: graham at rockcons.co.uk (Graham Nicholls) Date: Sun, 04 Jan 2004 18:18:27 +0000 Subject: Launching pdb from within a script Message-ID: I asked this before, but got no response, but I KNOW YOU KNOW ;-) A year or so ago, I was given a really useful answer to a question posed here, which showed me how to start the debugger from withing a script. Yes, of course I've lost the mail (and I have trawled through all my old mail), and yes, I know I'm stupid! I'm surprised this isn't a FAQ, BTW, as it seems such a useful facility. So come on guys, cough it up! Thanks Graham Nicholls -- #include From frank at pc-nett.no Tue Jan 27 09:03:05 2004 From: frank at pc-nett.no (frank) Date: Tue, 27 Jan 2004 15:03:05 +0100 Subject: ANN: Soprano 0.05 Message-ID: GUI (wxpython) network scanner written in python that scans a selected range of ip addresses and try to get info about the hosts such as users, localgroups, shares,operating system, open ports, etc. There is also binary windows package available. new in 0.0.5: new portscanner with the new 2.3 socket settimeout portscanner now also looks up portinfo from a txt file stored under "data\port-numbers.txt" (http://www.iana.org/assignments/port-numbers). now scans upto 5 hosts simultaneously. more settings: set portscanner timeout and set ping timeout Saves almost everything to xml. a lot of small fixes. note: this is very far from the final release http://sourceforge.net/projects/soprano/ From fumanchu at amor.org Tue Jan 6 18:02:08 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 6 Jan 2004 15:02:08 -0800 Subject: Pre-PEP: Dynamically evaluating default function arguments Message-ID: Daniel Ehrenberg wrote some stuff about evaluating function params at runtime. Some of us can recall statements like this one: "Nevertheless, there's no chance in hell this will ever change, so let's drop the subject." --Guido van Rossum http://mail.python.org/pipermail/python-dev/2002-August/028243.html ..and some of us who don't can easily Google for it. Are you sure you want to waste (I mean spend) time on this Sisyphean task Yet Again? Robert Brewer MIS Amor Ministries fumanchu at amor.org From adalke at mindspring.com Mon Jan 5 01:48:54 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 05 Jan 2004 06:48:54 GMT Subject: Project dream References: Message-ID: Lonnie Princehouse: > I keep thinking that a good graph module would be really handy (as in > nodes and edges, not plotting) I've wondered about Boost. There's Boost Python of course, and Boost includes a graph library with many of the features you've listed. But do the two work well together? I dunno. > with the ability to traverse and manipulate graphs in nice Pythonic ways, And I really don't know if the result will feel Pythonic. I barely understand how to make the examples work, much less what needs to be done to get a full melding. > basic graph theory (finding cycles, paths, cliques, etc). I've > started writing one, but it's nowhere near completion. I have two C extensions for Python which do max clique detection. See http://starship.python.net/crew/dalke/clique/ . But I haven't tested them in over 4 years. BTW, I've done various bits of graph theory work for molecular structures. I've found that the nomenclature is different enough that it's hard for chemistry and graph theory to share each other's data structures directly. (Eg, we want "atoms", which are "colored nodes", and "bonds", which are "colored undirected edges" of low valence (usually 4 or less, rarely above 6, and never larger than about 13.) Still, I'll be interested in anything you have, especially subgraph isomorphism. (There is Brian Kelly's "Frowns" package which has a Python interface to the VF algorithm but it needs to convert to VF's data structures before doing the search, and that apparently takes most of the time.) Andrew dalke at dalkescientific.com From peterwu at hotmail.com Wed Jan 21 15:23:00 2004 From: peterwu at hotmail.com (Peter Wu) Date: Wed, 21 Jan 2004 15:23:00 -0500 Subject: python mode question Message-ID: <87y8s1oxuj.fsf@tulip.whu.ca> A quick question: After firing C-c C-c to execute a python program in Python mode, an output buffer will be displayed at the bottom of the window. Also, the focus remains in the output buffer. How can I switch the focus from the output buffer to the editing buffer? Thanks! -- ,,, (o o) Peter Wu ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From simonb at NOTTHISBIT.webone.com.au Fri Jan 16 00:53:01 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Fri, 16 Jan 2004 16:53:01 +1100 Subject: Parsing c-code References: Message-ID: On Wed, 14 Jan 2004 09:27:55 +0100, tm wrote: > Hello, > > are there recommended modules for parsing c-code. I want to read in > c-structs and display it in a tree graphic. I wrote some c declaration parsing code last year. It handles, eg. gcc's std c library includes OK. (after preprocessing) http://arrowtheory.com/software/python/index.html Simon. From donn at u.washington.edu Mon Jan 12 19:34:34 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 12 Jan 2004 16:34:34 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> Message-ID: In article <7xeku496wx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > claird at lairds.com (Cameron Laird) writes: > > >I'd say don't bother with C++ unless you're working on a big > > >multi-person project. Its design will make no sense to you unless > > >you've faced the problems that come up in those projects. Otherwise > > >it's a big mess. > > > > And if you *are* working on a big multi-person project, and you > > choose C++, you're likely to end up with ... a big mess. > > C++ was motivated by the problems faced by big projects written in C. > I'm talking about stuff like telephone switches with hundreds of > programmers and millions of lines of code. Even with very competent > designers and managers, those projects usually ran amuck. C++ gives > some real help in keeping projects like that functioning, if the > programmers and managers know what they're doing. If they don't know > what they're doing (as is the case in most projects), C++ isn't that > likely to help and may make the problems worse. Hm, to me this proposition seems too self-reliant. If the designers and managers fail to thrive on C++, then Q.E.D. - must not have known what they were doing. At any rate, as you note, there are other languages such as Java that may or may not (can't say from experience) offer some or all of the benefits without the worst problems. Your telephone switch example reminds me to mention Erlang, which is by no means an attempt to offer any of C++'s features but seems to work in that space. I don't know if we're on very solid ground from which to laugh at C++, though. Python has the advantage of a clean start, but from a software engineering standpoint it really seems like a hacker language. Full of neat tricks that work like magic, but does it really even attempt to offer anything in the area you're talking about? If so, that might be a good direction for yet another book about Python. Donn Cave, donn at u.washington.edu From max at alcyone.com Tue Jan 13 21:42:22 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 13 Jan 2004 18:42:22 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> Message-ID: <4004AC8E.46A3104F@alcyone.com> "Brandon J. Van Every" wrote: > Why, because I turned around a project in 3 weeks while having the flu > half > the time? Since this "turnaround" involved abandoning your project, it's hard to see how having devoted 1.5 man-weeks to a project which it should have only taken you a few man-hours to realize was not going to pay off is an impressive achievement. (Why you thought the project was going to be further any of your personal goals in the first place is completely beyond my comprehension, as well, but that's another story.) > I laugh, over and over again, at all the people who declare 3D > spherical > icosahedral planetary display engines to be trivial, ... There's a big difference between "trivial" and "not nearly as impressive as you seem to think," particularly since your goal was to create a game and you got nowhere on the actual game (which in frustrating you abandoned at the time). And how many man-months did you seek into _that_ project? A "3D spherical icosahedral planetary display engine" may be darn neat, but it's hardly an impressive commercial achivement on its own (particularly considering how much effort you needed to put into it), and as a resume-building project it doesn't exactly excite the blood. Oh, and by the way, nobody's ever seen it in action except you -- so we have no idea whether or not it even qualifies as an accomplishment! > ... or VS .NET 2003 > ports > of Freeciv to be trivial, ... But by your own admission, you _haven't_ ported Freeciv to VS .NET 2003. You got it building, but it doesn't work. That's hardly an accomplishment. > ... or any other project I've sunk blood into > and run > into difficulties. I know better. It's water off my back because I > know > what an armchair peanut gallery sounds like. The problem is that from everybody else's perspective, you brag about accomplishments which, from the point of view of everyone else, are not accomplishments but failures; what projects are there that you have sunk time into and have paid off, either in having something to show for it, or having (gasp) made you money? You're trying to put this weird spin on your public displays of embarassment is not really working. Trying and failing is a part of life. Trying and failing, over and over again, consistently, despite insisting quite urgently on how important you are to a community, is starting to get suspicious. > Those who never taste failure are haughty. And those who never taste success should probably come to the realization, eventually, that they are doing something wrong. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ And a grateful nation will be in his debt. -- John F. Kennedy (on the pilot killed in the Cuban Missile From bkc at Murkworks.com Fri Jan 23 09:14:58 2004 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 23 Jan 2004 09:14:58 -0500 Subject: Python Consultants? References: <8e198b65.0401221315.6d5cb3fe@posting.google.com> Message-ID: "Dan" wrote in message news:8e198b65.0401221315.6d5cb3fe at posting.google.com... > Here are a pair XML problems that are available: > > #1) Setup to convert these xml files > http://www.gothamanalytics.com/PairTools/geturl?url=http://app.quotemedia.co m/data/getHistory.xml&symbol=SUNW > http://www.gothamanalytics.com/PairTools/geturl/?url=http://app.quotemedia.c om/data/getQuotes.xml?symbols=SUNW > into a vector of open,close,volume information suitable for use with a > numerical Python module. Doing this quickly is a plus. Can you better define "vector". Do you want a Numeric array, or a list or tuple? Do you want a different vector for each of (open, close, volume) (ie, 3 arrays) or do you want the three values stuck into one tuple/list element and that element put into an array/list? What do you mean by "quickly"? You haven't given an indication of the size of the file you wish to process. The URL shown above produces a rather small file. But are you planning to process megabytes of data with multiple symbols over long periods of time? SAX can easily parse those xml files without loading them entirely in memory. What platform are you running on? Maybe it's quicker to use a C extension like libxml2 if you're going to parse extremely large files. You haven't provided enough information about your problem domain. > #2) Expose the Salesforce.com SOAP functionality from salesforce.com > generated WSDL files, here is an example WSDL > http://gothamanalytics.com/Ex/enterprise.wsdl > See sforce.com for more info on the salesforce.com API. A Python > solution is preferred but a work around which uses Java and the > Salesform.com Apache Axis library and an appropriate gateway from > python might also be acceptable. Results from an attempt at using ZSI > to process the WSDL file is appended to this message. I think there are others on this list who are (or will soon) need to work with Salesforce.com. I have been evaluating it and DreamFactory for a few months, but I don't have any clients at the moment that need to use either. If you're just doing "bulk transfer" of data, you might consider a hybrid approach using JyRetic EAI Server http://sourceforge.net/projects/retic Otherwise, continued work on the pywebsvcs-talk list could arrive at a solution in time. In fact, I think I saw a post from you on the list this week. If your business has resources that can be applied to fixing problems in ZSI or SOAPPY that'd be a good way to solve your immediate problem, and "giving back" to the community. -Brad > -- > http://mail.python.org/mailman/listinfo/python-list > From maxm at mxm.dk Wed Jan 28 01:46:52 2004 From: maxm at mxm.dk (Max M) Date: Wed, 28 Jan 2004 07:46:52 +0100 Subject: Manipulating MIDI In-Reply-To: References: Message-ID: <40175ADC.6050907@mxm.dk> Premshree Pillai wrote: > I am in need of a module using which I could > manipulate musical information from MIDI files. What I > need is some module that could extract the frequency > components of the various instruments in the musical > piece. Any suggestions? http://www.mxm.dk/products/public/pythonmidi regards Max M From Johannes.Nix at web.de Fri Jan 2 13:16:12 2004 From: Johannes.Nix at web.de (Johannes.Nix at web.de) Date: 02 Jan 2004 19:16:12 +0100 Subject: Python as a numerical prototyping language. References: Message-ID: <67n0966wsz.fsf@aster.homelinux.net> Carl writes: > Now, I have always believed that Python is a poor performer in terms of > numerical speed. My experience, however, is that the efficient use of > dictionaries, lists, precompiled numerical libraries, etc makes Python a > higly competitive language for scientific computing (in comparison with > more traditional languages such as C, C++ and different versions of > Fortran). First, look at http://www.python.org/topics/scicomp/ . I am using Python + Numeric since a few years for really computing-intensive signal processing and real-time audio processing (explorative noise reduction for hearing aids). I code at least twenty times faster than I did in pure C. It works great and on some occations execution speed has been five times faster than Matlab; on a Linux system with kernel modifications, Python with C extensios can achieve worst-case latencies of 20 milliseconds or less for full-duplex audio processing. At the other hand side, I use it for really computing-intensive stuff on a Linux cluster (LAM) with 32 nodes. Plus, it runs neatly on multiprocessor Alpha or Opteron systems, and can run in embedded systems; no need for a graphic card. Another quality of Numerical Python that it is very easy to integrate C code and very mature stuff from Netlib. Scientfic code can be very difficult to test and verify so a good code base for numerical routines is paramount. An interesting project for Python would be to integrate the GNU scientific library and important Netlib routines as far as possible. The module philosophy of Python, as well as Python's community culture, supports it very well to use existing code again. One thing that is quite easy to do is to start coding everything in Python and develop the algorithm; then identify the hot spots by using the profiler, and move them to C. Something of the complexity of a MP3 player with net access and graphic user interface can be easily implemented in Python+C today. One point about Matlab: The basic Matlab is _expensive_. But in a commercial environment Matlab with signal processing extensions costs _tens of thousands of dollars_. If I were founding an engineering startup, I would avoid Matlab if possible at all. > > Where is Python heading? Will it be a viable replacement for traditional > number-crunching languages in the near-term future? > For applications like audio, script languages will replace C and C++ widely in few years, because processors are just fast enough. In my eyes, what Python, and Open Source in general, is still lacking is an very easy, fast and very high-quality library for scientific and financial plotting, although there are lots of good and thougthful beginnings like Gnuplot, OpenDX, and many more. This would be an essential building block to foster the use of Python in science. Another thing that is a hassle for real-time programming on multiprocessor systems is the Global Interpreter Lock (GIL). For signal processing and real time replacing the GIL by per-object locks would be an advance comparable to Linux-2.0. Currently the best workaround seems to be the use of shared memory and LAM (by the pypar module). Johannes P.S. The mail address above traps spam. Mail to string.replace(address, 'web', 'uni-oldenburg') From FBatista at uniFON.com.ar Fri Jan 30 07:49:05 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 30 Jan 2004 09:49:05 -0300 Subject: PEP 327: Decimal Data Type Message-ID: I'm proud to announce that the PEP for Decimal Data Type is now published under the python.org structure: http://www.python.org/peps/pep-0327.html This wouldn't has been possible without the help from Alex Martelli, Aahz, Tim Peters, David Goodger and c.l.p itself. After the pre-PEP roundups the features are almost established. There is not agreement yet on how to create a Decimal from a float, in both explicit and implicit constructions. I depend on settle that to finish the test cases and actually start to work on the code. I'll apreciate any feedback. Thank you all in advance. . Facundo From SBrunning at trisystems.co.uk Tue Jan 6 11:32:54 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Tue, 6 Jan 2004 16:32:54 -0000 Subject: Speed? Message-ID: <31575A892FF6D1118F5800600846864D01200E1D@intrepid> > From: Skip Montanaro [SMTP:skip at pobox.com] > Peter> And with Python, of course, it's almost trivial to do this kind > Peter> of thing, compared to some other languages. Sigh. > > Which was just another data point in your decision, right? After all, if > Python is so much easier to write your benchmarks in than some/most/all of > the alternatives, that has to factor into the choice of implementation > language. Not necessarily. Only if you are sane. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ -LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From rainerd at eldwood.com Fri Jan 16 13:23:26 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 16 Jan 2004 18:23:26 GMT Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <3064b51d.0401160539.49fc5893@posting.google.com> Message-ID: beliavsky at aol.com wrote: > What is so dangerous about the STL in C++? One thing is that iterators can get invalidated when the container is modified. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From computer.problemen at skynet.be Fri Jan 9 03:54:52 2004 From: computer.problemen at skynet.be (broebel) Date: Fri, 9 Jan 2004 09:54:52 +0100 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> Message-ID: <3ffe6a9b$0$1809$ba620e4c@news.skynet.be> as answered by d, this is dutch but thanks this how-to is really interesting "d" schreef in bericht news:UilLb.1570$nt4.1692 at attbi_s51... > Rene Pijlman wrote: > > > broebel: > >>first problem is the fact that I started out with a little program who was > >>part of a course but the problem is when I launch the program. I don't > >>have the time to see the result because the screen closes immediately. > >>Can anyone explain what's happening. > > > > The program started, did what it had to do and then terminated :-) > > > > "1 How do I run a Python program under Windows?" > > > http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-und er-windows > > > Worked fine for me on Linux... made two suggested changes: 1) use > raw_input(), not input(), 2) check user input for errors. Sorry, I don't > know how to say "Enter a number between 0 and 500" in whatever language > this is in (German?) > > > #!/usr/bin/env python > while 1: > bedrag = raw_input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) > try: > bedrag = int( bedrag ) > except ValueError: > print "Enter a number between 0 and 500" > else: > if bedrag < 0 or bedrag > 500: > print "Enter a number between 0 and 500" > else: > break > > > for munt in 200, 100, 50, 20, 10, 5, 2, 1 : > aantal = 0 > > while bedrag >= munt : > aantal = aantal + 1 > bedrag = bedrag - munt > > if aantal > 0 : > print aantal, 'x', munt > -- > /d/ From tracy at reinventnow.com Sat Jan 17 17:08:44 2004 From: tracy at reinventnow.com (Tracy Ruggles) Date: 17 Jan 2004 14:08:44 -0800 Subject: Does anyone else not find the fun in programming...? References: Message-ID: Jeff Epler wrote in message news:... > >>> "fun" in "programming" > 0 # DANGIT > >>> "programming".find("fun") > -1 # ARGARGHARGH > >>> "programming".index("fun") > ValueError: substring not found in string.index # F***! > >>> assert "programming" is "fun" > AssertionError # I'm going home curiosities = ("functional programming", "fundamental OO theory", \ "defunct languages", "economic funnels", "fungal analysis") ["fun" in curiosity for curiosity in curiosities] From google at axiomatize.com Thu Jan 15 14:38:39 2004 From: google at axiomatize.com (Laurent Therond) Date: 15 Jan 2004 11:38:39 -0800 Subject: Binary strings, unicode and encodings Message-ID: <265368cb.0401151138.37a3a47b@posting.google.com> Maybe you have a minute to clarify the following matter... Consider: --- from cStringIO import StringIO def bencode_rec(x, b): t = type(x) if t is str: b.write('%d:%s' % (len(x), x)) else: assert 0 def bencode(x): b = StringIO() bencode_rec(x, b) return b.getvalue() --- Now, if I write bencode('failure reason') into a socket, what will I get on the other side of the connection? a) A sequence of bytes where each byte represents an ASCII character b) A sequence of bytes where each byte represents the UTF-8 encoding of a Unicode character c) It depends on the system locale/it depends on what the site module specifies using setdefaultencoding(name) --- So, if a Python client in China connects to a Python server in Europe, must they be careful to specify a common encoding on both sides of the connection? Regards, L. From sebb at linuxcult.com Mon Jan 12 20:46:26 2004 From: sebb at linuxcult.com (sebb) Date: 12 Jan 2004 17:46:26 -0800 Subject: Problem with what raw_input() returns Message-ID: <56f42e53.0401121746.39b9e4db@posting.google.com> If I do the following script: # -*- coding: cp1252 -*- one = "??" two = one.replace("?","a") print two # it prints aa as I expected But with the following script: # -*- coding: cp1252 -*- one = raw_input() # When I run the script, I type ?? two = one.replace("?","a") print two # it still prints ?? and I want it to print aa Can someone help me with that problem? Thanks From skip at pobox.com Sun Jan 25 13:05:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 25 Jan 2004 12:05:23 -0600 Subject: Python and writing a CSV file In-Reply-To: <000c01c3e2b7$a6eabcc0$97443d42@homebass1> References: <20040121232549.GA28328@mail.theserver.ath.cx> <009501c3e07e$80b62e30$97443d42@homebass1> <16399.7079.192926.761791@montanaro.dyndns.org> <000c01c3e2b7$a6eabcc0$97443d42@homebass1> Message-ID: <16404.1379.563232.185092@montanaro.dyndns.org> Kevin> Thanks for responding. Currently we do not have Python 2.3 Kevin> installed on our server, is there another way to perform this Kevin> task with another module or without a module? Thanks! The Object Craft module does write CSV files. When we wrote the module included with 2.3, we conciously tried to keep it compatible with 2.2, so you might well be able to just download it and compile it with 2.2 like any other third-party module. If that fails, let me know and I'll see if I can't steer you in the right direction. Failing all that, if your data is very well-behaved, you can write valid CSV data quite easily. Given a list of lists like so: data = [ [1, 2, 4, "My data"], ["abc", "def", "ghi"], ["234234234", 1.2e7, "!@##%^*"], ] you should be able to write it to sys.stdout with something like (untested): for row in data: row = [str(e) for e in row] print '"' + '","'.join(row) + '"' Note that the data above doesn't include quotation marks in any of the fields, the separator is always a comma, and all output will be fully quoted. Also, it assumes you're on Windows where you'll automatically get CRLF terminators. You should be able to fairly easily extend the above code to handle those situations. Skip From mike at triplepc.com Tue Jan 6 10:23:01 2004 From: mike at triplepc.com (Michael T. Babcock) Date: Tue, 06 Jan 2004 10:23:01 -0500 Subject: Pre-PEP: new Path class In-Reply-To: References: Message-ID: <3FFAD2D5.8020209@triplepc.com> > > >So you're saying that a file object or a directory object "has-a" >path object? Sounds right to me. > > Correct; a path object should be a path, not a file, not a directory, but a path. I see comments about allowing 'touch' or 'chmod' or other such file-centric methods. I can even understand 'chmod' (in Unix environments) since all path objects have permissions, but this would be platform specific anyway. What's wrong with something like posix.chmod(path_object, permissions)? Anyway, enough of my rant for the moment. -- Michael T. Babcock From sancelot at free.fr Thu Jan 15 05:25:04 2004 From: sancelot at free.fr (stephane ancelot) Date: Thu, 15 Jan 2004 11:25:04 +0100 Subject: is it possible to create a win binary file from .py files ? Message-ID: <200401151125.04886.sancelot@free.fr> Hi, I am new to python and I would like to know if there are some ways to provide a binary file as target . Because my projects may contain lot of py files and I do not want to provide source files . for maintenance puproses it is too easier for me to send only one file to my customer. Best Regards Steph From ericavel at badgirl.com Mon Jan 12 20:24:47 2004 From: ericavel at badgirl.com (ericavel at badgirl.com) Date: Mon, 12 Jan 2004 20:24:47 -0500 Subject: code Really low price offer New XP Software task Message-ID: <8RafSsQWjBIi.koRSddyht9kP@badgirl.com> Hello Python-list I found This job unique site always done Windows XP Pro legal - 39.95$ site Office XP Pro access - 59.95$ http://spacert.org/cgi-bin/view.cgi?s=eri&m=ULQcVW-YbRQ.ULQcVW,VSd Best Software online here just wanna Best regards From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Jan 11 18:44:08 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 12 Jan 2004 00:44:08 +0100 Subject: Python installation breaks Outlook Express References: Message-ID: Hi ! I use P2.3.3 and O.E. without pb ?!? Suggest : perhaps is your wife buggued ? ;o) Michel Claveau From alanmk at hotmail.com Mon Jan 19 09:38:50 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 19 Jan 2004 14:38:50 +0000 Subject: Looking for very simple general purpose tokenizer References: Message-ID: <400BEBFA.49815910@hotmail.com> Maarten van Reeuwijk wrote: > I need to parse various text files in python. I was wondering if > there was a general purpose tokenizer available. Indeed there is: python comes with batteries included. Try the shlex module. http://www.python.org/doc/lib/module-shlex.html Try the following code: it seems to do what you want. If it doesn't, then please be more specific on your tokenisation rules. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= splitchars = [' ', '\n', '=', '/',] source = """ thisshouldcome inthree parts thisshould comeintwo andso/shouldthis and=this """ import shlex import StringIO def prepareToker(toker, splitters): for s in splitters: # resists People's Front of Judea joke ;-D if toker.whitespace.find(s) == -1: toker.whitespace = "%s%s" % (s, toker.whitespace) return toker buf = StringIO.StringIO(source) toker = shlex.shlex(buf) toker = prepareToker(toker, splitchars) for num, tok in enumerate(toker): print "%s:%s" % (num, tok) #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Note that the use of the iteration based interface in the above code requires python 2.3. If you need it to run on previous versions, specify which one. regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Jan 11 18:48:15 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 12 Jan 2004 00:48:15 +0100 Subject: delete file with zipfile References: <4ADeXb$9SJ@wretch.csie.nctu.edu.tw> Message-ID: :-) From nospam-deets at web.de Tue Jan 13 11:17:35 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Tue, 13 Jan 2004 17:17:35 +0100 Subject: (no subject) References: Message-ID: Hi, first of all: subjects are important - believe me. This is a question on serial port access, so you should have mentioned that. > I have read some of the documentation in Python. > Before using Python as our project language it would be useful to know > whether Python has functions, libraries/headers (like C does) capable of > handling the foll. : > > 1] open and close serial ports, > 2] set baud rates, > 3] check parity bit/byte, > 4] stop bits, > 5] Hardware handshaking, > 6] selection of port,...... There exists the very nice pyserial module, which makes serial access a charm in a os-neutral manner - you can even use jython (python on top of java) when you install javacom. I use it in several projects, and it e.g. allows DTR control and the like. I suggest you dive into the docs at pyserial.sf.net Diez From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Jan 13 09:03:50 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 13 Jan 2004 15:03:50 +0100 Subject: Python In-Reply-To: References: Message-ID: <4003fac6$0$319$e4fe514c@news.xs4all.nl> sandhya wrote: > How to generate a .pyd file from a c++ file?? http://www.python.org/doc/faq/extending.html http://www.python.org/doc/current/ext/ext.html --Irmen From fumanchu at amor.org Fri Jan 2 16:31:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 2 Jan 2004 13:31:51 -0800 Subject: Conditional except: blocks Message-ID: Aahz wrote: > That's pretty sick. If you really need to do that, here's a more > Pythonic approach: > > # This goes at beginning of program > # or maybe at class/instance initialization > if trapErrors: > exceptTuple = (Exception,) > else: > exceptTuple = (None,) > > # some time later > try: > return nextHandler(args) > except exceptTuple, exc: > # Handle exception Sure, sure. The point was not so much the JIT tuple-unpacking as it was the (conditional) use of None in the "except" expression. BTW, I don't think you need a tuple at all. Might we just as well write: if trapErrors: exceptTuple = Exception else: exceptTuple = None ? FWIW (and just to start a flame war ;) I tend to avoid using a flag (like 'trapErrors'), only to trigger such an intermediate step as the above. I get antsy when that intermediate value gets used "some time later". If I were to do something like the above, it would be put immediately before the actual use. The other option would be to have whoever is setting trapErrors (to True or False) instead directly set exceptTuple to Exception, None, or what-have-you. Robert Brewer MIS Amor Ministries fumanchu at amor.org From exarkun at intarweb.us Fri Jan 16 15:58:22 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 16 Jan 2004 15:58:22 -0500 Subject: Supressing PyChecker warnings Message-ID: <20040116205822.GA27418@intarweb.us> When using PyChecker on a project which uses bsddb, dozens of messages like the following are reported: warning: couldn't find real module for class bsddb._db.DBAccessError (module name: bsddb._db) I've looked through the PyChecker usage information, documentation, and browsed some of the source, but I can't find any options for supressing this. Is it possible? If so, how? Thanks in advance, Jp From premshree_python at yahoo.co.in Tue Jan 13 06:38:14 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 13 Jan 2004 11:38:14 +0000 (GMT) Subject: how can I execute a function string In-Reply-To: Message-ID: <20040113113814.4038.qmail@web8306.mail.in.yahoo.com> You need to use eval() to run code on-the-fly. See http://www.python.org/doc/current/lib/built-in-funcs.html --- Rajarshi Guha wrote: > Hi , > I have some code that generates a function on the > fly in a string. > At a later point in time I want to execute this > function (which also > requires a parameters to be passed to it). So the > code is something like > this: > > def generate_func(): > s = """ def function(x): > print x > return 2 > """ > return s > > funcstring = generate_func() > retval = .... > > That is, retval should have the value returned from > the evaluation of the > function in the string funcstring. > > Is this possible by means of simple function calls > or does this involve > some sort of black magic? > > Thanks, > -- > http://mail.python.org/mailman/listinfo/python-list ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From ajsiegel at optonline.com Tue Jan 13 13:00:58 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 13 Jan 2004 18:00:58 GMT Subject: Does anyone else not find the fun in programming...? References: Message-ID: On 13 Jan 2004 08:23:46 -0800, chris.lyon at spritenote.co.uk (Chris Lyon) wrote: >I find python very effective as a language and can generally project >most of my hazy thoughts into it. But FUN !!! This is work dammit, >I have now ground my teeth down from the number of times I read that >programming is fun. Football (association) is fun, walking along >canals is fun, Arguing about quite how useless the British Government >is fun but programming ? > I reserve Python for fun, i.e. use it for projects having no $ motive. Scheduling Python work on "when the mood stkes me" basis, i.e. unscheduled. >Do I need help ? Since, for me, it's most particularly fun when I *should* be doing something else: it would seem, I do. Art From python at quixs.com Thu Jan 15 13:47:05 2004 From: python at quixs.com (Lars Heuer) Date: Thu, 15 Jan 2004 19:47:05 +0100 Subject: needed PyXPCOM tutorial. In-Reply-To: <1689232226.20040115193843@quixs.com> References: <425cc8d1.0401150908.287de0d8@posting.google.com> <1689232226.20040115193843@quixs.com> Message-ID: <1576652975.20040115194705@quixs.com> Hi, > It seems, that the pyXPCOM architecture isn't widely used; this > mailinglist is also very silent. ;) Sorry, I meant the pyXPCOM mailinglist, this mailinglist isn't silent, of course. :) BTW: Are there any known apps which are using Mozilla as platform (beside Komodo), OpenSource apps? Thanks, Lars From francisgavila at yahoo.com Tue Jan 13 20:55:35 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 13 Jan 2004 20:55:35 -0500 Subject: Unicode and exception strings References: Message-ID: <1009fh9tdkk5d70@corp.supernews.com> Terry Carroll wrote in message ... >On 12 Jan 2004 08:41:43 +0100, Rune Froysa >wrote: >The only thing is, what to do with it once you get there. I don't think >0xF8 is a valid unicode encoding on its own. IIRC, it's part of a >multibyte character. Yes, about that. What are the semantics of hexadecimal literals in unicode literals? It seems to me that it is meaningless, if not dangerous, to allow hexadecimal literals in unicode. What code point would it correspond to? 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. >>> u'\xf8\u00f8'.encode('unicode-internal') '\xf8\x00\xf8\x00' I get the same on linux with Python 2.2.1, x86. So, is a hexadecimal literal a shorthand for \u00XX, i.e., unicode code point XX? Or does it bypass the code point abstraction entirely, preserving the raw bits unchanged for any encoding of the unicode string (thus rendering unicode useless)? Once again, I don't see why hexadecimal literals should be allowed at all, except maybe for compatability when moving to Python -U behavior. But I submit that all such code is broken, and should be fixed. If you're using hexadecimal literals, what you have is not a unicode string but a byte sequence. This whole unicode/bytestring mess is going to have to be sorted out eventually. It seems to me that it would be best to have all bare string literals be unicode objects (henceforth called 'str' or 'string' objects?), drop the unicode literal, and make a new type and literal prefix for byte sequences, possibly dropping the traditional str methods or absorbing more appropriate ones. Perhaps some struct functionality could be folded in? Of course, this breaks absolutely everything. -- Francis Avila From maketo at norge.freeshell.org Thu Jan 15 00:45:27 2004 From: maketo at norge.freeshell.org (Ognen Duzlevski) Date: Thu, 15 Jan 2004 05:45:27 +0000 (UTC) Subject: Numeric Python and C References: Message-ID: John Hunter wrote: >>>>>> "Ognen" == Ognen Duzlevski writes: > Ognen> Hi, can someone explain how to change a value within an > Ognen> array from a C function? > Warning: I am not a Numeric C API guru. > For 1D arrays I use the following macro [snipped] > You'll have to do a bit more work for 2D arrays, but this may speed > you on your way.... Hi, for 2D arrays it is much similar: get(ndx1,ndx2): array->data + ndx1*array->strides[0] + ndx2*array->strides[1] set(ndx1,ndx2): I use memcpy(same as get, &val, sizeof(val); Thanks, Ognen From bac at OCF.Berkeley.EDU Sat Jan 10 23:38:26 2004 From: bac at OCF.Berkeley.EDU (Brett) Date: Sat, 10 Jan 2004 20:38:26 -0800 Subject: python-dev Summary for 2003-12-01 through 2003-12-31 Message-ID: <4000D342.3010503@ocf.berkeley.edu> python-dev Summary for 2003-12-01 through 2003-12-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from December 1, 2003 through December 31, 2003. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the thirty-first and -second summaries written by Brett Cannon (a friend of a friend actually reads this thing! Hi, Elle). 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 something mentioned here. PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. 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 .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2003-10-16_2003-11-15.html ===================== Summary Announcements ===================== Sorry if this summary comes off as light, but I caught the flu the week of Christmas and it developed into walking pneumonia which I still have. On a more positive note, PyCon is hitting its stride. Online registration is available at http://pycon.org/dc2004 and early bird registration ends January 31. Online talk proposal submission is online at http://submit.pycon.org/ and the deadline is January 15. ========= Summaries ========= ---------------------------- 2.3.3 released to the masses ---------------------------- `Python 2.3.3`_ has gone out the door. Thanks to Anthony Baxter for being release manager (again!) and to all of python-dev and anyone who contributed code for this release. With this being a bugfix release this supercedes 2.3.2 and thus people should upgrade if possible. .. _Python 2.3.3: http://python.org/2.3.3/ Contributing threads: - `2.3.3 cycle `__ - `release23-maint branch CLOSED for release `__ - `Berkeley support in release23-maint `__ - `RELEASED Python 2.3.3 (release candidate 1) `__ - `2.3.3 portability audit `__ - `2.3.3 and beyond `__ - `RELEASED Python 2.3.3 (final) `__ - `status of 2.3 branch for maintenance checkins `__ ---------------------------------- Pie-thon competition work ramps up ---------------------------------- `Dan Sugalski`_, project leader of the Parrot_ VM that will be used for `Perl 6`_, reminded the list that the benchmark to be used for the `Pie-thon`_ needed to be written since the bytecode for the benchmark needed to be frozen. So Guido wrote some benchmarks. They are in CVS under nondist/sandbox/parrotbench . .. _Dan Sugalski: http://www.sidhe.org/~dan/blog/ .. _Parrot: http://www.parrotcode.org/ .. _Perl 6: http://dev.perl.org/perl6/ .. _Pie-thon: http://www.sidhe.org/~dan/blog/archives/000219.html Contributing threads: - `Merry December `__ - `Pie-thon benchmarks `__ - `Pie-thon benchmark code ready `__ -------------- PyCon is a go! -------------- http://www.pycon.org/ has gone live! Registration_ is live (early-bird ends January 31)! Online talk proposal submission is live (deadline is January 15)! .. _Registration: http://www.pycon.org/dc2004 Contributing threads: - `PyCon DC 2004 - Registration about to open! `__ - `PyCon DC 2004 - Submissions Now Open `__ ---------------------------------------- operator gains attrgetter and itemgetter ---------------------------------------- The operator module has now gained two new functions: attrgetter and itemgetter "which are useful for creating fast data extractor functions for map(), list.sort(), itertools.groupby(), and other functions that expect a function argument" according to Misc/NEWS . Contributing threads: - `Re: "groupby" iterator `__ ------------------- CObjects and safety ------------------- Michael Hudson pointed out how CObjects could be misused in Python code. Various ideas of how to make them safer by checking that the proper CObject was passed were proposed. The thread seemed to end without a resolution, though. Contributing threads: - `are CObjects inherently unsafe? `__ ----------------- Unicode is a pain ----------------- Want proof? How about the fact that you can store a character like "??" either as two characters ("a" followed by "previous character has an umlaut") or as one ("a with an umlaut"). The former is called "decomposed normal form" and is used in OS X. Windows, of course, uses the latter version. Contributing threads: - `test_unicode_file failing on Mac OS X `__ ------------------ Two new developers ------------------ Hye-Shik Chang has become a developer. You probably know him from his work on the CJK codecs. He is now an official developer. Vinay Sajip, implementor of the logging package has also been granted CVS checkin rights. Contributing threads: - `New developer `__ ------------------------ Compiling 2.4 under .NET ------------------------ Martin v. L?wis has started sandbox work on an MSI installer and moving Python 2.4 over to VC 7. Contributing threads: - `Py2.4 pre-alpha snapshot `__ - `First version of Python MSI available `__ - `Switching to VC.NET 2003 `__ ----------------------------- New method flag: METH_COEXIST ----------------------------- Raymond Hettinger, in his continual pursuit of speed, came up with a new method flag, METH_COEXIST, which causes a method to be used in place of a slot wrapper. The example that actually led to this is __contains__: a PyCFunction defining __contains__ tends to be faster than one in the sq_contains slot thanks to METH_O and other tricks. Contributing threads: - `FW: METH_COEXIST `__ ------------------------------ Better relative import support ------------------------------ There was a huge discussion on a better way to handle relative imports (think of the situation where you have your module ``import sys`` and you happen to have a module named sys in the same directory; should that local module be imported or the sys module from the stdlib?). Luckily Aahz volunteered to write a PEP on the whole thread so I am being spared from having to summarize the thing. =) Thanks, Aahz. Contributing threads: - `Re: Christmas Wishlist `__ - `Re: Python-Dev Digest, Vol 5, Issue 57 `__ - `Relative import `__ - `Another Strategy for Relative Import `__ ------------------------------ list.sorted becomes a built-in ------------------------------ Just as the title says, list.sorted has now been moved out of the list type and has been made a built-in. Contributing threads: - `python/dist/src/Python bltinmodule.c,2.304,2.305 `__ -------------------------------- What to do with old Python code? -------------------------------- Someone rewrote the bisect module in C. This brought up the question of what to do with the old Python version. Some suggest moving it to the Demo directory. Others suggest keeping the code but importing the C version in the Python module. The idea of keeping both was quickly shot down, though, like in the pickle/cPickle situation. This discussion is still going at this time. Contributing threads: - `SF patch 864863: Bisect C implementation `__ From steve at ninereeds.fsnet.co.uk Sat Jan 31 05:45:31 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sat, 31 Jan 2004 10:45:31 +0000 Subject: PEP 327: Decimal Data Type References: Message-ID: On 31 Jan 2004 01:01:41 -0800, danb_83 at yahoo.com (Dan Bishop) wrote: >I disagree. >But even if the number base of a measurement doesn't matter, precision >and speed of calculations often does. And on digital computers, >non-binary arithmetic is inherently imprecise and slow. Imprecise >because register bits are limited and decimal storage wastes them. >(For example, representing the integer 999 999 999 requires 36 bits in >BCD but only 30 bits in binary. Also, for floating point, only binary >allows the precision-gaining "hidden bit" trick.) Slow because >decimal requires more complex hardware. (For example, a BCD adder has >more than twice as many gates as a binary adder.) I think BSD is a slightly unfair comparison. The efficiency of packing decimal digits into binary integers increases as the size of each packed group of digits increases. For example, while 8 BCD digits requires 32 bits those 32 bits can encode 9 decimal digits, and while 16 BCD digits requires 64 bits, those digits can encode 19 decimal digits. The principal is correct, though - binary is 'natural' for computers where decimal is more natural for people, so decimal representations will be relatively inefficient even with hardware support. Low precision because a mantissa with the same number of bits can only represent a smaller range of values. Slow (or expensive) because of the relative complexity of handling decimal using binary logic. >> Perhaps a generalized BaseN module is called for. People >> could then generate floating point numbers in any base (up to perhaps >> base 36, [1-9a-z]). >> ... Of course then you have the same problem with doing math on two >> different bases as with doing math on rational numbers. > >Actually, the problem is even worse. > >Like rationals, BaseN numbers have the problem that there are multiple >representations for the same number (e.g., 1/2=6/12, and 0.1 (2) = 0.6 >(12)). But rationals at least have a standardized normalization. We >agree can agree that 1/2 should be represented as 1/2 and not >-131/-262, but should BaseN('0.1', base=2) + BaseN('0.1', base=4) be >BaseN('0.11', 2) or BaseN('0.3', 4)? I don't see the point of supporting all bases. The main ones are of course base 2, 8, 10 and 16. And of course base 8 and 16 representations map directly to base 2 representations anyway - that is why they get used in the first place. If I were supporting loads of bases (and that is a big 'if') I would take an approach where each base type directly supported arithmetic with itself only. Each base would be imported separately and be implemented using code optimised for that base, so that the base wouldn't need to be maintained by - for instance - a member of the class. There would be a way to convert between bases, but that would be the limit of the interaction. If I needed more than that, I'd use a rational type - I speak from experience as I set out to write a base N float library for C++ once upon a time and ended up writing a rational instead. A rational, BTW, isn't too bad to get working but that's as far as I got - doing it well would probably take a lot of work. And if getting Base N floats working was harder than for rationals, getting them to work well would probably be an order of magnitude harder - for no real benefit to 99% or more of users. Just because a thing can be done, that doesn't make it worth doing. >but what if that base is greater than >36 (or 62 if lowercase digits are distinguished from uppercase ones)? For theoretical use, converting to a list of integers - one integer representing each 'digit' - would probably work. If there is a real application, that is. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From galfip at freestart.hu Tue Jan 20 02:59:03 2004 From: galfip at freestart.hu (Peter Galfi) Date: Tue, 20 Jan 2004 08:59:03 +0100 Subject: Fw: PDF library for reading PDF files References: <400BFF7B.95F21050@netsurf.de> Message-ID: <017601c3df2b$4595d160$7800a8c0@mailer> Thanks. I am studying the PDF spec, it just does not seem to be that easy having to implement all the decompressions, etc. The "information" I am trying to extract from the PDF file is the text, specifically in a way to keep the original paragraphs of the text. I have seen so far one shareware standalone tool that extracts the text (and a lot of other formatting garbage) into an RTF document keeping the paragraphs as well. I would need only the text. Any suggestions? Peter ----- Original Message ----- From: "Andreas Lobinger" Newsgroups: comp.lang.python To: Sent: Monday, January 19, 2004 5:02 PM Subject: Re: Fw: PDF library for reading PDF files Aloha, > Peter Galfi schrieb: > I am looking for a library in Python that would read PDF files and I > could extract information from the PDF with it. I have searched with > google, but only found libraries that can be used to write PDF files. > Any ideas? Use file, split, zlib and a broad knowledge of the PDF-spec... Accessing certain objects in the .pdf is not that complicated if you f.e. try to read the /Info dictionary. Getting text from actual page content could be very complicated. Can you explain your 'information' further? Wishing a happy day LOBI -- http://mail.python.org/mailman/listinfo/python-list From anthony at interlink.com.au Wed Jan 14 10:02:40 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 15 Jan 2004 02:02:40 +1100 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: <20040114150240.72A6925AF47@bonanza.off.ekorp.com> >>> Bent C Dalager wrote > I've always thought of Cygwin as > > 1) an excellent way to run the Unix-like tools that I know and love and > > 2) a useful intermediate step while porting an app to Windows. Ah. But with MinGW on top of Cygwin, you get to use Unix tools, yet build genuine Windows apps. Best of both worlds, for those of us who can't stand the one enormous GUI style of software development. -- Anthony Baxter It's never too late to have a happy childhood. From cygnus at cprogrammer.org Wed Jan 28 11:42:02 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Wed, 28 Jan 2004 11:42:02 -0500 Subject: wxPython: images from URLs In-Reply-To: <84fc4588.0401280613.771ac07@posting.google.com> References: <84fc4588.0401280613.771ac07@posting.google.com> Message-ID: <20040128164202.GA15726@mail.theserver.ath.cx> # self._imgstream = urllib2.urlopen(url).read() # stream=cStringIO.StringIO(self._imgstream) # # try: # img=wxImageFromStream(stream) # except: # pass I have tried this and it appears to work, but once I have the image (from wxImageFromStream), I use it as follows: try: bm = wxBitmap(img) self.bitmap.setBitmap(bm) except Exception, e: print e And the exception (raised by wxBitmap(img)) is: String or Unicode type required (The exception is a TypeError exception.) Any ideas? No exceptions are raised by the block that creates the image from the data stream. The image is a JPG image, and I pass wxBITMAP_TYPE_JPEG to wxImageFromStream. I have also tried omitting it as well. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From jnoller at reference-info.com Wed Jan 21 11:00:39 2004 From: jnoller at reference-info.com (Jesse Noller) Date: 21 Jan 2004 08:00:39 -0800 Subject: problems iterating over a files lines Message-ID: <2835a96b.0401210800.4b89d878@posting.google.com> I am a relative newbie to python and I am having issues trying to iterate over the lines of a file. I have a text file - foo.bar inside of this file are lines of text: x-3411342 y-1324123 w-2314121 Each with a trailing \n to designate the end of the line. I am trying to read this file into python - which is simply in and of itself, however: file = open("foo.bar", "rb") while 1: lines = file.open().split('\n'): if not lines: break for lines in lines: key = line get.key(key) results = [key, get.up, get.down] file.close() Appends an extra "blank" line to the list of lines, which causes the program to crash - secondly, I've looked at about 20 examples, and all of them (including this one) suffer from the problem of looping over the lines for the number of lines. What I want to do is open the contents of the file - read the line and set a variable - key, and for each line in the file, I want to do something with that key - but only once. So I want to read in a line, set to a variable, do something, print, and then do it for the next line. Any help is appreciated. Thank you. From johnfabel at btinternet.com Wed Jan 21 14:35:55 2004 From: johnfabel at btinternet.com (John Abel) Date: Wed, 21 Jan 2004 19:35:55 +0000 Subject: Python database In-Reply-To: <3jmq001uhc0nbdartig19sbfovoo520g0a@4ax.com> References: <3jmq001uhc0nbdartig19sbfovoo520g0a@4ax.com> Message-ID: <400ED49A.60800@btinternet.com> My apologies for that. That'll teach me not to expand my mail window! Dennis Lee Bieber wrote: >On Tue, 20 Jan 2004 11:12:21 +0000, John Abel >declaimed the following in comp.lang.python: > > > >>*Have a look at gadfly, gadfly.sf.net >>* >> >> > He did... and said so... > > >>Brice Vissi?re wrote: >> >> >> > > > > >>>My first thought was to use Gadfly. I've downloaded and installed it. >>>Now, I'm investigating the documentation and examples to find string >>>capabilities of Gadfly, but at first look, it seems that it will not >>>fit to my needs. >>> >>> > > Must be an obscure paragraph... > >-- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > > From scott.b.drummonds.nospam at intel.com Tue Jan 27 14:48:28 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Tue, 27 Jan 2004 11:48:28 -0800 Subject: PyObject_Size Message-ID: Hi, everyone, I'm seeing a problem in a legacy Python script in a tool I use where the script is unable to load a shared library. Version 1.5.2 of Python complains that "...undefined symbol: PyObject_Size" while more recent versions work just fine. I presume that what's going on is that older versions of Python required shared libraries that are Python-loadable to have this function (which I realize returns an object's size) specified. It also appears that new versions don't require this function any more. What happened in between that old version and the current ones with regards to this symbol? Why was this required before but not any longer? Thanks, Scott -- Remove ".nospam" from the user ID in my e-mail to reply via e-mail. From mmoum-xxxspam at woh.rr.com Fri Jan 16 18:46:05 2004 From: mmoum-xxxspam at woh.rr.com (DoubleM) Date: Fri, 16 Jan 2004 23:46:05 GMT Subject: Tkinter: modal ok in windows, but not in Linux References: Message-ID: <1J_Nb.5971$372.2045@fe1.columbus.rr.com> Eric Brunel wrote: > This won't however solve the OP's problem, which is that the main window > can still be closed when the second window is running. > > We've had the same problem, and I finally ended up thinking this problem's > is not Python's fault, nor Tkinter's one, nor even tk's one: with X11, the > controls on the window frame are actually managed not by the client > application (from the X11 server point of view), but by the window > manager. If the window manager decides to ignore the grab set on one of > your windows and to continue to treat events for the other windows, you're > stuck. The only thing you can do is treating the window deletion event to > explicitely ignore it via a root.protocol('WM_DELETE_WINDOW', ...). There > may be a way of doing it automatically at tk's level, but it would > certainly be a big work, not to mention that there may be some window > managers that *do* take the grab_set into account, and so where this work > would be unnecessary. Thanks for the replies. I rather suspected as much, given that it works find in Windows XP, but was hoping I was wrong. Mike From quentel.pierre at wanadoo.fr Sat Jan 24 02:42:32 2004 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 24 Jan 2004 08:42:32 +0100 Subject: Server and Client Socket problem References: Message-ID: Apart from indentation, you had forgotten the "try" statement in client This should work better : Client --------------------- import socket def run(): try: cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cliente.connect(('localhost', 6969)) except: print "No he podido Conectar con el Servidor" return datos = '12345678' cliente.send(datos) #cliente.close() run() --------------------- Server --------------------- import socket def run(): servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servidor.bind(('localhost', 6969)) servidor.listen(1) while 1: (conexion, direccion) = servidor.accept() datos = conexion.recv(4069) print "Servidor Recibe", datos if datos == "quit": servidor.close() break run() --------------------- @+ Pierre From a.schmolck at gmx.net Thu Jan 8 07:59:03 2004 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 08 Jan 2004 12:59:03 +0000 Subject: Descriptor puzzlement References: Message-ID: "John Roth" writes: > What's happening here? cf. class AnotherObject(object): prop = AnObject("snafu") 'as From mbabcock at fibrespeed.net Fri Jan 9 10:45:06 2004 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 09 Jan 2004 10:45:06 -0500 Subject: Database interfacing Message-ID: <3FFECC82.20305@fibrespeed.net> I'm working with databases (MySQL primarily) more and more with Python, and having used PERL in the past for similar work, I'm wondering if there are good tools for doing 'intelligent' selects/inserts to/from dictionaries, etc. For example: data = {'FirstName': 'Michael', 'LastName': 'Babcock', 'Age': 99} lastid = db.insert('Users', data) ... which would execute "INSERT INTO Users (FirstName, LastName, Age) VALUES ('Michael', 'Babcock', 99)" And also helpful would be: data = db.query("dbname", "SELECT * FROM Users WHERE Age >= 99)") ... which would return me an array of dictionary items like: [ {'ID': 143, 'FirstName': 'Michael' ... }, {'ID': 242, ... }, ... ] Just curious, thanks (I've written a piece of code to generate the array of dictionary results myself actually, but I'm sure someone else's is better). -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From martin at v.loewis.de Sun Jan 18 16:56:19 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 18 Jan 2004 22:56:19 +0100 Subject: parse binary file in python? In-Reply-To: References: Message-ID: Andreas R?sdal wrote: > I want to parse a binary file in python. Does > python have some built in methods for doing this easily? > Any links to example code would be nice.. Depends on the kind of parsing you want to do. Python can naturally represent binary files in string objects, e.g. f = open("binaryfile.bin", "rb") # notice the b for binary mode data = f.read() f.close() You can then look at the individual bytes by index. People often use the struct and array modules to simplify processing. Whether or not you would call this "parsing", I don't know (for me, "parsing" implies presence of a context-free or regular grammar of some kind). Regards, Martin From me at here.there.com Wed Jan 14 15:09:16 2004 From: me at here.there.com (Peter Ashford) Date: Thu, 15 Jan 2004 09:09:16 +1300 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: >> >>Why do you think OS developers owe you any kind of value at all? > > > I don't. But that's not going to stop me from denigrating them for being > incapable of fulfillng the kinds of projects I have in mind. That's like criticising a high class restraunt for not serving burgers. If they don't propose to solve your particular needs, criticising them for not doing so is stupid and redundant. Many OS projects have aims which they fail to reach (often "completion" is one of those) and it is fair to criticise them for those failings. However it is utterly myopic to criticise them for not reaching aims to which they don't aspire - like being your bunch of personal slaves. It would just as dumb as me criticising you for not advancing OS software - you've never intended to, don't care, so the criticism would be stupid. Peter. From bart_nessux at hotmail.com Thu Jan 8 22:31:16 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 08 Jan 2004 22:31:16 -0500 Subject: convert a list to a string References: <3FFE1E29.20801@hotmail.com> <7xwu81dcr7.fsf@ruckus.brouhaha.com> Message-ID: <3FFE2084.7010700@hotmail.com> Paul Rubin wrote: > Bart Nessux writes: > >>number = random.sample(range(count), 1) >> >>This makes 'number' into a one entry list (I don't know why as 'count' >>is an integer). Is there an easy way to convert 'number' back to an >>int? > > > number = number[0] > > But why are you using random.sample for that? And making a list of > size count, just to throw it away? It sounds like you just want a > random number between zero and count. Do that with: > > number = random.randint(count) How does randint and sample differ? I was under the impression that sample was more random. From peter at engcorp.com Thu Jan 8 10:03:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Jan 2004 10:03:53 -0500 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> Message-ID: <3FFD7159.55630AE0@engcorp.com> Thomas Weholt wrote: > > My advice ( I got some experience in all of them ) : > > Medusa is old and you have to do alot yourself. You have to know abit about > HTTP, how async works etc. Get ready to get your hands dirty. > > Twisted is similar to Medusa, but comes with a bunch of very cool > ready-to-use/more-or-less-stable modules which can be combined into complex Heh. :-) Twisted is similar to Medusa in about the same way that Linux is similar to, say, CPM... -Peter From mwh at python.net Fri Jan 23 07:23:39 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 23 Jan 2004 12:23:39 GMT Subject: debugging References: <88bc63c6.0401230416.7acf904c@posting.google.com> Message-ID: writeson at earthlink.net (Doug Farrell) writes: > Hi all, > > Can someone help me out a little with Python? What do people use to > debug Python code? I don't understand how to use the built in > debugger What have you tried? pdb.run('...') and pdb.set_trace() may be your friends. > and I haven't had any luck getting ddd to debug my Python programs. I > end up falling back on inserting print statements in my code to figure > out what's going on. This works but isn't always the fastest route to > a solution. So, I'm just wondering what other people do. Well, quite a lot of the time I ... insert print statements in my code. I also find stopping and actually thinking hard every now and again helps, too :-) Cheers, mwh -- ARTHUR: Yes. It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard". -- The Hitch-Hikers Guide to the Galaxy, Episode 1 From jcarlson at uci.edu Mon Jan 19 22:11:54 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 19 Jan 2004 19:11:54 -0800 Subject: speedy Python strings? References: Message-ID: <20040119185543.ABC7.JCARLSON@uci.edu> > Another possibility is to buffer things in a list, using append to add > to the end and pop(0) to pop off the front (a roll-your-own queue). > Lists do not suffer from the quadratic behavor that string addition does. Deleting from the front of a list results in every item being shifted up a single entry. While this is insignificant for short lists, it is significant for long lists: >>> def del_from_front(size): ... a = range(size) ... t = time.time() ... while a: a.pop(0) ... return time.time()-t ... >>> del_from_front(1000) 0.016000032424926758 >>> del_from_front(10000) 0.85899996757507324 >>> del_from_front(20000) 3.2970001697540283 >>> def del_from_end(size): ... a = range(size) ... t = time.time() ... while a: a.pop() ... return time.time()-t ... >>> del_from_end(10000) 0.062999963760375977 >>> del_from_end(100000) 0.51600003242492676 >>> del_from_end(1000000) 5.4530000686645508 In terms of buffering as the parent post asks, file IO is already buffered by the underlying libraries and operating system. Another layer of Python buffering doesn't seem to make much sense. I would suggest writing off the buffering exercise as a learning experience. - Josiah From shatf at zoominternet.net Mon Jan 12 10:37:54 2004 From: shatf at zoominternet.net (Scott Hatfield) Date: Mon, 12 Jan 2004 10:37:54 -0500 Subject: win32com - date parameter for crystal reports Message-ID: <6.0.0.22.0.20040112102744.01d75648@pop3.zoominternet.net> Hello, all. I'm a newbie to Python and am using it to interface with crystal reports via com/activex. I have had wonderful success thus far, but am unable to pass a parameter of type 'date.' I tried using a PyTime object, but it would not work for a date parameter. It *does* work for a datetime. I searched comp.lang.python and found one person who had this same problem (though not with crystal reports), but no replies were posted. Can anyone shove me in the right direction? I'm using Python 2.3.2 on WinXP. Much Thanks, Scott From peter at engcorp.com Thu Jan 15 11:23:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Jan 2004 11:23:42 -0500 Subject: Portable filename comparison References: Message-ID: <4006BE8E.9D3BC764@engcorp.com> Ken Dyck wrote: > > Is there a way with Python 2.2 to portably test the equivalence of two > filenames? > > The os.path.samefile function seems to do what I want, but it is only > available on Unix and Mac. I need something that works on Windows. > > The os.path.normcase and os.path.normpath functions are available on all > platforms, but don't quite get me there. For example, on Windows > > >>> os.path.normcase(os.path.normpath("C:\Program Files")) > 'c:\\program files' > >>> os.path.normcase(os.path.normpath("C:\PROGRA~1")) > 'c:\\progra~1' > > I suppose I could find a way to call into the Win32 API directly, but I'd > prefer to use a portable solution if I can find one. I believe you need to make your own, since the whole concept of thus mungled long names on Windows is definitely not portable. Here's a snippet that might make this seem much easier: >>> def expand(shortname): ... from win32api import GetLongPathName ... return GetLongPathName(shortname) ... >>> expand('c:\\progra~1') 'c:\\Program Files' -Peter From simonb at NOTTHISBIT.webone.com.au Wed Jan 14 19:46:29 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Thu, 15 Jan 2004 11:46:29 +1100 Subject: Numeric Python and C References: Message-ID: On Wed, 14 Jan 2004 19:17:55 +0000, Ognen Duzlevski wrote: > Hi, > can someone explain how to change a value within an array from a C > function? > What about using PyObject_GetItem (is that what it's called?) I know numarray uses functions for this: PyArrayObject* NA_InputArray( PyObject *numarray, NumarrayType t, int requires) The purpose of NA_InputArray is to transfer array data from Pythonto C. PyArrayObject* NA_OutputArray( PyObject *numarray, NumarrayType t, int requires) The purpose of NA_OutputArray is to transfer data from C to Python. Practically speaking, the output numarray must be a PyArrayObject, and cannot be an arbitrary Python sequence. PyArrayObject* NA_IoArray( PyObject *numarray, NumarrayType t, int requires) NA_IoArray has fully bidirectional data transfer, creating the illusion of call-by-reference. Simon. From me at privacy.net Thu Jan 29 12:08:41 2004 From: me at privacy.net (Duncan Booth) Date: 29 Jan 2004 17:08:41 GMT Subject: number of arguments a function takes References: Message-ID: "Elaine Jackson" wrote in news:CSaSb.329909$ts4.189798 at pd7tw3no: > Suppose one of the arguments of a function f_1 is another function > f_2. Can f_1 access the number of arguments taken by f_2? (I'm > writing a little script to automate the construction of logical > truth-tables.) Thanks. Look at the inspect module, in particular you probably want inspect.getargspec: >>> import inspect >>> def f(a,b): pass >>> inspect.getargspec(f) (['a', 'b'], None, None, None) >>> help(inspect.getargspec) Help on function getargspec in module inspect: getargspec(func) Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. >>> From skip at pobox.com Sat Jan 31 10:58:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 31 Jan 2004 09:58:59 -0600 Subject: zlib In-Reply-To: References: Message-ID: <16411.53443.579705.529891@montanaro.dyndns.org> Dave> I am looking for a zlib implementation (or any other which can Dave> handle zip archives) for Python 1.5.2. I only found one for Python Dave> >= 2.2 :-( Assuming you have access to a C compiler, you might be able to fairly easily backport the 2.2 version of zlibmodule.c back to 1.5.2. Skip From aahz at pythoncraft.com Tue Jan 27 12:58:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2004 12:58:41 -0500 Subject: How does compare work? References: <40158680$0$7044$ba620e4c@news.skynet.be> <4016A368.9050806@skynet.be> Message-ID: In article <4016A368.9050806 at skynet.be>, Helmut Jarausch wrote: > >First let me say that IMHO this is a big misdesign of Python. Guido has come around to this POV. However, being able to compare different types does have some defensibility. Your example of an ``if`` isn't directly relevant; what's more important is the question of sorting a list containing arbitrary information. This is particularly true for the case of something like extracting keys from a dict -- you don't want an exception raised. What may well happen is that sort comparisons get a different set of special methods than relational operators. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From aahz at pythoncraft.com Fri Jan 9 13:01:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2004 13:01:55 -0500 Subject: Python 2.3.3 compilation problems an HP-UX References: Message-ID: In article , Olaf Meyer wrote: > >I'm having some problems compiling Python 2.3.3 on HP-UX (B.11.00). >I've tried sevral different options for the configure script (e.g. >enabling/disabling gcc, aCC) but I always get the same problem during >the final linking stage. Several PyThread_* symbols are undefined (for >details see the output below). I'd suggest that you look at the recent threads about compiling for HP-UX on python-dev. It's starting to look like a SIG might be a good way to go. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From newsgroups at jhrothjr.com Thu Jan 15 12:48:20 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Jan 2004 12:48:20 -0500 Subject: TUPLE & LIST References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <100dkld62mibs8a@news.supernews.com> "Yomanium Yoth Taripo?t II" wrote in message news:%7xNb.55$Uw3.50 at newsr2.u-net.net... > HI, > > 1) what are the differences between list and tuple? > 2) how to concatenate tuple and list? no method, no op?rator? > 3) im looking the manual, and can't add value in my tuple, when it > already created :/ > how to do it? Tuples are intended to be a quick way of passing around several heterogenous values. If you find yourself wanting to do anything to a tuple other than creating it and accessing members, then you're trying to do too much. Use a list if the values are of the same type, or create an object to hold whatever it is. John Roth > thx. > > > > From jepler at unpythonic.net Wed Jan 28 18:47:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jan 2004 17:47:54 -0600 Subject: executing an external app In-Reply-To: <101gae65oh6ig72@corp.supernews.com> References: <101gae65oh6ig72@corp.supernews.com> Message-ID: <20040128234754.GA30934@unpythonic.net> Jeff Epler wrote: > >Look at os.spawn* or os.popen* > . > . > . On Wed, Jan 28, 2004 at 09:29:42PM -0000, Cameron Laird wrote: > And os.system(). And commands.getoutput(). [jepler at parrot jepler]$ python -c 'import this' | grep "only one" There should be one-- and preferably only one --obvious way to do it. *sigh* Jeff From Bill.Scherer at verizonwireless.com Thu Jan 22 07:49:15 2004 From: Bill.Scherer at verizonwireless.com (Bill Scherer) Date: Thu, 22 Jan 2004 07:49:15 -0500 Subject: prog/lib to draw graphs In-Reply-To: References: Message-ID: <400FC6CB.6080608@VerizonWireless.com> [P&M] Florian Lindner wrote: >Hello, >I'm looking for a program or python library to draw graphs. >They should look like the that: > > >/--------\ /--------\ >| Node A | ------ belongs to ----> | Node B | >\--------/ \--------/ > Florian - Graphviz (http://www.graphviz.org) is a great package for drawing graphs. It ouputs to many formats. There is a python lib for it at http://www.freshports.org/graphics/py-graphviz/, but I have not used it. It's easy enough to generate dot[1] code and call dot to generate the graph image, so that's what I usually do. HTH, Bill 1. 'dot' is one of the graphviz commands. >Which is a result of the function call like that: > >connectNodes(firstNode, secondNode, description, lineStyle) >connectNodes("Node A", "Node B", "belongs to", dashed) > >It should have a open scalable vector format as output (DVI, SVG, PDF, ...) >and should be able to make automatic optimal placement of the items. >Do you know something like that? >Thx, >Florian > > From michael at foord.net Fri Jan 30 04:03:57 2004 From: michael at foord.net (Fuzzyman) Date: 30 Jan 2004 01:03:57 -0800 Subject: Printing From Python References: <8089854e.0401290555.501f0695@posting.google.com> <7jzahm2e.fsf@python.net> Message-ID: <8089854e.0401300103.8d2a271@posting.google.com> Thomas Heller wrote in message news:<7jzahm2e.fsf at python.net>... > michael at foord.net (Fuzzyman) writes: > > > I looked through the manual, I looked on the web and could find very > > little on this subject.... > > > > The closest I could find was : > > http://www.faqts.com/knowledge_base/view.phtml/aid/4549. > > > > Saying that printing (to a printer :-) wasn't easy (at least on > > windows - let alone *cross* platform) - and that was dated 2000. > > > > Oh and - http://mail.python.org/pipermail/python-list/2002-September/121462.html > > from 2002 giving two different methods for Unix and Windows... the > > windows one doesn't work across our network........ > > Although I am connected to a network printer, I have no problems opening > lpt1:, write some data to it, and the printer prints it: > > C:\>net use > Neue Verbindungen werden gespeichert. > > > Status Lokal Remote Netzwerk > > ------------------------------------------------------------------------------- > [...] > Getrennt LPT1 \\server\lexmarkps Microsoft Windows-Netzwerk > Der Befehl wurde erfolgreich ausgef?hrt. > > > C:\>copy con: lpt1: > hello, world > ^Z > 1 Datei(en) kopiert. > > C:\> > > > Another thing that comes to mind is something like 'notepad /p x.txt'. > > If you want to print other things than simple text files, it gets more > complicated IMO. > > Thomas You mean python isn't capable of it ? Fuzzy From skip at pobox.com Fri Jan 16 09:38:57 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 16 Jan 2004 08:38:57 -0600 Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: <16391.63361.420774.458069@montanaro.dyndns.org> Maxim> is there a way to process actions other than XML-RPC requests Maxim> using SimpleXMLRPCServer? Is is possible to do something like Maxim> server = SimpleXMLRPCServer(('', 8000)) Maxim> server.register_instance(MyClass()) Maxim> while(1) Maxim> if(checkSomeCondidion()): Maxim> server.serve_once() Maxim> else: server.stop() You should be able to override the serve_forever() method. Skip From cherico at bonbon.net Thu Jan 29 08:11:13 2004 From: cherico at bonbon.net (cherico) Date: 29 Jan 2004 05:11:13 -0800 Subject: popen2 with large input Message-ID: from popen2 import popen2 r, w = popen2 ( 'tr "[A-Z]" "[a-z]"' ) w.write ( t ) # t is a text file of around 30k bytes w.close () text = r.readlines () print text r.close () This simple script halted on w.write ( t ) Anyone knows what the problem is? From q2n8byu02 at sneakemail.com Fri Jan 2 16:52:40 2004 From: q2n8byu02 at sneakemail.com (Ivan Nestlerode) Date: 2 Jan 2004 13:52:40 -0800 Subject: KeyboardInterrupt and threading Message-ID: Hello comp.lang.python, I am attempting to write a threaded program right now in Python (version 2.3 on Debian unstable) and the current behavior of KeyboardInterrupt is causing me grief. From the documentation of the thread module in Python 2.3.3: "Threads interact strangely with interrupts: the KeyboardInterrupt exception will be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.)" So the current behavior is that some "arbitrarily chosen" thread receives the KeyboardInterrupt exception when the user hits Ctrl-C. My question is whether there is some way to always make the main thread receive the KeyboardInterrupt. The snippet at the end of the documentation is vague/confusing. It sounds like KeyboardInterrupt would always be delivered to the main thread, but I have tested this and it is definitely not behaving that way. Maybe it just means that the Unix signal is received by the main thread's signal handler (and at that point an arbitrary thread is picked for KeyboardInterrupt). I don't know. The reason I cannot use the current "arbitrary thread" KeyboardInterrupt delivery model: The current model seems to deliver the KeyboardInterrupt to the busiest thread (i.e. some sub-thread doing lots of computation, as opposed to my main thread that is sitting in a sleep() loop). This causes problems because the busy thread that I spawn runs library code that was not written by me. That library code may contain lines like "except:" that mask the KeyboardInterrupt so that the user experience is that the app seems to ignore Ctrl-C. If I could guarantee delivery of KeyboardInterrupt to the main thread, I could control things much more easily/consistently. With the current semantics code reuse becomes very difficult (I cannot use any code that is "sloppy" with its exception catching or Ctrl-C will be ignored). Any ideas (besides rewriting the sloppy library code) would be much appreciated. Thanks, -Ivan From na Sat Jan 10 10:17:43 2004 From: na (Andrew) Date: Sat, 10 Jan 2004 07:17:43 -0800 Subject: How to insert into listbox using wxPython References: <3ffda907$0$572$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Hi I had tried something similiar to that earlier. I typed what you wrote for x in self.results: self.listbox.Append(x[0]) and I got the same error as what I had tried earlier Traceback (most recent call last): File "S:\GUI\MYSQL\mysqlgui.py", line 65, in OnB2Button self.listbox.Append(x[0]) File "F:\Python22\Lib\site-packages\wxPython\controls.py", line 78, in Append val = controlsc.wxControlWithItems_Append(self, *_args, **_kwargs) TypeError: String or Unicode type required Any help is alway's appreciated From computer.problemen at skynet.be Fri Jan 9 03:53:22 2004 From: computer.problemen at skynet.be (broebel) Date: Fri, 9 Jan 2004 09:53:22 +0100 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> Message-ID: <3ffe6a41$0$1820$ba620e4c@news.skynet.be> thanks "Rene Pijlman" schreef in bericht news:5unrvv8u1vpske1j464epj4aff0f54k2nf at 4ax.com... > broebel: > >first problem is the fact that I started out with a little program who was > >part of a course but the problem is when I launch the program. I don't have > >the time to see the result because the screen closes immediately. > >Can anyone explain what's happening. > > The program started, did what it had to do and then terminated :-) > > "1 How do I run a Python program under Windows?" > http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-und er-windows > > -- > Ren? Pijlman From rob02omni at vodafone.it Thu Jan 15 04:53:39 2004 From: rob02omni at vodafone.it (Roberto) Date: Thu, 15 Jan 2004 10:53:39 +0100 Subject: How robust is embedding?? Message-ID: Hi there, I know that surely depend on how robust is my script just wondering if anyone is using this in production. Thanks, Rob -- Roberto Federici .:: SAEC - Studio Associato Enrico e Catozzo & C. .:::: Fraz. Pont Suaz, 104 Charvensod (AO) .:::::: Tel. 0165-43149 - Fax 0165-230153 .:::::::: info at saec.net www.saec.net ********************************************************************** Ai sensi della legge n. 675/1996 si informa che : Questa email (e relativi allegati) contiene informazioni riservate indirizzate ai soli destinatari. E' fatto esplicito divieto di utilizzare i contenuti per qualsiasi scopo. E' fatto altres? divieto di utilizzare gli indirizzi email per attivit? indesiderate e/o non richieste (spamming). In caso di ricevimento per errore vi preghiamo di segnalarlo a info at saec.net ********************************************************************** From aldo123 at onet.pl Fri Jan 23 08:43:49 2004 From: aldo123 at onet.pl (mic) Date: Fri, 23 Jan 2004 14:43:49 +0100 Subject: weird COM hazard Message-ID: I'm getting strange hazard while running MSIE automation script. This concerns MSIE events, especially OnDownloadBegin and OnClosing but I bet they're not the only ones. The simplified code looks like this: from win32com.client import DispatchWithEvents class ConnectionStatus: #this is 'static' class containing most of the parameters needed from other parts of the script MainBusy = False ChildBusy = False class MSIE: Main = DispatchWithEvents('InternetExplorer.Application',MainEvents) Child = DispatchWithEvents('InternetExplorer.Application',ChildEvents) """ then I do some browsing on 'Main' here, especially to the page that fires using JavaScript new window, that's being captured by Child object. Then the Child window is closed by using JS window.close() """ class MainEvents: def OnDownloadBegin(self): ConnectionStatus.MainBusy = True def OnDocumentComplete(self): ConnectionStatus.MainBusy = True """ this way I catch most of the available events. The only operation I do is set the ConnectionStatus class attributes The same goes to ChildEvents: """ class ChildEvents: def OnDownloadBegin(self): ConnectionStatus.ChildBusy = True def OnDocumentComplete(self): ConnectionStatus.ChildBusy = True The problem is that from time to time some of the child events raises exception: AttributeError: 'NoneType' object has no attribute 'ChildBusy' and after a short debugging it looks like at some moment I loose the reference to the ConnectionStatus class, though obviously I make no such operation at all. As it happens 50% of times I run the same script and seems to stop not only at the same event, I'm starting to believe that this is kind of a bug in win32com. Does anybody experienced anything like that? Thanks in advance, Michal From peter at engcorp.com Fri Jan 9 14:47:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 14:47:36 -0500 Subject: Variable Scope References: Message-ID: <3FFF0558.52C2892F@engcorp.com> Jens Thiede wrote: > > In the following terminal; could someone inform me as to why it is > posible to print a global variable without having to declare it using > global. This has affected some source of mine, and allows you to > modify a global in a local scope *without* the global keyword, for > instance, you can append to a global list, but *not* assign it a new > value, for then, you create a new local variable. -- Why. Have you read http://www.python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function ? It should clarify some of these issues. If it does not, please let us know what's still unclear and the FAQ can be improved. -Peter From rdsteph at earthlink.net Mon Jan 5 14:04:58 2004 From: rdsteph at earthlink.net (Ron Stephens) Date: 5 Jan 2004 11:04:58 -0800 Subject: Help: wxPython tutorials References: <425cc8d1.0401050434.235ca633@posting.google.com> Message-ID: <8e6e8e5d.0401051104.225aeece@posting.google.com> mir4uu at yahoo.com (mir nazim) wrote in message news:<425cc8d1.0401050434.235ca633 at posting.google.com>... > hi, > i am in urgent need of a good refrence material for wxPython. goo docs > will also do.(i already have wxWindows library refrence. but it is too > hectic for me to traverse throught it). > please help. Try these: wxPython
Tutorial on wxPython

wxPython for Newbies
Tutorial on wxPython < wxPython Small App Tutorial
Tutorial on wxPython wxPython Wiki Ron Stephens From ykingma at accessforall.nl Tue Jan 6 03:41:20 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Tue, 06 Jan 2004 09:41:20 +0100 Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: <3ffa7431$0$141$e4fe514c@dreader12.news.xs4all.nl> Sean R. Lynch wrote: > How about: > > def lock_call(mutex, func, *args, **kwargs): > mutex.acquire() > try: > res = func(*args, **kwargs) > finally: > mutex.release() > > return res Or even: def lock_call(mutex, func, *args, **kwargs): mutex.acquire() try: return func(*args, **kwargs) finally: mutex.release() Regards, Ype From exarkun at intarweb.us Tue Jan 6 11:02:02 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 6 Jan 2004 11:02:02 -0500 Subject: metadocumentation (keyword help) In-Reply-To: References: Message-ID: <20040106160202.GA8085@intarweb.us> On Tue, Jan 06, 2004 at 03:27:06PM +0100, Jacek Generowicz wrote: > Where can I find concise, clear documentation[*] describing what one has > to do in order to enable Python's internal help to be able to provide > descriptions of Python keywords ? "Quote them" help('if') Jp From aahz at pythoncraft.com Tue Jan 20 13:26:16 2004 From: aahz at pythoncraft.com (Aahz) Date: 20 Jan 2004 13:26:16 -0500 Subject: Delayed evaluation and setdefault() References: <400C25FF.A76B1FEA@engcorp.com> <400D5B48.9F69A788@engcorp.com> Message-ID: In article <400D5B48.9F69A788 at engcorp.com>, Peter Hansen wrote: >Aahz wrote: >> >> First of all, Peter made a boo-boo in naming a parameter ``dict``. > >Oops... I was, uh, writing pseudo-code, not Python! Yeah, that's it... Python *is* pseudo-code. That's why we like it, right? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From stevewilliams at wwc.com Fri Jan 16 22:46:15 2004 From: stevewilliams at wwc.com (Steve Williams) Date: Sat, 17 Jan 2004 03:46:15 GMT Subject: [OT] AS/400 In-Reply-To: <4005cd03@news.mt.net.mk> References: <4005cd03@news.mt.net.mk> Message-ID: ?????? ?. wrote: >>(will not mention that it works on AS/400, the best >>minicomputer(!) ever made). > > > Why is it the best minicomputer ever made? > I really want to know! > > HP/3000, taken off the sales list last Halloween. A joy to work with. Believe it or not, it was ported to run as a UNIX emulator in the '80s, so it could be available forever, but HP's politics killed it. Gresham's law applied to computing: bad software drives out good. (Perl vs Python, et cetera, et cetera). From cpl.19.ghum at spamgourmet.com Fri Jan 30 03:06:37 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 30 Jan 2004 09:06:37 +0100 Subject: Printing From Python References: <8089854e.0401290555.501f0695@posting.google.com> Message-ID: > Saying that printing (to a printer :-) wasn't easy (at least on > windows - let alone *cross* platform) - and that was dated 2000. Printing is not easy, it is a complicated matter. You can find 4 simplifications: 1) wxPython has a print-framework, wxPython is cross platform (alas, I only used it in win32) 2) print postscript. Ghostscript is available on "every" platform. (printing on PDAs and watches is really different). Postscript is documented 3) create PDF. PDF viewers & printers are available on "every" platform. PDF can be created by (free) ReportLab toolkit, and I'm sure there are more PDF-Classes 4) create XHTML & a Print.CSS. HTML viewers are available on every Plattform, .CSS allows fairly good styling of printouts. Harald From dlmurray at micro-net.com Tue Jan 6 23:06:20 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Tue, 6 Jan 2004 21:06:20 -0700 Subject: My Bad! Message-ID: Well, I stopped my headlong charge into learning by reinventing the wheel (took the advice from this forum) and started snooping around to see what was provided with the python package. Good grief! And it's free! Thanks for the advice. Just had to say that. Dave From dpharris76 at msn.com Thu Jan 1 17:48:06 2004 From: dpharris76 at msn.com (Dave Harris) Date: Thu, 1 Jan 2004 16:48:06 -0600 Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com><99dce321.0312311130.5b7c7c8a@posting.google.com> <3ff49f0e.776954150@news.blueyonder.co.uk> Message-ID: ----- Original Message ----- From: "Alan Gauld" Newsgroups: comp.lang.python To: Sent: Thursday, January 01, 2004 4:34 PM Subject: Re: Test if IDLE is a mature program > On Wed, 31 Dec 2003 14:48:59 -0500, "Aubrey Hutchison" > wrote: > > I understand the problem of using the names of common modules... > > > > But why do we need to work around that problem.. > > > However your test of maturity is completely bogus, it is an issue > of user error not IDLE error. How do you think IDLE should handle > the case you describe? How would it know whether you intended a > name clash or not? > The word 'test' has appeared so many times in this thread that I have to mention a name conflict that has to have bitten _every_ UNIX shell scripter. How many of you will fess up to have written a script named 'test' and were puzzled when it did not run?? UNIX and sh fail to be mature by the proposed measure. How much longer till they 'come of age'? Anecdotally, Dave Harris From Pieter.Claerhout at Creo.com Tue Jan 20 06:00:34 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 20 Jan 2004 12:00:34 +0100 Subject: Python database Message-ID: <490316A24CC5D411ACD700B0D078F7F003915DC1@cseexch01.cse.creoscitex.com> Have a look at SQLite: www.sqlite.org. pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: brice.vissiere at costes-gestion.net [mailto:brice.vissiere at costes-gestion.net] Sent: 20 January 2004 11:46 To: python-list at python.org Subject: Python database Hi python friends, I'm currently working on a data handling tool. For internal storage, I'm looking for a 100% python database. I have some constraints: + multi-platform + relational with built-in query system (SQL preferably) + built-in string functions + reliable + fast I don't care about: + network access + concurracy control + transaction commit/rollback One of the key feature I'm looking for is direct string handling in queries: concatenation, substring extraction, stripping, justifying, ... all we can do with python strings. My first thought was to use Gadfly. I've downloaded and installed it. Now, I'm investigating the documentation and examples to find string capabilities of Gadfly, but at first look, it seems that it will not fit to my needs. My problem would be solved by using a database allowing user function creation, but I don't know whether such a tool exists. So, have you any idea of a db tool I should use ? Thanks in advance. Brice -- http://mail.python.org/mailman/listinfo/python-list From http Fri Jan 23 00:06:32 2004 From: http (Paul Rubin) Date: 22 Jan 2004 21:06:32 -0800 Subject: cgi concurrency approaches? Message-ID: <7x7jzjgso7.fsf@ruckus.brouhaha.com> I'm wondering if folks here have favorite lightweight ways of dealing with concurrency in cgi's. Take a simple case: You want to write a cgi that implements a simple counter. The first time it's called, it prints "1". The next time, "2", etc. The naive implementation looks something like: fd = open("counter.num", "rw") n = int(fd.read()) fd.seek(0, 0) fd.write("%d"% n+1) print "Content-type: text/html\n\n" print n but of course there's the obvious race condition if two people hit the cgi at the same time. Fancier solutions include running an transactional database in another process and connecting to it, setting up a daemon that remembers the counter value in memory and serializes access through a socket that the cgi opens, using a file-system specific hack like linking to counter file to lock it, having a timeout/retry if the counter is locked, with a possible hangup if a lock file gets left around by accident, etc. Each is a big pain in the neck. Anyone have some simpler approaches? From brian.c.fagan at boeing.com Mon Jan 26 17:41:09 2004 From: brian.c.fagan at boeing.com (brian.c.fagan at boeing.com) Date: Mon, 26 Jan 2004 14:41:09 -0800 Subject: hello Message-ID: <200401262240.i0QMepd28060@smtp.bss.boeing.com> ------------------ Virus Warning Message (on slb-av-02) Found virus WORM_MIMAIL.R in file text.pif (in text.zip) The uncleanable file text.zip is moved to /quarantine/virWLW8TeOPU. An attachment to this email contained a virus, if you received the attachment, the virus was cleaned and no further action is necessary. If you did not receive the attachment, you should contact the sender to have them clean the file and resend it. If you have further questions, contact your computer support staff. --------------------------------------------------------- -------------- next part -------------- The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment. -------------- next part -------------- ------------------ Virus Warning Message (on slb-av-02) text.zip is removed from here because it contains a virus. --------------------------------------------------------- From tjreedy at udel.edu Fri Jan 16 15:24:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Jan 2004 15:24:46 -0500 Subject: Bug or feature? References: <3dtid1-594.ln1@beastie.ix.netcom.com> <3bhld1-914.ln1@beastie.ix.netcom.com> Message-ID: "Dennis Lee Bieber" wrote in message news:3bhld1-914.ln1 at beastie.ix.netcom.com... > But, since Python is dynamically typed, reversing the evaluation order > could have major effects on other operations... The "problem" is not > the order of evaluation, but that you have a "hidden" modification to a > term occurring. > > >>> def se(a): #side-effect > ... a.insert(0,3) > ... return a > ... > >>> def nose(a): #no side-effect > ... a = [3] + list(a) > ... return a > ... > >>> l = [1,5,7] > >>> l += nose(l) > >>> l > [1, 5, 7, 3, 1, 5, 7] > >>> l = [1,5,7] > >>> l += se(l) > >>> l > [3, 1, 5, 7, 3, 1, 5, 7] Lovely example, no hypotheticals needed. For those who did not get it, the key is that Python expressions evaluate to objects, and that the + operator does not reach into the objects to pull out values for the new object until it has (references to) both objects, which in the second case, are both the same. Terry J. Reedy From mhammond at skippinet.com.au Tue Jan 27 17:25:01 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 28 Jan 2004 09:25:01 +1100 Subject: Optional Parameters in python COM In-Reply-To: References: Message-ID: Rane Bowen wrote: > Hi, > > I am using python with a makepy generated wrapper on a COM application. One > of this object's methods has 3 parameters, two of which are optional. > If I call the method with just the non-optional parameter, or all three > parameters, it works. If I call it with the first two parameters, I get the > following error: > > (-2147352567, 'Exception occurred.', (0, 'Amphora.Session.1', 'A bad > parameter was passed to the method', None, 0, -1610547133), None) > > I have tried calling the method by using the names of the optional > parameters, and I have also tried using pythoncom.Missing and > pythoncom.Empty for the non essential parameter. I have also edited the > generated .py file so that it contains the following: > > defaultNamedOptArg=pythoncom.Empty > defaultNamedNotOptArg=pythoncom.Empty > defaultUnnamedArg=pythoncom.Empty > > But this has not made any difference! Any help would be very much > appreciated. Can you reproduce this problem with a "common" object, such as IE, MSOffice, or a trivial VB object with sourcecode? The problem is that it is up to each object to implement optional params, so it is very hard to pinpoint bugs in win32com here. Mark. From tr at jotsite.com Mon Jan 26 10:58:36 2004 From: tr at jotsite.com (Hoang) Date: Mon, 26 Jan 2004 15:58:36 GMT Subject: Unique ID for CD or DVD References: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: thanks everyone for your suggestions. I have decided to use MD5 since it is included as a module with Python. Finding a unique string from the CD won't be that hard and makes the approach more straight forward than any other method. Using MD5 makes it less proprietary than it needs to be. Hoang Do http://jotsite.com From jcarlson at nospam.uci.edu Sun Jan 25 01:38:41 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 24 Jan 2004 22:38:41 -0800 Subject: Newbie Nested Function Problem In-Reply-To: References: Message-ID: Brian Samek wrote: > Oh wow! Thanks a lot - that was exactly the issue. I changed the variable name and the program works perfectly now. I didn't realize that a variable name in a program would have that effect. > > Brian > "Rich Krauter" wrote in message news:mailman.753.1075001453.12720.python-list at python.org... > Looks like you are setting the variable 'leave' to the user input, and then you are calling the function leave(), but remember that 'leave' has been set to some string. > So say you enter 'xqz', and expect it to restart the loop when you get to the leave call --- well, what you are doing is trying to call the function xqz(). > Rich > On Sat, 2004-01-24 at 21:45, Brian Samek wrote: One thing you should REALLY change is the way you get the number. For general inputs, you need to deal with the fact that people may give bad input. try: number = int(raw_input('prompt> ')) except KeyboardInterrupt: #ctrl+c was pressed return except: #they didn't enter a number pass input() Will evaluate some things that are entered by the user. Below is a non-recursive version of what you wrote, which is not limited by the recursion limit of Python, so technically the upper bound can be tossed. It also uses a controlled infinite loop trick that I've found quite useful in a few projects. - Josiah def countdown(): while 1: try: number = int(raw_input("Please enter a number.\n> ")) if 1 <= number < 500: break except KeyboardInterrupt: return 0 except: pass while number > 0: print number number -= 1 while 1: leave = raw_input("Type 'y' to start over - type 'n' to exit. ") if leave == 'y': return 1 elif leave == 'n': return 0 else: print "Type either 'y' or 'n' please." while countdown(): pass From http Sat Jan 17 23:09:27 2004 From: http (Paul Rubin) Date: 17 Jan 2004 20:09:27 -0800 Subject: Inserting while itterating References: Message-ID: <7xektxx5hk.fsf@ruckus.brouhaha.com> Jeremy Bowers writes: > Actually, maximal readability is > > l[:] = [x for x in range(min(l), max(l) + 1)] > > but that will *certainly* be less efficient if you know the list is sorted > then my first post. Um, why the list comprehension? Something wrong with l[:] = range(min(l), max(l) + 1) ? From corey.coughlin at attbi.com Fri Jan 30 17:26:15 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 30 Jan 2004 14:26:15 -0800 Subject: number of arguments a function takes References: Message-ID: OK, here's my object. Basically, you set up a truth table with the input and output pins, then you can add values to it usings dictionaries of the form { 'pin name': 0 or 1......} to represent each state. The point here is more to deduce the boolean functions of a table from data observed from black box boolean functions, very useful for my job in semiconductors. Keep in mind that I wasn't exactly trained in software, so my code is usually a little rough and brute force, which keeps it from being less elegant, but easy to understand. Anyway, if you have any questions, feel free to ask. class TruthTable(object): def __init__(self,iinputs= [], ioutputs=[]): self.ttab = {} self.inpindex = {} self.vcount = 0 if iinputs and ioutputs: self.vcount = 2 ** len(iinputs) i = 1 for input in iinputs: self.inpindex[input] = i i = i * 2 for output in ioutputs: self.ttab[output] = [ None ] * self.vcount def reducetable(self): newinputs = [] onegone = False for ipin in self.inpindex.keys(): iused = False for opin in self.ttab.keys(): iused = iused or self.findtransitions(ipin, opin) if iused: newinputs.append(ipin) else: onegone = True if not onegone: return None i = 1 newindex = {} newttab = {} newcount = 2 ** len(newinputs) for ipin in newinputs: newindex[ipin] = i i = i * 2 for opin in self.ttab.keys(): newttab[opin] = [None] * newcount for i in range(newcount): curristate = {} for ipin, bplace in newindex.items(): curristate[ipin] = ( i & bplace ) / bplace for j in range(self.vcount): oldstate = self.vec2output(j) matched = True for ipin in curristate: matched = matched and curristate[ipin] == oldstate[ipin] if matched: for opin in newttab: newttab[opin][i] = oldstate[opin] self.ttab = newttab self.inpindex = newindex self.vcount = newcount def addvalues(self, ttentry): index = 0 foundall = True for ipin in self.inpindex: if ipin not in ttentry: raise KeyError, 'Pin %s not in %s' % (ipin, ttentry) else: index = index + ttentry[ipin] * self.inpindex[ipin] for pin, value in ttentry.items(): if pin in self.ttab: self.ttab[pin][index] = value def deloutput(self, outname): if self.ttab.has_key(outname): del self.ttab[outname] def vec2output(self, vec): outent = {} for input, binplace in self.inpindex.items(): outent[input] = ( vec & binplace) / binplace for output, outvals in self.ttab.items(): outent[output] = outvals[vec] return outent def getvalue(self, inpstate, opin): if opin not in self.ttab: raise IndexError, 'Incorrect output pin %s used in getvalue.' % opin stindex = 0 for ipin in self.inpindex: if ipin not in inpstate: raise KeyError, 'Pin %s cannot be found in inpstate %s' % (ipin, inpstate) stindex = stindex + self.inpindex[ipin] * inpstate[ipin] return self.ttab[opin][stindex] def __str__(self): outs = '' allpins = self.inpindex.keys() + self.ttab.keys() maxname = 0 for pin in allpins: if len(pin) > maxname: maxname = len(pin) if maxname < 5: maxname = 5 indicies = self.inpindex.values() indicies.sort() indicies.reverse() indtoinp = {} inputs = [] for input, index in self.inpindex.items(): indtoinp[index] = input for i in indicies: outs = outs + '%s ' % stringfill(indtoinp[i], maxname) inputs.append(indtoinp[i]) outs = outs + '| ' outputs = self.ttab.keys() outputs.sort() for out in outputs: outs = outs + '%s ' % stringfill(out, maxname) outs = outs + '\n' for i in range(self.vcount): currvec = self.vec2output(i) for inp in inputs: outs = outs + '%s ' % stringfill(str(currvec[inp]), maxname) outs = outs + '| ' for out in outputs: outs = outs + '%s ' % stringfill(str(currvec[out]), maxname) outs = outs + '\n' return outs def findtransitions(self, ipin, opin): indicies = range(self.vcount) binplace = self.inpindex[ipin] zerobits = filter(lambda x: x & binplace == 0, indicies) possibles = map(lambda x: ( x, x + binplace ), zerobits) foundtrans = [] for lowbit, highbit in possibles: ovec = self.ttab[opin] if (ovec[lowbit] != ovec[highbit] and ovec[lowbit] in [0,1] and ovec[highbit] in [0,1]): foundtrans.append( (lowbit, highbit) ) foundtrans = map(lambda x: ( self.vec2output(x[0]), self.vec2output(x[1]) ), foundtrans) return foundtrans def getoutfunc2(self, opin, notxwhens = []): if opin not in self.ttab: return '','' relpins = [] for ipin in self.inpindex.keys(): tranpairs = self.alltransitions(ipin) for lowst, highst in tranpairs: if lowst[opin] != highst[opin] and ipin not in relpins: relpins.append(ipin) if relpins == []: return '','' outhighs = [] outx = [] allone = True for vec in range(self.vcount): pvec = self.vec2output(vec) if pvec[opin] in [1, 'X']: saveout = pvec[opin] for pin in pvec.keys(): a = pin in self.ttab b = pin not in relpins if a or b: del pvec[pin] if len(pvec) > 0: allone = False if saveout == 1 and pvec not in outhighs: outhighs.append(pvec) if saveout == 'X' and pvec not in outx: outx.append(pvec) outfunc = '' xfunc = '' if allone: return '1','' for cwhen in outhighs: pstring = WhenString(cwhen) if outfunc == '': outfunc = '(%s)' % pstring else: outfunc = '%s|(%s)' % (outfunc, pstring) if notxwhens: print 'finding badxwhens' badxwhens = [] for cwhen in outx: for subwhen in notxwhens: if DictIn(cwhen,subwhen): badxwhens.append(cwhen) break for bwhen in badxwhens: outx.remove(bwhen) for cwhen in outx: pstring = WhenString(cwhen) if xfunc == '': xfunc = '(%s)' % pstring else: xfunc = '%s|(%s)' % (xfunc, pstring) return outfunc, xfunc def alltransitions(self, ipin): indicies = range(self.vcount) binplace = self.inpindex[ipin] zerobits = filter(lambda x: x & binplace == 0, indicies) possibles = map(lambda x: ( x, x + binplace ), zerobits) foundtrans = [] foundtrans = map(lambda x: ( self.vec2output(x[0]), self.vec2output(x[1]) ), possibles) return foundtrans def getinputs(self): return self.inpindex.keys() def getoutputs(self): return self.ttab.keys() def __len__(self): return self.vcount Oh, and a function called WhenString is also called, here's that: def WhenString(statein): pstring = '' pinlist = statein.keys() pinlist.sort() for pin in pinlist: if pstring != '': pstring = '%s&' % pstring if statein[pin] == 0: pstring = '%s!' % pstring if statein[pin] in [0, 1]: pstring = '%s%s' % (pstring, pin) if pstring and pstring[-1] in ['&', '!']: pstring = pstring[:-1] return pstring I took out some comments and a couple of differential specific functions to clear things up, and it's a little cluttered up with code to check for 'X' states, but that's it. Let me know what you think. :) From max at alcyone.com Wed Jan 14 02:15:42 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 13 Jan 2004 23:15:42 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <4004EC9E.1E2E2893@alcyone.com> "Brandon J. Van Every" wrote: > I don't. But that's not going to stop me from denigrating them for > being > incapable of fulfillng the kinds of projects I have in mind. If you're saying that you've come to the realization that volunteer programers on a project with which you only have a passing interest won't follow your orders and do whatever you say, I'd say pointing that out is less like "denigration" and more like "common goddamn sense." There are plenty of things you can get out of starting, getting involved with, and approaching open source projects. A legion of personal servants is not going to be one of them, and only a crass idiot would think otherwise. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ My heart is pure as the driven slush. -- Tallulah Bankhead From danb_83 at yahoo.com Tue Jan 27 15:31:38 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 Jan 2004 12:31:38 -0800 Subject: print format for binary representation References: <6f03c4a5.0401270700.713a73aa@posting.google.com> Message-ID: rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0401270700.713a73aa at posting.google.com>... > Hi, > > >>> print '%x' % 54 > 36 > >>> print '%b' % 54 > Traceback (most recent call last): > File "", line 1, in ? > ValueError: unsupported format character 'b' (0x62) at index 1 > >>> > > No formating string for binary? There %x for hex. Would %b make sense > for bin? Is this worth a PEP? Yes, it would. No, it isn't. What we really need is an inverse to the int constructor. Something like: def itoa(x, base=10): isNegative = x < 0 if isNegative: x = -x digits = [] while x > 0: x, lastDigit = divmod(x, base) digits.append('0123456789abcdefghijklmnopqrstuvwxyz'[lastDigit]) if isNegative: digits.append('-') digits.reverse() return ''.join(digits) > How do I get 00110110 printed instead of the traceback? print itoa(54, 2).zfill(8) From jjl at pobox.com Wed Jan 28 19:27:02 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Jan 2004 00:27:02 +0000 Subject: Problem connecting to https using ZSI (openssl problem) - python2.3 References: Message-ID: <87bronoazt.fsf@pobox.com> Adil Hasan writes: > Hello, > As a follow up to this. I noticed that the port that I was > contacting the server on was not correct. Now, I have moved forward > to an access denied message (I'll post that error in another news group). [...] You might have better luck using axis from Jython. ZSI seems to be fairly buggy (maybe that's not altogether fair: the protocols are apparently still a bit dodgy too, so the fault could be partly be on that end). I had some success with axis and SOAP/WSDL. John From steve at ninereeds.fsnet.co.uk Fri Jan 30 17:32:17 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 30 Jan 2004 22:32:17 +0000 Subject: [Python-Dev] PEP 327: Decimal Data Type References: Message-ID: <0lml109r6n6esrk1ou0nncdp3od4fnebo9@4ax.com> On Fri, 30 Jan 2004 07:06:21 -0800, Michael Chermside wrote: >Facundo Batista writes: >> I'm proud to announce that the PEP for Decimal Data Type is now published >> http://www.python.org/peps/pep-0327.html > >VERY nice work here. > >Here's my 2 cents: > > (1) You propose conversion from floats via: > Decimal(1.1, 2) == Decimal('1.1') > Decimal(1.1, 16) == Decimal('1.1000000000000001') > Decimal(1.1) == Decimal('110000000000000008881784197001252...e-51') > > I think that we'd do even better to ommit the second use. People who >really want to convert floats exactly can easily write "Decimal(1.1, 60)". But >hardly anyone wants to convert floats exactly, while lots of newbies would >forget to include the second parameter. I'd say just make Decimal(someFloat) >raise a TypeError with a helpful message about how you need that second >parameter when using floats. Good point. A 'DecimalExact' or similar function could perhaps be provided to replace the simple conversion when people have really thought about it and do really want it. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From newsgroups at jhrothjr.com Sat Jan 3 17:19:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 17:19:10 -0500 Subject: Creating a capabilities-based restricted execution system References: <9Jecnc6TZdy4lGqiXTWc-w@speakeasy.net> Message-ID: "Sean R. Lynch" wrote in message news:9Jecnc6TZdy4lGqiXTWc-w at speakeasy.net... > John Roth wrote: > > > Yes, you're missing something really obvious. Multi-level > > security is a real difficult problem if you want to solve it > > in a believable (that is, bullet-proof) fashion. The only way > > I know of solving it is to provide separate execution > > environments for the different privilege domains. > > In the current Python structure, that means different > > interpreters so that the object structures don't intermix. > > Hmmm, can you give me an example of a Python application that works this > way? Zope seems to be doing fine using RestrictedPython. > RestrictedPython is, in fact, an attempt to provide different execution > environments within the same memory space, which is the whole point of > my exercise. Now, I know that the lack of an example of insecurity is > not proof of security, but can you think of a way to escape from > RestrictedPython's environment? DoS is still possible, but as I'm not > planning on using this for completely untrusted users, I'm not too > concerned about that. Restricted Python was withdrawn because of a number of holes, of which new style classes were the last straw. I don't know what the exact holes were. Whether Zope security is subject to those holes is a question I can't answer (and I don't find it all that interesting, anyway.) The Restricted Execution environment's disabling access to __dict__ seems a bit ham-handed, but I suspect that it was simply the easiest way around one major difficulty. The Bastion hook (which is what I believe Zope security is built on top of) seems to be reasonably adequate. The rest of it probably needs to be rethought. John Roth From shalabh at cafepy.com Mon Jan 12 05:31:37 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Mon, 12 Jan 2004 10:31:37 GMT Subject: Article: The New Python - Part 1 - Types and Objects Message-ID: Announcing the initial public draft of: The New Python Part 1 - Types and Objects >From the abstract: "Describes the different new-style objects, and how they are related in the new Python world order (i.e. version 2.2 and up). The system is described in a ground up fashion, with plenty of diagrams. The system described is sometimes called the Python type system, or the object model." and preface: "To gain a better understanding of what and are, how classes, built-in types and class instances are related, and where metaclasses come from, I drew some paper diagrams while reading various official documentation on the subject. This book is a collection of those diagrams, accompanied by a portion of theory and examples." One big html file: http://www.cafepy.com/articles/python_types_and_objects python_types_and_objects.html Multiple small html files: http://www.cafepy.com/articles/python_types_and_objects/index.html Feedback greatly appreciated! Please send comments, suggestions, questions and corrections to shalabh at cafepy.com. Thanks, Shalabh Chaturvedi From paulo.pinto at cern.ch Wed Jan 28 04:53:29 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Wed, 28 Jan 2004 10:53:29 +0100 Subject: package similar to XML::Simple Message-ID: Hi, does anyone know of a Python package that is able to load XML like the XML::Simple Perl package does? For those that don't know it, this package maps the XML file to a dictionary. Of course I can build such a package myself but it would be better if it already exists :) -- Paulo Pinto From mickel at csc.fi Fri Jan 23 02:10:26 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 23 Jan 2004 09:10:26 +0200 (EET) Subject: Accessing Microsoft Word from Python Message-ID: Hi! I'm fiddling with Python for Windows (normally using Linux) and as a part of that I want to try to make a simple word frequency list generator to be used in conjunction with Microsoft Word. Does anybody have any good pointers on where I can find information about accessing Word-documents (or other Microsoft Office applications) from Python? To be more specific, I want to be able to: - get the text content of the full Word document - define a callback in Python that is called every time a user enters a character into the text of a Word document - get the last two graphical word tokens before the current position of the insertion cursor in the text of the Word document. Cheers! /Mickel -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From premshree_python at yahoo.co.in Mon Jan 12 15:00:25 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 12 Jan 2004 20:00:25 +0000 (GMT) Subject: Using switches with exec? In-Reply-To: <1005ufs36m9n5fd@corp.supernews.com> Message-ID: <20040112200025.59595.qmail@web8311.mail.in.yahoo.com> --- Francis Avila wrote: > Premshree Pillai wrote in message ... > > --- "Diez B. Roggisch" > wrote: > > >> I need to run a Python program dynamically within > >> > another program. I am using exec for the > purpose. > >> Is > >> > there a way to pass parameter switches to exec? > >> > >> You can pass a globals-dictionary to exec, which > can > >> hold the switches > >> values. > >> > >> Diez > >> -- > >> > http://mail.python.org/mailman/listinfo/python-list > > > >Could you please elucidate with a sample script. > >Suppose I need to pass the switch "-w" to the > >dynamically loaded code (using eval()/exec()). > >Any help is appreciated. > > > >-Premshree > > > > What do you mean by a parameter switch? You mean a > command-line switch? > > If this is what you mean, it seems you're mixing > concepts. If you run the > Python program as an external program, just do so > using os.system or > os.popen or such--the fact that it's written in > Python makes no difference, > and exec/execfile is not involved. os.system('python > mypythonprg -w'), for > example. > > If you want to have Python code from one program > exposed to another, the > best approach is to write a module which can be used > either as a library or > a stand-alone program. The idiom is to put > something like this: > > if __name__ == '__main__': main() > > at the bottom of your code. When you run this file > alone, main() will be > executed; if you import the file, it won't be. > > If you really need to execute external Python code > internally (and it's very > rare and special circumstances where you'd want to), > use execfile(). > > Now, if you're using execfile, it is unlikely that > the code you're running > would use command line switches--this implies that > it's a stand-alone > program, in which case you should either be running > it externally (as in > first solution above) or importing it, and providing > a mechanism to use it > programmatically. This is why I say you seem to be > mixing concepts. > > That said, command line arguments are available via > sys.argv, and this is > most likely how the external program accesses them. > You can modify sys.argv > before execfile(). > > This, however, is a mess, because you clobber the > global sys.argv of the > original program. You need to somehow redirect any > access to sys.argv by > the script. You can do so like this: > > >>> sys.argv > [''] > >>> class ShadowObject(object): > ... def __init__(self, shadowed, **override): > ... """Shadow attr access to shadowed with > override.""" > ... self.__dict__.update(override) > ... self.shadowed = shadowed > ... def __getattr__(self, attr): > ... """Called only if attr was not in > override.""" > ... return getattr(self.shadowed, attr) > ... > >>> exec '''print sys.argv #We get the > right one? > ... print sys.getdefaultencoding() #Make sure we're > shadowing. > ... sys.argv = sys.argv[-1:] #Test > reassignments. > ... print sys.argv > ... ''' in globals(), {'sys':ShadowObject(sys, > argv=['progname','-w'])} > ['progname', '-w'] > latin-1 > ['-w'] > >>> sys.argv # the real sys.argv is unchanged > [''] > > Don't do this. It's almost certainly not the best > way to do what you want. > Why don't you tell us your broader task, and maybe > we can suggest something > more Pythonic? > -- > Francis Avila > > -- > http://mail.python.org/mailman/listinfo/python-list Hmm...maybe I should have been clearer. What I need to do is run an external Python code from within another program, and while doing so I need to pas a switch (yes, like a command-line switch) to this code; i.e., I need to open an external Py program from within another Py program... Hope I'm clear this time around... -Premshree ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From nuffsaid at phreaker.net Sat Jan 17 17:31:59 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 17 Jan 2004 23:31:59 +0100 Subject: wxwindows question References: Message-ID: On Thu, 15 Jan 2004 11:17:45 -0200, Jorge Godoy wrote: > On Tuesday 13 January 2004 21:55 Nuff Said wrote in > : > >> (Even some of the widgets in the wxpython demo crash on Linux; >> and if you use wxpython with Unicode support, the situation gets >> even worse. This might change in the near future, but right now, >> wxpython is not stable enough on Linux IMHO.) > > Which ones? And in which version of wxPython + wxGTK + Python? I use(d) wxPython 2.4.2.4 with Python 2.3.x on various Linux systems (incl. SuSE and Fedora Core). When I compiled wxPython with Unicode support, the demo either did not work at all resp. every second or so widget crashed. Without Unicode support, e.g. the StyledTextControl (Scintilla) crashed whenever I tried to enter a 'special' character (i.e. a character which is not a 7 bit ASCII character). The use of other widgets resulted in seg faults, too; but I do not remember exactly, which ones. I tried to compile wxPython (resp. wxGTK) for GTK1 and GTK2; the former seemed to be more stable (but looked awful). After a week or two of testing, I gave up on wxPython (for the moment). I wrote a lot of cross platform applications in Python (together with C and, recently, C#) using Tkinter (resp. Tcl/Tk) and pyGTK (resp. GTK+ for other languages) and never had such problems. But both GUI toolkits lack some important widgets and therefore I became interested in wxPython (though I don't like the way I have to code in wxPython; but that's my personal problem :-) Recently, I write a lot of web applications (whenever possible), using good old CGIs, various frameworks and ASP.NET (with C#). But my dream for Python would be a native GUI toolkit (and not just a wrapper for something else which was not designed with Python in mind). Nuff From martin at v.loewis.de Sat Jan 17 19:46:54 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 18 Jan 2004 01:46:54 +0100 Subject: Retrive unicode keys from the registry In-Reply-To: References: <1xpzaa8i.fsf@python.net> <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> <40086EE5.7020708@v.loewis.de> Message-ID: Neil Hodgson wrote: > The documentation for RegQueryValue says: > """ Unicode: Implemented as Unicode and ANSI versions. Note that Unicode > support on Windows Me/98/95 requires Microsoft Layer for Unicode. """ Too bad. Perhaps we should link Python with MSLU? Regards, Martin From hwlgw at hotmail.com Fri Jan 9 08:07:17 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 9 Jan 2004 05:07:17 -0800 Subject: Bruce Eckel example / CGI server for localhost for Windows XP possible? Message-ID: Bruce Eckel has a good article about using a browser as UI for applications you write: http://mindview.net/WebLog/log-0045 His example code is nice, he sets up a webserver *and is able to kill it too via a HTML button*. But his webserver does not do CGI. I have been trying to change the code with CGIHTTPRequestHandler and other such things, I have also tried various "recipes" for CGI webservers, but I can not get something that works well enough. Could well be that my poor programming skill is to blame here. Especially handling POST is important (if a user inputs a file via HTML then you don't want the whole file in the URL location bar. I have a version that handles the first POST but crashes on subsequent POSTs. So now I just use the Apache CGi webserver, but this means that if I want to give somebody else my CGI program they also have to install Apache. Is there anybody who can provide simple example code like found in Fredrik Lundh's Python Standard Library book for setting up a CGI server for localhost with Python? Perhaps the examples that are available work on linux, but not on my Windows XP laptop with Python 2.3.3: GET works and the first POST works too, subsequent POSTs crash. From deets_noospaam at web.de Wed Jan 14 14:27:06 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 14 Jan 2004 20:27:06 +0100 Subject: Printing to console (No Scroll) References: Message-ID: Totte Karlsson wrote: > Any alternatives to ncurses? It seems like a overkill for this... Maybe you can use sys.stdout.write in conjunction with control-codes for moving back the cursor to column one. But you'll have to lookup these for yourself :) Diez From PeterAbel at gmx.net Tue Jan 6 18:39:29 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 6 Jan 2004 15:39:29 -0800 Subject: looping to define a sequence of functions? References: Message-ID: <21064255.0401061539.43ca3c01@posting.google.com> "r.e.s." wrote in message news:... > Suppose we want to define ten functions such that the > nth function of x simply returns x**n. Is there a way > to avoid explicitly writing ten function def's? (They > have to be ten distinct functions, not just a single > one like def f(n,x): return x**n.) > > E.g., the following doesn't work: > > f = {} > for n in range(10): > def f[n](x): > return x**n > > Thanks. >>> # A parametric factory-function that returns >>> # a function depending on the parameter n >>> def factory_function(n): ... def fn(x): ... return x**n ... return fn ... >>> # A list of ten different functions >>> func_list=map(factory_function,range(10)) >>> # And an example of the result with x=2 >>> for i,func in zip(range(len(func_list)),func_list): ... print '%2d: %d' % (i,func(2)) ... 0: 1 1: 2 2: 4 3: 8 4: 16 5: 32 6: 64 7: 128 8: 256 9: 512 >>> Regards Peter From newsreply at transfertech.de Thu Jan 29 08:44:56 2004 From: newsreply at transfertech.de (Axel Mittendorf) Date: Thu, 29 Jan 2004 14:44:56 +0100 Subject: Rookie question about data types (hashtables) References: Message-ID: "Steve D. Perkins" wrote: > Hello all - Hi > when you type the letter "a" the box will contain all English words > starting with the letter "a". When you then type "n", the box will > narrow further and contain all words starting with "an", etc... until Maybe you could use a normal python dictionary (you call it hashtable). Look at this script (You would need one dictionary for each direction.): #!/usr/bin/python # generate dictionaries (AKA hashtables). # direction: English --> German EN2DE = {} # direction: German --> English DE2EN = {} # inserts a word and its translation into the dict d def insertWord( d, key, val): # does the key exist if d.has_key( key): # yes d[ key].append( val) else: # no d[ key] = [val] # returns a list words that begin with s def getBeginWith( d, s): l = s.__len__() res = [] keys = d.keys() for k in keys: if k.__len__()>=l and k[:l] == s: # use "k[:l].lower() == s.lower()" to ignore case res.append( k) return res # insert some entries insertWord( EN2DE, "someword", "meaning 1") insertWord( EN2DE, "someword", "meaning 2") insertWord( EN2DE, "my_codingstyle", "evil") insertWord( EN2DE, "son", "Sohn") insertWord( EN2DE, "sunday", "Sonntag") insertWord( EN2DE, "wednesday", "Mittwoch") insertWord( EN2DE, "Weapon of mass destruction", "George Walker Bush") insertWord( EN2DE, "sold", "verkauft") # show that it works print "all keys that begin with 'so': ", getBeginWith( EN2DE, "so") print "translations for 'someword': ", EN2DE['someword'] Instead of doing this you could maybe subclass UserList from the standard library. > Steve HTH, Axel From aahz at pythoncraft.com Thu Jan 8 15:55:37 2004 From: aahz at pythoncraft.com (Aahz) Date: 8 Jan 2004 15:55:37 -0500 Subject: OT: What is Mac OS X? Message-ID: http://www.kernelthread.com/mac/osx/ Good technical summary for all the Macaholics here. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From sross at connectmail.carleton.ca Sat Jan 3 13:42:53 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 13:42:53 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> Message-ID: <11EJb.20461$Vl6.3782481@news20.bellglobal.com> "Frank" wrote in message news:3987e01c.0401030832.114c6f2a at posting.google.com... > Hi, > > can anybody help with the following problem? > > In C++ > > i = 5 / 10 and > i = -5 / 10 both have the same result 0. > > In python > > i = 5 / 10 gives me 0 as expected, but > i = -5 / 10 gives -1 as result. > > Is this a feature or a bug? I remember Delphi gave me the same result as > C++. > > TIA, > Frank Using the division algorithm: Let a,b be integers with b>0. Then there exist unique integers q and r such that: a = bq + r and 0<=r I have a question which is more about OO design than Python per se. I've noticed that a number of posters to this list have very good suggestions for SE issues, so I'm hoping that someone will be able to give me some guidance. My question is about how to architect a class hierarchy where some methods are nearly identical between a superclass and a subclass, but differ slightly. For example: class Sup(object): def __init__(self): self.specialFlag = False def aMeth(self): class Sub(Sup): def __init__(self): self.specialFlag = True In this example, the method aMeth just checks for specialFlag, and if it's True, does the special stuff required. This allows me to share aMeth, and not have to duplicate code. However, this doesn't feel great to me because Sup has to know about Sub in some fashion. If later I add other subclasses with their own special needs, the entanglement will just get worse. An alternative I thought of was creating a module with helper functions. That module would contain a function which implements whatever aMeth does, and knos about the special needs of Sub. Both Sup and Sub would invoke the helper method. That allows me to share code, avoids a direct dependency of Sup on Sub, but does add a new module. I'm guessing that there is some well known pattern that addresses this issue, but I don't know what it is. Does anyone have suggestions for architecture that provides a good solution? thanks, -robert From markus_wankus at hotmail.com Wed Jan 21 13:18:28 2004 From: markus_wankus at hotmail.com (Markus Wankus) Date: Wed, 21 Jan 2004 13:18:28 -0500 Subject: Help, *.CHM, etc -> *nix .chm viewer References: Message-ID: On Wed, 21 Jan 2004 11:48:48 -0600, Christian Wilcox wrote: >> I wonder if anyone has written a cross-platform CHM decoder and browser >> that has the help browser look & feel. I can't find one, but it seems >> that python would be a great language to make such a thing. Maybe >> I'll take a crack if it hasn't been done. I like monolithic, >> compressed help vs. a big directory full of html. > > http://xchm.sourceforge.net/ > > Description from the page: > > xCHM is a .chm viewer for UNIX (Linux, *BSD, Solaris), written by Razvan > Cojocaru. > Success stories of xCHM on Mac OS X have also been received, and > apparently xCHM even works if compiled under the Cygwin environment in > Windows. > > HTH > > Christian Wilcox > Doesn't wxPython/wxWindows include a cross-platform HTML-Help widget set? I'm pretty sure it did when I was playing with this, but it wasn't exposed in earlier versions, or you needed to get it out of CVS or something - which is why I went the .chm route. Well, OK - I'll get off my lazy ass and check: >>> from wxPython.wx import * >>> from wxPython.html import * >>> from wxPython.htmlhelp import * >>> print dir(wxHtmlHelpController) ['AddBook', 'AddPendingEvent', 'Connect', 'Destroy', 'Disconnect', 'Display', 'D isplayContents', 'DisplayID', 'DisplayIndex', 'GetClassName', 'GetEvtHandlerEnab led', 'GetFrame', 'GetNextHandler', 'GetPreviousHandler', 'KeywordSearch', 'Proc essEvent', 'ReadCustomization', 'SetEvtHandlerEnabled', 'SetNextHandler', 'SetPr eviousHandler', 'SetTempDir', 'SetTitleFormat', 'UseConfig', 'WriteCustomization ', '__del__', '__doc__', '__init__', '__module__', '__repr__', '_setOORInfo'] >>> It seems to depend on importing in the above order. I am running an older version of wx so it may be better in newer versions. -- Markus From paul at boddie.net Fri Jan 16 06:31:32 2004 From: paul at boddie.net (Paul Boddie) Date: 16 Jan 2004 03:31:32 -0800 Subject: More than one python in a linux References: Message-ID: <23891c90.0401160331.287648a@posting.google.com> Zunbeltz Izaola wrote in message news:... > Hi, > > I've build and installed python 2.2 and python2.3 in a linux box. I think we need to know... * How you built those Python releases: compiled from source, used a source RPM or other source package, used a binary RPM or other binary package (which really isn't building, however). * What kind of Linux distribution you used and whether it had Python installed already. > Now i want to install some packages (Numeric, wxPython and > scipy). I've install Numeric and wxPython for python2.3 without > problem (python2.3 setup.py install ... and so on). But when I try > > python2.2 setup.py install [...] > error: invalid Python installation: unable to open /usr/lib/python2.2/config/Makefile (No such file or directory) This suggests that you don't have the development stuff installed for that particular Python 2.2 installation. I note that /usr is the prefix, meaning that either... * You built Python from source and specified /usr as the prefix instead of using the default /usr/local as prefix. This is unlikely as the Makefile would probably be where setup.py is looking. * You installed a package which put the installation in /usr (eg. /usr/bin/python2.2) but which didn't include the development stuff. That might mean that you need to find the corresponding "devel" package. * You already have /usr/bin/python2.2 installed as part of the Linux distribution and it is this program that is being run when you attempt to install things using setup.py, despite the possible existence of a Python 2.2 installation in /usr/local. In this case, verify using "which python2.2" the actual program being run and adjust your PATH environment variable to use your own Python 2.2 installation; for example: PATH=/usr/local:$PATH python2.2 setup.py install I hope this helps you track down the problem. Multiple Python installations are easy enough to manage and use, especially if you remember to use python2.2 and python2.3 (as you've done) to control the version you want to use. Paul From Mike at DeleteThis.Geary.com Tue Jan 6 03:57:05 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 6 Jan 2004 00:57:05 -0800 Subject: Downloading files off Interet References: Message-ID: > Blaktyger wrote: > B> I would like to download some mp3 files from a web site. > B> There is to much of them and I had the idea of writing a > B> script to do it for me. > > B> Code: > B> import string > B> import urllib > > B> f = urllib.urlopen(""" http://www.somemp3site.com/somemp3.com""") > > B> fic=open('mp3file.mp3','w') > B> fic.write(f.read()) > B> fic.close() > B> f.close() > > B> I ran the program and the file is not playing. > B> Can someone help me? > B> Thanks Egor Bolonev wrote: > may be devas esti wb > fic=open('mp3file.mp3','wb') Or, as someone pointed out when I posted similar code a while back, you can do the whole thing with a single call: import urllib urllib.urlretrieve( 'http://www.foo.com/bar.mp3', 'bar.mp3' ) See the documentation for urllib.urlretrieve for additional information, especially the optional reporthook argument that lets you provide a callback function so you can display the progress for a long file. -Mike From sidharthk at hotmail.com Mon Jan 26 03:04:06 2004 From: sidharthk at hotmail.com (Sidharthk) Date: 26 Jan 2004 00:04:06 -0800 Subject: efficient updating of nested dictionaries References: Message-ID: <8d02ff63.0401260004.4b056111@posting.google.com> omission9 wrote in message news:... > I have a dictionary that looks like this > MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO > > I am having a problem updating this with a simple > MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting > into the inner dicts. > Getting the keys of each and iterating through and updating each one is > terribly slow as the number of keys gets bigger and bigger. > What is the bst way to update my nested dicts? Use a tuple MY_DICT[(KEY_X,KEY_Y,KEY_Z)]=FOO unless you have a particular reason to use these nested dicts :) From candiazoo at comcast.net Fri Jan 2 12:20:45 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 17:20:45 GMT Subject: Problem building on BeOS... Message-ID: For some reason, the Python preprocessing balks on the "\" line continuation character. Any ideas/thoughts? Is it just that my version of gcc is not supported? I don't "need" numeric in my current project, but it is a nice package to have! Apps that do not need to be compiled install and run fine. Actually, SQLite built and installed fine... Thanks, in advance. Mike Python 2.2.2 (#13, Dec 6 2002, 00:42:47) [GCC 2.9-beos-991026] on beos5 $ python setup.py build running build running build_py not copying Lib/ArrayPrinter.py (output up-to-date) not copying Lib/LinearAlgebra.py (output up-to-date) not copying Lib/MLab.py (output up-to-date) not copying Lib/Matrix.py (output up-to-date) not copying Lib/Numeric.py (output up-to-date) not copying Lib/Precision.py (output up-to-date) not copying Lib/RandomArray.py (output up-to-date) not copying Lib/UserArray.py (output up-to-date) not copying Lib/numeric_version.py (output up-to-date) not copying Packages/FFT/Lib/FFT.py (output up-to-date) not copying Packages/FFT/Lib/__init__.py (output up-to-date) not copying Packages/MA/Lib/MA.py (output up-to-date) not copying Packages/MA/Lib/MA_version.py (output up-to-date) not copying Packages/MA/Lib/__init__.py (output up-to-date) not copying Packages/RNG/Lib/Statistics.py (output up-to-date) not copying Packages/RNG/Lib/__init__.py (output up-to-date) running build_ext building '_numpy' extension gcc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include -I/boot/home/config/include/python2.2 -c Src/_numpymodule.c -o build/temp.beos-5.0.4-BePC-2.2/_numpymodule.o In file included from /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:4: /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:234: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:239: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:241: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:244: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:247: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:251: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:253: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:255: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:257: stray '\' in program In file included from /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:6: /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:101: stray '\' in program /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:103: stray '\' in program error: command 'gcc' failed with exit status 1 $ From usenet_spam at janc.invalid Wed Jan 14 22:01:57 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 15 Jan 2004 03:01:57 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: paul m schreef: > JanC wrote: >> >> You think "cross-platform" means "it runs out-of-the-box on all >> possible platforms that ever existed, now exist, and will ever >> exist"? > vi might come close... ;-) It won't even run on my ZX Spectrum 48K, I suppose. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From http Tue Jan 13 14:05:35 2004 From: http (Paul Rubin) Date: 13 Jan 2004 11:05:35 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <7xhdz08xgy.fsf@ruckus.brouhaha.com> <1073978329.887910@yasure> <87brp7agl7.fsf@pobox.com> Message-ID: <7xvfnfmzy8.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > But at any rate, I thought we were talking about huge projects > > involving many programmers, and I don't think Grail was of that > > sort at all. > > Right. Wasn't it a research project? In any case, hardly a > large-scale programming effort along the lines of Mozilla! Grail wasn't huge but I think any serious browser qualifies as substantial. If you're saying it didn't really fail but actually wasn't even seriously attempted, ok, that's even fewer substantial programs that have even been tried in Python. From sross at connectmail.carleton.ca Fri Jan 2 12:44:28 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 2 Jan 2004 12:44:28 -0500 Subject: finding file size References: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com> <99dce321.0401012246.712dd2fb@posting.google.com> Message-ID: "David M. Wilson" wrote in message news:99dce321.0401012246.712dd2fb at posting.google.com... > 1) Using 'fd' as a name for a file object is a bad idea - you can get > fds from os.open. If you insist on C-ish names, how about 'fp' > instead? :) > or just f would work ... > 2) There's nothing to stop the file object from having a size method, except that file-like objects then have more to implement. See Martin v. Loewis' post for some other rationale. > > How about something like: > > py> class SizedFile(file): > ... def __len__(self): > ... oldpos = self.tell() > ... self.seek(0, 2) > ... length = self.tell() > ... self.seek(oldpos) > ... return length > ... > py> bleh = SizedFile("/etc/passwd") > py> len(bleh) > 1520 > py> len([ x for x in bleh ]) > 33 > > > > As I wrote this I realised it's wrong - size() would be better, since > the length of the sequence is not the number of bytes. Maybe it is in > binary mode? Dunno, me sleepy, goodnight.. > > > David. Right. size() is more apt. Also, while I appreciate the effort of subclassing file, what I was looking for was to have the builtin file (or file-like) objects expose this operation, not just custom implementations. Thanks for your response, Sean From gerryq at indigo.ie Thu Jan 15 06:46:35 2004 From: gerryq at indigo.ie (Gerry Quinn) Date: Thu, 15 Jan 2004 11:46:35 GMT Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: In article , "Brandon J. Van Every" wrote: >Agreed, and more specifically, there is a huge *cultural divide* between >most OSS developers and proprietary commercial developers who simply want to >add some OSS "to get the boring bits over with." And guess what bits of a project OSS programmers often tend not to bother finishing? As somebody once said, the purpose of paying wages is not to motivate people to work. It's to motivate them to come in on Monday mornings. Think of the boring bits as commercial software's secret weapon ;-) Gerry Quinn -- http://bindweed.com Screensavers, Games, Kaleidoscopes Download free trial versions From john.abel at pa.press.net Tue Jan 20 06:12:21 2004 From: john.abel at pa.press.net (John Abel) Date: Tue, 20 Jan 2004 11:12:21 +0000 Subject: Python database In-Reply-To: References: Message-ID: <400D0D15.5030001@pa.press.net> *Have a look at gadfly, gadfly.sf.net * Brice Vissi?re wrote: >Hi python friends, > >I'm currently working on a data handling tool. > >For internal storage, I'm looking for a 100% python database. > >I have some constraints: > + multi-platform > + relational with built-in query system (SQL preferably) > + built-in string functions > + reliable > + fast > >I don't care about: > + network access > + concurracy control > + transaction commit/rollback > >One of the key feature I'm looking for is direct string handling in >queries: concatenation, substring extraction, stripping, justifying, >... all we can do with python strings. > >My first thought was to use Gadfly. I've downloaded and installed it. >Now, I'm investigating the documentation and examples to find string >capabilities of Gadfly, but at first look, it seems that it will not >fit to my needs. > >My problem would be solved by using a database allowing user function >creation, but I don't know whether such a tool exists. > >So, have you any idea of a db tool I should use ? > >Thanks in advance. > >Brice > > From jepler at unpythonic.net Mon Jan 5 09:54:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Jan 2004 08:54:52 -0600 Subject: Embedding Python with Dynamic Loading (win) In-Reply-To: <5e571368.0401050603.265d469d@posting.google.com> References: <5e571368.0401050603.265d469d@posting.google.com> Message-ID: <20040105145452.GB5514@unpythonic.net> Simon, I have heard that vim can use dlopen() (the unix equivalent of LoadLibrary) to run Python extensions if it's configured that way. You might want to look at their code. Jeff From artur_spruce at yahoo.com Thu Jan 29 10:15:04 2004 From: artur_spruce at yahoo.com (Artur de Sousa Rocha) Date: Thu, 29 Jan 2004 07:15:04 -0800 (PST) Subject: Error under Cygwin - threading module In-Reply-To: <20040129145637.GD920@tishler.net> Message-ID: <20040129151504.47508.qmail@web21105.mail.yahoo.com> --- Jason Tishler wrote: > AdSR, > > Please keep you replies on-list. Oops. OK, here it goes. > On Wed, Jan 28, 2004 at 09:30:40AM -0800, Artur de Sousa Rocha wrote: > > --- Jason Tishler wrote: > > > I "spoke" too soon -- I was able to reproduce the problem after 160 > > > iterations. Please try the latest snapshot: > > > > > > http://cygwin.com/snapshots/ > > > > > > and report back whether or not this solves your problem. > > > > I installed the latest snapshot of cygwin1.dll > > (cygwin1-20040126.dll.bz2). The problem persists, error messages show > > about as often as previously. AdSR __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From Test at spam.stop.now Sun Jan 25 04:28:42 2004 From: Test at spam.stop.now (Test) Date: Sun, 25 Jan 2004 11:28:42 +0200 Subject: Test References: Message-ID: i see you ok! "solo" ???????/???????? ? ???????? ?????????: news:bv014r$200e$1 at pandora.alkar.net... > Sorry, it's a test. From peter at engcorp.com Wed Jan 28 09:11:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 09:11:56 -0500 Subject: Portable /dev/null? References: Message-ID: <4017C32C.F87637B7@engcorp.com> Josiah Carlson wrote: > > Nicolas Fleury wrote: > > > Hi everyone, > > Is there an object in some standard library that would be the > > portable equivalent of "file('/dev/null','w')" or do I have to create my > > own class and object to do it? If it doesn't exist, do you think it > > would be a good idea to have such an object in a standard library? > > > > Thx and Regards, > > > > Nicolas > > > > In Windows you can open the file 'NUL' and it will work the same as > '/dev/null' in *nix. Note that Nicolas asked for a "portable" approach... clearly neither NUL nor /dev/null are portable. From andymac at bullseye.apana.org.au Sun Jan 25 06:20:23 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 25 Jan 2004 22:20:23 +1100 (EST) Subject: Psyco on PowerPC? In-Reply-To: References: <30E0BEC9-4DE7-11D8-B663-000393DB5438@andrew.cmu.edu> <26b7aa41.0401232250.3e6588a8@posting.google.com> Message-ID: <20040125221804.T80281@bullseye.apana.org.au> On Sat, 24 Jan 2004, Benjamin Han wrote: > Ok here is what I did > > 1. pulled the latest CVS > 2. did a "python setup.py install" > 3. ran this testing program: {...} > The result (on my PowerBook G4): > > 2597406.... (big number) > * Elapsed time = 2.41602706909 > Fatal Python error: psyco: out of memory > Abort trap > > > I have 1 GB memory. Maybe it's still in the early development stage? As its not part of a public psyco release, I think that would be a safe assumption. -- 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 brian at rk-speed-rugby.dk Tue Jan 13 10:48:19 2004 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 13 Jan 2004 16:48:19 +0100 Subject: Generate PDF or LaTeX ? References: Message-ID: "Sinclair" writes: > I am looking for a way to generateLaTeX or PDF code from python/zope > objects. The goal is to produce print documents. > Does any python module exist to do that ? I did some which worked quite well for production of a Conference proceedings from a set of pdfs including keyword and author index. It is doing a latex step before the pdf. If you are interested, take a look at: http://www.et.dtu.dk/staff/be/proceedings/proceedingsdoc.pdf http://www.et.dtu.dk/staff/be/proceedings/proceedings.zip -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From na Fri Jan 9 11:42:10 2004 From: na (Andrew) Date: Fri, 9 Jan 2004 08:42:10 -0800 Subject: How to insert into listbox using wxPython Message-ID: Hi I just started learning wxPython I wanted to know how I could do this in wxPython self.listbox.delete(0, END) for item in self.results: self.listbox.insert(END, item) I don't know but I think the insert and delete things here are specific of Tkinter which I have been studying for the last little while Anyhelp would be cool From timr at probo.com Fri Jan 9 20:57:54 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 09 Jan 2004 17:57:54 -0800 Subject: CGI module problem: duplicated output References: Message-ID: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> Mimal wrote: > >Hello, > I started to learn how to use python with CGI. I went through some >tutorials, but then I found one problem, that seems to be something >stupid. I tried to find answer using google, but I couldn't. > >This is my simple CGI script: > >#!/usr/bin/python >import cgi > >print "Content-type: text/html\n" >print "Hello, world!" Pardon me for saying so, but I don't believe you. Your script must actually look like this: #!/usr/bin/python import cgi print "Hello, world!" print "Content-type: text/html\n" print "Hello, world!" That's the only answer that fits your results, and it would produce exactly the results you describe. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hans at zephyrfalcon.org Mon Jan 12 21:53:10 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 12 Jan 2004 21:53:10 -0500 Subject: how can I execute a function string In-Reply-To: References: Message-ID: <40035D96.2040800@zephyrfalcon.org> Rajarshi Guha wrote: > Hi , > I have some code that generates a function on the fly in a string. > At a later point in time I want to execute this function (which also > requires a parameters to be passed to it). So the code is something like > this: > > def generate_func(): > s = """ def function(x): > print x > return 2 > """ > return s > > funcstring = generate_func() > retval = .... > > That is, retval should have the value returned from the evaluation of the > function in the string funcstring. > > Is this possible by means of simple function calls or does this involve > some sort of black magic? It's possible: >>> def generate_func(): ... s = """def f(x): ... print x ... return 2""" ... d = {} ... exec s in d ... return d['f'] ... >>> >>> g = generate_func() >>> g(4) 4 2 >>> ...but this way of doing it has several drawbacks. For example, exec is picky about the strings it accepts; e.g. if you leave a trailing newline you get a syntax error. Compare: >>> def generate_func(): ... s = """def f(x): ... print x ... return 2 ... """ ... d = {} ... exec s in d ... return d['f'] ... >>> g = generate_func() Traceback (most recent call last): File "", line 1, in ? File "", line 7, in generate_func File "", line 4 ^ SyntaxError: invalid syntax Also, if the string containing the syntax comes from an "untrusted source", then it's a potential security hazard. I'm not sure what you're trying to do here, but you might want to consider generating an actual function, rather than a string to be evaluated: >>> def generate_func(): ... def f(x): ... print x ... return 2 ... return f ... >>> h = generate_func() >>> h(5) 5 2 HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From beliavsky at aol.com Fri Jan 16 08:39:43 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 16 Jan 2004 05:39:43 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> Message-ID: <3064b51d.0401160539.49fc5893@posting.google.com> grahamd at dscpl.com.au (Graham Dumpleton) wrote in message > Would agree that more often than not it is the programmers working > on the project. I have met very very few programmers who I thought > had what it takes to develop decent C++ code which is understandable > and maintainable. Part of the problem though is not the programmers > but the C++ libraries they have to work with. Even though the > STL may be the "standard template library", it is pretty dangerous stuff. > Your average programmer however will tell you it is wonderful stuff > and never understand its danger and how one can so easily create > huge disasters with it. What is so dangerous about the STL in C++? From wotan at oneeye.com Fri Jan 16 06:14:42 2004 From: wotan at oneeye.com (Eternal Vigilance) Date: Fri, 16 Jan 2004 11:14:42 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <4007C6CF.5DB6F586@oneeye.com> Congradulations. You finally discovered that people will not do your work for you for Free. Open Source projects produce 99% garbage and thats for the projects that already have a good working 'product'. If you want it done right, do it yourself. (Either that or get alot better at talking the right people into doing the work and then manage them without interfering too much) "Brandon J. Van Every" wrote: > "Brandon J. Van Every" wrote in > message news:bsd101$c1oj1$1 at ID-207230.news.uni-berlin.de... > > I am > > > > - *TENTATIVELY* - > > > > (operative word) undertaking the project of porting the GPL open source > game > > "Freeciv" to Python. Freeciv is, in essence, an almost straight clone of > > Sid Meier's Civilization II, albeit with better cross-platform and > > multiplayer support. www.freeciv.org > > Here's a postmortem. Short version: I've canned the project. Many of you > will say "I told you so," but at least I almost have a VS .NET 2003 build to > show for it. > > First I decided to tackle the subgoal of freeing Freeciv from the UNIX > Cygwin / MinGW crud. As I write this, I have it compiling and running on VS > .NET 2003, and that isn't a small accomplishment. But, the game hangs > shortly after the server starts. I'm probably within spitting distance of > completing this subgoal, but it has taken too long and has been really > really boring. If there isn't some major lurking horror I'll get it working > eventually, but I've put it on the backburner. Personal projects have to be > personally rewarding, and this isn't it. > > Looking at the Freeciv C code in more detail, I've realized that there's way > too much code to consider "generally" rewriting stuff in Python. Rather, > I'd have to embed Python and add / rework game functionality piecemeal. > This is a lot of work, there's a whole lot of boring "wrapper code" to cough > up. Between performing this kind of labor on a GPL project, and performing > it for Ocean Mars, I've decided that the former is not rational. And more > importantly, it doesn't make me happy. > > I've also become extremely disillusioned with Open Source developers. > Basically, for a commercially minded developer such as myself, I don't think > they're any value add at all. Ergo, all public projects I might conceive of > are fundamentally DOA. > > For 6 months I've experimented with how Open Source development might fit my > commercial goals. What I've found is that I can't rely on people, only > their coding artifacts. Every Open Source game developer I've met in the > past 6 months has been, at a basic level, a hobbyist. Hobbyists simply > don't manage projects according to the demands of commercial development. > This implies that if I'm in charge, they won't like my style; and when > they're in charge, it drives me fucking nuts. I've now accepted that the > Open Source talent pool is what it is. It is capable of being fun for > programmer geeks. But with few exceptions, such as perhaps > http://nebula.sourceforge.net, it cannot achieve the kinds of projects I > have in mind. > > I'm also starting to downright despise Linuxers. If I see another project > that's "cross-platform, so long as your platform is Linux," I'm going to cut > someone's head off. Linuxers have this completely broken piece of shit > build management mentality about them. They think that because on *their* > OS all these libraries are preinstalled, and everyone's compiling things all > the time, that they don't have to do anything to maintain consistent builds > on other platforms. Rather, it's always the induhvidual's responsibility to > download and install all the needed component libraries. Of course these > are usually UNIX-centric libraries, often not readily compiled on Windows. > Or requiring Cygwin or MinGW, which real Windows developers don't want to > use. Versioning becomes a nightmare, is it the Cygwin or MinGW version? > It's just not the way mainstream Windows developers do things. > > Whether my Freeciv VS .NET 2003 build makes it into the official Freeciv > source pool remains to be seen. The Freeciv people are, after all, a bunch > of Linuxers. They don't have a single .NET developer among them, and I'm > not about to become their .NET buildmaster. When I say things like "Windows > people want to link libpng and zlib against MSVCRT71.dll," they say, "we > don't want to bloat our source tree with needed libraries." Maybe in time I > will get them to accept a separate package of underlying libraries for > Windows folk. > > -- > Cheers, www.indiegamedesign.com > Brandon Van Every Seattle, WA > > "Desperation is the motherfucker of Invention." - Robert Prestridge From eltronic at juno.com Mon Jan 5 00:39:53 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Mon, 5 Jan 2004 00:39:53 -0500 Subject: Recurring dates module [was: Project dream] Message-ID: <20040105.004000.-3691831.0.eltronic@juno.com> writes: > > eltronic> rats, datetime IIR is only py2.3 unless it already > works in > eltronic> py2* or some kind soul has backported it ala sets and > some of > eltronic> itertools. > > Tim originally wrote datetime in Python. You can grab the latest > version > from the CVS sandbox: >http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/sandbox/date time/datetime.py > thanks, recur's test use of datetime rev=1.159 didn't require any tweak. recur itself only needs from __future__ import generators from enumerate import enumerate and /python22/lib/enumerate.py which was easy enough to create. > > There has been recent discussion on python-dev about what to do with > the > Python version of a module after it's been rewritten in C. It would > be nice > if someone figured out a way to keep datetime.py in sync with the C deep dreaming. a program to produce specifications of a modules functions from just the module itself? all such modules include a _version or something? maybe I can find the unit tests from py2.3 and see if any errors turn up. e please forward all spam to "me" ________________________________________________________________ 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 miki.tebeka at zoran.com Mon Jan 12 03:30:11 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 12 Jan 2004 00:30:11 -0800 Subject: Search and replace a specific word in a file object. References: <56f42e53.0401111519.2da31b8a@posting.google.com> Message-ID: <4f0a9fdb.0401120030.2c2534c2@posting.google.com> Hello, Use the fileinput module: from fileinput import input def replace(filename, old, new): for line in input(filename, inplace=1): print line.replace(old, new) HTH. Miki From snake at penza-gsm.ru Thu Jan 15 02:07:39 2004 From: snake at penza-gsm.ru (Alexey Nezhdanov) Date: Thu, 15 Jan 2004 10:07:39 +0300 Subject: Bug or feature? In-Reply-To: References: Message-ID: <200401151007.39791.snake@penza-gsm.ru> > Alexey Nezhdanov wrote: > > Hello. Found a strange python behaivoir while writing some > > object. I've > > stripped out all other stuff so the problem is stright here: > > ================================= > > #!/usr/bin/python > > > > class Object: > > def __init__(self,val): > > self.val=val > > > > def Sub(self,delta): > > self.val-=delta > > return delta > > > > c=Object(1) > > > > ### case 1 ### > > d=c.Sub(1) > > c.val+=d > > print 'case A:',c.val > > > > ### case 2 ### > > c.val+=c.Sub(1) > > print 'case B:',c.val > > ================================= > > Case 1 and case 2 prints out different calues (1 and 2 respectively). > > Do not know - if this is a bug or feature of python. > > Disassembly is your friend: > ... > As you can see, the order of evaluation in pluseq() is: > load val, call Sub(), add, store result. > whereas the order in subthenplus() is: > call Sub(), load val, add, store result. > > ...which explains things a bit. If we had written inst.val = inst.val + > inst.Sub(1), the order would be the same as pluseq (but we'd get a > binary add instead of inplace). > Robert Brewer Ok. Let me explain. I know the reasons of this particular effect. I have not disassembled code myself but nevertheless I come to the same idea myself. The question is - is such *python* behaivoir is correct or not. Since one person can write string like c.val+=c.Sub(1) he can expect that both addition and Sub execution will complete and no results will be dropped. -- Respectfully Alexey Nezhdanov From theller at python.net Fri Jan 16 11:51:08 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 17:51:08 +0100 Subject: Retrive unicode keys from the registry Message-ID: First I was astonished to see that _winreg.QueryValue doesn't accept unicode key names, then I came up with this pattern: def RegQueryValue(root, subkey): if isinstance(subkey, unicode): return _winreg.QueryValue(root, subkey.encode("mbcs")) return _winreg.QueryValue(root, subkey) Does this look ok? Thomas From eric.brunel at N0SP4M.com Mon Jan 19 09:42:34 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 15:42:34 +0100 Subject: Tkinter References: Message-ID: km wrote: > Hi all, > > Is there any good online tutorial which is a good intro for Tkinter programming in Python ? "Thinking in Tkinter", by Stephen Ferg: http://www.ferg.org/thinking_in_tkinter/index.html See also Tkinter example scripts in the Python *source* distribution (in Demo/tkinter) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From martin at v.loewis.de Sun Jan 25 03:58:11 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 Jan 2004 09:58:11 +0100 Subject: utf8 encoding problem In-Reply-To: <2c60a528.0401241501.11cab334@posting.google.com> References: <20040122103549.GA5620@wiggy.net> <2c60a528.0401241501.11cab334@posting.google.com> Message-ID: Andrew Clover wrote: > Quite so, in theory. Of course in reality, no browser today includes a > Content-Type header in the subparts of a multipart/form-data submission, > so there's nowhere to specify an charset here either! argh. Right. In this case, the algorithm Wichert quotes should apply. I once tried to study why browsers won't send Content-Type headers. Actually, they *do* send Content-Type headers, but omit the charset= parameter. I submitted various bug reports, and the Mozilla people replied that they tried to, and found that various CGI scripts would break when confronted with the standards-conforming request, but work when they get the deprecated form. So it looks like this situation will extend indefinitely. > multipart/form-data as implemented in current UAs is just as encoding-unaware > as application/x-www-form-urlencoded, sadly. In practical terms it does not > really matter much which is used. Right - for practical terms, standards don't matter much. As this thread shows, the form used *does* matter in practical terms though: Users of application/x-www-form-urlencoded are now confronted with the unescaping-then-decoding issue, which apparently is a challenge. Regards, Martin From http Sat Jan 3 18:45:03 2004 From: http (Paul Rubin) Date: 03 Jan 2004 15:45:03 -0800 Subject: pickling lambdas? References: <9abf3a27.0401031446.4d73cfb2@posting.google.com> Message-ID: <7x65fs38cg.fsf@ruckus.brouhaha.com> "John Roth" writes: > > however, upon google searching for "python lambda pickle" i find 2 > > posts, one including gvr, which apparently demonstrate that this was > > being attempted and even suggest that it is feasible. has this become > > available yet, or will it be soon? > > Why do you want to do this? According to the docs, all that > is saved for a function or a class is the name. Code, data and > so forth is not saved, so it makes no sense to try to pickle > a lambda unless you've bound it to a name at the module level. I think the idea may be to pickle a closure, to save the data inside it. I do remember some mention about pickling generators. Anyway, in Python 2.x the closest you can come to that is pickling class instances. From wilkSPAM at OUTflibuste.net Sat Jan 17 06:20:44 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sat, 17 Jan 2004 12:20:44 +0100 Subject: py2exe 0.5.0 (finally) released References: <87wu7rpn9d.fsf@blakie.riol> Message-ID: <87ptdi6ctv.fsf@blakie.riol> I answer to myself, the problem was because i didn't remove an old py2exe version in site-packages. Bye Wilk writes: > Hi, > > I just try this new release with the simple sample, it throw an > exception : > > Traceback (most recent call last): > File "setup.py", line 34, in ? > console = ["hello.py"], > 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 391, in create_ > binaries > arcname, target.script) > File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 590, in build_e > xecutable > self.add_versioninfo(target, exe_path) > File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 609, in add_ver > sioninfo > from py2exe.resources.VersionInfo import Version, RT_VERSION > File "C:\PYTHON23\Lib\site-packages\py2exe\py2exe.py", line 3, in ? > raise RuntimeError, "something's wrong" > RuntimeError: something's wrong > > hello.exe works indeed > > I try it on win98 and winNT, with last python2.3.3 > > There is no unicode file do download for winNT ? > > bye > > -- > Wilk - http://flibuste.net -- Wilk - http://flibuste.net From just at xs4all.nl Sat Jan 31 11:43:05 2004 From: just at xs4all.nl (Just) Date: Sat, 31 Jan 2004 17:43:05 +0100 Subject: zlib References: Message-ID: In article , Skip Montanaro wrote: > Dave> I am looking for a zlib implementation (or any other which can > Dave> handle zip archives) for Python 1.5.2. I only found one for Python > Dave> >= 2.2 :-( > > Assuming you have access to a C compiler, you might be able to fairly easily > backport the 2.2 version of zlibmodule.c back to 1.5.2. zlib is part of the 1.5.2 distro, but zipfile.py was new in 1.6 it seems. Just From __peter__ at web.de Wed Jan 28 14:19:31 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jan 2004 20:19:31 +0100 Subject: Nested lists or conditional logic? References: Message-ID: mike beck wrote: > this is not all complex, but as a noob i'm having a hard time getting > my head around it. > > i have a list of items. i need to print the items in batches of x, > with a summary line after each complete or partial batch, and a total > line at the end of the job. [...] > i've done the following, which works, but it seems like there must be > a better/simpler/faster way to do this with nested loops. ideas? Your code looks OK to me (apart from the duplicate colon). Here's a "no maths" variant that uses nested loops: from itertools import islice ITEMSINBATCH = 3; ARBITRARYNUM = 11; sample = ["item #%d" % i for i in range(ARBITRARYNUM)] it = iter(sample) while True: more = False for item in islice(it, ITEMSINBATCH): more = True print item if not more: break print "summary" I'm generally fond of the itertools module; this time I didn't find a way to get rid of the ugly more flag, though. Implementing your own iterator with a hasMore() method seems overkill. Peter From djordje.telebak at telekom.yu Thu Jan 29 10:02:42 2004 From: djordje.telebak at telekom.yu (Djordje Telebak) Date: Thu, 29 Jan 2004 16:02:42 +0100 (Central Europe Standard Time) Subject: Upload with FTP Message-ID: <40192092.00000F.03492@DX_GX100_79> Hi all I'm trying to write a little python file for file upload. I have wrote something like this from ftplib import FTP ftp = FTP('172.xxx.yyy.zzz') ftp.login('login_name','password') ftp.storlines('STOR PRE',something) ftp.quit() I don't know what is wrong and what I have to put instead of something or to change i this line to make this work (to upload file PRE from let's say C:\ directory to some home dir. on host 172.xxx.yyy.zzz). BR Djordje Telebak -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: IMSTP.gif Type: image/gif Size: 494 bytes Desc: not available URL: From jensthiede at webgear.co.za Wed Jan 21 13:16:46 2004 From: jensthiede at webgear.co.za (Jens Thiede) Date: 21 Jan 2004 10:16:46 -0800 Subject: ServingSocket question regarding the SystemExit exception Message-ID: How do I get SystemExit to be of use, but not noticed in a StreamRequestHandler spawned by a ThreadingTCPServer? I tried various ways of getting rid of a StreamRequestHandler thread namely thread.exit() sys.exit() (which is basicly just raises SystemExit) and all these were caught (for that reason). So I tried os._exit(0) and even os.kill(pid, 15) and os.kill(pid, 9) but, ofcourse they get rid of my program all together. Help would be valued, Jens Thiede From noemail at noemail4u.com Thu Jan 22 07:46:44 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 22 Jan 2004 12:46:44 GMT Subject: Checking for duplicate instances of a script... References: <400e4638$0$19274$626a54ce@news.free.fr> Message-ID: <8b146afd37580ecc733f713e953b542c@news.teranews.com> On Wed, 21 Jan 2004 10:28:20 +0100, "Guillaume Dargaud" wrote: >Hello, python beginner here, >How can I make sure that a given script is never run more than once at the >same time in a system ? >Besides checking 'ps' for its own name. Most modern langages have a direct >way to do that. >Thanks What modern language has a direct way to do that? --dang From gagenellina at softlab.com.ar Fri Jan 30 20:53:44 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: 30 Jan 2004 17:53:44 -0800 Subject: Automatic access serialization Message-ID: <946d2ebc.0401301753.5bbe87c5@posting.google.com> Hello! I have a number of objects that are not thread-safe - no locking mechanism was originally provided. But I want to use them in a thread-safe way. I don't want to analyze each class details, looking for where and when I must protect the code. So I wrote this sort-of-brute-force locking mechanism using threading.RLock() around __getattr__ / __setattr__ / __delattr__. The idea is that *any* attribute and method access is protected by the lock. The calling thread may acquire the lock multiple times, but other threads must wait until it is released. This may be too much restrictive, and a bottleneck in performance, since *all* accesses are effectively serialized - but it's the best I could imagine without deeply analyzing the actual code. I *think* this works well, but since I'm not an expert in these things, any comments are welcome. Specially what could go wrong, if someone could anticipate it. Note: As written, this only works for old-style classes. I think that just by adding a similar __getattribute__ would suffice for new-style classes too - is that true? --- begin autolock.py --- import threading class AutoLock: # "brute-force" locking wrapper to any object # *all* attribute access is serialized in a thread-safe way. def __init__(self, target): dict = self.__dict__ dict['_%s__lock'%self.__class__.__name__] = threading.RLock() dict['_%s__target'%self.__class__.__name__] = target def __getattr__(self, key): self.__lock.acquire() try: return getattr(self.__target, key) finally: self.__lock.release() def __setattr__(self, key, value): self.__lock.acquire() try: setattr(self.__target, key, value) finally: self.__lock.release() def __delattr__(self, key): self.__lock.acquire() try: delattr(self.__target, key) finally: self.__lock.release() --- end autolock.py --- Gabriel Genellina Softlab SRL From Kyler at news.Lairds.org Tue Jan 20 10:12:05 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 20 Jan 2004 15:12:05 GMT Subject: efficent test for array with only one value? References: <00ird1-dmd.ln1@jowls.lairds.org> <25mud1-s1m.ln1@jowls.lairds.org> Message-ID: Robert Kern writes: >However, alltrue(a.flat == a.flat[0]) will work but won't short-circuit. How did I miss that?! Yes, that's the kind of operation I sought. I'm surprised that it doesn't short-circuit. It *should*, right? It's a shame that it only works along a single axis. The use of "flat" is a problem for me. I'm looking at sections of an image (building a quadtree) so the arrays I'm checking are not contiguous. I think that means I have to resort to something ugly like this. Numeric.alltrue(Numeric.alltrue(a == a[0,0])) That eliminates many opportunities for short-circuiting. I can also flatten the array using reshape() before checking it. I assume that also means a lot of possibly unnecessary operations. (Does reshape() return a copy of the array or just an array with the original data and a new shape?) >Fast, though, if the array isn't huge. Indeed, I think I'll use it. I can always write a clean short- circuiting C version later. Thank you! --kyler From hameedkhaan at yahoo.com Sat Jan 24 03:07:53 2004 From: hameedkhaan at yahoo.com (Hameed Khan) Date: Sat, 24 Jan 2004 00:07:53 -0800 (PST) Subject: there is no exitfunc in sys module Message-ID: <20040124080753.97159.qmail@web61109.mail.yahoo.com> hi, i was reading the manual for sys module. i found a description for a function known as exitfunc. and it says the function installed by sys.exitfunc(cleanUpFunc) call will be called when the interpreter exits. but when i try to call this function on Python interactive prompt it says there is no attribute named exitfunc in sys module. ### >>> sys.exitfunc Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'exitfunc' >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout_ _', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'call stats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info', 'exc_type', 'excepthook' , 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemenc oding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'hexversion', 'last_traceback', ' last_type', 'last_value', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'p ath_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrec ursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', ' winver'] ### i am wondering that only i dont have this in my sys module or it is being deleted from sys module. and if only i dont have this function what reason it could be that i dont have this function. ### Version information >>> sys.version '2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]' Thanks, Hameed Khan __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From srsy70 at yahoo.com Mon Jan 19 10:24:50 2004 From: srsy70 at yahoo.com (S.Ramaswamy) Date: 19 Jan 2004 07:24:50 -0800 Subject: ConfigParser - setting the order of options in a section Message-ID: I am trying unsuccessfully to set the order of options using the set(section,option,value) method ( Python 2.2.2) and writing to a file. But the options always appear in a random order. Before each option I am writing a comment line using set(section,"#",value) - a one line explanation for the option that follows - but the comments get re-ordered randomly. ------------------------------------------------------------------------------------ cfg.add_section("COOL") cfg.set("COOL","#","This is option A001") cfg.set("COOL","A001","1") cfg.set("COOL","#","This is option B001") cfg.set("COOL","B001","2") cfg.set("COOL","#","This is option C001") cfg.set("COOL","C001","3") cfg.write(file) ------------------------------------------------------------------------------------- The comments for the options get jumbled up - I want them to be written before the option=value line. Instead the comments for options A001,B001,C001 all get ordered randomly. Any help in getting the sections to be written in order will be appreciated. srsy - From gerrit at nl.linux.org Thu Jan 15 13:01:41 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 15 Jan 2004 19:01:41 +0100 Subject: TUPLE & LIST In-Reply-To: References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <20040115180141.GA5217@nl.linux.org> Christos TZOTZIOY Georgiou wrote: > Examples: > Use a list for a list of names. > Use a tuple for (x,y) coordinates in some area. > Use a list of (name,phone,address) tuples for your poor man's address > book which you will implement in python. What if someone moves away? That is, I think one could better use a mutable type for the address book. yours, Gerrit. -- 46. If he do not receive a fixed rental for his field, but lets it on half or third shares of the harvest, the grain on the field shall be divided proportionately between the tiller and the owner. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From nomail at nospam.net Tue Jan 13 05:19:23 2004 From: nomail at nospam.net (Olaf Meyer) Date: Tue, 13 Jan 2004 10:19:23 GMT Subject: problems with dict() in python 2.2 In-Reply-To: References: Message-ID: Just wrote: > In article , > Olaf Meyer wrote: > > >>I'm trying to build a dictionary using python's dict type, but somehow >>it does not work the way I expect it to. Here's the code: >> >>Python 2.2.1 (#7, Jan 9 2004, 16:59:31) [C] on hp-ux11 >>Type "help", "copyright", "credits" or "license" for more information. >> >>> data=dict(red=1) >>Traceback (most recent call last): >> File "", line 1, in ? >>TypeError: 'red' is an invalid keyword argument for this function >> >>What am I doing wrong? > > > You're using a 2.3 feature in 2.2. > > Just Allright, I thought it was 2.2. Too bad, since I cannot get 2.3 compiled on HP-UX. Olaf From tcdelaney at optusnet.com.au Tue Jan 20 01:20:52 2004 From: tcdelaney at optusnet.com.au (Tim Delaney) Date: Tue, 20 Jan 2004 17:20:52 +1100 Subject: speedy Python strings? References: <20040119185543.ABC7.JCARLSON@uci.edu> Message-ID: <400cc8c4$0$26115$afc38c87@news.optusnet.com.au> "Josiah Carlson" wrote: > Deleting from the front of a list results in every item being > shifted up a single entry. While this is insignificant for > short lists, it is significant for long lists: Note that there's been some very interesting discussions on python-dev recently that may end up alleviating this issue somewhat in the future - but no promises - there doesn't appear to be a consensus on the "right way" ... Tim Delaney From ddw at missioncriticalit.com Thu Jan 22 12:00:55 2004 From: ddw at missioncriticalit.com (Dominique de Waleffe) Date: Thu, 22 Jan 2004 18:00:55 +0100 Subject: Simple requests sequentialiser? Message-ID: <401001C7.8010005@missioncriticalit.com> I have a need to have a simple multithreaded sort of proxy wich listens to a given port and for each client session, sends the requests to a single server (mono thread and listening on one single port) that sits behind and returns the answers to the appropriate client. I confess that I have spent very little time on finding a solution to this yet. I have a feeling that this should be a piec of cake for python possibly with twisted or even without it.... Is there anyone that can give me a pointer to an example or to a specific place in the voluminous documentation of python and tools for such a thing.... Thansk, D. -- Dominique de Waleffe Email: ddw at missioncriticalit.com [No HTML please] Mission Critical, Dr?ve Richelle 161 B?t N, B-1410 Waterloo, Belgium Phone: +32 2 757 10 15 Fax: +32 2 759 27 60 ICQ: 289-306-495 From k.robert at gmx.de Mon Jan 19 12:22:25 2004 From: k.robert at gmx.de (Robert) Date: Mon, 19 Jan 2004 18:22:25 +0100 Subject: interface to win job scheduler portable from win98 .. winXP / cmdline or COM ? Message-ID: <400c134c$0$9745$9b622d9e@news.freenet.de> I found the os.popen("AT /?") way .... however it works not on Win98 and the "Day" you enter at the AT are language dependent. (e.g. Mi(ttwoch) in german, We(dnesday) in english Windows versions) I need a solution work from Win98..WinXP most independent from internationalization etc. is there portable way - or at all a way to manipulate the Win98/ME scheduler ? if no simple means, even COM stuff would be ok. any pointers? robert From phleum_nospam at chello.se Fri Jan 9 16:45:13 2004 From: phleum_nospam at chello.se (Carl) Date: Fri, 09 Jan 2004 22:45:13 +0100 Subject: Python is far from a top performer according to benchmark test... References: Message-ID: Krzysztof Stachlewski wrote: > "Carl" wrote in message > news:ryELb.238$tK2.228 at amstwist00... > >> I have been experimenting with numerical algorithms in Python with a >> heavy use of the Numeric module. My experience is that Python is quite >> fast in comparison with (and sometimes as fast as) traditional languages >> such as C or C++. > > With "heavy use of Numeric module" you were calling functions > written in C. So how can you say that Python is fast, > when C code is doing all the work. > > Stach Well, I guess you are right! What I meant was that when I run my Python algorithm it runs "almost as fast as" when I run similar code in C or C++. This is of course due to the highly efficient Numeric module. However, the point is that Python is a viable language from a numerical perspective. Carl From gerrit at nl.linux.org Fri Jan 23 07:20:27 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 23 Jan 2004 13:20:27 +0100 Subject: strtotime? In-Reply-To: <40106680.849ADEFA@engcorp.com> References: <40105afb$0$319$e4fe514c@news.xs4all.nl> <40106680.849ADEFA@engcorp.com> Message-ID: <20040123122027.GA2914@nl.linux.org> Peter Hansen wrote: > Leif K-Brooks wrote: > > Irmen de Jong wrote: > > >> PHP has a very nice strtotime function (http://php.net/strtotime) > > >> which converts a date/time in virtually any format into a timestamp. > > >> Does Python have a similar function? > > > > > > I guess you're looking for: time.strptime > > > > Thanks, but no. PHP's strtotime() function magically guesses the format > > on its own, time.strptime() just uses a fixed format. > > Perhaps the mx.DateTime package would help: Or DateUtil: https://moin.conectiva.com.br/DateUtil >>> parse("3rd of May 2001") datetime.datetime(2001, 5, 3, 0, 0) yours, Gerrit. -- 6. If any one steal the property of a temple or of the court, he shall be put to death, and also the one who receives the stolen thing from him shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From swalters_usenet at yahoo.com Mon Jan 5 16:06:43 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 21:06:43 GMT Subject: explicit variable declaration References: Message-ID: |Thus Spake Luis Sol?s On the now historical date of Mon, 05 Jan 2004 08:23:56 +0000| > Hi > It is possible to declare some variables as int, long... ? , or something > like visual basic option explicit. > In some situations could be usefull. > Thanks Well, in python, that is left to programmer's discretion. Once you get used to it, it's less of a hassle and danger zone than you'd expect. You can read GvR's (Our Benevolent Dictator For Life) thoughts on contracts in python here: http://www.artima.com/intv/pycontract.html As a fallback, you can always use the isinstance() and type() functions to check what type of variable you have on hand. Generally, isinstance is what you want to use because it returns true for subclasses. If the subclass doesn't do everything you'd expect of it's superclass, then either your or the subclass writer have broken their contract. If you absotively posolutely must know that a variable is a certain class, not a subclass and nothing but the bona fide variable type you expected, then use type(). This, however, is seldom the case because using type() could prevent future programmers from extending your code. If you want even more assurances, look into pylint and pychecker: http://www.logilab.org/projects/pylint http://pychecker.sourceforge.net/ HTH Sam Walters. p.s. The python-tutor list is probably a better place to ask questions like this. You're most likely to get helpful answers to questions about the basics than you are here. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From __peter__ at web.de Thu Jan 8 11:51:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Jan 2004 17:51:01 +0100 Subject: Calling a function dynamically References: <924a9f9c.0401080742.39eba581@posting.google.com> Message-ID: Paradox wrote: > I would like to call a function whose name I supply at runtime. > Something like this but it didn't work > > functionName = 'run' > instance = ClassDef() > args = [1, 2] > > #want the dynamic equivalant of > #instance.run(*args) > > #This didn't work cause there was no __call__ attribute. Why? > value = instance.__call__[functionName](*args) The __call__() method is implicitly invoked when you write value = instance(some, args) Here's a way to abuse the [] operator (implemented by __getitem__()) to dynamically select a method: >>> class Test: ... def __getitem__(self, name): ... return getattr(self, name) ... def run(self, *args): ... print "run%s" % (args,) ... >>> t = Test() >>> t["run"] > "bound method" means that both instance and method are stored, so that for the actual call you need not provide an explicit self parameter: >>> t["run"]("alpha", "beta", "gamma") run('alpha', 'beta', 'gamma') Peter From mborgerding at cinci.rr.com Sat Jan 17 14:27:19 2004 From: mborgerding at cinci.rr.com (Mark Borgerding) Date: Sat, 17 Jan 2004 19:27:19 GMT Subject: yield In-Reply-To: References: Message-ID: km wrote: > Hi all, > > i didnt understand the purpose of 'yield' keyword and the concept of 'generators' in python. can someone explain me with a small example how generators differ from normal function calls? > kindly enlighten > regards, > KM > I think of it as an "interrupt" that provides a value back to the caller for each value in a sequence. It can also be loosely thought of as an iterator(sort of). Here's an example that may (or may not) help: def foo(): print 'entering foo function' for i in range(3): print 'yielding %s' % i yield i print 'leaving foo function' for x in foo(): print 'x is %s' % x ################ prints out the following: entering foo function yielding 0 x is 0 yielding 1 x is 1 yielding 2 x is 2 leaving foo function From piet at cs.uu.nl Mon Jan 26 04:58:27 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 26 Jan 2004 10:58:27 +0100 Subject: compress string of data References: Message-ID: >>>>> Gerrit Holl (GH) wrote: >> How i could compress string of data?. >>>> import zlib >>>> zlib.compress("Hello, world") GH> 'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' GH> http://www.python.org/doc/current/lib/module-zlib.html Waw, that compresses it from 12 bytes to 20 bytes :=) -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From peter at engcorp.com Fri Jan 9 09:35:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:35:22 -0500 Subject: silent saveas ? References: Message-ID: <3FFEBC2A.CFA39FA3@engcorp.com> Please don't post HTML to this list/newsgroup. > I?m having difficulties to save the web browser in silent when I try to use > WebBrowser1.ExecWB OLECMDID_SAVEAS, OLECMDEXECOPT_DONTPROMPTUSER, "c:\blank.html", > "c:\blank.html" > The save window keep prompting up. How can I keep the save window in silent? > Please help me, Thanks a lot To answer your question as best I can: have you checked the Microsoft documentation for WebBrowser1? Surely it will answer the question for you... at the least, there's nothing Python-related in your question, and your code doesn't even appear to be Python, so I'm not sure why you're posting here. (Note: if that was really supposed to be Python, you should know that using a \b in a string like that will not generate a backslash and a "b", but will actually generate a single BACKSPACE character.) -Peter From tzot at sil-tec.gr Tue Jan 13 12:45:09 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 13 Jan 2004 19:45:09 +0200 Subject: Does anyone else not find the fun in programming...? References: Message-ID: <4hb800hefrkre2p12o6pijr5lb2pui55n2@4ax.com> On Tue, 13 Jan 2004 18:28:13 +0100, rumours say that Rony might have written: [snip: Chris Lyon doubts that programming is fun] >> Do I need help ? >> >> (Actually typing this was quite fun, so perhaps) [Rony] >Well I agree... >Meeting people, having a drink with them, sex.. is fun > >Programming is just a job Programming can be fun if seen as creation. It's hard to be fun when you do what others request, but it *is* fun when you write programs for your own reasons... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From wilkSPAM at OUTflibuste.net Fri Jan 16 17:00:30 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Fri, 16 Jan 2004 23:00:30 +0100 Subject: py2exe 0.5.0 (finally) released References: Message-ID: <87wu7rpn9d.fsf@blakie.riol> Hi, I just try this new release with the simple sample, it throw an exception : Traceback (most recent call last): File "setup.py", line 34, in ? console = ["hello.py"], 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 391, in create_ binaries arcname, target.script) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 590, in build_e xecutable self.add_versioninfo(target, exe_path) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 609, in add_ver sioninfo from py2exe.resources.VersionInfo import Version, RT_VERSION File "C:\PYTHON23\Lib\site-packages\py2exe\py2exe.py", line 3, in ? raise RuntimeError, "something's wrong" RuntimeError: something's wrong hello.exe works indeed I try it on win98 and winNT, with last python2.3.3 There is no unicode file do download for winNT ? bye -- Wilk - http://flibuste.net From llothar at web.de Mon Jan 12 14:09:54 2004 From: llothar at web.de (Lothar Scholz) Date: 12 Jan 2004 11:09:54 -0800 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <6ee58e07.0401120542.5d79090d@posting.google.com> Message-ID: <6ee58e07.0401121109.52d5dc56@posting.google.com> cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote in message news:... > At some point, llothar at web.de (Lothar Scholz) wrote: > > > Samuel Walters wrote in message news:... > > > >> I know very little about numeric processing, and even less about Fortran. > >> It's true that my background is in mathematics, but in *pure* mathematics > >> where pointer-based languages tend to be helpful, not hurtful. > > > > Okay seems that you don't know a lot about compiler writing. > > > > A C compiler only knows a little bit about the context so it must > > always assume that a data inside a member can be referenced from > > another place via an alias pointer. > > > > Fortran does not have this problem so a lot of optimizations can be > > done and values can be hold in registers for a much longer time, > > resulting in much greater speed. > > > > Remember that on supercomputers a 25% spped enhancement (which a good > > fortran compiler is faster then C) can mean a few million dollars of > > saved hardware costs. The coding time is not importing compared to the > > running time. So real hard numerics are always done in Fortran. > > > > GNU Fortran is a stupid project because it translates the Fortran code > > to C. > > Err, no. You're thinking of f2c. GNU Fortran uses the same backend as > the GNU C compiler, in that it translates to the same intermediate > language (sort of assembly language) on which optimizations are done. > But the C front end and the Fortran front end are separate. > But the front end is, as far as i know, only responsible for syntax analysis. All code generation like control flow analysis, register allocation etc. is done on the intermediate 3 register language. And the hints you could get from the fortran language are simply unused. But i must say that i never used Fortran (when i studied physics) in the last 15 years for any real programming. I only wanted to point out that a lot of languages are by design faster then C. Fortran was one of these. You can find articles on the web where the same is explained for lisp and functional languages. C and C++ is not a good compilation language when it comes to compiler optimization. From tjreedy at udel.edu Thu Jan 8 14:07:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jan 2004 14:07:11 -0500 Subject: Name of the function References: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> Message-ID: "anton muhin" wrote in message news:btjuct$84v33$1 at ID-217427.news.uni-berlin.de... > Olaf Meding wrote: > > I am looking for a way to get at the name of the function (while > > executing code inside the function) without (!) knowing the name of > > the function. > > > This seems to work: > > def foo(): > print inspect.currentframe().f_code.co_name as does this ... >>> def f(): print f.func_name ... >>> f() f ... as long as 'f' remains bound to that function in the same module, which it will unless rebound either from within or without. Terry J. Reedy From bart_nessux at hotmail.com Fri Jan 23 14:43:37 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 23 Jan 2004 14:43:37 -0500 Subject: when x process isn't running... do something Message-ID: Howdy, I'm trying to time how long it takes dd to run on a G5, versus how long it takes to run on a G4 (PATA vs. SATA). Both sytems have Mac OS X 10.3.2 and Python 2.3. Could someone demonstrate how I might use Python to monitor for the presense of a process and to do something (in this case send an email which I know how to do) as soon as that process is no longer present? Any suggestions on how to monitor? Call top every 5 secs and read it's output searching for 'dd'??? TIA, Bart From jcarlson at nospam.uci.edu Fri Jan 30 03:33:36 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 00:33:36 -0800 Subject: mod_speling for python In-Reply-To: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Message-ID: > I know there are drawbacks, disadvantages, this is "evil", etc. I > only wanted to know what ways there are to add such a hook if it is > possible without altering the C source for python itself. Ambiguities during execution are bad. I've got two functions Foo and foO, if I type in foo, what did I mean? - Josiah From gumuz at looze.net Thu Jan 15 08:43:50 2004 From: gumuz at looze.net (Guyon Morée) Date: Thu, 15 Jan 2004 14:43:50 +0100 Subject: QT usage confusion Message-ID: <40069912$0$251$4d4ebb8e@news.nl.uu.net> hmmm, all this time that I am fooling around with python I never took a good look at (py)QT. I want to have a go at it, after being a bit disapointed about the alternatives. I have read multiple docs about it and searched this newsgroup I came to the conclusion that, as I am a windows user, I have only 2 options: - buy a commercial qt license - try it out for 30 days (!) that sucks ;) am I wrong? please tell me I'm wrong. From enleverca-bknews at ifrance.com Tue Jan 13 12:41:36 2004 From: enleverca-bknews at ifrance.com (=?ISO-8859-1?Q?=22C=E9dric_V=2E=22?=) Date: Tue, 13 Jan 2004 18:41:36 +0100 Subject: error at "import anydbm" Message-ID: <40042edd$0$24038$626a54ce@news.free.fr> Hi, I am unable to import anydbm without error under Python2.2 or 2.3 (Linux). this script: >#!/usr/bin/env python >import anydbm > >if __name__ == "__main__": > db = anydbm.open("test", "rwc") > db["test"] = "ok" returns at execution: >cedric at dev _test $ python dbm.py >Traceback (most recent call last): > File "dbm.py", line 2, in ? > import anydbm > File "/usr/lib/python2.3/anydbm.py", line 59, in ? > _errors.append(_mod.error) >AttributeError: 'module' object has no attribute 'error' (the same with python2.2) do I have forgotten something? or is it another problem? thanks in advance, -- CV From mwh at python.net Thu Jan 15 06:13:06 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 15 Jan 2004 11:13:06 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <4003cfeb$0$19263$626a54ce@news.free.fr> Message-ID: Christos "TZOTZIOY" Georgiou writes: > On Tue, 13 Jan 2004 12:21:00 +0100, rumours say that Bruno Desthuilliers > might have written: > > > > >Woops ! The problem with Perl is actually that it's more or less a > >write-only language !-) > > > > I think you mean Perl is a WORN language (Write Once, Read Never). WORA (Write Once, Run Away)? Cheers, mwh -- Worryingly, DEFUN appears to be a function that removes all the fun from something: after using it all your code is converted to C++. -- Tim Bradshaw, comp.lang.lisp From aldo123 at onet.pl Mon Jan 26 09:46:25 2004 From: aldo123 at onet.pl (mic) Date: Mon, 26 Jan 2004 15:46:25 +0100 Subject: weird COM hazard References: Message-ID: I've found the walkaround by setting within the child event class constructor the local attribute that's equal to the external status class. I can then reach the status without previously mentioned, random exceptions. Strange, but works ok. Now I'm just investigating why my COM proxy object returns at first string 'Microsoft Internet Explorer' and after a while: win32com.client.COMEventClass. Does anyone know why? From mcherm at mcherm.com Mon Jan 5 09:51:58 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Mon, 5 Jan 2004 06:51:58 -0800 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module Message-ID: <1073314318.3ff97a0e68ffe@mcherm.com> Peter writes: > There's a new PEP available: > > PEP 324: popen5 - New POSIX process module > > A copy is included below. Comments are appreciated. Just one really minor suggestion: in the class Popen, the default values for the arguments close_fds and universal_newlines should be False not 0. And I vote +1 on changing the name from "popen5" to something else. "process" (as suggested in the PEP) isn't too bad, but I'd certainly be open to another name. If this is to replace the entire rest of the popenX family for most normal purposes, a separate, more comprehensible name will help newbies find it. -- Michael Chermside From jzgoda at gazeta.remove-this.pl Tue Jan 20 14:29:41 2004 From: jzgoda at gazeta.remove-this.pl (Jarek Zgoda) Date: Tue, 20 Jan 2004 19:29:41 +0000 (UTC) Subject: python As400 References: Message-ID: Enrique pisze: > I'm very interested in python for AS/400. I must migrate an application that > is running under windows to AS/400. > Has anyone worked with python in that platform?? Yes, with real pleasure. ;) > what about performace?? Worse than CL/RPG, similar to Java, better than REXX -- in case of batch jobs. Didn't try running Python scripts interactively. > The scripts are basicly of string manipulation and i/o. Check http://www.iseriespython.com/ -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From mcfletch at rogers.com Thu Jan 22 00:08:10 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 22 Jan 2004 00:08:10 -0500 Subject: [Numpy-discussion] Status of Numeric In-Reply-To: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> Message-ID: <400F5ABA.3090608@rogers.com> Arthur wrote: >On Wed, 21 Jan 2004 16:22:43 -0700, Tim Hochberg > wrote: > > ... >>The first is that last I heard the crossover point where >>Numarray becomes faster than Numeric is about 2000 elements. It would be >>nice if that becomes smaller, but I certainly wouldn't call it extreme. >>In fact I'd venture that the majority of cases where numeric operations >>are a bottleneck would already be faster under Numarray. In my >>experience, while it's not uncommon to use short arrays, it is rare for >>them to be a bottleneck. >> >> > >Couldn't one argue that - for example - in 3d graphic applications the >performance as to short arrays is crucial. > > I would imagine so, but then I'm a 3D guy, and really, the numeric community is not AFAIK mostly 3D guys. Most in the numeric community seem to be the scientific guys, who want to deal with really big arrays. Moderately sized scenegraphs are going to have 1000s of nodes with 3 or 4 matrices each (each matrix being 3, 4, or occasionally 16 values) and then a few hundred larger matrices for defining vertex/colour/normal/texture content, plus a few hundred matrices created/destroyed per frame (1/60th of a second or so)). But then most Python scenegraph engines (OpenGLContext being the only counterexample of which I know) are going to simply expose such matrices from their C/C++ engine, not use Num* arrays. Memory would likely be the most critical question for such applications. Not sure how much extra overhead is really being discussed. 4000 extra dictionary-based instances could really add up memory-wise. But a 20 or 30 byte overhead/matrix isn't likely going to kill anything that performs adequately in Python to begin with. >But hoping that in fact numarray does come to be accepted as the >"standard". > > AFAIK we still can't compile PyOpenGL with numarray, so I suppose I'm on the fence :) . Should really figure out what makes it fail some day soon I suppose. >>The second point is the relative speediness of Numeric at low array >>sizes is the result that nearly all of it is implemented in C, whereas >>much of Numarray is implemented in Python. >> >> > >Good for me. I'll be able to understand more of it. > > Hmm, this does concern me a little. 3D graphics needs to do a lot of a very small number of operations (dot and cross product, and basic add/multiply/divide mostly). If each of those calls is going through an extra Python layer, there might be pretty significant slowdowns. >>This results in a larger >>overhead for Numarray, which is why it's slower for small arrays. As I >>understand it, the decision to base most of Numarray in Python was >>driven by maintainability; it wasn't an attempt to optimize large arrays >>at the expense of small ones. >> >> > >I was indeed making an assumption here. Ifs its wrong, its indeed >wrong. > > Sounds as though the Python layer is being used to dispatch C or C++ coded functions on internal structures of the array, which would be consistent with the optimisation pattern (larger the dispatched operation, the less percentage overhead involved). >For reasons that are non-technical, I believe it much to the best that >the community continue to look to one package of the sort as a >standard. To me. even better if it makes it into the core >distribution. > > Core or not doesn't really concern me. But definitely one standard. Even now, we're starting to get users stymied by having Numarray and having it pretend to be Numpy so that PyOpenGL craps out with nasty errors when it tries to do anything with Numpy. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From nuffsaid at phreaker.net Mon Jan 19 16:06:18 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Mon, 19 Jan 2004 22:06:18 +0100 Subject: Tkinter color names/codes References: Message-ID: On Mon, 19 Jan 2004 20:39:18 +0000, Jeff Seale wrote: > I just happend to notice that there are very FEW colors that you have to > generate using #hex codes. But I was wondering, how many colors have names > assigned to them in Tkinter and what are their #hex translations? It'd be > nice to know these so I don't accidentally create a color that already has > a name. http://wiki.tcl.tk/8606 - list with all named colors in Tcl/Tk http://wiki.tcl.tk/colors - W3C names, hex codes and Tcl/Tk names for the 16 HTML 3.2 colors (i.e. the basic VGA set) HTH / Nuff From newsgroups at jhrothjr.com Thu Jan 15 22:12:22 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Jan 2004 22:12:22 -0500 Subject: keeping Python code properly indented References: <3064b51d.0401151125.711ade4c@posting.google.com> Message-ID: <100elmgcoiva8a@news.supernews.com> wrote in message news:3064b51d.0401151125.711ade4c at posting.google.com... > How do you keep Python code properly indented as you modify it? I use > an Emacs-type editor that has a Python mode, so the initial indenting > is easy. If I later want to put a 'for' loop (or an 'if' statement) > around a bunch of code, I find myself going through the body of the > loop, manually re-indenting to keep the nested loops correct. There > should be a better way. > > I think that having a 'for' loop end with a matching 'next' statement, > as done in (for example) Basic, is a safer and clearer way of writing > loops, although some Python programmers consider this a 'feature' > rather than a 'bug'. Just about every editor in existence allows you to select a range of lines and indent or dedent them as a group. If your editor doesn't let you do this, get a better editor. John Roth From skip at pobox.com Tue Jan 13 18:05:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 13 Jan 2004 17:05:31 -0600 Subject: error at "import anydbm" In-Reply-To: References: <40042edd$0$24038$626a54ce@news.free.fr> <4004482A.A66C2886@engcorp.com> Message-ID: <16388.31163.312989.480225@montanaro.dyndns.org> Paul> What if the standard library modules were put into a "std" Paul> package, to help get them out of the global import namespace? (Of Paul> course, this would break *scads* of code, so maybe should be Paul> deferred to 3.0. Or for migration purposes, implement this in a Paul> 2.x release, and provide shadow xxx imports that import the Paul> std.xxx modules.) This has come up before. It is definitely PEP territory. I think it would be a good idea, though in the short term (e.g., 2.4, 2.5) the best you can probably hope for is that a std package and the current modules live side-by-side. A couple problems were raised during the last go-round on python-dev. Any PEP would have to address them: 1. In a naive implementation these two statements: import std.sys import sys will result in two separate entries in sys.modules and thus the module level code will be executed twice. During a transition period you have to assume that an application will have a combination of both styles of imports. 2. A simple way to achieve a std package parallel to the current global namespace on Unix-y systems would be to use symbolic links. This won't work on Windows. You'd like to avoid duplicating modules, in part because it would probably make it harder to solve #1 above. Skip From skip at pobox.com Mon Jan 5 07:00:53 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 5 Jan 2004 06:00:53 -0600 Subject: intellectual property agreements and open source . was - Re: Why does this fail? [2] In-Reply-To: References: <84fc4588.0401042209.60cdb724@posting.google.com> Message-ID: <16377.20981.968499.465567@montanaro.dyndns.org> Dave> How does participating in open source work for someone (me) who Dave> has signed the customary intellectual property agreement with the Dave> corporation that they work for? Since programming is part of my Dave> job, developing test solutions implemented on automatic test Dave> equipment (the hardware too) I don't know if I would/could be Dave> poison to an open source project. How does that work? Only your corporate counsel knows for sure. Seriously, the degree to which you are allowed to release code to an open source project and the manner in which is released is probably a matter best taken up with your company's legal department. Some companies are fairly enlightened. Some are not. You may need very little review to release bug fixes or test cases (my guess is you might be pretty good at writing test cases ;-), more review to release a new module or package, and considerable participation by management and the legal eagles if you want to release a sophisticated application into the wild. In any case, if you make large contributions to an open source project such as Python, I'm pretty sure a release form for substantial amounts of code will be required at the Python end of things. See here http://www.python.org/psf/psf-contributor-agreement.html for more details. Note that it hasn't been updated in a couple years. I don't know if MAL has something which is more up-to-date. Skip From achim.marcel at uqam.ca Tue Jan 13 12:22:55 2004 From: achim.marcel at uqam.ca (Marcel Achim) Date: Tue, 13 Jan 2004 17:22:55 GMT Subject: tkinter canvas postscript fontmap Message-ID: Hi, I want to set the fontmap to be used when saving the file. I write to the canvas using Arial and would like to get either Arial or Courier in the resulting .ps instead of MsSansSerif... I haven't found any sample on the net. Has anyone done this before with success ? What is the format of the "fontmap" option ? thanks Marcel From bart_nessux at hotmail.com Tue Jan 13 15:26:01 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 13 Jan 2004 15:26:01 -0500 Subject: Make a function call itself after set amount of time In-Reply-To: References: Message-ID: Peter Otten wrote: > Bart Nessux wrote: > > >>Bart Nessux wrote: >> >>>How do I make a function call itself every 24 hours. Also, is there a >>>way to start the program automatically w/o depending on the OS functions >>>like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and >>>xp. Below is an example of what I'm trying to do. > > > [...] > > >>I figured it out. I added this to the function definition: >>ipconfig_email() > > > Note that Python has a limit for nesting functions: > > >>>>depth = 0 >>>>def callself(): > > ... global depth > ... depth += 1 > ... callself() > ... > >>>>try: > > ... callself() > ... except RuntimeError, e: > ... print "depth", depth > ... print e > ... > depth 999 > maximum recursion depth exceeded > > >>>>999/365.25 > > 2.7351129363449691 > > This means that your app will probably crash in less than three years. > Would that be a problem on W2K ? > > If so, a loop could go much longer: > > while True: > ipconfig_email() > > Seriously, you should reconsider the OS features. > > Peter > The computers are turned off and on... the script starts at boot. I don't think I'll hit a limit, do you? From loic at yermat.net1.nerim.net Thu Jan 1 19:08:03 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Fri, 2 Jan 2004 01:08:03 +0100 Subject: UML tools for python References: <13dc97b8.0312301543.39192aa2@posting.google.com> Message-ID: "Rimidalv" a ?crit dans le message de news:mailman.15.1072980620.12720.python-list at python.org... > Andy Bulka wrote: > > > [...] > > Andy Bulka > > http://www.atug.com/andypatterns > Try Dia http://www.lysator.liu.se/~alla/dia/ > also autodia http://droogs.org/autodia/ > and if you Google a little i guess that you can find dia2code (sorry > couldn't find url) Right but there is nothing where you can edit both code and diagram... The question is which good editor to extend ? ArgoUml seems good but do you know another one that is quite complete ? Which one is easiest to extend ? A program in java should it be extend in Jython ? Cheers, Yermat From JasonHarper at pobox.com Mon Jan 26 21:59:47 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Mon, 26 Jan 2004 19:59:47 -0700 Subject: JPG - PNG conversion problem References: Message-ID: <4015D3C1.C4850255@pobox.com> "Raaijmakers, Vincent (GE Infrastructure)" wrote: > Who can explain the huge increase in size when I convert a JPG into a PNG format using PythonMagick: > I read the JPG from a video server and has a resolution of 352x240, size is about 15k > After my PNG conversion and resizing the resolution to 160*120, the size is 64k!! JPEG is a lossy compression format (well, normally - there are some obscure exceptions to this). It throws away subtle details (details that the human eye is relatively insensitive to) in order to achieve its high compression ratios. PNG uses only lossless compression. You are guaranteed that the image you get out will be pixel-for-pixel identical to the image you put in. Unfortunately, this greatly limits the possibilities for compression - in fact, no lossless compressor can guarantee ANY reduction in file size over all possible inputs. Basically, converting a lossy to a lossless format gives you worst of both worlds - the loss of detail of one, and the large file size of the other. Jason Harper From ptmcg at users.sourceforge.net Tue Jan 13 17:27:45 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Tue, 13 Jan 2004 22:27:45 GMT Subject: error at "import anydbm" References: <40042edd$0$24038$626a54ce@news.free.fr> <4004482A.A66C2886@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:4004482A.A66C2886 at engcorp.com... > > Generally speaking, you should try to avoid using the same names as > the standard library modules for your own code. > > This is an understandable limitation, but for new (and some not-so-new) Python users, it is not always obvious what module names to avoid. What if the standard library modules were put into a "std" package, to help get them out of the global import namespace? (Of course, this would break *scads* of code, so maybe should be deferred to 3.0. Or for migration purposes, implement this in a 2.x release, and provide shadow xxx imports that import the std.xxx modules.) -- Paul From try_vanevery_at_mycompanyname at yahoo.com Thu Jan 15 16:16:26 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 15 Jan 2004 13:16:26 -0800 Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to Python CANNED) References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: Tom Plunket wrote: > Brandon J. Van Every wrote: > >> Agreed, and more specifically, there is a huge *cultural divide* >> between most OSS developers and proprietary commercial developers >> who simply want to add some OSS "to get the boring bits over with." >> There are also huge cultural divides between Linux and Windows >> developers, and again between commercial game developers and >> hobbyist game developers. > > So why waste their time even asking if they would consider > aligning their goals with yours? That seems like the ridiculous > part- OF COURSE hobbyists are not going to want to take > commercial concerns into account, THAT'S THE POINT. Reminds me again of the joke about the 2 economists: Two economists are walking down the street. Near the gutter, a $20 bill flutters. One economist looks down, looks at the other, and exclaims, "Hey! There's a $20 bill on the ground by the gutter!" The second economist says, "Nonsense, if there was someone would have picked it up already" and they keep right on walking. In other words, 6 months ago I had no reason to assume that hobbyist labor would be completely useless to me. I knew they wouldn't have the same agendas as myself, but I thought they might have sufficient overlap to get something of value to me accomplished. I was mistaken. Linux hobbyist game developers of GPL flavor are of no use whatsoever to Windows commercial game developers of BSD flavor, even if both are doing open source and might benefit from common tools. That may seem obvious to you, but it wasn't to me, and I'd question why it should seem obvious to you at first glance. I looked at a *lot* of open source projects in the name of avoiding Not Invented Here. In hindsight, I should have gotten back to my own Ocean Mars code a lot sooner. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA When no one else sells courage, supply and demand take hold. From michael at foord.net Wed Jan 28 09:22:58 2004 From: michael at foord.net (Fuzzyman) Date: 28 Jan 2004 06:22:58 -0800 Subject: Simple Database Package Message-ID: <8089854e.0401280622.4e145267@posting.google.com> I'm looking to build a simple database application for use on the desktop (customer contact and feedback database). Anyone able to reccomend a simple module / package I can use... ? I've never done any database work before and am ken to learn - but most of the ones I've seen seem to rely on a database engine buit into a server.. I need a simple stand alone engine. Of course I could just build the functions I need - but that would be a bit of a waste and not so extendable........ Thanks in advance for your help. Fuzzy fuzzy man AT atlantibots DOT org DOT uk -- 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.voidspace.org.uk/atlantibots/pythonutils.html The home of Python dateutils - dateutils, ConfigObj, StandOut, CGI-News etc From merkosh at hadiko.de Tue Jan 20 18:00:40 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Wed, 21 Jan 2004 00:00:40 +0100 Subject: always the same object Message-ID: Hi, I am using struct.unpack() quite often. unpack() returns a tuple, however a tuple with always the same id(), which is AFAIK the memory location of the structure. I found myself working with above tuple, initialising other data structures, etc... and when I tried to change one list element, suddenly all list elements change => so they all contain the identical object Now what are the rules when Python re-uses an old object (as with struct.unpack() ) and when does it create new objects? And what ist the proposed solution for dealing with this situation, i.e. how to I create a true copy of what struct.unpack() returns me? Thanks in advance Ciao Uwe From gandalf at geochemsource.com Tue Jan 20 04:00:58 2004 From: gandalf at geochemsource.com (Gandalf) Date: Tue, 20 Jan 2004 10:00:58 +0100 Subject: Python-based file synchronizer (like Unison)? References: Message-ID: <400CEE4A.2020406@geochemsource.com> > > >I've been using Unison > http://www.cis.upenn.edu/~bcpierce/unison/ >for awhile and it causes me a lot of grief. I'd love to have a >Python version which would be vastly easier to modify. > >Anyone know of anything like this? It doesn't seem like it >should take a lot to sit on top of rsync and resolve conflicts. > >I see that someone implemented rsync in Python and that there's >a SWIG wrapper for librsync. > http://minkirri.apana.org.au/~abo/projects/pysync/README >I might have to take a whack at this on my own, but I'd prefer >to use something better that someone has already crafted. > Well, I have something for you called PySynchro. I wrote a simple client/server application entriely in Python. Personally I use it for synchronize source codes between various computers. It uses secure connections, authentication (OTP variant). It is plaform independent (I tried it on FreeBSD, Linux and Windows. I don't know how it works on Macs.) It is not a hyperspeed syncronizer (although it transfers the files in compressed chunks). It requires some popular libraries to be present but the main point was independency. It does not require any external programs / database servers etc. On the client side, there is a class representing the client interface and I have a wxPython UI that uses this interface to synchronize files. There are some problems, though. I would like to implement persistent file locking and auto-locking but it is not written yet.. It would be also possible to store 'versions' but it is done yet. From other aspects, the UI interface is similar to Borland's TeamSource (with some major differences in the background). If you only want to compare and merge directories, you will find some useful classes inside. The code is fairly well documented (with epydoc) but the whole idea of the program is not. Let me know if you are interested. I have been using it for months without problems but you can be the first beta tester. :-) G From tweedgeezer at hotmail.com Tue Jan 27 22:57:15 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Jan 2004 19:57:15 -0800 Subject: [ANN] ip2cc-0.3: now it works with Python 2.3 References: <84e0f331.0401271515.2ed5c4f0@posting.google.com> Message-ID: <698f09f8.0401271957.66344665@posting.google.com> rshaw2 at midsouth.rr.com (Richard) wrote in message news:<84e0f331.0401271515.2ed5c4f0 at posting.google.com>... > I get an error when trying to use it... here's the problem below: > > C:\Tools>ip2cc.py www.google.com > Traceback (most recent call last): > File "C:\Tools\ip2cc.py", line 338, in ? > db = CountryByIP(db_file) > File "C:\Tools\ip2cc.py", line 14, in __init__ > self.fp = open(filename, 'rb') > IOError: [Errno 2] No such file or directory: 'C:\\Tools\\ip2cc.db' > > Looks like the database file is not included with the download. > > Richard That's probably why it includes update.py, a tool for updating/building the database. Jeremy From jjl at pobox.com Fri Jan 9 09:16:45 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jan 2004 14:16:45 +0000 Subject: Python and Jython are kinda different References: Message-ID: <87wu81jjg2.fsf@pobox.com> Dave Benjamin writes: [...] > Is there anyone here that works on Jython? Do you need help? What kind of They certainly need help. > help do you need? What's your estimation of the amount of work needed? Is Asking on the Jython list seems like a good idea. > the work done with PyPy helpful? I'm really curious. PyPy is a research effort, so not immediately useful. It may have big payoffs if successful, of course. John From fmsumkin at users.sourceforge.net Tue Jan 13 18:07:07 2004 From: fmsumkin at users.sourceforge.net (Fedor Sumkin) Date: Wed, 14 Jan 2004 01:07:07 +0200 Subject: BlackAdder version 1.0-040112 Released Message-ID: Rancho Santa Margarita, CA -- 13 January 2004 -- theKompany.com, producers and distributors of high-quality open source and commercial Linux software, are pleased to announce the availability of BlackAdder 1.0-040112, a Windows/Linux UI development environment for Python based on Qt. BlackAdder combines a visual design environment with debugging, syntax highlighting, ODBC interfaces and extensive documentation into a comprehensive platform for developing Python applications with PyQt. BlackAdder is an exciting product for rapidly developing applications on Linux or Windows using the popular Python language. Besides being a powerful IDE with an extensive array of tools to make developing your application quick and easy. BlackAdder is tightly integrated with PyQt which is a set of bindings for Python to allow you to make use of the popular Qt multi-platform windowing toolkit from Trolltech. Our optional Business Edition gives you a full commercial license for both PyQt and Qt as used from BlackAdder. This new release has significant enhancements to the Editor and Designer components of the system. Take advantage of the popular and powerful Python language coupled with the Qt/PyQt windowing toolkit to create applications faster than you ever thought possible, and get multi-platform capability virtually for free. Forget Visual Basic, BlackAdder is the future. Features: * Integrated Qt Designer * Syntax highlighting text editor * Supports the latest versions of Python, PyQt and Qt * eGenix.com mx Extensions for ODBC access from Python have been included. * Integrated Debugger * The debugger allows class instance objects to be displayed. * No restrictions are placed on the types of files that can be included in a project. * Project Explorer for adding existing file sets to a project * Extensive project management capability * Integrated CVS support * and much more? BlackAdder can be purchased or free demos downloaded from www.thekompany.com/products/blackadder. -- From mesteve_b at hotmail.com Sat Jan 3 18:29:57 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 03 Jan 2004 23:29:57 GMT Subject: Lists are weird when they are instance members References: Message-ID: thanks for the helpful replies. I guess I was just in confusion as to why I was able to leave alone the string variables in class FileGroup, such as sourceDir and destinDir, and nothing unpredictable happened with those, but with the list variable, I had to treat differently. But after I again read closely, Python In a Nutshell, I'm sure I will understand. "python newbie" wrote in message news:ffHJb.5475$HL3.4277 at newssvr29.news.prodigy.com... > hey, > okay, I'm trying to figure out why my books: Quick Python, Python in a > Nutshell, Python Cookbook and Learning Python don't say anything about the > weird behavior of a list when you have one as an object instance member. > > for instance (my first pun of 2004), if I have, > > test.py > ---------------- > > global_filegroup_array = [] # array of filegroup objects > > class FileGroup: > a = 0 > mylist = [] # here it is > > def put_stuff_in_my_list(self, anyfile): > self.mylist.append( get just a single string from file) # > pls excuse the psuedo > > def __init__(self): > put_stuff_in_my_list(anyfile) > > def main(): # do ten times: instantiate the > above object, and add to the global array > for i in xrange(10): > filegroup = FileGroup() > global_filegroup_array.append(filegroup) > > > # print the list contents > print global_filegroup_array[0].mylist > > ------------ end of file > > Output is: [u'.string1', u'.string2', u'.string3' ] # only > u'string1' should show up > > No matter which index I use into the global array, I always get ALL of > the strings > showing up. I should only get u'string1' showing up, and u'string2' > if > I used "[1].mylist" > > > How I resolved it, is by slipping in > > self.mylist = [] > > before > > put_stuff_in_my_list(anyfile) > > in __init__(self) > > Why should I have to empty out the list when it's a member of a newly > instantiated object? > > thanks > > p.s. ( I'm actually not doing exactly the thing with the > files, but instead iterating through a xml file with dom, > debugging it showed the behavior ) > > > > > > > > From altis at semi-retired.com Mon Jan 26 12:32:34 2004 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 26 Jan 2004 09:32:34 -0800 Subject: ANN: OSCON 2004 (Python 12) call for participation - proposal deadline February 9th! Message-ID: 2004 O'Reilly Open Source Convention Call for Participation: Opening the Future: Discover, Develop, Deliver http://conferences.oreillynet.com/os2004/ The O'Reilly Open Source Convention (OSCON) will be held July 26-30, 2004 at the Portland Marriott Downtown in Portland, OR. Proposals Submission Information--Deadline: February 9, 2004 http://conferences.oreillynet.com/cs/os2004/create/e_sess Sebastopol, CA--"There is an upheaval in the open source landscape, particularly Linux, and the corporate landscape is changing too," observes Tim O'Reilly, founder and CEO of O'Reilly & Associates. Economic pressures and legal battles have combined to push open source topics to the front burner as companies, institutions, and governments of every size make technology decisions. O'Reilly, long a vocal open source advocate, brings together open source influencers, early adopters, technology activists, developers, and business leaders to evaluate and debate the evolving open source landscape at OSCON, the annual O'Reilly Open Source Convention. The 2004 O'Reilly Open Source Convention, to be held in Portland, OR from July 26-30, is now accepting proposals delving into topics that matter most to the entire open source community, which includes new--and perhaps unexpected--players. "OSCON provides an analysis of what's happening now and what may come--what will affect the future landscape. This convention brings together projects in a way that other conferences don't. We're able to cover a broad range of topics in a deep, coherent way," says OSCON program chair Nathan Torkington. "It's not just about trimming costs at large companies, it's about collaborating and innovating our way into the next big thing. This convention is like a radar. It's a mix of what you'll be doing as soon as you get back to your desk and what you'll be doing differently in six months." The keynote speakers for the next OSCON exemplify the event's wide-ranging mix: Freeman, George, and Esther Dyson, presenting a joint keynote address; Robert Lefkowitz, who was one of OSCON 2003's most thought-provoking speakers; Milton Ngan of Weta Digital, the company that created the digital effects for "The Lord of the Rings" films; and Tim O'Reilly. Other influential open source leaders will come to OSCON to accept the first Open Source Awards, produced by the Open Source Institute (OSI) and ZDNet (winners will be announced in stages during the winter and spring of 2004). Proposals Submission Information--Deadline: February 9, 2004 http://conferences.oreillynet.com/cs/os2004/create/e_sess Individuals and companies interested in making session or tutorial presentations, or participating in panel discussions, are invited to submit proposals. Presentations by marketing staff or with a marketing focus will not be accepted; neither will submissions made by anyone other than the proposed speaker. Session presentations are 45 or 90 minutes long, and tutorials are either a half-day (three hours) or a full day (six hours). The theme for OSCON 2004 is "Opening the Future: Discover, Develop, Deliver." Proposals for sessions that help attendees discover new open source projects, develop new relationships, or deliver value to their employers and coworkers are especially welcome. Proposals that are not related to the theme are also encouraged, such as case studies showing how open source software solved thorny problems or replaced expensive closed source software, best practices for a tool or system, new features or modules, and fundamental skills. The tracks and conferences running in parallel at the convention include: Linux - Management, security, administration, configuration - Desktop, server farm, back office, personal productivity tools, development PHP Conference 4 - Unix, Windows, Apache, and beyond - New developments, security, case studies, large-scale applications development, best practices The Python 12 Conference - Python and Zope - Using the latest modules, software engineering, case studies Perl Conference 8 - Perl 5, Perl 6, Parrot, mod_perl - Useful modules, software development tips, developing for Parrot and Perl 6 MySQL and PostgreSQL - Configuration, migration, data warehousing, tuning - Clustering and replication, fallover, backups - Efficient client-side processing and query design Apache httpd, Java, and XML projects - Apache web server: 2.0, modules, configuration, performance tuning, security - Apache XML projects: Xerces, Xalan, Cocoon, FOP, SOAP, XML-RPC, XML Security - Apache and Open Source Java projects: Jakarta, Jserv, Avalon, Geronimo XML - XML Schemas, Transformations, Software, Services, and Standards - New standards, best practices, web services, IP issues around standards and schemas Applications - System administration tools, servers, back office utilities - GUI systems, user applications, productivity tools Ruby - Introductions to aspects of Ruby for people unfamiliar with the language - Power user talks for experienced Ruby programmers OSCON is the one place open source practitioners of every stripe can gather to learn useful skills, discover what's new, and "cross-fertilize" projects. Concludes Tim O'Reilly, "OSCON is for anyone interested in open source. It's the one event that brings together leaders of all the major open source projects not only with the hacker community but also with commercial software developers, business leaders, analysts, and even opponents of open source." From joshway_without_spam at myway.com Fri Jan 9 16:32:12 2004 From: joshway_without_spam at myway.com (JCM) Date: Fri, 9 Jan 2004 21:32:12 +0000 (UTC) Subject: Variable Scope 2 -- Thanks for 1. References: <3fff16b6$0$315$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: ... > A very important concept with Python is that you don't have variable > assignment, but name binding. An "assignment statement" binds a name on an > object, and the object can be of any type. A statement like this: > age = 29 > doesn't assign the value 29 to the variable age. Rather, it labels the integer > object 29 with the name age. I think this statement is misleading--it seems to imply the integer object is altered somehow. Personally I see no problem with saying the value 29 is assigned to the variable age, so long as you understand the semantics. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Jan 15 08:09:50 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 15 Jan 2004 14:09:50 +0100 Subject: Python used in Freedom Force In-Reply-To: References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> Message-ID: <4006911e$0$327$e4fe514c@news.xs4all.nl> Roberto Amorim wrote: > Not only Freedom Force, but also Severance: Blade of Darkness (3rd-person > action medieval game) and Bridge Commander (Star Trek TNG simulator). And also Cyan's URU:Ages Beyond Myst. I discovered some Python dlls and files in the game directory... --Irmen From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Jan 16 20:27:52 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 17 Jan 2004 02:27:52 +0100 Subject: problems with os.path.isdir on windows shares (i've read the FAQ) References: <4489035c.0401161545.75b63ce@posting.google.com> Message-ID: Hi ! \\\\ren\\backup is perhaps no a directory, but the name of a shared ressource. @-salutations -- Michel Claveau From danb_83 at yahoo.com Mon Jan 12 04:10:11 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Jan 2004 01:10:11 -0800 Subject: OT: Of C, Fortran and pointer aliasing Was: Python if far from a top performer... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: Samuel Walters wrote in message news:... > |Thus Spake Rainer Deyke On the now historical date of Sun, 11 Jan 2004 > 06:46:50 +0000| > > > Samuel Walters wrote: > [Fortran is faster than C.] > ... > I went digging for technical documents, but thus far haven't found many > useful ones. It seems everyone but me already understands pointer > aliasing models, so they might discuss them, but they don't explain them. > I am limited in part by my understanding of compilers and also by my > understanding of Fortran. Here is what I have gathered so far: > > Fortran passes all arguments by reference. (This is the peppiest way to do > it, especially with static allocation) Btw, for some early compilers, this was the case even with literals, which meant that code like CALL FOO(4) PRINT *, 4 could print something other than 4. > ...I'm a bit hazy as to whether > Fortran 90 uses static or dynamic allocation, or a combination of both, You can use both, at least for arrays. > and whether it permits recursion. Fortran 90 does permit recursion, although you have to explicitly declare functions as "recursive". > Now, for C: ... > C lacks many of the fundamental array handling semantics and primitives > that Fortran programs rely on. Implementing them in C is a real PITA. This is one of my least favorite things about C. > C memory allocation is just plain goofy in comparison to Fortran. And even worse in comparison to Python ;-) From mtk at qm.com Wed Jan 14 12:52:37 2004 From: mtk at qm.com (Totte Karlsson) Date: Wed, 14 Jan 2004 09:52:37 -0800 Subject: Printing to console (No Scroll) Message-ID: Hi, How can I print to the console without having it scrolling to a new line for each print statement? I want to print a count down in the console, but for each count it scrolls the screen (of course). Is there another way? Here is the simple script for now print "Closing window in :" for second in range(10): time.sleep(1) print `10-second` +" seconds" thanks /totte From jepler at unpythonic.net Sat Jan 24 13:58:27 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 24 Jan 2004 12:58:27 -0600 Subject: Perl vs. Python for text manipulation In-Reply-To: References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <871xpp1i8r.fsf@pobox.com> Message-ID: <20040124185827.GE32445@unpythonic.net> On Sat, Jan 24, 2004 at 09:00:17PM +0300, Serge Orlov wrote: > If not, threads can > have separate caching. After all, doing I/O on the same file from multipile > threads is uncommon so it can suffer. 99+ percent of I/O in the world > is done from one thread, why should it suffer? The "unlocked I/O" mentioned earlier refers to locking inside the standard C library, so Python can't avoid it except by calling non-portable functions such as getc_unlocked* or by using lower-level I/O primitives such as posix read(2)/write(2). In these cases, Python would either have to hold the GIL during I/O operations or add its own locking to them (or else decree that file object access is not thread-safe). There's no guarantee that this could be faster than the thread safety already provided in the C library. Jeff * Actually, my getc_unlocked() manpage says that the function is in POSIX.1, so this may be as portable as read/write would be From jseale18 at insightbb.com Mon Jan 19 00:12:39 2004 From: jseale18 at insightbb.com (Jeff Seale) Date: Mon, 19 Jan 2004 05:12:39 GMT Subject: time module question Message-ID: How would one go about writing a program which included a clock that updated itself? Right now I'm able to display the time in a text widget in the window but I can't get it to update. From piedmontbiz at aol.com Thu Jan 22 00:01:03 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 22 Jan 2004 05:01:03 GMT Subject: Secure Voting software References: <87zncgy544.fsf@strauser.com> Message-ID: <20040122000103.21852.00000518@mb-m06.aol.com> >At 2004-01-22T01:35:01Z, Paul Rubin writes: > >> The book "Security Engineering" by Ross Anderson is a good place to start >> reading if you're interested in the subject. > >I just finished "Practical Cryptography" by Niels Ferguson and Bruce >Schneier. It was almost enough to make me not want to bother trying. :-/ >=2D --=20 >Kirk Strauser >The Strauser Group >Open. Solutions. Simple. >http://www.strausergroup.com/ I checked out the site: http://gnosis.python-hosting.com/voting-project/ This is a huge and important project. I suppose the programming language is really not that important. The issue is trustworthy system development (applications, operating systems, drivers, libraries, hardware, etc.), and developing ways to validate software. A completely different programming paradigm will need to be developed. allen From pinard at iro.umontreal.ca Fri Jan 16 09:37:39 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 16 Jan 2004 09:37:39 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: <20040116143739.GA14990@alcyon.progiciels-bpi.ca> [Andrew Dalke] > My favorite program for this is /bin/true. On some machines it is 0 > bytes long. Yet, the AT&T empty file for True is heavily copyrighted. Stretching the meaning a bit (maybe more than a bit!), it amuses me to think that nobody may produce an empty file anymore without being indebted to them. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ods at strana.ru Thu Jan 29 06:18:47 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 29 Jan 2004 14:18:47 +0300 (MSK) Subject: [ANN] ip2cc-0.3: now it works with Python 2.3 In-Reply-To: Message-ID: On Wed, 28 Jan 2004, Serge Orlov wrote: SO> > IOError: [Errno 2] No such file or directory: SO> 'C:\\Tools\\ip2cc.db' SO> > SO> > Looks like the database file is not included with the SO> download. SO> SO> Try running update.py first to retrieve the database from SO> internet. SO> The exception should of course be caught by ip2cc script and SO> a clear explanation should be printed. Thank you for feedback. I'm going to fix this in next release. -- Denis S. Otkidach http://www.python.ru/ [ru] From eddie at holyrood.ed.ac.uk Fri Jan 16 06:48:49 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 16 Jan 2004 11:48:49 +0000 (UTC) Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: "John Benson" writes: >Hi, I see a lot of posts asking about "the best Python book." In my >experience, there is no such thing, but there are a lot of good books that >will help you along in different ways, and at different times. >First of all, I'd like to clarify my position on learning: I subscribe to >the adobe hacienda school of autodidactic technology, to wit: >"If you throw enough adobe at the side of the hacienda, some of it will >stick" >At one time or another, I've dipped into the various O'Reilly Python books, >Grayson's Python and Tkinter Programming, and Christopher's Python >Programming Patterns. They're all good, but I need to see the same difficult >or complex thing presented various times in various contexts to really get >comfortable with it. Hence the multiple viewpoints of multiple books, and I >will also read an individual book more than once, interspersed with other >volumes. Enough adobe ends up adhering to my mental hacienda so that I can >accomplish things in Python. >And now, some encouragement for old techies who have considered going into >management with writing cool software is enough: >My formal education in data processing stopped with Advanced Data Structures >back in the eighties, and I coasted along doing journeyman programming in >various COBOLs, Cs and proprietary languages. Of course, I stayed reasonably >current with stuff like Dijkstra's Structured Programming, DeMarco's >Structured Analysis, Date's Relational Database and other flavors of >business software technology which were my stock in trade, but otherwise I >avoided the paradigm of the week. Then I ran into Python about two years ago >and all of a sudden there was OOP, functional programming, aspect-oriented >programming and other stuff that I had maybe heard about but hadn't actually >worked with, all staring back at me from the pages of Python books and the >mailing list. It's been pretty much a process of creative destruction: >starting all over, but from a higher and clearer conceptual vantage point. >And, of course, I didn't really forget all the other stuff, I just pushed it >into the background long enough to get a new appreciation of it from this >new point of view. In summary, I'd like to recommend getting into Python as >a rather easy and fun way to talk the talk and walk the walk nowadays; it's >been a very rewarding and refreshing software engineering update. The next step is to read "Structure and Interpretation of Computer Programs" aka SICP and start all over again, in terms of "clearer conceptual vantage point" it just can't be beat. It's even availabe online somewhere. Eddie From bloom at caltech.edu Fri Jan 2 14:49:42 2004 From: bloom at caltech.edu (Jesse Bloom) Date: Fri, 02 Jan 2004 19:49:42 +0000 Subject: problem using pickle / cPickle Message-ID: <3FF5CB56.4000309@caltech.edu> I keep running into a problem when I use pickle or cPickle to unpickle a python object I have serialized from the database. I read the string for the serialized object. Apparently I am missing an argument? Here's what happens: cPickle.loads(s) Traceback (most recent call last): File "", line 1, in ? TypeError: __new__() takes exactly 2 arguments (1 given) Same thing happens when I use pickle: >>> pickle.loads(s) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/local/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/local/lib/python2.3/pickle.py", line 1097, in load_newobj obj = cls.__new__(cls, *args) TypeError: __new__() takes exactly 2 arguments (1 given) From raims at dot.com Tue Jan 13 16:44:55 2004 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 13 Jan 2004 22:44:55 +0100 Subject: id3v2 module References: Message-ID: <87u12z1q20.fsf@mobile.foo> Jarek Zgoda writes: > This one is able to read and write only ID3v1.1 tags. Search for pyid3 not id3py -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From http Sat Jan 31 19:30:05 2004 From: http (Paul Rubin) Date: 31 Jan 2004 16:30:05 -0800 Subject: OT: why do web BBS's and blogs get so slow? References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xbrojej5e.fsf@ruckus.brouhaha.com> Jay O'Connor writes: > This is similar to what I wrote in Smalltalk several years and is now > running http://www.ezboard.com Uh oh, ezboard.com is pretty slow. Is it hopeless? From jcarlson at nospam.uci.edu Fri Jan 30 15:40:05 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 12:40:05 -0800 Subject: mod_speling for python In-Reply-To: References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com> Message-ID: Skip Montanaro wrote: > >> I know there are drawbacks, disadvantages, this is "evil", etc. I > >> only wanted to know what ways there are to add such a hook if it is > >> possible without altering the C source for python itself. > > Josiah> Ambiguities during execution are bad. I've got two functions > Josiah> Foo and foO, if I type in foo, what did I mean? > > I didn't interpret the OP's question as wanting to automatically map Foo to > foO, but to give the user a more helpful error message, suggesting other > candidate names which he might have mistyped. That could be useful, if what you say is actually what he meant. - Josiah From davecook at nowhere.net Tue Jan 13 08:05:27 2004 From: davecook at nowhere.net (David M. Cook) Date: Tue, 13 Jan 2004 13:05:27 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: In article <40029dad$0$28706$a729d347 at news.telepac.pt>, Bicho Verde wrote: > I have now free time and money to do what I want :-) > I have some basic skills in programming (C, Pascal, Macromedia > Actionscript) but don't know exactly what to do in the world of programming. > And also I don't know exactly why would I learn Python rather than C#, > C++ or Perl. Basicaly I don't know where to start, if there is much to do or You could casually pick up enough Python to be useful in a week or so of evenings. Perl is not much harder, but has a lot of "gotchas". I think Perl is more natural as a system administration language, though, as that is what it was designed for. The others require much more up-front study before one can start writing useful programs. C#/Java are much easier than C++, but have huge, complex APIs (my experience here is with Java, not C#) and require a lot of boilerplate to get things done. http://www.ferg.org/projects/python_java_side-by-side.html > if it is has it seems and there is software to everything nowadays and so > doesn't make sense to spend time in learning a programming language. This is where the ease of writing "one off" Python programs comes in. When you do find yourself needing to write some custom code, you'll find it very easy to cobble together something useful quickly. Dave Cook From bdesth.tagada at tsoin-tsoin.free.fr Tue Jan 13 06:21:00 2004 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Tue, 13 Jan 2004 12:21:00 +0100 Subject: Why learn Python ?? In-Reply-To: References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <4003cfeb$0$19263$626a54ce@news.free.fr> Samuel Walters wrote: > |Thus Spake Bicho Verde On the now historical date of Mon, 12 Jan 2004 > 13:05:19 +0000| > > >>I have now free time and money to do what I want :-) > > Go to the Bahamas. You'll enjoy it more. > > [chop] > > >> Anyone would help me and give me some hints? > > > Here's my two cents on which languages to learn, why and in what order. > (snip) > > Perl: > I don't like perl, but you shouldn't judge a language on my opinion of it. > Perl is very popular and is worthy understanding the basics of. Even if > you don't like it, learn enough of it to read programs written in it. Woops ! The problem with Perl is actually that it's more or less a write-only language !-) Bruno From google at klaff.org Fri Jan 2 16:05:14 2004 From: google at klaff.org (David Klaffenbach) Date: 2 Jan 2004 13:05:14 -0800 Subject: Starting a script interactively? Message-ID: <37d5fe8f.0401021305.349a440@posting.google.com> Is there a way from within a python script to cause the interpreter to be in interactive mode after the script finishes? so that if I run: myscript.py it will always execute as if I had run: python23.exe -i myscript.py I know I could use a batch file or shell script but can it be done from within the script itself? Thanks, Dave From swalters_usenet at yahoo.com Mon Jan 5 12:55:33 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 17:55:33 GMT Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> <5sFJb.20923$Vl6.3818930@news20.bellglobal.com> Message-ID: |Thus Spake Sean Ross On the now historical date of Sat, 03 Jan 2004 16:31:17 -0500| > I think you're supposed to do something like this a = bq + r, 0<= r < > |b| It is, indeed, 0 <= r < abs(b) "If a and b are integers such that b != 0, then there exist unique integers r and q such that a = q*b + r and 0 <= r < abs(b)" For non-mathematical spectators, the divmod() function is defined so that q, r = divmod(a, b) by the definition above. Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From ptmcg at austin.rr.com Sun Jan 18 19:15:14 2004 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 Jan 2004 00:15:14 GMT Subject: re question - finiding matching () References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> <20040118192118.61fea23f.no.spam@box> Message-ID: "Christophe Delord" wrote in message news:20040118192118.61fea23f.no.spam at box... > On 18 Jan 2004 07:51:38 -0800, Miki Tebeka wrote: > > > Anyway a better solution would be to use a syntactic parser. You can > write your own by hand or make your choice here: > http://www.python.org/sigs/parser-sig/ > > Best regards, > Christophe. Another parser not listed on this page can be found at http://pyparsing.sourceforge.net. The download includes an algebraic expression parser, that handles parenthesis nesting. -- Paul From __peter__ at web.de Fri Jan 30 13:40:35 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Jan 2004 19:40:35 +0100 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: Aahz wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: >>Aahz wrote: >>> >>> import __main__ >>> tmp = parse_funky_language("Hey, this is far out, man.") >>> setattr(__main__, tmp.name, tmp.value) >>> >>> In the context of the interactive interpreter, it's a bit harder to do; >>> I don't remember off-hand what the namespace of the interpreter is. >> >>You don't need to :-) >> >>Python 2.3.3 (#1, Jan 3 2004, 13:57:08) >>[GCC 3.2] on linux2 >>Type "help", "copyright", "credits" or "license" for more information. >>>>> __name__ >>'__main__' > > Yes, but how do you access that from a module? import sys import __main__ setattr(sys.modules["__main__"], "name", "value") __main__.anotherName = "another value" Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import interp >>> name 'value' >>> anotherName 'another value' >>> Or is this a misunderstanding continued? Peter From james at logicalprogression.net Mon Jan 19 11:56:45 2004 From: james at logicalprogression.net (James Henderson) Date: Mon, 19 Jan 2004 16:56:45 +0000 Subject: subclassing "file" In-Reply-To: References: Message-ID: <200401191656.45641.james@logicalprogression.net> On Monday 19 January 2004 4:14 pm, Uwe Mayer wrote: > when extending a build in class, what does the constructor __init__(...) > have to return? A bit more detail now I've read your message properly. :) It shouldn't have a return statement. This means that it returns None. Strictly speaking __init__ isn't a constructor, since the instance has already been created before being passed to it. (A real constructor, __new__, has been added to the language for subclassing immutable types.) __init__ just modifies self in place. > and how does the constructor call its base-class construtor? (or is this > done automatically?) The __init__ method of the base class, assuming it must be called at all, must be called explicitly as an unbound method, as I showed in my last e-mail. Reminder: if "self.__init__()" is the bound method then "MyClass.__init__(self)" is the unbound method. The two are generally equivalent, but the unbound form is needed in inheritance to specify a superclass of self's immediate class. J. -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From akhavr at kds.com.ua Sun Jan 11 09:34:05 2004 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Sun, 11 Jan 2004 16:34:05 +0200 Subject: script to translate from compiler AST Message-ID: Hi! I'm looking for a script to translate from 'compiler' AST to py source and executable code. Google search reveals hardly useful links. Is there something like that or it is left as an exercise for a curious developer? -- Andrey V Khavryuchenko http://www.kds.com.ua/ Silver Bullet Software Solutions http://www.kds.com.ua/training/ From max at alcyone.com Sat Jan 17 19:13:37 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 17 Jan 2004 16:13:37 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <1074370049.790131@radsrv1.tranzpeer.net> Message-ID: <4009CFB1.FF64F9C9@alcyone.com> Corey Murtagh wrote: > Actually I kind of agree here. I've had plenty of problems with > Cygwin > - although less with MinGW. An OSS project that requires a Linux > emulation shim to run on any other platform is not, IMHO, > cross-platform > at all. Problem here is, Freeciv _does_ have a native win32 binary available. So the entire premise that Brandon was starting with was totally false. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ In this world, nothing is certain but death and taxes. -- Benjamin Franklin From sross at connectmail.carleton.ca Sat Jan 31 15:41:17 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 31 Jan 2004 15:41:17 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> Message-ID: <8sUSb.46657$mf4.1789355@news20.bellglobal.com> "Daniel Ehrenberg" wrote in message news:711c7390.0401311220.763be80a at posting.google.com... [snip] >> there isn't any magical syntax that is > > usable on one Python x.y installation, that isn't on another. > > > > - Josiah > > What are you talking about? [snip] Syntax that can be used on one Python x.y.z installation, can be used on another installation of the _same_ version (x.y.z) of Python. From mmontagne at walkermacy.com Thu Jan 15 20:20:52 2004 From: mmontagne at walkermacy.com (michael montagne) Date: Thu, 15 Jan 2004 17:20:52 -0800 Subject: best book In-Reply-To: References: Message-ID: <100ef3le0dl12a8@corp.supernews.com> km wrote: > Hi all, > > What is the best book to start with python ? i am have been working since 1 yr with Perl. > > kindly enlighten, > > thanks, > KM > > > The Quick Python Book . Daryl Harms. Fantastic. From gerrit at nl.linux.org Thu Jan 8 15:32:56 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 8 Jan 2004 21:32:56 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <20040108203256.GA5903@nl.linux.org> John Roth wrote: > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q I have updated a lot of things on the PEP in the past few days. There are still larger and smaller open issues, though, besides the usual 'I-can-change-my-mind-and-the-PEP-can-change-its-mind' things: Quoting my own PEP: Should path.__eq__ match path.samefile? There are at least 2 possible ways to do it: - Normalize both operands by checking to which actual file they point (same (l)stat). - Try to find out whether the paths point to the same filesystem entry, without doing anything with the filesystem. pro - A path usually points to a certain place on the filesystem, and two paths with different string representations may point to the same place, which means they are essentially equal in usage. con - We would have to choose a way, so we should first decide which is better and whether the difference is intuitive enough. - It makes hashing more difficult/impossible. conclusion - I don't know. links - Bernard Herzog `points out `__ that it would essentialy make path-objects non-hashable. - `James Orendorff's Path`_ inherits str.__eq__. - `Mike C. Fletcher's Path`_ chooses for the first variant. Do we need to treat unicode filenames specially? I have no idea. links - An `explanation `__ by Martin von Loewis. - should os.tempnam be included? - can normpath be coded using only os.path constants (if so, it's in the 'platform-independent' class? (I think no) - Should normalize be called normalized or not? - Should stat be defined in the platform-dependent or -independent class? - Should we include chdir and chroot? If so, where? - Should rename return a new path object? - Should renames be included? And one meta-question: Shall I submit this as an official PEP? Or shall I first fill in more open issues and perhaps give the possibility to change "closed" issues? See also: http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html yours, Gerrit. -- 202. If any one strike the body of a man higher in rank than he, he shall receive sixty blows with an ox-whip in public. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From aahz at pythoncraft.com Sun Jan 4 14:31:21 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2004 14:31:21 -0500 Subject: Proposal: new peps always in clpa References: Message-ID: In article , Gerrit Holl wrote: > >would it be a good idea to automatically sumbit all new peps to >comp.lang.python.announce? After all, each PEP is an announcement and >may be important to the entire Python community. Another possibility >would be to python-dev, but since c.l.py.announce has a broader public, >I'd prefer the first one. What do you think? That's a good idea, but c.l.py.announce needs to have its Followup-To: set to c.l.py. I think I asked for that once before, but didn't get a response. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From ptmcg at austin.rr.com Sat Jan 3 13:59:03 2004 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 03 Jan 2004 18:59:03 GMT Subject: KeyboardInterrupt and threading References: Message-ID: "Ivan Nestlerode" wrote in message news:a6562e06.0401021352.65aac82b at posting.google.com... > Hello comp.lang.python, > > I am attempting to write a threaded program right now in Python > (version 2.3 on Debian unstable) and the current behavior of > KeyboardInterrupt is causing me grief. From the documentation of the > thread module in Python 2.3.3: > > "Threads interact strangely with interrupts: the KeyboardInterrupt > exception will be received by an arbitrary thread. (When the signal > module is available, interrupts always go to the main thread.)" > Is the signal module not available to you? > Any ideas (besides rewriting the sloppy library code) would be much > appreciated. > > Thanks, > -Ivan Assuming you have access to the signal module: 1. Create a boolean that you can periodically test for in your thread code, to see if you should keep processing. This may be a global singleton, a global boolean, or something, but it needs to be visible to both the main thread and the threaded code. You probably have some compute intensive loops such as: while( prime_factors < 1e15 ): or while( optimization != converged ): or even just while( True ): Change these to reference the "keep processing" flag. while( keep_processing and prime_factors < 1e15 ): or while( keep_processing and optimization != converged ): or even just while( keep_processing ): # no need to 'and' with True 2. Create a signal handler to trap for SIGINT. In the signal handler, set the "keep-processing" bit to False: import signal def discontinue_processing(signl, frme): global keep_processing keep_processing = False return 0 signal.signal( signal.SIGINT, discontinue_processing ) Now your main thread will get the ^C interrupt and clear the "keep_processing" flag, which will eventually get picked up by your worker thread the next time it tests for it. HTH, -- Paul From andymac at bullseye.apana.org.au Wed Jan 7 05:43:25 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 7 Jan 2004 21:43:25 +1100 (EST) Subject: debugging memory management via C API In-Reply-To: <3FFBBD02.3010501@sympatico.ca> References: <3FFBBD02.3010501@sympatico.ca> Message-ID: <20040107214153.J38682@bullseye.apana.org.au> On Wed, 7 Jan 2004, Stefan Seefeld wrote: > I'm writing some C python extension and I'd like > to debug the memory management, i.e. run some > tests to see whether I did the ref counting > correctly, etc. A debug build of Python will help considerably. -- 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 mark at mceahern.com Sun Jan 18 12:05:20 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 18 Jan 2004 11:05:20 -0600 Subject: re question - finiding matching () In-Reply-To: <4f0a9fdb.0401180751.4b66d974@posting.google.com> References: <4f0a9fdb.0401180751.4b66d974@posting.google.com> Message-ID: <1074445520.18656.30.camel@dev.internal> On Sun, 2004-01-18 at 09:51, Miki Tebeka wrote: > Hello All, > > To all of you regexp gurus out there... > > I'd like to find all of the sub strings in the form "add(.*)" > The catch is that I might have () in the string (e.g. "add((2 * 2), 100)"), The pattern you have is so simple and the necessary regex (it seems to me) so unnecessarily complex (for a 100% regex solution) that I think using only regex's for this problem is overkill. Anyway, here's a test-based approach: #!/usr/bin/env python import re import unittest def findOperands(verb, text): """Find operands in text for verb. E.g., findOperands('add', 'add(1, 2, 3)') == ['1', '2', '3'] """ raw = '%s\((.*)\)' % (verb,) pat = re.compile(raw) matches = pat.findall(text) if not matches: raise RuntimeError('No matches found for pattern %s.' % (raw,)) assert len(matches) == 1 match = matches[0] operands = match.split(',') for i, item in enumerate(operands): operands[i] = item.strip() return operands class test(unittest.TestCase): def test(self): text = 'add(2, 3)' operands = findOperands('add', text) expected = ['2', '3'] self.assertEquals(operands, expected) text = 'add((2 * 2), 100)' operands = findOperands('add', text) expected = ['(2 * 2)', '100'] self.assertEquals(operands, expected) text = 'add(1, 2, 3)' operands = findOperands('add', text) expected = ['1', '2', '3'] self.assertEquals(operands, expected) text = 'multiply(1, 2, 3, 4)' operands = findOperands('multiply', text) expected = ['1', '2', '3', '4'] self.assertEquals(operands, expected) text = 'add 2, 3' self.assertRaises(RuntimeError, findOperands, 'add', text) unittest.main() From vzd1s1fs at verizon.net Sat Jan 10 21:39:21 2004 From: vzd1s1fs at verizon.net (Zachary) Date: Sun, 11 Jan 2004 02:39:21 GMT Subject: help with Python Environment For Blind User Message-ID: Hello, I'm a blind non-programmer trying to learn Python. I've got python 2.3 for windows, but the problem is that Idle doesn't seem to work two well with my screen reading program. Is notepad, then, my only other real choice? Pythonwin worked similarly badly. The problem is my programs inability to track the cursor. It doesn't tell me what line I'm on, where I am in that line, or what I just deleted. It would do this in a normal editor. Any help with this would be appreciated. Zack From matt at pollenation.net Mon Jan 12 06:01:51 2004 From: matt at pollenation.net (Matt Goodall) Date: Mon, 12 Jan 2004 11:01:51 +0000 Subject: CGI module problem: duplicated output In-Reply-To: References: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> Message-ID: <40027E9F.2010209@pollenation.net> Mimal wrote: >> How about renaming it to mimal_cgi.py! > > > For a second I thought: "That's it!" Unfortunately, that doesn't seem > to help. I renamed the file and I got the same. :-( > Check there is no cgi.pyc from when the script was still called cgi.py. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenationinternet.com e: matt at pollenation.net From harry.g.george at boeing.com Fri Jan 9 03:09:19 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 9 Jan 2004 08:09:19 GMT Subject: pyxml-0.8.3 install problem on RedHat 9 References: Message-ID: jangseungwook at nate.com (jang, seungwook) writes: > >> python setup.py build > > running build > running build.py > no copying xml/FtCore.py (output up-to-date) > blah blah .. > > running build_scripts > not copying scripts/xmlproc-parse (up-to-date) > not copying scripts/xmlproc_val (up-to-date) > > > How can I fix it ? > Please help me ~~ > Fix what? The "not copying" is the normal response if the files are current. This might happen if you had an older PyXML installation and were doing an update -- files that were the same would not need to be installed again. When you try importing one of the modules, does it work? > > > Seungwook, Jang -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From jdhunter at ace.bsd.uchicago.edu Thu Jan 22 15:28:23 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 22 Jan 2004 14:28:23 -0600 Subject: Ordered dictionary? In-Reply-To: (Leif K-Brooks's message of "Thu, 22 Jan 2004 20:18:25 GMT") References: Message-ID: >>>>> "Leif" == Leif K-Brooks writes: Leif> I need to associate a string (key) with an integer Leif> (value). A dictionary would do the job, except for the fact Leif> that it must be ordered. I also need to look up the value Leif> for a specific key easily, so a list of tuples wouldn't Leif> work. google : python ordered dictionary click : I'm feeling lucky JDH From jcarlson at nospam.uci.edu Mon Jan 26 10:18:55 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 07:18:55 -0800 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: David M. Cook wrote: > In article , Josiah Carlson wrote: > > >>Speaking of which... >>http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html > > > I'm still flabbergasted that this is on whitehouse.gov and not on > whitehouse.org. > > Dave Cook > I think even the White House staff is coming to realize they are working for a schmuck. - Josiah From mnations at airmail.net Fri Jan 9 20:17:02 2004 From: mnations at airmail.net (Marc) Date: 9 Jan 2004 17:17:02 -0800 Subject: Databases: Which one's right for me? Message-ID: <4378fa6f.0401091717.1ae63541@posting.google.com> Hi all, Having never used a database before and immersing myself in reading stuff about databases over the last two days I have come to this conclusion, I still don't know which one I need. I've been using Python for a while, storing things that I'll need later in files. I am now looking for a better solution; ergo the need for a database. Basically I need a db that will travel with my executable script and faithfully store and edit the data needed in that script. People using this script will need to be stand alone users. Having a client/server arrangement is not possible over a network. Also, installing some type of db engine outside of Python is also not possible. This rules out installing such readily available databases as mySQL or any other type of db that must have a separate install. Everything must be contained within the Python executable package. However, all of the users WILL have MS Access already installed. So that is a good possibility, and I have already played around with DAO and run a couple of scripts with it. However, I've also read some things about the Python independent db called Gadfly. This is also an interesting possibility as it reduces the need to even have Access around and lowers the complexity in freezing applications (which can run into problems when using COM clients sometimes). So from reading I've narrowed it down to two possibilities - MS Access with DAO and Gadfly. What I can't get from reading is experience or someone who has done this type of thing before and already knows which one will work best based on what I need to do. Or, if there exists another solution other than the two I mentioned, please throw that out there because it's almost impossible to completely examine every possibility out there. All suggestions are helpful. Thanks ahead of time, Marc From theaney at cablespeed.com Thu Jan 22 23:39:07 2004 From: theaney at cablespeed.com (Tim Heaney) Date: Thu, 22 Jan 2004 23:39:07 -0500 Subject: get "yesterday's" date in iso format References: Message-ID: <877jzjb7o4.fsf@mrbun.watterson> necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com writes: > > I am trying to find a simple way to get "yesterday's" date. I know I can > build various check to seee if we are in leap year, if we are the 1st then > yesterday is the 31(or 30 depending of the month) etc. but there is got to > be a simpler way than that. Since time.time() gives the time in seconds since the epoch, you could just subtract a day from that to get yesterday. >>> import time >>> time.gmtime(time.time()-24*60*60) (2004, 1, 22, 4, 36, 3, 3, 22, 0) I hope this helps, Tim From __peter__ at web.de Thu Jan 8 08:05:17 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Jan 2004 14:05:17 +0100 Subject: Descriptor puzzlement References: Message-ID: John Roth wrote: > Using Python 2.2.3, I create this script: > > [beginning of script] > > class AnObject(object): > "This might be a descriptor, but so far it doesn't seem like it" > def __init__(self, somedata): > self.it = somedata > def __get__(self, obj, type=None): > print "in get method" > return self.it > def __set__(self, obj, it): > print "in set method" > self.somedata = it > return None > ## def foo(self): > ## return 1 > > class AnotherObject(object): > def __init__(self): > self.prop = AnObject("snafu") > > myClass = AnotherObject() > print myClass.prop > myClass.prop = "foobar" > print myClass.prop > > [end of script] > > Then I execute it: > > C:\Documents and Settings\John\My Documents\Projects\AstroPy4>b > > C:\Documents and Settings\John\My Documents\Projects\AstroPy4>python b.py > <__main__.AnObject object at 0x0086D248> > foobar > > It doesn't look like the descriptor protocol is getting > invoked at all. > > What's happening here? The descriptor protocol works on the class, not the instance, so class AnotherObject(object): prop = AnObject("snafu") or something similar should work. This means in particular that you have to store the property's state in the AnotherObject rather than the AnObject instance. Peter From bart_nessux at hotmail.com Thu Jan 8 18:17:17 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 08 Jan 2004 18:17:17 -0500 Subject: count objects in a list and random numb gen Message-ID: New to Python... trying to figure out how to count the objects in a list and then map the count to the objects or convert the list to a dict... I think the latter would be better as I need a number associated with each entry. Any pointers? Also, does this bit of code look to be truely random? def random_number_gen(): winner = [] winner.append(random.sample(xrange(100000), 1)) print winner TIA, Bart From jacek.generowicz at cern.ch Wed Jan 7 03:46:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2004 09:46:19 +0100 Subject: metadocumentation (keyword help) References: <3ffb0edf$1@nntp0.pdx.net> Message-ID: sdd writes: > Jp Calderone wrote: > > > On Tue, Jan 06, 2004 at 03:27:06PM +0100, Jacek Generowicz wrote: > > > > >>Where can I find concise, clear documentation[*] describing what one has > >>to do in order to enable Python's internal help to be able to provide > >>descriptions of Python keywords ? > > "Quote them" > > > help('if') > > > Jp > > Or simply use help() > and interactively enter lines. Yes, but this actually does not work out of the box (on any of the GNU/Linux, Mac OS X, and even Windoze installaitions I have tried). You get an error message complaining about the absence of HTML documentation and setting PYTHONDOCS. So, to rephrase my question ... Where can I find clear instructions on how to install and configure the Python documentation which is necessary to make the following work: >>> help('and') ? From theller at python.net Fri Jan 9 07:37:09 2004 From: theller at python.net (Thomas Heller) Date: Fri, 09 Jan 2004 13:37:09 +0100 Subject: unable to register PythonService.exe References: Message-ID: prof_888 at hotmail.com (ChrisD) writes: > I'm running Python 2.3.3 with Win32 extensions win32all-163. I'm > working through Chapter 18 of Mark Hammond's excellent "Python > Programming on Win32". On page 350 the simple NT service example > requires that the PythonService.exe program be registered. However, > when I attempt it I get this error: > > --------------------------------- > C:\Python23\Lib\site-packages\win32>PythonService /register > Registering the Python Service Manager... > Fatal Python error: PyThreadState_Get: no current thread > > abnormal program termination > --------------------------------- > > Any thoughts on how I can fix this problem? Looks like a bug to me, it behaves the same for me. OTOH, it seems that it's not required to do this registration since the sample PythonTestService.py works fine for me. Thomas From netquest at sympatico.ca Mon Jan 26 18:00:39 2004 From: netquest at sympatico.ca (KNS) Date: Mon, 26 Jan 2004 15:00:39 -0800 Subject: winapi: mouseclick Message-ID: Hello, Can someone please suggest how to test for a mouse click using the WinAPI? I have dispatched a windows application and would like to detect any mouseclicks (and keyboard entry for that matter)... Thanks. From max at cNvOiSsiPoAnMtech.com Fri Jan 16 12:06:37 2004 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Fri, 16 Jan 2004 17:06:37 GMT Subject: SimpleXMLRPCServer In-Reply-To: References: Message-ID: Bernhard Mulder wrote: > Here is an example of a server which runs as long as self.running > is set: > > class SimpleXMLRPCServer_with_stop(SimpleXMLRPCServer.SimpleXMLRPCServer): > > def __init__(self, *args, **kwds): > self.running = True > SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kwds) > > def serve_while_running_is_set(self): > """Server while running is set.""" > while self.running: > self.handle_request() So putting it in my original terms this would be: server = SimpleXMLRPCServer(('', 8000)) server.register_instance(MyClass()) while(1) if(checkSomeCondidion()): server.handle_request() else: server.stop() ? thanks. From francisgavila at yahoo.com Mon Jan 12 17:13:51 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 12 Jan 2004 17:13:51 -0500 Subject: How to call a system command with flexibility on Windows References: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> <40031266.B76A5B6F@engcorp.com> Message-ID: <1006734gmrededc@corp.supernews.com> Peter Hansen wrote in message <40031266.B76A5B6F at engcorp.com>... >It can be done on Windows, although at the very least you cannot redirect >stderr properly from the command line on Win98.... not sure about other >issues. Win98 is particularly bad: >>> os.system('dir') #output snipped 0 #return code >>> os.system('foo') Bad command or file name 0 >>> >I'm pretty sure return codes are available with os.system() under Windows, >but I rarely use them and forget any relevant details. -- Francis Avila From jjl at pobox.com Wed Jan 14 20:07:44 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 01:07:44 +0000 Subject: Python and XForms: existing implementations? References: Message-ID: <87n08qrpcv.fsf@pobox.com> "Christian Wilcox" writes: > Does anyone know of any existing Python implementations of an XForms > viewer? What environment does it have to work in? Does it have to be cross-platform? Does it have to be in pure Python, or just useable from Python? Does it have to integrate with a particular GUI framework, or with MS OLE? Does it have to be open source? etc. (BTW, you might want to disambiguate this: XForms is both an XML standard and an old GUI toolkit -- I assume you mean the former) John From sombDELETE at pobox.ru Sun Jan 25 11:39:11 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 25 Jan 2004 19:39:11 +0300 Subject: trouble w/ unicode file References: Message-ID: "Guilherme Salgado" wrote in message news:mailman.766.1075043602.12720.python-list at python.org... > On Sun, 2004-01-25 at 06:54, Serge Orlov wrote: > > "Guilherme Salgado" wrote in message news:mailman.752.1074995324.12720.python-list at python.org... > > > Hi there, > > > > > > I have a python source file encoded in unicode(utf-8) with some > > > iso8859-1 strings. I've encoded this file as utf-8 in the hope that > > > python will understand these strings as unicode () > > > strings whithout the need to use unicode() or u"" on these strings. But > > > this didn't happen. > > > > You hoped, but you forgot to pray Why do you think Python > > should behave this way? There is (an experimental?) option -U that > > Ok, ok. I'll remember to pray next time. :-) > I need to store unicode strings(declared in files) in ZODB, but i don't > want to use u"" around all my strings (cause most of them are latin-1), > so i think storing the file as unicode will work. Is there a better way > for doing this? Not that I'm aware of. > > We have a bug here as well. But in your code. The coding must > > be the same as the coding of your source file. bar.py must be: > > #-*- coding: latin-1 -*- > > x = '????????????' > > print x, type(x) > > > > I didn't understand this (even after some pray) :-) > My file is encoded in utf-8, look: > $ file bar.py > bar.py: UTF-8 Unicode text > > Why should i declare it as latin1 encoded though? Sorry, I was confused by your words "with some iso8859-1 strings". I thought you were using simple (unaware of encodings) editor and just added #-*- coding: utf-8 -*- with hope that it will work. You're right the coding should stay utf-8. After that you have two options: either use -U option or put u before every string. -- Serge. From claird at lairds.com Thu Jan 22 17:40:31 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 22 Jan 2004 22:40:31 -0000 Subject: Buffer overruns (was: Secure Voting software) References: <20040121174434.28446.00000428@mb-m15.aol.com> <7xvfn4lq9m.fsf@ruckus.brouhaha.com> Message-ID: <1010kavl44l76c4@corp.supernews.com> In article <7xvfn4lq9m.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >Buffer overruns are just one narrow type of security failure. . . . Yes and no. Yes, a security audit needs to consider at least hundreds of distinct categories of technical hazards, and buffer overruns are just one of these, and arguably not the riskiest. HOWEVER, we make up for that with the frequency with which we do them; that is, although all the analysis buffer overruns require was available at least twenty years ago, it remains, in my experience, much the most frequent identifiable security-pertinent fault our industry writes in, day after day. We sure look dumb. 'Course, that's certainly not the fault of Python folk. -- Cameron Laird Business: http://www.Phaseit.net From mfranklin1 at gatwick.westerngeco.slb.com Thu Jan 29 10:56:10 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 29 Jan 2004 09:56:10 -0600 Subject: Pausing python programs In-Reply-To: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> References: <40192a20$0$9389$ed9e5944@reading.news.pipex.net> Message-ID: <1075391770.1041.10.camel@m-franklin> On Thu, 2004-01-29 at 09:41, Graham wrote: > How can I cause a python program to pause/suspend execution for a period of > time? I am checking status of an external system and only want to check > every second as opposed to my current which checks may times a secnod and > hogs my cpu in the process!!! > > Thank you to anyone who can help. > > Graham Smith > > PeopleSoft Technical Team Leader > OXFAM GB > +44 (1865) 313255 gsmith at oxfam.org.uk You should really get into pydoc:-) For example pydoc time Help on module time: NAME time - This module provides various functions to manipulate time values. FILE /usr/local/lib/python2.3/lib-dynload/time.so Functions: time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone so time.sleep(1) could be what you are after. Also don't forget google is you friend :-) Cheers Martin -- Martin Franklin From bignose-hates-spam at and-benfinney-does-too.id.au Tue Jan 27 22:19:05 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Jan 2004 14:09:05 +1050 Subject: Python on portable storage References: Message-ID: On Mon, 26 Jan 2004 21:34:56 -0600, Jeff Epler wrote: > One idea would be a directory structure that looks like the source > tree: [...] Thanks for this idea. I probably won't get the time to implement it for a while, but when I do at least this gives an idea for where to start. -- \ "A free society is one where it is safe to be unpopular." -- | `\ Adlai Stevenson | _o__) | Ben Finney From arjen.dijkstraNoSpam at hccnet.nl Fri Jan 16 07:53:40 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Fri, 16 Jan 2004 13:53:40 +0100 Subject: Setting Window Size using Pack Under Tkinter References: <8089854e.0401160134.5674a86c@posting.google.com> <4007de09$0$151$e4fe514c@dreader5.news.xs4all.nl> Message-ID: <4007dedc$0$166$e4fe514c@dreader5.news.xs4all.nl> from Tkinter import * gui=Tk() ####code#### gui.geometry("+%d+%d" %(300, 100)) gui.resizable(0,0) gui.mainloop() Will work offcourse too.. :-) cheers, Arjen "duikboot" schreef in bericht news:4007de09$0$151$e4fe514c at dreader5.news.xs4all.nl... > from Tkinter import * > gui=Tk() > > ####code#### > gui.geometry("+%d+%d" %(300, 100)) > gui.resizable(0,0) > > if __name__=='__main__': > gui.mainloop() > > > > > "Fuzzyman" schreef in bericht > news:8089854e.0401160134.5674a86c at posting.google.com... > > I'm having trouble implementing my GUI using Tkinter...... > > I've been working through the Tkinter tutorials from 'Programming > > Python' and am generally happy enough with the functionality and feel > > of the results *but* - I can't see how to set the size of the root > > window (or any top level window) and to stop it being resized........ > > > > Thanks for any help. > > > > Fuzzyman > > > > > > -- > > > > YAPLP > > Yet Another Python Links Page > > http://www.voidspace.org.uk/coollinks/python_links.shtml > > > > Python Utils > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > > > -- > > > > 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.atlantibots.org.uk > > http://groups.yahoo.com/group/atlantis_talk/ > > Atlantibots - stomping across the worlds of Atlantis. > > --- > > 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 ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ Tue Jan 13 09:28:00 2004 From: ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ (Istvan Albert) Date: Tue, 13 Jan 2004 09:28:00 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED In-Reply-To: References: Message-ID: Brandon J. Van Every wrote: > all public projects I might conceive of are fundamentally DOA. There is no argument about that... Your only talent is trolling. You do it well enough, peppering your expose with subtle and quasi intelligent insults just to keep the discussion going. And that's what trolling is all about. But I don't know whether one can make a living out of that. i. From knoppix at laptop.home.net Sun Jan 11 17:43:32 2004 From: knoppix at laptop.home.net (Knoppix User) Date: Sun, 11 Jan 2004 16:43:32 -0600 Subject: [Newb] Still not able to solve class attribution References: Message-ID: On Sun, 11 Jan 2004 18:36:22 +0100, Peter Otten wrote: You were on the right track, Peter! Your comment go me thinking some more. The error was not in the last line, but the second to last. I have quite a long init method, and the conflict was between the code that sets up the StaticBitmap, and a prior reference to that code, from a Button. Thanks for jarring my mind-track in the right direction!!!! Steve From jimmy at retzlaff.com Fri Jan 16 04:28:44 2004 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Fri, 16 Jan 2004 01:28:44 -0800 Subject: data structures module Message-ID: MetalOne wrote: > Today, I wanted a priority queue. As of 2.3 Python does have a priority queue: http://www.python.org/doc/current/lib/module-heapq.html Jimmy From fumanchu at amor.org Thu Jan 8 10:58:16 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Jan 2004 07:58:16 -0800 Subject: Descriptor puzzlement Message-ID: Peter Otten wrote: > John Roth wrote: > > It doesn't look like the descriptor protocol is getting > > invoked at all. > > The descriptor protocol works on the class, not the instance, so > > class AnotherObject(object): > prop = AnObject("snafu") > > or something similar should work. This means in particular > that you have to > store the property's state in the AnotherObject rather than > the AnObject > instance. I got bit by this myself, a while ago. Would there be any benefit to providing something like what John wanted, where the descriptor can maintain its own state, and be referenced by the owner instance (instead of the owner class)? I could sure use it in a couple of spots where my __getattr__/__setattr__ code is getting ugly. Robert Brewer MIS Amor Ministries fumanchu at amor.org From rganesan at myrealbox.com Sat Jan 24 11:16:55 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Sat, 24 Jan 2004 21:46:55 +0530 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> <871xpp1i8r.fsf@pobox.com> Message-ID: >>>>> "John" == John J Lee writes: > Ganesan R writes: >> > Is that all that people mean, though, when they talk about Perl's >> > superiority for text mangling? Is there more to it? -- > [...] >> The perl "built-in" idioms for text processing is not only a syntactic >> convenience, there are real performance advantages. For example a simple >> perl loop like >> >> while (<>) { } >> >> is nearly 6 times slower in python (8 time slower with Python 2.2) using > [...] > Did you try 'for line in file:'? ISTR Tim Peters optimized that (or > was that fileinput?), precisely because of every hacker and their dog > running this as a benchmark. fileinput is not optimized yet, at least I don't remember any mails about fileinput in python-devel since python 2.3 was released. I know that it is slow. for line in file: does seem to be optimized though. The last time I ran the tests python was definitely twice as slow (which was before python 2.3 was officially released); now it appears to be only about 40% slower. I need to revisit these crude benchmarks. Ganesan -- Ganesan R From jetman516 at hotmail.com Thu Jan 15 18:03:54 2004 From: jetman516 at hotmail.com (The Jetman) Date: 15 Jan 2004 15:03:54 -0800 Subject: [Q & A]Weirdness About Python 2.3x and Its Environment Vars Under Windows Message-ID: I just spent the last hour or so trying mightily to 'fix' Python (2.3.3) under WinME. Have been using it on various Win9X/XP systems for years (since 1.52) for routine scripting. LOVE IT !!! Heretofore, the ONLY environment variable I've EVER used for ANY Pythonstallation was PYTHONPATH (ie. SET PYTHONPATH=.;C:\MYPY;) However, today I started working on a 'new' development machine and I couldn't get IDLE or PYTHONWIN to operate at all. I finally tracked it down to one thing: the absence of the PYTHONHOME env var. PYTHONWIN would crap out w/ an error dialog about not finding pywin.framework.startup and IDLE would simply display an hourglass for a sec, then nothing. I recently heard about PYTHONHOME, added it to my AUTOEXEC, and suddenly all was working again. Another problem was that the cmd-line version of PYTHON wouldn't find ConfigParser (ie. a std Python module) from a very short, working script of mine. Anyway, my question (at last) is: has anyone had this occur to them ? I've NEVER had a problem like this, altho I suspect this is the 1st time I've installed Python 2.3. I figure someone else will get stumped like this and the thread will help. Later....Jet From seanl at chaosring.org Sat Jan 3 13:40:42 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 10:40:42 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: Martin v. Loewis wrote: > > The biggest problem is that new-style classes are both available through > the type() builtin, and callable to create new instances. > > For example, if you have managed to open a file object f, then > > type(f)("/etc/passwd").read() > > lets you access a different file, bypassing all machinery that may > have been designed to prevent that from happening. > > Of course, for the specific case of file objects, there is additional > machinery preventing that from happening, but in the general case, > there might be more problems in that area. For example, > object.__subclasses__() gives you access to quite a lot of stuff. RestrictedPython avoids this by removing the type() builtin from the restricted __builtins__, and it doesn't allow untrusted code to create names that start with _. Zope3 has a type() builtin, but it returns a proxy (written in C) to the type object to prevent access. Right now I'm providing a same_type function instead to compare types. Later I'll probably start playing around with C proxies. I think the main thing that's liable to introduce new security problems (beyond what RestrictedPython may already have) is the fact that RestrictedPython is mostly designed to protect the trusted environment from the untrusted environment, and what I'd really like to do is give programmers in the untrusted environment a way to create objects and pass them around to one another; for example, in the original setup, class statements are allowed but not very useful in the restricted environment, because objects created from those classes would be read-only due to the fact that you can't create any special attributes to tell the system how to handle security from within the restricted environment, which is why I'm adding private attributes to the system and figuring out a way to allow methods defined on a class to assign to attributes on instances of that class without allowing all code to do so. From alert at notification.messagelabs.com Tue Jan 27 08:51:01 2004 From: alert at notification.messagelabs.com (alert at notification.messagelabs.com) Date: 27 Jan 2004 13:51:01 -0000 Subject: WARNING. You sent a potential virus or unauthorised code Message-ID: <20040127135101.13434.qmail@server-7.tower-27.messagelabs.com> For English instructions please scroll down. ISION MailScan hat einen potenziellen Virus oder eine verd?chtige Datenstruktur in einer von Ihnen verschickten oder an Sie gesendeten Nachricht entdeckt. ____________________________________________________________ Einige Informationen zu der infizierten eMail ____________________________________________________________ Zur besseren Identifikation der Nachricht: Der Absender der Nachricht war: python-list at python.org Der Empf?nger der Nachricht war: john at spiegel.de Der Betreff war: 'HELLO' Die Nachricht wurde verschickt am Tue, 27 Jan 2004 13:52:01 +0100 Um die Nachricht genauer zu identifizieren: Scanner 7 (Unpacker) berichtet folgendes: >>> W32/MyDoom.A in '1536475_3X_AZ-S_PA2__document.scr' Die Originalnachricht ist in den ISION Quarant?ne_Server umgeleitet worden, in mail server server-7.tower-27.messagelabs.com (id 1536475_1075211460) und wird dort f?r 30 Tage gespeichert bevor sie endg?ltig gel?scht wird. ____________________________________________________________ Weitere Hilfe ____________________________________________________________ Lesen Sie bitte die haeufig gestellten Fragen ( FAQ) fuer eine solche Situation unter http://www.ision.net/mailscan/faq Hier werden die meisten Ihrer Fragen beantwortet. Wenn Sie weitere Informationen ben?tigen oder glauben, dass es sich um einen falschen Alarm handelt, kontaktieren Sie bitte das ISION Customer Interaction Center unter support at ision.net Sollten Sie mit dem Support in Kontakt treten, geben Sie bitte immer die nachfolgende Virus Identifikationsnummer an: {{{ mail server server-7.tower-27.messagelabs.com (id 1536475_1075211460) }}} ______________________________________ Diese Nachricht wurde von ISION MailScan unter Nutzung des MesssageLabs Virus Control Centers auf alle bekannten Viren untersucht. Wenn Sie mehr ?ber diese Dienstleistung erfahren m?chten, besuchen Sie http://www.ision.net/mailscan/faq _________________________________________________________________ *************************ENGLISH********************************* ISION Mailscan discovered a possible virus or unauthorised code (such as a joke program or trojan) in an email sent by you. Please read this whole email carefully. It explains what has happened to your email, which suspected virus has been caught, and what to do if you need help. ____________________________________________________________ Some details about the infected message ____________________________________________________________ To help identify the email: The message was titled 'HELLO' The message date was Tue, 27 Jan 2004 13:52:01 +0100 The message identifier was (empty) The message recipients were john at spiegel.de To help identify the virus: Scanner 7 (Unpacker) reported the following: >>> W32/MyDoom.A in '1536475_3X_AZ-S_PA2__document.scr' The message was diverted into the virus holding pen on mail server server-7.tower-27.messagelabs.com (id 1536475_1075211460) and will be held for 30 days before being destroyed. ____________________________________________________________ What should you do now? ____________________________________________________________ If you sent the email from a corporate network, you should first contact your local Helpdesk or System Administrator for advice. They will be able to help you disinfect your workstation. If you sent the email from a personal or home account, you will need to disinfect your computer yourself. To do this you will need an anti_virus program. We suggest using one of the leading industry anti_virus packages such as McAfee, F_Secure or Cybersoft, which cost ?15_?30 per copy. ____________________________________________________________ Getting more help ____________________________________________________________ You may like to read the Support FAQs at http://www.ision.net/english/mailscan/faq These will answer many of the most common queries. If you believe this message to be a false alarm or you require further assistance, you can email ISION UK Support at:_ support at ision.net.uk or contact ISION Internet by telephone on:_ +44 (0) 208 293 73 00 Please quote the following Virus Pen ID when contacting Support. {{{ mail server server-7.tower-27.messagelabs.com (id 1536475_1075211460) }}} ________________________________________________________________________ This email has been scanned for all viruses by the MessageLabs Email Security System. For more information on a proactive email security service working around the clock, around the globe, visit http://www.messagelabs.com ________________________________________________________________________ From poelzi at poelzi.org Tue Jan 6 14:26:12 2004 From: poelzi at poelzi.org (daniel.poelzleithner) Date: Tue, 06 Jan 2004 20:26:12 +0100 Subject: Problems with threads and embedding In-Reply-To: <3FFAC395.9080900@poelzi.org> References: <3FFAC395.9080900@poelzi.org> Message-ID: <3FFB0BD4.1030502@poelzi.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 daniel.poelzleithner wrote: | Every script is started in an own interpreter instance and registers | some callback functions for different events. | The module is threadsafe and everything works just fine, with one | exceptions, dead threads are not removed from the process list. Ok, the problem is solved. It seems that my installation is just broken :( On other machines, this problem doesn't occure. Days spent for nihil.... regards ~ Daniel - -- nihil me cirumdat .. . .. ... . . .. . ... . .. . ... . . . pgp key @ http://files.poelzi.org/pgp.txt ED80 E53D 5269 4BB1 1E73 3A53 CBF9 A421 0A7B 003D -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Debian - http://enigmail.mozdev.org iD8DBQE/+wvUy/mkIQp7AD0RAtqmAKDPxw0bwcpEPiedG2OK5mYiEFNb7wCfUQF1 Ae8S1jhvaRLsHtFQZBK7Idw= =SVbE -----END PGP SIGNATURE----- From jcarlson at nospam.uci.edu Sun Jan 25 13:02:30 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 10:02:30 -0800 Subject: makeExe.py In-Reply-To: References: Message-ID: > package = re.split("/",package[len(package) - 1]) > package = re.split(".py",package[len(package) - 1]) You'll find the readability increases when using: package = re.split("/", package[-1]) package = re.split(".py", package[-1]) Negative indices are your friends. - Josiah From bignose-hates-spam at and-benfinney-does-too.id.au Mon Jan 26 21:45:52 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jan 2004 13:35:52 +1050 Subject: efficient updating of nested dictionaries References: Message-ID: On Mon, 26 Jan 2004 21:32:28 -0500, Rich Krauter wrote: > Oh crap. Sorry about the html emails. I've been meaning to turn that > off. Thanks for reminding me. Much better! Thanks for being considerate. -- \ "When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety." -- Steven Wright | Ben Finney From fumanchu at amor.org Thu Jan 8 18:29:50 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Jan 2004 15:29:50 -0800 Subject: count objects in a list and random numb gen Message-ID: Bart Nessux wrote: > New to Python... trying to figure out how to count the > objects in a list > and then map the count to the objects or convert the list to > a dict... I > think the latter would be better as I need a number > associated with each > entry. Any pointers? You want enumerate(). >>> for index, val in enumerate(['a', 'b', 'c']): ... print index, val ... 0 a 1 b 2 c FuManChu From antonmuhin at rambler.ru Mon Jan 19 08:02:02 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Mon, 19 Jan 2004 16:02:02 +0300 Subject: Escaping slashes (double backslash plague) In-Reply-To: References: Message-ID: Aloysio Figueiredo wrote: > I need to replace every ocurrence of '/' in s by '\/' > in order to create a file named s. My first attempt > was: > > s = '\/'.join(s.split('/')) > > but it doesn't work: > > >>>>s = 'a/b' >>>>s = '\/'.join(s.split('/')) why not replace: s.replace('\/', '/')? >>>>s > > 'a\\/b' > >>>>repr(s) > > "'a\\\\/b'" Try print s, and you'll see what you want. > > > '\/'.join() escapes the backslashes and I don't know > why. > > Any help? > > Aloysio Figueiredo > regards, anton. From mhammond at skippinet.com.au Sat Jan 31 22:56:59 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 01 Feb 2004 14:56:59 +1100 Subject: What's the difference between win32ui and win32gui? In-Reply-To: <543bb43c.0401311928.3be1fe36@posting.google.com> References: <543bb43c.0401311928.3be1fe36@posting.google.com> Message-ID: Corwan wrote: > What's the difference between win32ui and win32gui? win32ui is an attempt to wrap MFC, which is itself an object oriented wrapper around the Windows GUI API (ie, a "window" is an object, and has methods). win32gui is a lower-level interface to the raw API (ie, a window is represented by an integer handle, and all functions are global) Naming things has never been my strong point, especially given the benefit of hindsight Mark. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat Jan 10 15:20:34 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 10 Jan 2004 21:20:34 +0100 Subject: Multithreaded COM server problem... References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> Message-ID: Hi ! * Sorry for my bad english : french is very more easy, and nice ;-) * I have try another way. I use a procedure for manage thread : GlobalTacheID=[None]*16 def tache(ordre, numtache=1, nomtache=None, fonction=None): global GlobalTacheID import threading if ordre=="Lance": GlobalTacheID[numtache] = threading.Thread(target=fonction,name=nomtache) GlobalTacheID[numtache].start() print(nomtache+' num.'+str(numtache)) elif ordre=="Liste": return(string.join(threading.enumerate(),'\n')) elif ordre=="Etat": return(str(GlobalTacheID[numtache].isAlive())) And, in my public_method, i call this procedure, with the parameters "ordre=Lance" for run a thread, "ordre=Etat" for see his state (fonction= the name of the method 'threaded'). And it's OK. I can run a thread from an Excel-COM-client. I can also run an thread on a method caontained in a string gived by Excel. Python is very smart-dynamic-agile language. Bonne soir?e -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From sross at connectmail.carleton.ca Sat Jan 3 15:20:01 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 15:20:01 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> Message-ID: <5sFJb.20923$Vl6.3818930@news20.bellglobal.com> "Rainer Deyke" wrote in message news:kTEJb.724242$HS4.5376202 at attbi_s01... > Sean Ross wrote: > > a = bq + r and 0<=r > But 0 <= r < b is a contradiction when b < 0. > > -- > Rainer Deyke - rainerd at eldwood.com - http://eldwood.com > > Hmm.... >>> a = 5 >>> b = -10 >>> q,r = divmod(a,b) >>> q -1 >>> r -5 >>> Here, the division algorithm does not apply (b is a negative integer). Perhaps there's some other theorem for this case? b Hello all, I still can't convert Oracle tables to a Mysql database. See thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&threadm=mailman. 282.1073834719.12720.python-list%40python.org&rnum=1&prev=/groups%3Fsourceid %3Dmozclient%26ie%3Dutf-8%26oe%3Dutf-8%26q%3Dpython%2Boracle%2Bmysql The tables in Oracle and Mysql are the same. Is there anyone who can help me with this? Thanks in advance, Arjen #######code###### import cx_Oracle, MySQLdb from time import time tabellen=["machine", "machinegroup", "machines", "operation", "orders", "run", "step"] tijd=time() conO=cx_Oracle.connect("some/some") cursO=conO.cursor() conMy=MySQLdb.Connect("localhost", db="some") cursMy=conMy.cursor() for tabel in tabellen: cursO.execute("select * from " + tabel) cursMy.execute("truncate " + tabel) #print cursO.description a_oracle=cursO.fetchone() cursMy.execute("insert into %s values %s", (tabel, a_oracle)) conO.close() conMy.close() print "\n\nklaar in :\n" print time()-tijd, " seconden\n\n" #####error#### Traceback (most recent call last): File "A:/tabellen2.py", line 20, in ? cursMy.execute("insert into %s values %s", (tabel, a_oracle)) File "E:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "E:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "E:\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (1064, 'You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'machine\' values ("\'230KM\'", "\' \'", "\'230KM\'", "\'1980-01-01 00:') >>> From tepihlaj at NOpaju.SPAMoulu.fi Mon Jan 5 11:17:52 2004 From: tepihlaj at NOpaju.SPAMoulu.fi (Tero Pihlajakoski) Date: 5 Jan 2004 16:17:52 GMT Subject: Python/C and PYTHONPATH References: Message-ID: Jeff Epler wrote: > You'd need to tell us how you're invoking Python. When the Python Take a look at: http://www.python.org/doc/current/ext/pure-embedding.html. Basically, it's about same (and I tested with it too, same results: failing) > executable is invoked without arguments, the current directory is on the > sys.path: > $ 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 sys >>>> sys.path[0] > '' > When you run a script, the directory of that script is in sys.path[0]: > $ echo "import sys; print sys.path[0]" > /tmp/script.py > $ python /tmp/script.py > /tmp If I run "python" as a shell (python ), everything works ok. Says path is ok: [ '', '', ... ]. However, from C, something works differently: PyRun_SimpleString("import sys\nprint sys.path"); Shows no '' (the rest is ok). The question is: Why is there no '', and what is the "official/safe" way to set it? Just insert it to the list? (Setting "PYTHONPATH= " helps, but I'd like it to run "off the box") Tero From randall at tnr.cc Sat Jan 3 18:38:20 2004 From: randall at tnr.cc (Randall Smith) Date: Sat, 03 Jan 2004 23:38:20 GMT Subject: datetime string to datetime object converter Message-ID: Is there an existing module or script that can convert a datetime string of unknown format to a python datetime object ? Randall From usenet at mail-2-me.com Fri Jan 30 07:44:50 2004 From: usenet at mail-2-me.com (Dirk Hagemann) Date: 30 Jan 2004 04:44:50 -0800 Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain References: Message-ID: Tim Golden wrote in message news:... > [... snip my suggestion of pdc = win32net.NetGetAnyDCName (None, > "name_of_other_domain") ...] > > >From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com] > > > >Thanks for your help, but that does not work. I get an error message > >which sais it can't reach the domain. > >But I'm sure did not make an syntax-error, because if I enter my own > >domain it works. > > > >Any other idea? > > > >Dirk > > > > > > To ask the obvious question: do you definitely have all > the necessary security / connectivity in place to reach > the domain controller on that domain? > > Can you log onto it normally with whatever name you're > running under now? > > (I don't have more than one domain here, so it's difficult > for me to test) > TJG > I can reach the other domains and I have all rights. That's no the problem. Dirk From bart_nessux at hotmail.com Tue Jan 27 09:00:38 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 27 Jan 2004 09:00:38 -0500 Subject: threads Message-ID: Could someone explain the concept of threads and how I might use them in Python? I was a math major, not a CS major (theory instead of practice). Most of my programming knowledge has grown out of system administration and shell scripting, not professional software development. How could I make this script threaded, and why should I, how would it benefit me? The script already takes up 100% CPU resources, what would using threads gain for me: #!/usr/bin/python #change this to your Python's path def cpu_test(): x = 0 while x < 999999999: x = x + 1 print x cpu_test() cpu_test() If the above is not suitable for threading, please give me a short example of something that is. Thanks!!! From LittleDanEhren at yahoo.com Sat Jan 31 21:08:15 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 31 Jan 2004 18:08:15 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: <711c7390.0401311808.3914a94b@posting.google.com> > Do you know why the creator of IO decided not to use the now-ubiquitous > "." operator? I don't know whether I can define a "." operator that has > the appropriate behaviour but that wouldn't help anyhow. > > Paul Prescod In the opinion of the creators of Io, a space looked cleaner. Using a period looks kinda like you're finishing a sentence and starting a new one. Consider the following syntaxes: Dog barks //Io Dog.barks() #Python Regardless of which one is more common, which looks more like language? You say that "." is more ubiquitous, but "{}" is more ubiquitous than ":" by far, yet Python uses the latter and we don't complain. (note that in Io, unlike other languages with similar syntax such as Ruby, functions are first class objects.) Daniel Ehrenberg From adonisv at REMOVETHISearthlink.net Mon Jan 19 21:46:48 2004 From: adonisv at REMOVETHISearthlink.net (Adonis) Date: Tue, 20 Jan 2004 02:46:48 GMT Subject: Launching Wordpad on Windows References: Message-ID: "Patrick L. Nolan" wrote in message news:buhtvp$l0j$1 at news.Stanford.EDU... > I'm trying to find a clean way to launch a Wordpad editor > on Windows. By "clean", I mean that it should work on as > many versions of Windows as possible, and it shouldn't > require installing any extra software. I assume everyone > has win32api and its friends. > > The problem is to find the path to wordpad.exe. At first > I just copied the path from my XP machine: > c:\Program Files\Windows NT\Accessories\WORDPAD.EXE > > I verified that the same path works on W2K, but I don't > know about older versions. With some labor I was able > to come up with a longer, more obfuscated bit of code: > > item = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\WORDPAD.EXE" > key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, item, 0, > win32con.KEY_QUERY_VALUE) > info = win32api.RegQueryValueEx(key, None) > win32api.RegCloseKey(key) > editor = win32api.ExpandEnvironmentStrings(info[0]) > > I would like to solicit learned opinions about this. Which > version will work in more versions of Windows? Is there a > better approach? > > -- > * Patrick L. Nolan * > * W. W. Hansen Experimental Physics Laboratory (HEPL) * > * Stanford University * This works for me: (Using WinXP Pro) 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 os >>> os.system("start wordpad") 0 Hope this helps. Adonis From nomail at nospam.net Mon Jan 12 04:58:45 2004 From: nomail at nospam.net (Olaf Meyer) Date: Mon, 12 Jan 2004 09:58:45 GMT Subject: building strings with variable input Message-ID: Sometimes if find it clumsy unsing the following approach building strings: cmd = "%s -start %s -end %s -dir %s" % (executable, startTime, endTime, directory) Especially if you have a lot of variable input it makes it hard to match the variables to the proper fields. From other scripting languanges I'm used to something like: $cmd = "$executable -start $startTime -end $endTime -dir $directory" This makes it very easy to see how the string is actually built. You dont't have to worry where which variables go. Is there a similar way to do this in python? Thanks, Olaf From __peter__ at web.de Thu Jan 8 04:58:48 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Jan 2004 10:58:48 +0100 Subject: Rookie Speaks References: <3FFC9855.3070901@lawson.com> Message-ID: William S. Perrin wrote: I thinke your function has a sane design :-) XML is slow by design, but in your case it doesn't really matter, because is probably I/O-bound, as already pointed out by Samuel Walters. Below is a slightly different approach, that uses a class: class Weather(object): def __init__(self, url=None, xml=None): """ Will accept either a URL or a xml string, preferrably as a keyword argument """ if url: if xml: # not sure what would be the right exception here # (ValueError?), so keep it generic for now raise Exception("Must provide either url or xml, not both") sock = urllib.urlopen(url) try: xml = sock.read() finally: sock.close() elif xml is None: raise Exception("Must provide either url or xml") self._dom = minidom.parseString(xml) def getAttrFromDom(self, weatherAttribute): a = self._dom.getElementsByTagName(weatherAttribute) return a[0].firstChild.data def asRow(self): # this will defeat lazy attribute lookup return "%13s\t%s\t%s\t%s\t%s\t%s\t%s" % (self.name, self.fahrenheit, self.wind, self.barometric_pressure, self.dewpoint, self.relative_humidity, self.conditions) return def __getattr__(self, name): try: value = self.getAttrFromDom(name) except IndexError: raise AttributeError( "'%.50s' object has no attribute '%.400s'" % (self.__class__, name)) # now set the attribute so it need not be looked up # in the dom next time setattr(self, name, value) return value This has a slight advantage if you are interested only in a subset of the attributes, say the temperature: for url in listOfUrls: print Weather(url).fahrenheit Here getAttrFromDom() - the equivalent of your getattrs() - is only called once per URL. The possibility to print a tab-delimited row is still there, print Weather(url).asRow() but will of course defeat this optimization scheme. Peter From usenet_spam at janc.invalid Wed Jan 21 22:56:14 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 22 Jan 2004 03:56:14 GMT Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <90f2d9db.0401210935.428e0a0e@posting.google.com> Message-ID: its1louder at yahoo.com (Tom) schreef: > As for the other question, a portable html browser that looks & feels > like the chm help browser. I realized that Boa Constructor Project > has such a component, since I've used Boa help in windows and unix. I > wonder if anyone has written a cross-platform CHM decoder and browser > that has the help browser look & feel. I can't find one, but it seems > that python would be a great language to make such a thing. Maybe > I'll take a crack if it hasn't been done. I like monolithic, > compressed help vs. a big directory full of html. helpviewer.py in site-packages/wxPython/tools is part of wxPython, not Boa: """ helpviewer.py -- Displays HTML Help in a wxHtmlHelpController window. Usage: helpviewer [--cache=path] helpfile [helpfile(s)...] Where helpfile is the path to either a .hhp file or a .zip file which contians a .hhp file. The .hhp files are the same as those used by Microsoft's HTML Help Workshop for creating CHM files. """ Also try xCHM for a cross-platform .CHM viewer: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From amuys at shortech.com.au Thu Jan 15 23:58:43 2004 From: amuys at shortech.com.au (Andrae Muys) Date: 15 Jan 2004 20:58:43 -0800 Subject: Suggested generator to add to threading module. Message-ID: <7934d084.0401152058.164a240c@posting.google.com> Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next = gen.next() finally: lock.release() yield next I considered suggesting it for itertools, but really it's thread specific so I am suggesting it for the threading module. Andrae Muys From w.henney at astrosmo.unam.mx Fri Jan 23 09:43:37 2004 From: w.henney at astrosmo.unam.mx (Will Henney) Date: 23 Jan 2004 06:43:37 -0800 Subject: prog/lib to draw graphs References: Message-ID: <9ddba974.0401230643.668a717a@posting.google.com> Florian Lindner wrote in message news:... > Hello, > I'm looking for a program or python library to draw graphs. > They should look like the that: > > > /--------\ /--------\ > | Node A | ------ belongs to ----> | Node B | > \--------/ \--------/ > > Which is a result of the function call like that: > > connectNodes(firstNode, secondNode, description, lineStyle) > connectNodes("Node A", "Node B", "belongs to", dashed) > > It should have a open scalable vector format as output (DVI, SVG, PDF, ...) > and should be able to make automatic optimal placement of the items. Since you mention DVI you probably know about LaTeX. You might want to try its `psfrag' package, which can do all you want and more. Learning curve is a bit steep, but the results are _very_ high quality. Nothing to do with Python though...... From michael at foord.net Fri Jan 9 05:12:32 2004 From: michael at foord.net (Fuzzyman) Date: 9 Jan 2004 02:12:32 -0800 Subject: Python Utils - A simple config file parser and output object References: <8089854e.0401070044.1e8116ad@posting.google.com> Message-ID: <8089854e.0401090212.4826925d@posting.google.com> I've done a slight update to these (v1.0.1 :-) a couple of bugfixes and added a couple of small but nifty features........ (all to ConfigObj) I have to use google groups to post these messages as our work firewall block nntp.... I'm thinking of building a newsgroup reader that uses google groups via http but provides a better interface... anyone interested ?? Fuzzy michael at foord.net (Fuzzyman) wrote in message news:<8089854e.0401070044.1e8116ad at posting.google.com>... > A couple of little scripts I've written for my python project > (AAAcontroller - see www.atlantibots.org.uk) might be useful to others > - so I've stuck them up on the web : > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > They're my new config object - ConfigObj - and my output object > StandOut....... > > ConfigObj parses and updates simple config files (including multiple > values for keywords, preserving comments, and updating sections of the > file). > StandOut is an output object that can print messages to the screen > *and* to a logfile..... > > > Fuzzy -- 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.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. --- 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 nav+posts at bandersnatch.org Fri Jan 16 11:05:09 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 16 Jan 2004 11:05:09 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Brandon J. Van Every" writes: > I've also become extremely disillusioned with Open Source developers. > Basically, for a commercially minded developer such as myself, I don't think > they're any value add at all. "I've become very disillusioned with cats. For a stick-fetching minded person like myself, I don't think they make good pets at all." Well, duh! > I'm also starting to downright despise Linuxers. If I see another project > that's "cross-platform, so long as your platform is Linux," I'm going to cut > someone's head off. And you seemed to want something cross-platform, as long as it runs on .NET. I don't see your position being any better, from a cross-platform standpoint, than that of the "Linuxers". Wait, let's look at the FreeCiv download page: http://freeciv.org/download.phtml... I even see Win32, Mac OS-X, and OS/2. That seems pretty damn cross-platform to me. > Rather, it's always the induhvidual's responsibility to > download and install all the needed component libraries. If their distro doesn't include the components, they will go and get them, or switch to a different distro. Your preferred platform comes in only one distro, which means there's no incentive for the provider to include a wide selection of components. Actually, your provider is disincentivesed from including components other than the ones they control. Other than being frustrating for you, I think the Linuxers have made a much more rational choice of platforms than you have. > Or requiring Cygwin or MinGW, which real Windows developers don't want to > use. Where "real Windows developers" == "Brandon Van Every". I see plenty of open source Windows projects with compilation instructions that require the use of Cygwin or MinGW. > Whether my Freeciv VS .NET 2003 build makes it into the official Freeciv > source pool remains to be seen. The Freeciv people are, after all, a bunch > of Linuxers. I'm guessing it won't, especially since rejecting it means they won't have to continue dealing with someone like you. Consider me trolled, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From dave at pythonapocrypha.com Fri Jan 9 17:48:47 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 9 Jan 2004 15:48:47 -0700 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) Message-ID: <027401c3d702$be589a50$6401fea9@YODA> Dave wrote: > I program in Python full-time and each spend approximately zero hours > optimizing. In the past two years I can think of two instances in which I went > into heavy optimization mode: one was for a web server that needed to handle > hundreds of requests per second and the other was a log processor that needed > to parse and process several gigabytes of log data per hour. > > In the server I added a tiny C extension to make use of the Linux sendfile API, > all the other optimizations were algorithmic. In the log processor all the > optimizations ended up being either algorithmic or doing fewer dumb things > (like recomputing cacheable data). > > > From bart_nessux at hotmail.com Tue Jan 13 09:43:23 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Tue, 13 Jan 2004 09:43:23 -0500 Subject: Make a function call itself after set amount of time In-Reply-To: References: Message-ID: Bart Nessux wrote: > How do I make a function call itself every 24 hours. Also, is there a > way to start the program automatically w/o depending on the OS functions > like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and > xp. Below is an example of what I'm trying to do. > > TIA > > def ipconfig_email(): > from email.MIMEText import MIMEText > import smtplib > import time > import os > > u = "user name" #Change This to user's name. > f = "my-email-addy" > t = "my-email-addy" > > fp0 = os.popen("ipconfig /all", "r") > fp1 = os.popen("psinfo -d -s", "rb") > msg = MIMEText(fp0.read() + fp1.read()) > fp0.close() > fp1.close() > > msg["Subject"] = "%s's IPconfig Report" % u > msg["From"] = f > msg["To"] = t > > h = "my.smtp.server" > s = smtplib.SMTP(h) > s.sendmail(f, t, msg.as_string()) > s.quit() > time.sleep(86400) #24 hour sleep > HOW_DO_I_CALL_THE_FUNCTION_AGAIN? > > ipconfig_email() > I figured it out. I added this to the function definition: ipconfig_email() I feel like an ass, sorry to bother you guys! From jcarlson at nospam.uci.edu Sun Jan 25 20:09:40 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 17:09:40 -0800 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: > Either that or Microsoft. ;-) Or he's plain stupid. > > Mikl?s Never underestimate the power of stupidity (or ignorance, or denial, or...). Speaking of which... http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html - Josiah From peter at engcorp.com Tue Jan 6 08:34:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 08:34:32 -0500 Subject: Starting a script interactively? References: <37d5fe8f.0401021305.349a440@posting.google.com> Message-ID: <3FFAB968.3B8DDDC1@engcorp.com> David Klaffenbach wrote: > > Is there a way from within a python script to cause the interpreter to > be in interactive mode after the script finishes? Added in Python 2.3, according to http://www.python.org/2.3/highlights.html: PYTHONINSPECT - A program can now set the environment variable $PYTHONINSPECT to some string value in Python, and cause the interpreter to enter the interactive prompt at program exit, as if Python had been invoked with the -i option. In other words, this should work: import os os.environ['PYTHONINSPECT'] = '1' (untested) -Peter From jmob at unm.edu Mon Jan 12 04:49:45 2004 From: jmob at unm.edu (Jason Mobarak) Date: Mon, 12 Jan 2004 02:49:45 -0700 Subject: Division oddity In-Reply-To: <7at3005sjtd6clgfm6e7v1gq83ohlrc2td@4ax.com> References: <7at3005sjtd6clgfm6e7v1gq83ohlrc2td@4ax.com> Message-ID: <6b2dnS9lM559YpzdRVn-ig@comcast.com> Denis Sarrazin wrote: > Try 1.0/2 instead of 1/2. Note that when I do eval("1/2") I get 0 not > 0.5 Please note: "from __future__ import division", see PEP 238 which changes the behavior of the divisino operator. My results with Python 2.3.3: >>> from __future__ import division >>> eval('1/2') 0.5 >>> input() 1/2 0 >>> eval(raw_input()) 1/2 0.5 > > -Denis > > Le Sun, 11 Jan 2004 23:45:48 +0000, Tim Rowe > a ?crit : > > >>If I do from __future__ import division then eval(1/2) gives me 0.5 as >>expected. But if I do print input("enter a sum: ") and enter 1/2 as >>the sum I get 0 as if I hadn't done the import. I thought input was >>supposed to give the same behaviour as an eval on raw input -- why the >>difference here? > > From no.spam at no.spam.com Mon Jan 5 09:37:47 2004 From: no.spam at no.spam.com (Maciej Sobczak) Date: Mon, 05 Jan 2004 15:37:47 +0100 Subject: Multiple interpreters in a single process Message-ID: Hi, I'm interested in embedding the Python interpreter in a C++ application. What I miss is the possibility to create many different interpreters, so that the stuff that is running in one interpreter does not influence the other. In essence, the interpreter can be used in different modules of a single application. It would be nice to isolate them. There are two possibilities: 1. The interpreters need to run in paraller (from different threads of the master application). Definitely, separate interpreters are needed. 2. Different modules use a single Python interpreter in non-overlapping times. At least the possibility to clean up the interpreter is needed. Is this problem easy to solve? Or maybe are there alternative approaches (switchable dictionaries, etc.)? Thank you very much, -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From rmangaliag at slu.edu.ph Fri Jan 30 03:59:30 2004 From: rmangaliag at slu.edu.ph (ali) Date: Fri, 30 Jan 2004 16:59:30 +0800 Subject: what is the use of weakref? Message-ID: <1jipe1-fqq.ln1@news.slu.edu.ph> i've seen a lot of times in programs but until now i still dont know the use of the weakref module... any help will be appreciated... thanks... ali From jcb at iteris.com Fri Jan 16 02:06:44 2004 From: jcb at iteris.com (MetalOne) Date: 15 Jan 2004 23:06:44 -0800 Subject: data structures module Message-ID: <92c59a2c.0401152306.1c6a17f5@posting.google.com> I am fairly new to Python. Today, I wanted a priority queue. I notice that Python does not have any sorted lists. I know that I can call list.sort(), but that seems rather inefficient to call every time an element is added. I am wondering why there is not a module or modules containing many common data structures. Has such a thing been decided against? Is it that just nobody has done it? Has nobody else suggested the need for it? Maybe I should search, but I am too tired now, I need sleep. From roberson at ibd.nrc-cnrc.gc.ca Mon Jan 26 13:32:42 2004 From: roberson at ibd.nrc-cnrc.gc.ca (Walter Roberson) Date: 26 Jan 2004 18:32:42 GMT Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> <40136b6d@news.victoria.tc.ca> <7fe97cc4.0401260943.2442ba4e@posting.google.com> Message-ID: In article <7fe97cc4.0401260943.2442ba4e at posting.google.com>, Xah Lee wrote: :* when it gets one to think about design, File::Basename is one :fucking turd. The suffix list should not be regex in the first fucking :place. (it shouldn't even require a suffix list by default). The need :to feed it OS type (fileparse_set_fstype($os)) is fucking defeating :the main point of using this module. You don't -need- to feed it the OS type: it defaults to using the information from the currently running OS ($^O). The fileparse_set_fstype is there so that one can write routines targetted at specific OSes. For example, one could import a VMS log file onto a Unix system and parse it there without having to roll one's own filename parsing routines. :The suffix list should not be regex in the first fucking :place. Why not? Anyone who read the documentation would see immediately that regexes were called for in that position. Perhaps -you- don't need the flexibility of having regexes there, but is that any reason to deny other people the flexibility? :it shouldn't even require a suffix list by default It doesn't. If you don't pass it a suffix list, then that will be treated as the empty array, and suffixes will not be broken out. Are you perhaps saying that on Unix systems, it should default to using '\.[^.]*$' as the suffix list, thus breaking out from the last period onwards? -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth From wichert at wiggy.net Thu Jan 22 09:16:28 2004 From: wichert at wiggy.net (Wichert Akkerman) Date: Thu, 22 Jan 2004 15:16:28 +0100 Subject: utf8 encoding problem In-Reply-To: References: <20040122103549.GA5620@wiggy.net> Message-ID: <20040122141628.GJ7377@wiggy.net> Previously Denis S. Otkidach wrote: > You have to pass 8-bit string, but not unicode. The following > code works as expected: > > >>> urllib.unquote('t%C3%A9st').decode('utf-8') > u't\xe9st' Ah, that does work indeed, thanks. > P.S. According to HTML standard, with > application/x-www-form-urlencoded content type form data are > resricted to ASCII codes: > http://www.w3.org/TR/html4/interact/forms.html#form-data-set > http://www.w3.org/TR/html4/interact/forms.html#submit-format Luckily that is not true, otherwise it would be completely impossible to have websites using non-ascii input. To be specific, the encoding used for HTML forms is determined by: 1. accept-charset attribute of the form element if present. This is not handled by all browsers though. 2. the encoding used for the html page containing the form 3. ascii otherwise this is specified in section 17.3 of the HTML 4.01 standard you are referring to. Wichert. -- Wichert Akkerman It is simple to make things. http://www.wiggy.net/ It is hard to make things simple. From tjreedy at udel.edu Fri Jan 9 23:03:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Jan 2004 23:03:00 -0500 Subject: Python is far from a top performer according to benchmark test... References: Message-ID: "Krzysztof Stachlewski" wrote in message news:btn5db$2f8$1 at absinth.dialog.net.pl... > "Carl" wrote in message > news:ryELb.238$tK2.228 at amstwist00... > With "heavy use of Numeric module" you were calling functions > written in C. So how can you say that Python is fast, > when C code is doing all the work. Well gee. *All* of the functions exposed in builtins *and* in built-in modules are also written in C. So are all the methods of builtin types and all the hidden functions (some exposed in the C API), including the compilation and interpretation. So how can anyone even talk about the speed of Python, when C code is doing all the work, whether quickly or slowly! [and in another post] >I just think that the Numeric package is not the best example > of the speed of Python itself. But what is 'Python' itself? I think you are making a false distinction. Numerical Python and other scientific code driving C and Fortran functions was a, if not the killer app for Python when I learned it about 7 years ago. It was so important to the early success of Python, such as it was, that the slice object was added just for its use. Terry J. Reedy From engsolnom at ipns.com Mon Jan 5 20:41:02 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Mon, 05 Jan 2004 17:41:02 -0800 Subject: Quck question References: <3125790e.0401051610.5e24de28@posting.google.com> Message-ID: <534kvvgceuqteq41ta3n2qug588ihmlvm8@4ax.com> On 5 Jan 2004 16:10:21 -0800, sinzcere at hotmail.com (J) wrote: >I have the following information in a file : >r1kcch Serial0/0/0 propPointToPointSerial >Mon Jan 5 13:15:03 PST 2004 InOctets.1 0 >Mon Jan 5 13:15:05 PST 2004 OutOctets.1 0 > >I want to be able to extract each line into a comma delimited list. >Bellow i am trying to print out my list print currentList but nothing >is comming out. I added a line after print test to make sure the file >has the information. Can someone help me with this? > > >#Read a file >true = 1 >in_file = open("test.txt","r") >text = in_file.read() >while true: > in_line = in_file.readline() > if in_line == "": > break > currentList = string.split(in_line,",") > #print out the contents of the current list > print currentList > #make the inline stop reading > in_line = in_line[:-1] >in_file.close() Here's an alternate way.... fd_in = open('myfiles/test_text.txt', 'r') each_line = '' a_list = [] for line in fd_in.readlines(): for word in line.split(): each_line += word + ',' a_list.append(word) # If a real list is desired print each_line # Keep the trailing comma print each_line.rstrip(',') # Delete the trailing comma each_line = '' # Ready for the next line #a_list = [] # Clear the list if one line per # list is desired print a_list # Otherwise the whole file is # contained in the list fd_in.close() Prints: This,is,line,one, This,is,line,one This,is,line,two, This,is,line,two This,is,line,three, This,is,line,three This,is,line,four, This,is,line,four This,is,line,five, This,is,line,five This,is,line,six, This,is,line,six ['This', 'is', 'line', 'one', 'This', 'is', 'line', 'two', 'This', 'is',...] Several concepts are embedded, if that's a confusion, I apologize. Of course, you can write to an output file in lieu of the prints. Norm (just a newbie) From roberson at ibd.nrc-cnrc.gc.ca Sun Jan 25 01:18:50 2004 From: roberson at ibd.nrc-cnrc.gc.ca (Walter Roberson) Date: 25 Jan 2004 06:18:50 GMT Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: In article <7fe97cc4.0401242131.22acf485 at posting.google.com>, Xah Lee wrote: :the crime in question this time is the module File::Basename. :1. create a directory containing a file of this name: "cdrom.html". :2. "use File::Basename;", with the line: : ($name,$path,$suffix) = fileparse($File::Find::name, ('.html', :'.m')); :3. Notice that your cdrom.html will be parsed into "cdr" with suffix :"om.html". :Now, if you peruse the "documentation" of "perldoc File::Basename", :you'll see that it shouldn't be so. The program did what it was documented to do. : The : remainder of the input file specification is then : divided into name and suffix based on the : optional patterns you specify in : @suffixlist. Each element of this list can be a : qr-quoted pattern (or a string which is : interpreted as a regular expression), and is : matched against the end of name. If this : succeeds, the matching portion of name is removed : and prepended to suffix. So the suffixlist is a set of *patterns*. And '.m' is a *pattern* that means "any character followed by the character 'm'. Probably what you wanted to code was: ($name,$path,$suffix) = fileparse($File::Find::name, ('\.html', '\.m')); : Here is a better documentation for the fileparse subroutine. Your "better" documentation does not describe how the directory string is derived. :Not every morons in this world is using unix with its morinic :convention of appending things to file names as a versioning system, There is no widespread unix convention of appending things to file names as a versioning system. The convention of appending a version was probably most common in VMS, which used filenames of the form $device:[directory.directory]filename.filetype;version such as $DISK0:[ROBERSON.SOURCE]HELLO.C;17 The use of extension information was present in CPM (1973) -- borrowed from VMS. CPM begat QDOS which begat DOS which begat Windows. The VMS structure of filename.filetype;version was adopted as the ISO9660 filesystem for CDROMs. You don't *see* that because there are common extensions to provide filename mapping, but every ISO standard CDROM filesystem uses that structure underneath. Including the common Rockridge extensions, and including when you put a Joilet filesystem on a CDROM. -- Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is NOTHING like Shakespeare. -- Blair Houghton. From pythonlist at dan-gottlieb.com Sun Jan 25 13:29:43 2004 From: pythonlist at dan-gottlieb.com (Dan Gottlieb) Date: Sun, 25 Jan 2004 13:29:43 -0500 Subject: Mod_python on Windows Troubles Message-ID: <009101c3e371$37325180$6401a8c0@X1000> Hi, I realize that this is somewhat vague, but I'm not really sure what to do next. I'm trying to get Apache and mod_python set up on my windows XP box for testing purposes. I installed the Apache 2.0.48 windows binaries using the Apache installer, tested it and it worked fine. I then installed the mod_python 3.0.4 windows binaries using the installer which correctly found my ActiveState Python 2.2 installation and the aforementioned Apache installation. I tested Apache again, and it loaded fine. However, when I add the line "LoadModule python_module modules/mod_python.so" to httpd.conf, the Apache service refuses to start with the following error: "Cannot load C:/Program Files/Apache Group/Apache2/modules/mod_python.so into server: The specified module could not be found." Any help would be greatly appreciated. Regards, Dan From francisgavila at yahoo.com Thu Jan 22 00:47:10 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 22 Jan 2004 00:47:10 -0500 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: <400F3D90.2176087B@alcyone.com> Message-ID: <100up1eosgqun2a@corp.supernews.com> Erik Max Francis wrote in message <400F3D90.2176087B at alcyone.com>... >- wrote: > >> Why 5 does not appear ? (this was the source of a deep bug in a 4000+ >> lines networked program...) > >You are iterating over a mutable sequence while you are mutating it. >That is a big no-no. > Try this instead: a = [i for i in range(8) if not i == 4] -- Francis Avila From akhavr at kds.com.ua Mon Jan 12 13:03:47 2004 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Mon, 12 Jan 2004 20:03:47 +0200 Subject: script to translate from compiler AST References: <4f0a9fdb.0401120037.13686194@posting.google.com> Message-ID: Miki, "MT" == Miki Tebeka wrote: MT> Have you looked at the parser module? MT> (http://www.python.org/doc/current/lib/module-parser.html) it does MT> have some functions operating on AST. The is also a visitor patter MT> support in the compiler module. Well, I'm speaking exactly about the compiler module. Imagine, I've built an AST that I want to run. I've not found an easy (read library) way to do that, hence the questions. -- Andrey V Khavryuchenko http://www.kds.com.ua/ Silver Bullet Software Solutions http://www.kds.com.ua/training/ From jsbenson at bensonsystems.com Wed Jan 14 15:28:26 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 14 Jan 2004 12:28:26 -0800 Subject: CCPL: a new software stealth license Message-ID: <020301c3dadc$f7147840$8d09500a@jsbwxp3> Regarding the following post: Once Groucho Marx said something really funny, and someone asked him "Is that original?" His reply: "It was once..." I hereby place the below-quoted code fragment under the CCPL (Cheshire Cat Public License). You are permitted to use the code covered by this license for any purpose whatsoever as long as you don't include the CCPL and copyright (which shouldn't be too hard, because they have been encrypted and shredded to facilitate compliance, plus I'm going to neuralyze myself now...). What was this post about? Message: 4 Date: Tue, 13 Jan 2004 20:32:38 -0700 From: "Dave Murray" Subject: Re: I come not to bury C++, but to praise it... To: python-list at python.org Message-ID: <1009e0uldj5eq29 at corp.supernews.com> > sprintf("All the cool guys use %s because %s\n", Myfavoritelanguages, > Mylimitedexperience) Very good! I hope that that's not under copyright, I plan to use it. Dave From mtadin66 at yahoo.com Sun Jan 18 23:45:48 2004 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Mon, 19 Jan 2004 05:45:48 +0100 Subject: Searching for UTF8 capable font for REPORTLAB References: Message-ID: Try following code, replace value of my_location_of_TTF with your location of TTF (of course you should have TT fonts somewhere on your machine, on windows they are allways there, AFAIK you can download them for linux): There is also mailing list on ReportLabs website, it is where I found the hint how to use ReportLab and Unicode. from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont canv = canvas.Canvas('test_03.pdf') fontname = 'CS' my_location_of_TTF = 'C:\WINNT\FONTS\comic.TTF' pdfmetrics.registerFont(TTFont(fontname,my_location_of_TTF)) a=u'\u010d\u0107\u017e\u0161\u0111\u010c\u0106\u017d\u0160\u0110' canv.setFont(fontname,10) canv.drawString(50,100,'Some text:'+a.encode('UTF8')) canv.save() "Andreas Jung" wrote in message news:mailman.429.1074256100.12720.python-list at python.org... > Reportlab has some problems with creating PDFs from UTF8 encoded text. For > this reason > they are using a truetype font rina.ttf which looks *very ugly*. Does > anyone know of a > suitable free available truetype font that works with UTF8? > > -aj > > From newsgroups at jhrothjr.com Sun Jan 4 20:28:04 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Jan 2004 20:28:04 -0500 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Serge Orlov" wrote in message news:btac4k$1ekr$1 at nadya.doma... > > "John Roth" wrote in message news:vvh75ienj7g244 at news.supernews.com... > > > > "Serge Orlov" wrote in message > > news:bta2ng$16v7$1 at nadya.doma... > > > > > > "John Roth" wrote in message > > news:vvg0h93ue63c0b at news.supernews.com... > > > > > > > > One problem I've been playing around with is: how would you > > > > implement something functionally equivalent to the Unix/Linux > > > > chroot() facility? The boundaries are that it should not require > > > > coding changes to the application that is being restricted, and it > > > > should allow any and all Python extension (not C language > > > > extension) to operate as coded (at least as long as they don't > > > > try to escape the jail!) Oh, yes. It has to work on Windows, > > > > so it's not a legitimate response to say: "use chroot()." > > > > > > I don't see any unsolvable problems. Could you be more specific > > > what is the problem? (besides time, money, need to support > > > alternative python implementation, etc...) > > > > Well, I don't see any unsolvable problems either. The biggest > > sticking point is that the Unices use hard links to create > > a directory tree that has the necessary programs availible. > > Windows does not have this capability, so an implementation > > would have to build a virtual directory structure, intercept all > > paths and map them to the virtual structure backwards and > > forwards. > > > > The reason I find it an interesting problem is that I can't see > > any way to do it with the kind of "generic" facility that was > > in the Python Restricted execution facility, at least without a > > complete redesign of the file and directory functions and > > classes in the os module. Without that, it would > > require code in the C language implementation modules. > > Right now the file and directory management modules are a > > real mess. > > Right, you can do it with a custom importer and wrapper > functions over all file and directory functions. But that's > a mess over a mess and any mess is *bad* for security. > The way out the mess is probably filepath object that > should consolidate all access to files and directories. > If you wanted to make a point that std library should > be designed with security in mind I agree with you. > One step in that direction is to design everything OO. > OO design plays nice with capabilities. > > -- Serge. Sean Ross took a pass at this idea in the thread "Finding File Size" starting on 1/1. That got renamed to "Filename Type" somewhere fairly quick. There's now a pre-pep http://tinyurl.com/2578q for the notion, thanks to Gerrit Holl. John Roth > > From dietrich at zdome.net Mon Jan 26 01:04:07 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 25 Jan 2004 22:04:07 -0800 Subject: [OPINION] - does language really matter if they alldothe samething? In-Reply-To: References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com><028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net><4011C497.1040302@prescod.net><58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: <73BCD13A-4FC5-11D8-804D-0003934ACDEC@zdome.net> On Jan 25, 2004, at 6:13 PM, Terry Reedy wrote: > I assume that in your code, the same recursion base-casing is hidden > within > the no-source-given choose-random-assoc macro, by how it rewrites the > text > of its 'arguments'. I suspect that if choose-random-assoc were an > ordinarily lisp function, including in CL, with arguments evaluated > before > the call, then random_sword_magic_power() would have to explicitly > conditionalize its recursive call, just as in other languages. If so, > then > one very much does have to know that c-r-a is a macro in order to use > it > efficiently and not write a redundant base-case check. Yah, it is hidden, or as I would put it, abstracted away. It's stuff I don't need to look at or know any more. The 'and' solution wouldn't in the following: (defun some-beverages () (choose-random (5 '(water)) (2 '(milk)) (3 '(orange-juice)) (5 (append (some-beverages) (some-beverages))))) This is a bit closer, as I can't recall any recursive function I've written where the recursion can be excluded before we know which item 'choose-random' selected. Copying and pasting the above into clisp (after loading choose-random) yields results like: (orange-juice) (milk orange-juice) (water water) I strongly disagree with the statement that I need to know that 'choose-random' is a macro. In Python, I don't need to know that 'lambda' creates a 'closure'. All I need to know is how to use it. I didn't give the source for 'choose-random' because I don't think it necessary, and besides, it's the first macro I ever wrote -- so it's poorly written (but I don't care as long as it works). If I were to rewrite it, I would eliminate a level of parentheses. By the way, I would NOT touch the parentheses issue with a ten-plus-one foot pole, ESPECIALLY on a Python list. In Lisp, you could (and often do) use things that are macros and never know. Such as the following: (defun abs (x) (cond ((> x 0) x) (T (- x)))) Can you spot the macro? There are anywhere from zero to two or more macros, depending on implementation. 'cond' will sometimes turn itself into a bunch of 'if' expressions (sometimes vice versa), and 'defun' often turns into a 'define' and a 'lambda', sometimes more (such as if the function has a docstring). So if I wanted to use 'choose-random' would knowing that it's a macro help? No. What I need to know is that it takes pairs of probabilities and values and randomly evaluates one of the values. A clarification probably says that it's safe to recurse inside 'choose-random'. If I were new to Lisp, I would say, "Huh, cool. Wonder how they did that?" If I were experienced, I would think, "Oh, it's a macro." But either way it's not really important. P.S. In some flavors of Lisp, choose-random would be an ordinary function. This includes a toy version that I wrote in Python, no less. P.P.S. I thought of a paradigm that would be exceptionally painful to implement in Python. It's a function found in some flavors of Lisp called 'arb'. It returns its argument which causes the program to exit successfully, otherwise causes the program to exit unsuccessfully. Think about that. From jim.vickroy at noaa.gov Tue Jan 27 17:33:15 2004 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 27 Jan 2004 15:33:15 -0700 Subject: map float string '0.0' puzzle Message-ID: Howdy, I do not understand the following behavior for: PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. >>> >>> float('0.0') 0.0 >>> row = ('0.0', '1.0', None) >>> map(lambda setting: setting and float(setting) or None, row) [None, 1.0, None] >>> map(lambda setting: setting and (setting,float(setting)) or (setting,None), row) [('0.0', 0.0), ('1.0', 1.0), (None, None)] >>> Specifically, why is the return value of the first map operation: [None, 1.0, None] I was expecting: [0.0, 1.0, None] Thanks in advance for the help. From petrilaakso at otapois.kolumbus.fi Sun Jan 11 07:24:16 2004 From: petrilaakso at otapois.kolumbus.fi (Petri Laakso) Date: Sun, 11 Jan 2004 12:24:16 +0000 (UTC) Subject: wxPython Application over the net References: <1d17eeb7.0401091838.3eef2093@posting.google.com> Message-ID: On 9 Jan 2004 18:38:08 -0800 dj00302003 at yahoo.com (Jay Davis) wrote: > We have an application in wxPython that works quite well on > our local computers, but we want people to be able to run > the program over the internet. One way that would work > is to use an Xwindows server and just have people connect > to the program on our local host, but we would like to work > in an internet browser because not everyone has an Xserver. > > Is there any reasonable way to run a wxPython app inside > a browser? How about Java VNC client which connects to vncserver? It's easy to run networked programs on that. I've used for a while nicotine (soulseek-like program) over network Petri From jjl at pobox.com Fri Jan 16 10:59:39 2004 From: jjl at pobox.com (John J. Lee) Date: 16 Jan 2004 15:59:39 +0000 Subject: I come not to bury C++, but to praise it... References: <87ad4qrmut.fsf@pobox.com> Message-ID: <87vfnbzxxw.fsf@pobox.com> "Derek" writes: > "John J. Lee" wrote... > > [...] > > > Maybe I didn't make myself clear. I counted the ease > > > with which memory can be corrupted in C++ as a minus for > > > C++ and a plus for Python. I agree with you. > > > > No, you don't (assuming I understand Jp's post), because... > > > > > On the flip side, C++ can catch errors immediately that > > > Python will not complain about until runtime, and in this > > > imperfect world tests may not catch all such errors up > > > front. In this respect I consider C++ safer. > > > > ...you made no evaluation of the relative importance of > > these two qualities (memory-safety and static type-safety). > > Nor of the fact that C++ comes unavoidably packaged with the > > more-lines-of-code-per-function-point anti-feature -- KIS! > > Are you joking? No. > Because if you have some magical way to assign a > meaningful relative importance to unrelated language features that is > sufficiently general to be useful, I'd like to hear it. (No funny business here, just straightforwardly trying to answer your question to advance the debate:) Well, yes, I do: I think about it rationally, just as you do. I think about the "unrelated" language features (though I suppose few language features are truly unrelated), consider their impact on things like detection and location of bugs, and make a judgement about how they, as a result, affect the success and costs of the development process. I'm afraid I'm probably completely missing what you're getting at here, though! (again, not trying to make any rhetorical point, just puzzled) For the particular issues at hand, Jp made an evaluation that looked quite rational to me, as do your comments immediately below. > For *me* memory safety in C++ is not an issue. I use range-checked > containers, scoped pointers, shared pointers, etc. and don't encounter > memory management/safety problems. Oh. That's interesting. Do those practices get rid of all such issues? > For *me* the lack of static type safety in Python is an issue. We Yes, many people -- including me! -- agree on this, I think (but not everyone -- see the quote from Alex Martelli in my reply to Andrew Koenig). The question is one of the relative sizes of the various costs and benefits, and of the way those costs and benefits are tied to each other in current languages. If only we could pick language properties a la carte... > have a lot of developers working on a relatively large Python > codebase, and sooner or later some edge case calls a function with an > argument who's type makes no sense. Sometimes tests catch the problem > early, sometimes they don't. I think we've been round this loop already. Schematically, though: Static typechecking tests reliably for a small set of bugs. Unit testing tests unreliably for a very large set of bugs. No controversy so far, I hope. Now, the bugs found by unit testing are in practice almost a simple superset of those found by static typechecking (clearly, this point can generate much debate!). C++ buys you static typechecking (gain: a small number of bugs found that your unit tests miss), but also buys you a big jump in lines of code (loss: many extra bugs created (amongst other losses)). I don't argue that this is a fundamental limitation of static typechecking, or that Python is the best of all possible worlds. I do claim that Python achieves a net gain in safety over C++ by dropping the naive static checking found in C++. John From jsbenson at bensonsystems.com Wed Jan 14 15:46:44 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 14 Jan 2004 12:46:44 -0800 Subject: parsing c-code Message-ID: <021a01c3dadf$85ddbe90$8d09500a@jsbwxp3> I'm currently making my way through Thomas Christopher's Python Programming Patterns which describes an LL(k) parser generator that might be of help. I know there are other Python parsing tools out there as well, per Chapter 15 of the Python Cookbook. Message: 4 Date: Wed, 14 Jan 2004 09:27:55 +0100 From: "tm" Subject: Parsing c-code To: python-list at python.org Message-ID: Hello, are there recommended modules for parsing c-code. I want to read in c-structs and display it in a tree graphic. -- Torsten From maketo at norge.freeshell.org Wed Jan 14 14:17:55 2004 From: maketo at norge.freeshell.org (Ognen Duzlevski) Date: Wed, 14 Jan 2004 19:17:55 +0000 (UTC) Subject: Numeric Python and C Message-ID: Hi, can someone explain how to change a value within an array from a C function? For example, I have the following array: scoremat = zeros((10,10)) and the following C function: PyObject *DynAlign(PyObject *self, PyObject *args) { PyArrayObject *p; int ok; /* get the array */ ok = PyArg_ParseTuple(args,"O!", &PyArray_Type, &p); /* this gets a value p[5][5] */ v55 = *(double *)p->data + 5*p->strides[0] + 5*p->strides[1]); } How to I change the value at p[5][5] and retain it in the same array after function exit? So, from Python I might have: from Numeric import * scoremat = zeros((10,10)) DynAlign(scoremat) print scoremat[5][5] Thank you, Ognen From its1louder at yahoo.com Tue Jan 20 21:03:36 2004 From: its1louder at yahoo.com (Tom) Date: 20 Jan 2004 18:03:36 -0800 Subject: Help, *.CHM, etc Message-ID: <90f2d9db.0401201803.6f2adbf8@posting.google.com> A question for gui application programmers. . . I 've got some GUI programs, written in Python/wxPython, and I've got a help button and a help menu item. Also, I've got a compiled file made with the microsoft HTML workshop utility, lets call it c:\path\help.chm. My question is how do you launch it from the GUI? What logic do I put behind the "help" button, in other words. I thought it would be os.spawnv(os.P_DETACH, "c:\\path\\help.chm", []) but I get an error: OSError: [Errno 8] Exec format error so I guess help.chm isn't executable itself, but is associated with some unknown executable. I tried explorer.exe- at the dos cmd line it basically works to type explorer.exe c:\path\help.chm although there is a nag screen that would be nice to do without. so you'd think os.spawnv(os.P_DETACH, 'explorer.exe', ["c:\\path\\help.chm"]) would be equivalent but it fails. I have to believe someone out there in python community likes to include help.chm with their applications, nad there is a right way to do this. On another note, are there pure python based help viewers that people use instead? The reason I ask is that would be more portable then the *.chm files are. If there is such a beast I can't find it. From aahz at pythoncraft.com Fri Jan 30 12:22:54 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2004 12:22:54 -0500 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Aahz wrote: >> >> import __main__ >> tmp = parse_funky_language("Hey, this is far out, man.") >> setattr(__main__, tmp.name, tmp.value) >> >> In the context of the interactive interpreter, it's a bit harder to do; >> I don't remember off-hand what the namespace of the interpreter is. > >You don't need to :-) > >Python 2.3.3 (#1, Jan 3 2004, 13:57:08) >[GCC 3.2] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> __name__ >'__main__' Yes, but how do you access that from a module? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From gerrit at nl.linux.org Sun Jan 4 03:34:48 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 4 Jan 2004 09:34:48 +0100 Subject: datetime string to datetime object converter In-Reply-To: References: Message-ID: <20040104083448.GA13987@nl.linux.org> Randall Smith wrote: > Is there an existing module or script that can convert a datetime string > of unknown format to a python datetime object ? You are probably looking for DateUtil : https://moin.conectiva.com.br/DateUtil yours, Gerrit. -- 25. If fire break out in a house, and some one who comes to put it out cast his eye upon the property of the owner of the house, and take the property of the master of the house, he shall be thrown into that self-same fire. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From gerrit at nl.linux.org Sun Jan 25 04:10:51 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 25 Jan 2004 10:10:51 +0100 Subject: perl bug File::Basename and Perl's nature In-Reply-To: <7fe97cc4.0401242131.22acf485@posting.google.com> References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: <20040125091051.GA14795@nl.linux.org> > Just bumped into another irresponsibility in perl. What's this doing in the Python newsgroup? Gerrit. From dk123456789 at REMOVEhotmail.com Fri Jan 30 17:51:57 2004 From: dk123456789 at REMOVEhotmail.com (Dave K) Date: Fri, 30 Jan 2004 23:51:57 +0100 Subject: conditional expression sought References: Message-ID: On Fri, 30 Jan 2004 01:06:55 GMT in comp.lang.python, "Elaine Jackson" wrote: >Sorry to take so long but I wasn't sure what a "unit test" was (the other guy's >post clarified it). Tell me if this isn't what you're looking for: > >falsies=[0,0.0,[],(),{},'',None] >truies=[49,3.14,[1,2,3],(4,5,6),{7:8,9:10},'nonempty'] > >def demo(A,B): > print "If A is ",A > print "and B is ",B > print "then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = ", > print (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) > >A=[] >from random import randint >for i in range(3): > A.append(bool(randint(0,1))) >B=truies[0:3] >demo(A,B) > >A=[False,False,False] >B=falsies[0:3] >demo(A,B) >print "I would have liked this to be B[2] = ",B[2] > (snip) Do you mean that the expression should return the last element in B if all elements in A are false? If all subexpressions before the last are false, the whole conditional reduces to: A[-1] and B[-1] So simply force (a copy of) A[-1] to always be true. Instead of rewriting demo, I'll cheat by modifying the call: >>> A=[False, False, False] >>> B=[0, 0.0, []] >>> demo(A[:-1]+[True], B) If A is [False, False, True] and B is [0, 0.0, []] then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = [] >>> print A [False, False, False] For complete generality, you should also consider the case where len(A) != len(B). Truncate the longer list, or extend the shorter? Does it matter which list is shorter? Or forget the whole mess and raise an exception? There are lots of reasonable possibilities, but they won't all lead to the same result for certain input values. You're in charge of this project, you decide :) Dave From newsgroups at jhrothjr.com Fri Jan 23 14:43:58 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 23 Jan 2004 14:43:58 -0500 Subject: [OPINION] - does language really matter if they all do the samething? References: Message-ID: <1012ue2jnpq8c5b@news.supernews.com> "Python Baby" wrote in message news:mailman.707.1074882690.12720.python-list at python.org... > Are programming languages like spoken languages, in the sense > that they all say the same things, just using different words? > > Like many PHP people, I was never a "real" programmer, but just > picked up PHP as my HTML websites started to mature. Now that > even my PHP sites have grown, (50,000 lines of PHP!), I got > interested in object-oriented approach. Since my old website > needed an overhaul anyway, I thought it'd be a good time to learn. > > I start learning Ruby. Then Python. Wondering if, since I'm > about to re-write my entire website anyway, if I should use > Ruby or Python instead of PHP. > > As I've fretted over this for way too many hours, I started wondering: > > Can Ruby do something (important) that Python can't? > Can Python do something (important) that PHP can't? > Can PHP do something (important) that Ruby or Python can't? > > Are they all just the same, and it's just a matter of taste? > > Should I stick with PHP for the same reason that pop singers > worldwide sing in English for maximum compatibility with the medium? > > Though PHP wasn't design for OOP should I use it that way anyway? > > Any opinions on the subject, from people that know and use many > languages, would be appreciated. In one sense, they all do the same thing, but that's a very trivial sense. Different languages have different things they focus on, so they make some things easier and some things harder. Python tries to maintain a balance between clarity, ease of learning, and usability. Of the major scripting languages, it's probably the easiest to write maintainable code. A lot of people think that Ruby's blocks and pervasive use of the visitor pattern provide a very productive setting; to me there's nothing there that Python can't do. Both of them are object oriented from the ground up: if being object oriented is important to you, PHP, Perl and TCL aren't in the ball game. Their OO features are bolted on afterthoughts. Some of them are quite nice afterthoughts, but the kludge shows. John Roth > > From ramen at lackingtalent.com Thu Jan 8 12:32:21 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 08 Jan 2004 17:32:21 -0000 Subject: Calling a function dynamically References: <924a9f9c.0401080742.39eba581@posting.google.com> Message-ID: In article , Peter Otten wrote: > Paradox wrote: > >> I would like to call a function whose name I supply at runtime. >> [snip] > > Here's a way to abuse the [] operator (implemented by __getitem__()) to > dynamically select a method... > >>>> t["run"]("alpha", "beta", "gamma") > run('alpha', 'beta', 'gamma') I wouldn't necessarily consider this abuse. This behavior (where square-bracket- and dot-syntax are functionally equivalent) is the normal behavior of JavaScript, and it makes dynamic lookup of method names a snap. Python is more flexible in giving you the option to have separate namespaces for items and attributes, but if it makes more sense for an object to merge the two, I see nothing wrong with it. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From jepler at unpythonic.net Fri Jan 16 15:02:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 16 Jan 2004 14:02:52 -0600 Subject: Suggested generator to add to threading module. In-Reply-To: <40083eac$0$321$e4fe514c@news.xs4all.nl> References: <7934d084.0401152058.164a240c@posting.google.com> <40083eac$0$321$e4fe514c@news.xs4all.nl> Message-ID: <20040116200252.GF7659@unpythonic.net> On Fri, Jan 16, 2004 at 08:42:36PM +0100, Ype Kingma wrote: > > Found myself needing serialised access to a shared generator from > > multiple threads. Came up with the following > > > > def serialise(gen): > > lock = threading.Lock() > > while 1: > > lock.acquire() > > try: > > next = gen.next() > > finally: > > lock.release() > > yield next > > Is there any reason why the lock is not shared among threads? > >From the looks of this, it doesn't synchronize anything > between different threads. Am I missing something? Yes, I think so. You'd use the same "serialise" generator object in multiple threads, like this: p = seralise(producer_generator()) threads = [thread.start_new(worker_thread, (p,)) for t in range(num_workers)] Jeff From jepler at unpythonic.net Wed Jan 28 14:23:22 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jan 2004 13:23:22 -0600 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? In-Reply-To: <6ed33425.0401281103.61987e72@posting.google.com> References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: <20040128192321.GU18498@unpythonic.net> In Tk, each event has a 'state' field, which can tell you whether modifier keys or mouse buttons were pressed when an event was received. Note that for the KeyPress event which is a modifier key, the state field will not reflect the newly pressed key (the same goes for button presses), as implied by this section of the XKeyEvent manpage: The state member is set to indicate the logical state of the pointer buttons and modifier keys just prior to the event, which is the bitwise inclusive OR of one or more of the button or modifier key masks: But- ton1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask, Shift- Mask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, and Mod5Mask. from Tkinter import * # for pre-2.3 versions #def enumerate(l): # for i in range(len(l)): yield i, l[i] # Set up a mapping from bits to names # (I'm not sure if these values match on Windows) names = "Shift Caps Control Alt Num Mod3 Mod4 Mod5 1 2 3 4 5".split() mods = [(1< <1> ".split(): l.bind(binding, setModifiers) t.mainloop() Jeff From marco at bubke.de Wed Jan 21 09:41:38 2004 From: marco at bubke.de (Marco Bubke) Date: Wed, 21 Jan 2004 15:41:38 +0100 Subject: Numarray und NA_NewAll Message-ID: Hi If I understand the code right then there will be mset called if buffer is NULL. Why? I want only a empty array, why not a malloc? The data section after that will be overwritten by me. Maybe I'm wrong. static PyArrayObject * NA_NewAll(int ndim, maybelong *shape, NumarrayType type, void *buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) { PyArrayObject *result = NA_NewAllFromBuffer( ndim, shape, type, Py_None, byteoffset, bytestride, byteorder, aligned, writeable); if (result) { if (!NA_NumArrayCheck((PyObject *) result)) { PyErr_Format( PyExc_TypeError, "NA_NewAll: non-NumArray result"); result = NULL; } else { if (buffer) { memcpy(result->data, buffer, PyArray_NBYTES(result)); } else { memset(result->data, 0, PyArray_NBYTES(result)); <-- ?????????????????? } } } return result; } def get_polygon_stipple(): """Return the polygon stipple pattern""" cdef maybelong lenght cdef void** data lenght = 128 new_array = NA_NewArray(NULL, tUInt32, 1, lenght) glGetPolygonStipple(NA_OFFSETDATA(new_array)) assert glGetError() != INVALID_OPERATION,\ "can't be called between gl.begin() and gl.end()" return new_array Here my code. I'm not sure if this is possible? I have also found NA_getBufferPtrAndSize? Should I use this? regards Marco From ebolonev at rin.ru Sat Jan 3 05:16:09 2004 From: ebolonev at rin.ru (Egor Bolonev) Date: Sat, 3 Jan 2004 20:16:09 +1000 Subject: python and LAN Message-ID: Hello, All! I wish to write a programs for LAN, but I don't know where to begin. For example I have to get a hostlist of my network: ... 192.168.1.35 acca 192.168.3.38 alligator 192.168.1.1 alpha 192.168.2.31 andp-duha 192.168.5.76 angel 192.168.2.49 anny 192.168.3.26 antracit 192.168.3.35 array 192.168.5.39 arsen 192.168.4.64 asperansa 192.168.2.44 assasin 192.168.5.17 asterix 192.168.4.53 baggins 192.168.2.38 bars 192.168.4.24 basilio 192.168.4.28 batchhq 192.168.5.46 bazuka 192.168.2.27 benladen 192.168.2.48 bigmag 192.168.4.39 bilya ... How can I do it with python? With best regards, Egor Bolonev. E-mail: ebolonev at rin.ru From jcarlson at uci.edu Tue Jan 20 17:05:34 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 14:05:34 -0800 Subject: py2exe 0.5.0 (finally) released References: <8a27e309.0401201304.7ee860b0@posting.google.com> Message-ID: <20040120140452.1C42.JCARLSON@uci.edu> > Maybe I'm missing it, but I don't see how to specify an icon to use > for the exe. Is that funtionality no longer available? > > -Ruben Perhaps I'm not using the latest version, but --icon seems to work for me. - Josiah From jangseungwook at nate.com Thu Jan 8 20:29:32 2004 From: jangseungwook at nate.com (jang, seungwook) Date: 8 Jan 2004 17:29:32 -0800 Subject: pyxml-0.8.3 install problem on RedHat 9 Message-ID: >> python setup.py build running build running build.py no copying xml/FtCore.py (output up-to-date) blah blah .. running build_scripts not copying scripts/xmlproc-parse (up-to-date) not copying scripts/xmlproc_val (up-to-date) How can I fix it ? Please help me ~~ Seungwook, Jang From donald.welch.nospam at hp.com Sat Jan 10 13:40:30 2004 From: donald.welch.nospam at hp.com (djw) Date: Sat, 10 Jan 2004 10:40:30 -0800 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> Message-ID: <40004743@usenet01.boi.hp.com> As this is obviously a class assignment of some sorts, I don't know how much help you are going to get (or should get) in directly writing the code. But, what I will say is that you should be able to look at the way the code works now, how it keeps track of how many bills are needed for each denomination (200, 100, etc), and apply the same idea to the total number of bills required using another variable that is initialized before the loop begins. -d broebel wrote: > hey, > > for the real programmers amongst you, this may be really annoying but I've > been learning the language for only two days. > > this is my problem, > in this programm,which already works I now have to make a total count of > how many coins are used. > this program gives the total per coin. It should be a small peace of code > (as explained in a tutorial i read, without the answer.)that counts the > total of all the coins. > I ve been searching for two days and for this kind of programm it really > seems kind of long. > > thanks in advance > > # Een bedrag gepast betalen met zo min mogelijk euromunten > > bedrag = input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) > > for munt in 200, 100, 50, 20, 10, 5, 2, 1 : > aantal = 0 > > while bedrag >= munt : > aantal = aantal + 1 > bedrag = bedrag - munt > > if aantal > 0 : > print aantal, 'x', munt > > what i need is: > for example > the programm gives > 68= 50*1 > 10*1 > 5*1 > 2*1 > 1*1 > I need an additional code to get the "5" total of all the coins together. From __peter__ at web.de Fri Jan 2 16:02:32 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jan 2004 22:02:32 +0100 Subject: re References: Message-ID: Maxim Khesin wrote: > I am studying the re module and still do not understand how to do some > really simple tasks: > 1) say I need to capitalize any word that is between the words 'United' > and 'of America'. So I do With the help of A. M. Kuchling's Regular Expression Howto: >>> import re >>> sample = " ".join(["United %s of America" % s for s in "birds states rocks".split()]) >>> r = re.compile("(United )(.*?)(of America)") >>> def fun(m): ... return m.group(1) + m.group(2).capitalize() + m.group(3) ... >>> r.sub(fun, sample) 'United Birds of America United States of America United Rocks of America' >>> sample 'United birds of America United states of America United rocks of America' >>> Disclaimer: I'm no regexpert, so there may be simpler solutions. Peter From LittleDanEhren at yahoo.com Fri Jan 30 20:26:46 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 30 Jan 2004 17:26:46 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <711c7390.0401301726.3e38da27@posting.google.com> "Sean Ross" wrote > Hi. > I took a look at Io because of your post, and I have a question: > > Are there prototype(?) _and_ instance methods/slots? > > In other words, is there a shared state mechanism between instances of a > prototype? > If so, could you show an example. > > Thanks, > Sean I'm not sure how to tell you this so I'll just give a heavily commented example (comments in Io are with #, //, or /* */) parentProto := Object clone //makes parentProto a new object //:= is used for creating new variables parentProto shared := 5 //parentProto's new slot shared holds 5 parentProto different := 6 parentProto sum := method(shared + different) //self isn't necessary write("parentProto's sum: ", parentProto sum, "\n") x := parentProto clone //essentially new instance of parentProto y := parentProto clone x different = 2 //just updating slots is done with =. y different = 3 write("first x sum ", x sum, "\n", "first y sum ", y sum, "\n") parentProto shared = 7 //should show up on all clones write("later x sum", x sum, "\n", "later y sum", y sum, "\n") Does that illustrate it well? I know the difference between := and = is annoying, but you'll get used to it, and it allows really cool things to be done with scopes and inheretance. Daniel Ehrenberg From tim.golden at viacom-outdoor.co.uk Tue Jan 27 09:09:06 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 27 Jan 2004 14:09:06 -0000 Subject: winapi: mouseclick Message-ID: >From: KNS [mailto:netquest at sympatico.ca] > > >Thank you for the response. I am actually using win32all to launch an >application and am waiting for user actions or changes in state. Once >the application is launched (e.g., IE) the program just >records changes >in URLs. Now I would like the various states (e.g., time, mouse >position) saved whenever the mouse is clicked on the application (or >even the desktop). So, can I just use an 'if' (within a >while-loop) to >test whether WM_LBUTTONDOWN == 0 and if so what is the appropriate >syntax with win32all? > >Thanks. Could you *please* post some code, or at least pseudo-code, to show us what you're doing. What is sounds like to me, is that you're doing this, say: import win32api win32api.ShellExecute (0, "open", "iexplore.exe", None, None, 1) and then you want to know what the user's doing within that application so that you can, eg, keep track of URLs accessed etc. Am I close? If I am, this isn't easy. If it is, strictly, Internet Explorer that you're trying to use, then it does have an Events mechanism (about which I know nothing) which I believe can be accessed from Python. If it is any application in general which you're trying to keep track of, that's more difficult. Windows (and by that I mean any modern GUI system) apps don't work like your old-fashioned batch / terminal apps. You don't "wait" for a user to press something; rather, you set up an event loop and handle or ignore any event which comes in. Each application does this on its own behalf. To do the same on behalf of another application requires either subclassing (messy) or system key / mouse hooks (cf http://cvs.sourceforge.net/viewcvs.py/uncpythontools/pyHook/) or some other arcane mechanism. 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 samirw at connection.com Wed Jan 7 01:07:36 2004 From: samirw at connection.com (Sambo) Date: Tue, 06 Jan 2004 22:07:36 -0800 Subject: Finaly found a simple enough task for python, took the plunge, but..... References: <3FFB5312.1030803@connection.com> <3FFB8071.9070107@connection.com> Message-ID: <3FFBA228.7070403@connection.com> Well, I was hopeful but no luck under w2000 and python 2.3.3 The window is just as obscured as under w95 Must be p2.3.3, oh well 9Mb of junk, good think I upgraded to UNLIMITED access, hehe. Ciao. engsolnom at ipns.com wrote: > (top posting..sorry) > > I tried Vincent's suggested code and it works just fine with Win2000, Python2.3. > I did change the code to return the path to a selected file, rather than just a directory. > Shows the value of the newsgroups...I was unaware (of course us newbies are unaware of lots of > things) of tkFileDialog...and was about to write a tk interface to do the same thing. Saved a ton of > time, and probably newsgroup bandwidth. > Thanks, Vincent! From pythongnome at hotmail.com Thu Jan 29 20:09:11 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 30 Jan 2004 01:09:11 GMT Subject: Easy way to make EXEs... References: Message-ID: "Xero Limit 126" wrote in message news:NMDRb.28013$i4.26542 at newsread1.news.atl.earthlink.net... > Okay, I am completely new to Python, and I really dont understand much, but > I was wondering how to make a python script/program into a standalone .EXE? > I dont understand py2exe at all, so if someone could tell me or find me an > easy (For a newbie) to convert Python scripts to EXEs, please let me know! > > Thanks for any help! > > You should have no trouble with py2exe at all. A simple setup script would be: #setup.py from distutils.core import setup import py2exe setup(name="myfile.py", scripts=["myfile.py"], ) Then to compile that file, go to the command prompt and switch to the directory that the file is in. For example on my machine I would do the following: Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Lucas Raab>cd C:\Python23 C:\Python23>python setup.py py2exe Wait a few moments for py2exe to compile your script and Voilla!! you have an executable. From theller at python.net Fri Jan 16 14:14:07 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 20:14:07 +0100 Subject: py2exe 0.5.0 (finally) released Message-ID: **py2exe 0.5.0** (finally) released =================================== py2exe is a Python distutils extension which converts python scripts into executable windows programs, able to run without requiring a python installation. News Python 2.3 is required, because the new zipimport feature is used. The zipimport mechanism is able to handle the early imports of the warnings and also the encodings module which is done by Python. Creates a single directory, which must be deployed completely. py2exe can create any number of console and gui executables in this directory, plus optionally windows service exes, plus optionally exe and dll com servers. The com servers can expose one or more com object classes. All pure Python files are contained in a single zip archive, which is shared by all the executables. The zip archive may also be used by programs embedding Python. Since extension modules cannot be imported from zipfiles, simple pure Python loaders are included in the zipfile which load the extensions from the file system (without requiring that the directory is in sys.path). It is now simple to build py2exe from the sources, provided you have MSVC6 installed - there are no dependencies on win32all sources. The created executables are standard PE executable files now, no longer is something appended to the exe portion. Download from the usual location: Many thanks to Mark Hammond who worked hard to improve the COM support, and suggested and implemented a lot of the new features. Enjoy, Thomas From francisgavila at yahoo.com Thu Jan 15 14:18:36 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 15 Jan 2004 14:18:36 -0500 Subject: TUPLE & LIST References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <100dpuer745vfa0@corp.supernews.com> Gerrit Holl wrote in message ... >Christos TZOTZIOY Georgiou wrote: >> Examples: >> Use a list for a list of names. >> Use a tuple for (x,y) coordinates in some area. >> Use a list of (name,phone,address) tuples for your poor man's address >> book which you will implement in python. > >What if someone moves away? >That is, I think one could better use a mutable type for the address book. That's why it's a "poor man's" address book. :) -- Francis Avila From frank at chagford.com Wed Jan 7 02:01:36 2004 From: frank at chagford.com (Frank Millman) Date: 6 Jan 2004 23:01:36 -0800 Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> Message-ID: <246a4e07.0401062301.880cb64@posting.google.com> Samuel Walters wrote in message news:... > > What exactly *is* a vertical tab? I don't think I've ever seen it on a > keyboard or used in the wild. I think I may have seen it on the > keybindings for a mainframe terminal I once used, but I didn't really dig > too deep because, as far as operating the mainframe was concerned, I was a > well trained monkey who could check and restart failed jobs. > > Inquiring minds want to know. > > Sam Walters I could be wrong, but I seem to remember reading years ago that vertical tabs were used to control line printers - you could force the printer to skip straight to a line number instead of issuing a series of line feeds. Frank Millman From peter at engcorp.com Mon Jan 26 14:47:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Jan 2004 14:47:19 -0500 Subject: makeExe.py References: Message-ID: <40156EC7.27EFC3F6@engcorp.com> Premshree Pillai wrote: > > Wrote a simple Python script that makes life a wee bit > easier when using py2exe: > > """ > makeExe.py > - Simple Python script to automate the creation > of Python executables using py2exe. > [snip] > fp = open("setup.py","w") > temp = """from distutils.core import setup > import py2exe > setup(name = "%s", > scripts = ["%s"], > )""" % (package,fileName) > fp.write(temp) > fp.close() You could save yourself a fair bit of trouble, and avoid writing a "setup.py" file to the filesystem (possibly overwriting an existing one which might be important) by just calling the setup() method directly yourself. The only trick is that it checks sys.argv[] for the "py2exe" argument, so you have to fake that first: sys.argv[1:] = ['py2exe'] from distutils.core import setup setup(name=package, scripts=[fileName]) That should do the trick.... if you're interested in integrating the changes, and maintaining it, I'll forward our own script which you can pull apart and reuse as required... -Peter From michael at foord.net Fri Jan 9 08:09:41 2004 From: michael at foord.net (Fuzzyman) Date: 9 Jan 2004 05:09:41 -0800 Subject: urllib - changing the user agent Message-ID: <8089854e.0401090509.3dd74859@posting.google.com> I'm writing a function that will query the comp.lang.python newsgroup via google groups....... (I haven't got nntp access from work..) I'm using urllib (for the first time)..... and google don't seem very keen to let me search the group from within a program - the returned pages all tell me 'you're not allowed to do that' :-) I read in the urllib manual pages : class URLopener( [proxies[, **x509]]) Base class for opening and reading URLs. Unless you need to support opening objects using schemes other than http:, ftp:, gopher: or file:, you probably want to use FancyURLopener. By default, the URLopener class sends a User-Agent: header of "urllib/VVV", where VVV is the urllib version number. Applications can define their own User-Agent: header by subclassing URLopener or FancyURLopener and setting the instance attribute version to an appropriate string value before the open() method is called. Could anyone tell me how to subclass this correctly with the version attribute set and what text string I should use to mimic Internet explorer and/or mozilla ? Ta Fuzzy From michele.simionato at poste.it Wed Jan 14 01:24:54 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 Jan 2004 22:24:54 -0800 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <95aa1afa.0401130424.49749912@posting.google.com> Message-ID: <95aa1afa.0401132224.1a8230c@posting.google.com> Jacek Generowicz wrote in message news:... > Lest anyone infer that Lisp has an "application niche" consisting of > AI and theory of programming languages ... take a look at > > http://www.franz.com/success/ > > and glance at the column on the left. Okay, let's restate my point in this way: if you need a very big programming power (which, I agree, is not only needed in A.I. & similia), then Lisp is a good choice. Most of the people in the word don't need a very big programming power, though. They can need a very big numerical power, then they use Fortran. Or they can need moderate programming power and moderate numerical power (such as in bioinformatics) and then they use Perl or Python. > I suspect that Aahz' working definition of "successful" had more to do > with success in terms of popularity, rather than success in terms of > technical excellence: please remember that quality and popularity are > very weakly correlated. > > If you want to analyze the popularity of a technology, you will get > far better insight by studying the sociological and historical > contexts surrounding it rather then its actual technical merits. I completely agree. > For example, how many readers of this post will be surprised to learn > that (most) Common Lisp implementations compile to efficient native > machine code, that Common Lisp has an ANSI standard which includes > very powerful support for object-oriented programming (to name but two > features that everybody "knows" it doesn't have) ? > > Go on, raise your hand if you thought that "Lisp" is a slow, > interperted functional langugage. Never thought so. IMHO people don't use List because they don't need it, not because they think it is a slow, interperted functional language. There are simpler alternative languages that are good enough for most people and more suitable in terms of libraries (i.e. Fortran for numerics, Perl for bioinformatics). Still, Lisp is successful for a certain audience (I concede, not restricted to A. I. only, but rather small anyway). So, it is successful but not popular. This was my point, in contrast to Aahz's view, and I think we agree. Michele Simionato From http Mon Jan 12 08:14:38 2004 From: http (Paul Rubin) Date: 12 Jan 2004 05:14:38 -0800 Subject: need help translating a PHP for statement to python References: <944baf3371667ab5b21f6020c57ad385@news.teranews.com> Message-ID: <7xu131s401.fsf@ruckus.brouhaha.com> Dang Griffith writes: > >Haha ... you must be originally a perl coder. Who else writes attricious > >code like this > > if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) > > Any C programmer worth his salt. I miss those days. Sort of. But that line almost certainly has the parentheses in the wrong place. Look carefully. From rkern at ucsd.edu Mon Jan 19 17:19:27 2004 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 19 Jan 2004 22:19:27 GMT Subject: efficent test for array with only one value? In-Reply-To: <00ird1-dmd.ln1@jowls.lairds.org> References: <00ird1-dmd.ln1@jowls.lairds.org> Message-ID: Kyler Laird wrote: > I'm trying to discover if there's an efficient way to determine > if all of the values of a Numeric array are the same. In C, I > would search from the second value, checking each against the > first value. The first one that doesn't match would trigger a > False return value. If the loop completes, True would be > returned. > > Looking through array functions, I'm not finding anything like > that. I'm imagining that there should be something like an > equal function (Is that Lisp I'm recalling?) that performs > a[0,0] == a[0,1] == a[0,2] == ... > and returns False as soon as it is known. I don't see that. > > I can, of course, iterate through all of the values, but it > seems like there should be an efficient built-in function to do > it. Python 2.3.3 (#1, Dec 28 2003, 00:16:29) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from Numeric import * >>> a = ones((3,5)) >>> equal.reduce(a.flat) 1 >>> a[0,3] = 0 >>> equal.reduce(a.flat) 0 >>> Ufuncs are wonderful things. > Thank you. > > --kyler -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From richie at entrian.com Tue Jan 27 11:52:32 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 27 Jan 2004 16:52:32 +0000 Subject: os.path.split: processing paths from one OS on another In-Reply-To: <401691D7.8050607@holmes.nl> References: <401691D7.8050607@holmes.nl> Message-ID: Hi Martijn, > My server needs to be run on either Linux or Windows, it receives > requests from clients that may run either OS. To process those requests > i need to split the path and filename. I hoped to solves this using > os.path.split (), any suggestions as to how to fix this? Explicitly use ntpath for Windows clients and posixpath for Linux clients: >>> import ntpath, posixpath >>> print ntpath.split('C:\\TEST\\FILE.EXT') ('C:\\TEST', 'FILE.EXT') >>> print posixpath.split('/TEST/FILE.EXT') ('/TEST', 'FILE.EXT') Alternatively, change your client to always use forward slashes - then it (apparently) doesn't matter which you use: >>> print posixpath.split('c:/test/file.exe') ('c:/test', 'file.exe') >>> print ntpath.split('c:/test/file.exe') ('c:/test', 'file.exe') >>> print posixpath.split('//server/share/file.exe') ('//server/share', 'file.exe') >>> print ntpath.split('//server/share/file.exe') ('//server/share', 'file.exe') Beware - there may well be cases where they differ. Windows itself is happy using forward slashes as a directory separator, so your client can use them throughout. It's only the Windows shell that requires backslash rather than forward slash. -- Richie Hindle richie at entrian.com From reply.in.the.newsgroup at my.address.is.invalid Thu Jan 8 12:32:00 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 08 Jan 2004 18:32:00 +0100 Subject: what is Python's module search path? References: Message-ID: Stephen Ferg: >I need a little help here. See "6.1.1 The Module Search Path" on http://www.python.org/doc/current/tut/node8.html -- Ren? Pijlman From Kyler at news.Lairds.org Wed Jan 21 10:12:06 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Wed, 21 Jan 2004 15:12:06 GMT Subject: calling Pyrex results from C References: <20040120172733.GA7666@titan.progiciels-bpi.ca> <20040120234855.GV22782@jowls> Message-ID: The help I've gotten in this thread has enabled me to complete my assignment...well, at least I can generate C code that spits out the answer. I'd like to factor out more of the Python so that my handwritten C code can do more of the high-level operations. I'm having some difficulties passing data between my C and the Pyrex code. One of the first things I thought I'd build is a helper function to return a string representation of an object. I thought that this would be fairly straightforward. Unfortunately it segfaults when called with some Python objects. Pyrex: cdef public image_file_open(char* image_filename): return(Image.open(image_filename)) cdef public image_size(image_PIL): return(Image.size) cdef public char* string(x): s = str(x) return(s) my C: void *im, *im_size; im = image_file_open(input_filename); im_size = image_size(im); printf("im=%s\n", string(im)); printf("im_size=%s\n", string(im_size)); The first call to string() succeeds but the second one fails. I suspect that I've expected too much of Pyrex again. Do I need to allocate memory, manipulate reference counts or something like that? It's difficult for me to get back to thinking in terms of passing around data in C ways. I almost forgot what a boon tuples have been. (Perhaps I need to code in assembly for awhile to get back in that frame of mind.) Someday I might try to pass structures between C and Pyrex. I'm slowly getting comfortable with Pyrex but I can see how my code can get *much* cleaner once I understand more of its capabilities. Thank you. --kyler From mark.buch at t-online.de Fri Jan 30 08:53:51 2004 From: mark.buch at t-online.de (Mark Buch) Date: Fri, 30 Jan 2004 14:53:51 +0100 Subject: Python ODBC Driver Module Message-ID: Hi, where can i find a freeware python odbc module for windows? Thanks - Mark From jjl at pobox.com Sat Jan 17 15:28:21 2004 From: jjl at pobox.com (John J. Lee) Date: 17 Jan 2004 20:28:21 +0000 Subject: Python COM Server with C++ References: Message-ID: <87d69itj4q.fsf@pobox.com> Thomas Heller writes: > andre.bernemann at gmx.de (Andre Bernemann) writes: [...] > I think you should create the typelib first, and then write a com object > implementing the interfaces. > > I don't have done it myself, but I suggest to look into the spambayes > project. It contains an outlook plugin, written by Mark Hammond. > Most certainly a bag full of ideas. There's a cut down to bare-bones version of this in the win32all package. I wasn't able to get it working with the problem I tried, though (in contrast to ctypes). I didn't try too hard, though, I admit ;-) John From RaymondChu at nospam.com Thu Jan 8 18:29:13 2004 From: RaymondChu at nospam.com (Ray Chu) Date: Thu, 08 Jan 2004 15:29:13 -0800 Subject: Looking for a Python interface to TAPI on Win32 References: <2259b0e2.0307180401.5dae02f2@posting.google.com> <3f17f883$0$49107$e4fe514c@news.xs4all.nl> <2259b0e2.0307190529.57338b3f@posting.google.com> <2259b0e2.0307200604.44d343f4@posting.google.com> Message-ID: I'd like to get familiar with the Win32 phone interface by using Python. Googling has just yielded Linux apps. Would appreciate specific help or suggestions about where to look. - TIA Ray From dmm at machinic.net Sat Jan 10 03:50:07 2004 From: dmm at machinic.net (Davis Marques) Date: 10 Jan 2004 00:50:07 -0800 Subject: need help translating a PHP for statement to python Message-ID: hi; I'm translating some PHP scripts to Python and have hit a roadblock with a for statement. If someone could explain to me how one should translate the multiple increment, evaluations, etc. in the first line I would appreciate it deeply ... for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { $prd = $q * $y_ar[$y] + $car; $prd -= ($car = intval($prd / 1E7)) * 1E7; if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7; } thanks, Davis From Vincent.Raaijmakers at ge.com Mon Jan 26 09:01:33 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Mon, 26 Jan 2004 08:01:33 -0600 Subject: JPG - PNG conversion problem Message-ID: <971323274247EB44B9A01D0A3B424C85058496FD@FTWMLVEM02.e2k.ad.ge.com> Who can explain the huge increase in size when I convert a JPG into a PNG format using PythonMagick: I read the JPG from a video server and has a resolution of 352x240, size is about 15k After my PNG conversion and resizing the resolution to 160*120, the size is 64k!! This is what I do: ##image = jpg data read from a server with a 352x240 resolution blob = Blob() blob.data = str(image) data_len="jpg length data: %s" % len(blob.data) logger.info(data_len) ## size is about 15k ## convert blob data into a Image img = Image(blob) img.depth = 8 img.magick = "PNG" s = "!%sx%s" % (160, 120) img.sample(s) # convert back into data for streaming purposes blob = Blob() img.write(blob) data_len="png length data: %s" % len(blob.data) logger.info(data_len) ## size now 64k?! what is wrong, or what do I forget to do? Is it the direct conversion from JPG to PNG, do I need to add a step in between to RGB... Also, tried to play with quality settings on the image, compressionTypes... nothing seem to help. Needs advice! thanks in advance, Vincent From skip at pobox.com Fri Jan 2 13:02:33 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 2 Jan 2004 12:02:33 -0600 Subject: version-independence between Python & BerkDB in Solaris packages? Message-ID: <16373.45625.635475.90942@montanaro.dyndns.org> This is kinda off-topic for this group, but since I'm packaging Python perhaps not too far OT. I built a Solaris package for Python 2.3.3 then copied it to another system and installed it. Nothing too earth-shaking there. When I ran the regression test it barfed in test_bsddb because it couldn't find the Berkeley DB library. I went back to the first system and am now in the midst of updating from DB 4.0.14 to DB 4.2.52 and will then build a Solaris package for it. Unfortunately that means I'll have to rebuild and repackage Python as well, since _bsddb.so depends on a specific Berkeley DB package: % ldd _bsddb.so libdb-4.0.so => /usr/local/BerkeleyDB.4.0/lib/libdb-4.0.so libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1 /usr/platform/SUNW,Ultra-80/lib/libc_psr.so.1 Is it possible to compile and package Python and the external libraries it uses to minimize coupling between package versions like this? I note that other modules which link to specific external libraries don't have such problems: % ldd zlib.so libz.so => /usr/lib/libz.so libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1 /usr/platform/SUNW,Ultra-80/lib/libc_psr.so.1 Maybe it's just unavoidable with Berkeley DB because there are so many versions liable to be installed simultaneously. Thanks, Skip From jepler at unpythonic.net Mon Jan 26 22:35:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 26 Jan 2004 21:35:41 -0600 Subject: Python on portable storage In-Reply-To: References: Message-ID: <20040127033541.GB24260@unpythonic.net> I forgot to mention that you should refer to the documentation to find out about using .zip files to store .py/.pyc modules. This will have a fairly dramatic effect on the amount of space needed to store the standard library. Jeff From and-google at doxdesk.com Mon Jan 12 11:52:06 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 12 Jan 2004 08:52:06 -0800 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <5d83790c.0401120125.7d186102@posting.google.com> Message-ID: <2c60a528.0401120852.4f8aaf32@posting.google.com> Raymond Hettinger wrote: > So, the way to get eval() to respond to the import is to pass along > the current environment: > >>> from __future__ import division > >>> eval('9/2', globals()) > 4.5 You can also put a future-import in the string, allowing you to run code with features not known until run-time (and without affecting the host script). Of course the catch is that import is a statement, not an expression, so you have to do it with 'exec', eg.: expr= '9/2' features= 'division' scope= {} exec 'from __future__ import %s\n__assign= (%s)'%(features,expr) in scope print scope['__assign'] 4.5 What you then *can't* do is have a future-import in the host script without it affecting the script in the exec block. Python 2.2+ has a much nicer way of doing it involving passing flags to the 'compile' function, which is preferable if you don't need backwards compatibility. Anyway, straying from the original point here. From xah at xahlee.org Mon Jan 26 12:43:09 2004 From: xah at xahlee.org (Xah Lee) Date: 26 Jan 2004 09:43:09 -0800 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> <40136b6d@news.victoria.tc.ca> Message-ID: <7fe97cc4.0401260943.2442ba4e@posting.google.com> just a few notes to wrap this thread up. * several perl morons didn't heed my imperative of perusing the notes in "perldoc File::Basename". By their nature, they skimmed and scanned and came back with "the doc said so!". They posses no attention to detail nor knowledge of precision writing, consequently with lowered reading comprehension. Like a man exposed to noise or shit or malfunction, they hear nothing, smell nothing and ebythin's alright. * when it gets one to think about design, File::Basename is one fucking turd. The suffix list should not be regex in the first fucking place. (it shouldn't even require a suffix list by default). The need to feed it OS type (fileparse_set_fstype($os)) is fucking defeating the main point of using this module. Fuck Perl and fuck Perl morons around the world. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html -------------------------------------- Responsible Software License By: Xah Lee, 2003 July Software is a interesting invention. Software has this interesting property, that it can be duplicated without cost, as if like copying money. Never in history are goods duplicable without cost. But with the invention of computer, the ephemeral non-physical programs breaks that precept. In digital form, program and music and books all become goods in essentially infinite quantity. All is good except, bads in digital form can also multiply equally, just as goods. Wellknown examples are computer viruses and email spams. Unknown to the throng of unix morons is software bads. In a unix moron's mind, the predominant quip among hackers is "where is your code?", singnifying the mentality that a hacker's prestige is judged on how much code he has contributed to the community. Therefore, every fucking studs and happy-go-lucky morons put their homework on the net, with a big stamp of FREE, and quite proud of their "contributions" to the world. These digital bads, including irresponsible programs, protocols, and languages, spread like viruses until they obtained the touting right of being the STARDARD or MOST POPULAR in industry, as if indicating superior quality. Examplary are C, Perl, RFC, X-Windows, Apache, MySQL, Pretty Home Page (and almost anything out of unix). The harm of a virus is direct. The harm of irresponsible software (esp with unscrupulous promotion) is the creation of a entire generation of bad thinking and monkey coders. The scales can be compared as to putting a bullet in a person brain, versus creating a creed with the Holocaust aftermath. Distribution of software is easily like pollution. I thought of a law that would ban the distribution of software bads, or like charging for garbage collection in modern societies. The problem is the difficulty of deciding what is good and what is bad. Like in so many things, i think the ultimate help is for people to be aware; so-called education; I believe, if people are made aware of the situation i spoke of, then irresponsible software will decrease, regardless any individual's opinion. -- The most important measure to counter the tremendous harm that irresponsible software has done to the industry is to begin with responsible license, such that the producer of a software will be liable for damage incurred thru their software. As we know, today's software licenses comes with a disclaimer that essentially says the software is sold as is and the producer is not responsible for any damage, nor guaranteeing the functionality of the software. It is this, that allows all sorts of sloppitudes and fucking fads and myths to rampage and survive in the software industry. Once when software producers are liable for their products, just as bridge or airplane or transportation or house builders are responsible for the things they build, then injurious fads and creeds the likes of (Perl, Programing Patterns, eXtreme Programing, "Universal" Modeling Language...) will automatically disappear by dint of market force without anyone's stipulation. In our already established infrastructure of software and industry practices that is so already fucked up by existing shams, we can not immediately expect a about-face in software licenses from 0 liability to 100% liability. We should gradually make them responsible. And this, comes not from artificial force, but gradual establishment of awareness among software professionals and their consumers. (Producers includes single individual to software houses, and consumers includes not just mom & pop but from IT corps to military.) archived at http://xahlee.org/UnixResource_dir/writ/responsible_license.html Xah xahlee.org http://xahlee.org/PageTwo_dir/more.html From nospam at nowhere.hu Sun Jan 25 18:33:44 2004 From: nospam at nowhere.hu (Miklós) Date: Mon, 26 Jan 2004 00:33:44 +0100 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: "Skip Montanaro" wrote in message news:mailman.772.1075066543.12720.python-list at python.org... > > Does Jack Schofield perhaps work for SCO? > > Skip > Either that or Microsoft. ;-) Or he's plain stupid. Mikl?s From wilkSPAM at OUTflibuste.net Sun Jan 4 07:37:43 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sun, 04 Jan 2004 13:37:43 +0100 Subject: Cheetah best for templating? References: Message-ID: <87wu87nb3c.fsf@blakie.riol> "Roger Jack" writes: > I have just finished reading Code Generation In Action which uses Ruby for > code generation. I would like to use Python instead. Is Cheetah the best > tool to use for templating source code files and then generating code? Is > there something more mature or better? My graphist and me found it excellent, fast, clear, simple, stable : Pythonic ! We found the others engines too verbose, more perlish ;-) Like python, the best is to try somes engines, you will see quickly wich one you need. First, like everybody, i did my own engine, but Cheetah was finaly a better wheel ! I use it to generate html, latex and xml -- Wilk - http://flibuste.net From dave at pythonapocrypha.com Fri Jan 23 16:37:27 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 23 Jan 2004 14:37:27 -0700 Subject: progress bar References: <59e5b87.0401231329.6e084d6f@posting.google.com> Message-ID: <033701c3e1f9$19037870$6401fea9@YODA> > OS: Win2K > Python version: 2.2 > > Seeking references to documentation that discuss how a python script > can handle displaying a progress bar. Also, if you are aware of any > sample code that illustrates this, I'm interested in looking at that > sample code. > > Are there ways to accomplish this that do not involve using a > full-featured GUI toolkit like Tkinter or wxPython or PythonCard? Try Venster: http://venster.sourceforge.net IIRC the test_coolbar.py script includes a progress bar. -Dave From hgeldenhuys at gims.com Wed Jan 28 09:54:52 2004 From: hgeldenhuys at gims.com (Herman Geldenhuys) Date: Wed, 28 Jan 2004 16:54:52 +0200 Subject: Security validation issue Message-ID: <004301c3e5ae$af7b00d0$b10d10ac@metasalio> I've written a Zope product that exposes a "MenuItem". I add a menuItem in a Zope folder, and I have no difficulty accessing and editing it via the ZMI. I've written an xml-rpc-like protocol for Zope, that basically validates the security "manually". This menuItem has an attribute called "def getVersion(self):" which returns an int. This is the Code that prevents me from accessing the method in python, via my protocol: if not AccessControl.getSecurityManager().validate(None, object, attributes[-1]): raise UnauthorisedAccessException('Unauthorised: ' + originalAddress) object = > This is the method getVersion attributes[-1] = "getVersion" (string) UnauthorisedAccessException: Unauthorised: menus.administration.addUser.getVersion This code works for any other default Zope type, but not mine. Did I perhaps forgot a permission or something? I can access this fine via the ZMI, but when I validate it this way, python just starts cursing at me. Can somebody help? Thanks H -------------- next part -------------- An HTML attachment was scrubbed... URL: From lbates at swamisoft.com Fri Jan 23 11:00:16 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 23 Jan 2004 10:00:16 -0600 Subject: debugging References: <88bc63c6.0401230416.7acf904c@posting.google.com> Message-ID: <8aidnWC5nryR2Izd4p2dnA@comcast.com> Doug, I use a loggerclass to log debugging/tracing information to a log file during the program execution. I trigger these logging statements by setting python variables _trace and _debug at the top of my program execution (normally by reading them from a .INI file using ConfigParser). This way I can trace/debug my program and then easily turn them off when the code is finalized. I leave this code in the application and find that it can prove to be very valuable should a problem arise in the future. Just turn on trace/debug and take a look at the log file. I don't believe that there is significant overhead in a few "if _debug: logf.writelines..." statements in the code. -Larry "Doug Farrell" wrote in message news:88bc63c6.0401230416.7acf904c at posting.google.com... > Hi all, > > Can someone help me out a little with Python? What do people use to > debug Python code? I don't understand how to use the built in debugger > and I haven't had any luck getting ddd to debug my Python programs. I > end up falling back on inserting print statements in my code to figure > out what's going on. This works but isn't always the fastest route to > a solution. So, I'm just wondering what other people do. > > Thanks, > Doug From NAVMSE-SRV003 at techblu.com Thu Jan 29 08:35:59 2004 From: NAVMSE-SRV003 at techblu.com (Anti Virus Administrator) Date: Thu, 29 Jan 2004 05:35:59 -0800 Subject: Norton AntiVirus detected and quarantined a virus in a message you sent. Message-ID: Recipient of the infected attachment: SRV003, First Storage Group\Mailbox Store (SRV003), Neha Manchanda/Inbox/resume Subject of the message: ERROR One or more attachments were quarantined. Attachment lvfpu.zip was Quarantined for the following reasons: Virus W32.Novarg.A at mm was found. Virus W32.Novarg.A at mm was found in lvfpu.doc .exe. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Jan 22 16:48:38 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Jan 2004 16:48:38 -0500 Subject: What is object() References: <10105gchtsl1a21@news.supernews.com> Message-ID: In article <10105gchtsl1a21 at news.supernews.com>, John Roth wrote: >"Aahz" wrote in message >news:bup01m$hjm$1 at panix1.panix.com... >> In article , >> Hameed Khan wrote: >>> >>> i was reading library refrence manual. there i found >>>object() function. they says in library refrence that >>> "Return a new featureless object. object() is >>>a base for all new style classes. It has the methods >>>that are common to all instances of new style >>>classes." >> >> There's not much use for an instance of object. Don't worry about it. > >Unless, of course, you're using the __new__() method. "Not much" != "none" ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From bignose-hates-spam at and-benfinney-does-too.id.au Mon Jan 26 21:09:26 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jan 2004 12:59:26 +1050 Subject: Python on portable storage Message-ID: Howdy all, I'm experimenting with carrying my personal computing environment around on a keychain USB flash storage device. I have the usual suspects on there: SSH keys, GPG keys, program configs. I'm probably not the first to think that a standalone distribution of Python would be a useful thing to have in my back pocket. Finding information on that is proving to be a problem, however. Can anyone provide pointers to how to go about this? My goals are: - Carry a working Python >= 2.3 on the thing (must). - Be able to run it on GNU/Linux systems from the device (must). - Be able to run it on Win32 systems from the device (maybe). - Refer to one copy of the standard library, regardless of how many instances of the python executable (must). - Ease of updating when future Python releases come out (maybe). -- \ "Time's fun when you're having flies." -- Kermit the Frog | `\ | _o__) | Ben Finney From mark at mceahern.com Sun Jan 25 17:51:24 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 25 Jan 2004 16:51:24 -0600 Subject: find function In-Reply-To: References: Message-ID: <1075071084.27914.90.camel@dev.internal> On Sun, 2004-01-25 at 16:25, Uwe Mayer wrote: > Hi, > > is there for python a find() function, like the perl module Find or the > command line tool find? Try: import glob pattern = '*.pyc' for name in glob.glob(pattern): print name glob's not recursive, though. For that, consider os.walk: import os path = '.' extensions = ('.pyc',) for root, dirs, files in os.walk(path): for name in files: prefix, ext = os.path.splitext(name) if ext not in extensions: continue fullname = os.path.join(root, name) print fullname The above code may have syntax errors since I didn't run it. // m From paul at prescod.net Sat Jan 24 18:24:33 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 24 Jan 2004 15:24:33 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> Message-ID: <4012FEB1.5000106@prescod.net> Dietrich Epp wrote: > Please understand, before you read this, that I think Python is the most > elegant language that looks and feels natural. My point is that there > are plenty of programming techniques which aren't natural in Python, but > are still useful. I don't dispute this. Python is not the last and only programming language. But your specific examples were not compelling. I would have believed you if you'd said you do a bunch of logic programming and found Prolog more comfortable. (but even in extreme cases like that I would be tempted to see whether the task can be accomplished with a library or mixin rather than a new language) > Well, I don't mean that you absolutely can't capture a message, but it's > just not something that's natural in Python the way it is in Objective > C. In Objective C, I can create an object which doesn't respond to some > message "foo". However, if I send "foo" to the object, it gets a chance > to respond. In Python, there is no concept of messages. You would have > to override the function that gets an object's attribute and create a > function for it to return. You can capture function calls, but > capturing method calls is a two-step process in Python which requires a > little bit of magic to implement. Programming languages are designed to turn processes that take N steps into processes that take M steps. You seem to know enough Python to trivially write a function that does the filtering necessary to capture method calls. You can steal the code from the XML-RPC lib that is already in the standard library. > If I wanted to make this personal, I would accuse you of choosing your > patterns to fit the language rather than vice versa. I don't mean to be personal. But a lot of ex-Lisp programmers do not feel the need to go back to Lisp to accomplish common tasks and a lot of ex-Perl programmers use Python without going back to Perl. It's quite possible that it is just a matter of preference. Some people would rather go back to the language with the built-in feature and others would rather extend Python with the feature they need. They are benefits to both ways of doing it. I tend to lean towards the integrating approach: it feels like more of a "solution" to the problem than a workaround (i.e. once I've extended Python it remains extended but if I switch languages then I have to keep switching language the next time I have a similar problem). What if you run into one of these problems in the middle of a ten thousand line program? You have to figure out a way to exchange data between Python and the other language, you have to distribute both interpreters, make sure people on the team can read both languages, etc. Of course there are (rare) circumstances where the other languages' advantages are so extreme that it justifies the cost of integration, distribution, training, etc. >... > Of course, you haven't seen my code, nor I yours. My most recent Perl > script was about twenty lines of nothing but regular expressions and a > couple dictionary operations. That would have been even less readable > and writable in Python. My experience is that the readability of regexp programs in Perl and Python is roughly the same. I'll give a concrete example in a separate email on Cameron Laird's thread. > ... My Lisp project related to an RPG and random > generation of items. It had lots of code like the following: > > (defun random-sword-magic-power (quality) > (choose-random-assoc > quality (poor medium good) > ((5 0 0) (glows-in-the-dark)) > ((3 3 0) (magically-silent)) > ((1 5 1) (elemental-power (select-random '(earth water air fire)))) > ((0 2 4) (magical-keen-edge)) > ((0 0 2) (append (random-sword-magic-power 'medium) > (random-sword-magic-power 'medium))))) module game_symbols class symbol: pass water = symbol(water) earth = symbol(earth) poor = symbol(poor) medium = symbol(medium) good = symbol(good) ======= from random import choice from game_symbols import * def choose_random_assoc(selector, properties): # I can't find a defintion for this through Google # So I presume you invented and implemented it yourself value, options = selector for key, value in properties.items(): ... do something ... function random_sword_magic_power(quality): return choose_random_assoc( selector = (quality, (poor, medium, good)), properties = { (5, 0, 0): glows_in_the_dark(), (3, 3, 0): magically_silent(), (1, 5, 1): elemental_power( choice([earth, water, air, fire]) (0, 2, 4): magical_keen_edge(), (0, 0, 2): ????} I don't follow what you are doing with the last line so I didn't duplicate it. So let's score this. I don't expect you to argue that the Python one is some kind of stylistic slam-dunk. Personally I PREFER the variety of syntax rather than using parens for everything. That's why I used a dict instead of a tuple for the properties mapping. I used predeclared symbols for things like "poor", "medium", "good" etc. so I'll get better error messaging if I mistype them. (I could of course have used just strings) > The numbers on the left are probabilities relative to the other > probabilities in the same column. So, when generating a random 'poor' > magic quality of a sword, you have a 5/9 chance of getting 'glow in the > dark'. For a 'good' quality, you have a 2/7 chance of getting two > 'medium' qualities instead. It is difficult for me to imagine how one > would go about making this function more concise, to me it looks > downright minimal. The only thing I could see making it smaller would > be removing the parentheses, but they would have to be replaced by > something else such as commas or tabs. The question isn't whether the Python could be massively better. That would be moving the goal post. The question is whether the Lisp version is different enough that a Python programmer should switch to Lisp for this project. I wouldn't advise it myself. > I'm not trying to say that all applications are like my application, and > I'm not trying to say that my application can't be written in Python. > I'm just saying that using macros, a paradigm that Python doesn't even > come close to supporting, makes reading and writing functions like the > above a lot easier. You don't even need to know that > 'choose-random-assoc' is a macro, you just need to know how to use it. > Heck, defun is a macro in Clisp. I didn't know it was a macro and I don't know why it needs to be a macro rather than a function. One argument could be performance. If so, I'd plead no contest. A good reason to use other languages is performance. C for memory manipulation performance. Perl for regexp performance. Lisp and C++ for "do things at compile time rather than runtime" performance. But as I understood the conversation we were talking about expressiveness, not performance. > I agree that functions are objects in Python. However, not everything > in Python is an object. For example, names are not objects. In the > above example, "foo.bar()", neither "foo" nor "bar" are objects, but > they are references to objects. In some languages, such as C and Lisp, > references to objects can be directly manipulated (Lisp has symbols, C > has pointers). Pointers are not at all analogous to Python names. C variables and struct fields are analogous to Python names. Those can only be manipulated by the C preprocessor. >... > > In Python you have to be careful because this won't normally capture > just method calls, but all attribute accesses. > def reset_settings(self): > method = None > try: > method = self.delegate.default_settings > except AttributeError: > ... > If you think this example is contrived, maybe you haven't worked with > the paradigms used in Objective-C very much. I don't dispute it is real. I would say that it is RARE, but not contrived. The example above was used > dozens of times in a class that I wrote in Objective-C which draws a > grid to the screen, for example, when it asks itself or its delegate > what color the grid should be, or the maximum scale allowed. The > practice is also used heavily by Apple's Cocoa libraries, which are my > favorite UI libraries of all time to program with. There is no question that some things take 2 lines in one programming language and 5 in another. But let's say you wrap this pattern up in a base class or metaclass or function. Is Python _still_ much more complicated for this problem area than Objective-C? In this particular case it should be easy to tell. What does Python/Cocoa code look like? Surely you would agree that if a problem can be easily solved by a little bit of code which can be saved in a library then it is not a particularly deep problem. That's not the sort of thing I would switch languages for. Now the differences between Java and Python are pretty deep. Trying to make Python statically typed or O'CAML dynamically typed is a Big Deal. But I really don't really see Python's regular expression or "message capturing" conventions to be deep issues. Paul Prescod From phleum_nospam at chello.se Wed Jan 14 16:39:04 2004 From: phleum_nospam at chello.se (Carl) Date: Wed, 14 Jan 2004 22:39:04 +0100 Subject: function minimization References: Message-ID: Stefano Covino wrote: > Hi! > > Does anyone of you know a python library to find minima of > multivariable mathematical functions? > > I know that in SciPy there is what I need, however I wonder if there is > something lighter without the need to install the whole package. > > Thank you a lot, > Stefano See http://pylab.sourceforge.net/ then optimize.py /Carl From dlmurray at micro-net.com Tue Jan 13 22:32:38 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Tue, 13 Jan 2004 20:32:38 -0700 Subject: I come not to bury C++, but to praise it... References: Message-ID: <1009e0uldj5eq29@corp.supernews.com> > sprintf("All the cool guys use %s because %s\n", Myfavoritelanguages, > Mylimitedexperience) Very good! I hope that that's not under copyright, I plan to use it. Dave From marco at bubke.de Wed Jan 7 11:13:51 2004 From: marco at bubke.de (Marco Bubke) Date: Wed, 07 Jan 2004 17:13:51 +0100 Subject: shelve and writeback References: Message-ID: Hi Have updated to 2.3.3 and the bug is gone. Sorry regards Marco From featherstone80 at hotmail.com Wed Jan 14 16:03:22 2004 From: featherstone80 at hotmail.com (Narsil) Date: 14 Jan 2004 13:03:22 -0800 Subject: Quick question..... Message-ID: <379178f1.0401141303.62713fbf@posting.google.com> I have a list, which consists of just numbers. Is there a command that will allow me to total up these numbers and get an average? Say for example, the list looks thus: numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] How would I get the total, and how would I get the average? Thanks in advance TomN From eltronic at juno.com Sat Jan 10 22:52:52 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Sat, 10 Jan 2004 22:52:52 -0500 Subject: help with Python Environment For Blind User Message-ID: <20040110.225253.-3953201.1.eltronic@juno.com> On Sun, 11 Jan 2004 02:39:21 GMT "Zachary" writes: > I'm a blind non-programmer trying to learn Python. > I've got python 2.3 for windows, but the problem is that Idle > doesn't seem > to work two well with my screen reading program. > Is notepad, then, my only other real choice? no, try http://www.editpadlite.com/ you can rename it notepad.exe and put it in place of the origional notepad.exe . it indents, can put spaces when you hit tab and handles larger files than notepad. where can someone find details about the screen reading program? maybe idle can be fixed. e ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From trickster121990 at hotmail.com Wed Jan 21 22:47:20 2004 From: trickster121990 at hotmail.com (Jess Martin) Date: Thu, 22 Jan 2004 14:17:20 +1030 Subject: python Message-ID: i need help. im just learning to program and every time i try to do a command more than a line long it wont work _________________________________________________________________ Get less junk mail with ninemsn Premium. Click here http://ninemsn.com.au/premium/landing.asp From eric.brunel at N0SP4M.com Thu Jan 8 08:09:42 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Thu, 08 Jan 2004 14:09:42 +0100 Subject: Communicating with MSVC++ via COM: how? Message-ID: Hi all, We're trying to communicate with Microsoft Visual C++ 6.0 via COM to make it perform a few operations. Our main need is to set a breakpoint on a given line in a given file. We ended up with the following script: --------------------------------------------- import win32com.client import time ## Get MSVC++ main application app = win32com.client.Dispatch('MSDev.Application') ## Make the window visible time.sleep(2) app.Visible = 1 ## Get loaded documents in MSVC++ and close them all docs = app.Documents docs.CloseAll() ## Load pseudo-workspace for our executable workSpace = "C:\\tmp\\AllCheckings\\AllCheckings\\Debug\\AllCheckings.exe" docs.Open(workSpace, 'Auto', 1) ## Open file where we want to put the breakpoint docs.Open( "C:\\tmp\\AllCheckings\\ccg\\MyFile.c" ) ## Get MSVC++ debugger dbgr = app.Debugger ## Get breakpoint list bkpts = dbgr.Breakpoints ## Clear all break points, then add the one we want bkpts.RemoveAllBreakpoints() bkpts.AddBreakpointAtLine(86) --------------------------------------------- This script doesn't work: the call to docs.CloseAll fails with the error: Traceback (most recent call last): File "test.py", line 13, in ? docs.CloseAll() TypeError: object of type 'int' is not callable which is quite weird, to say the least... Since we didn't understand what was going on, we finally decided to comment out this line and to try again. The script then fails on the last line with the error: Traceback (most recent call last): File "test.py", line 30, in ? bkpts.AddBreakpointAtLine(86) File "H:\Tools\Python\bin\Windows\Python21\win32com\client\dynamic.py", line 151, in __call__ return self._get_good_object_(apply(self._oleobj_.Invoke,allArgs),self._olerepr_.defaultDispatchName,None) pywintypes.com_error: (-2147352573, 'Membre introuvable.', None, None) The weird thing is that apparently, something is actually called, since a breakpoint *is* set, but not on the line we requested. It seems to be set on the line where the cursor is in the file opened in MSVC++. In fact, it seems like just doing docs.CloseAll or bkpts.AddBreakpointAtLine (without the ()) does not return the method, but actually calls it. We tried to use makepy to generate the COM support files for the objects we used, but the result were even weirder: the line "app.Visible = 1" crashed, saying that the attribute could not be set. Using gencache.EnsureModule didn't help: it also crashed because of an attribute MinorVersion missing on a module. Did we miss something here? We're somewhat rookies wrt COM, but we're quite fluent with Python (apparently, this doesn't seem to help a lot...). Did anyone succeed in communicating with MSVC++ via COM from Python? Or did anyone see the kind of problems we're having here? We're using Python 2.1 with win32all-136. TIA -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From peter at engcorp.com Mon Jan 12 09:15:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 09:15:07 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> <7xsmio4uhs.fsf@ruckus.brouhaha.com> Message-ID: <4002ABEB.9E7E7EFB@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > This is my "straw poll" question: > > > > Do you spend a "significant" amount of time actually optimizing your > > Python applications? (Significant is here defined as "more than five > > percent of your time", which is for example two hours a week in a > > 40-hour work week.) > > Yes, absolutely. > > > Algorithmic improvements that you would make regardless of implementation > > language do not qualify, and wasting time optimizing a script that you > > run once a year so it takes ten seconds instead of fifteen also does not > > qualify because you certainly didn't need to do it... > > Sometimes I'll take the time to implement a fancy algorithm in Python > where in a faster language I could use brute force and still be fast > enough. I'd count that as an optimization. I would count it as optimization as well, which is why I qualified my comment with "regardless of implementation language". Clearly in your case that clause does not apply. -Peter From jjl at pobox.com Fri Jan 23 07:40:05 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 12:40:05 +0000 Subject: Accessing Microsoft Word from Python References: Message-ID: <874qum6dp6.fsf@pobox.com> Josiah Carlson writes: > Mickel Gr?nroos wrote: > > Hi! > > I'm fiddling with Python for Windows (normally using Linux) and as a > > part > > of that I want to try to make a simple word frequency list generator to be > > used in conjunction with Microsoft Word. Does anybody have any good [...] > Sounds like something that could be done with VB. VB will let you > script anything in Word or Office, but then it requires you to learn > the horror that is VB. Perhaps a limited interface is available > through COM, but I wouldn't bet the farm on it. I think the entire thing is exported through COM, and VB uses that. John From skip at pobox.com Sat Jan 10 08:50:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 07:50:09 -0600 Subject: QOTW? In-Reply-To: References: Message-ID: <16384.785.498004.8567@montanaro.dyndns.org> QOTW perhaps? Sam> I read the benchmark and I think it doesn't measure python in it's Sam> target area. That's like taking a world-class marathon runner and Sam> wondering why he doesn't compete well in a figure-skating event. Skip From ralph at sluiters.de Wed Jan 7 02:01:57 2004 From: ralph at sluiters.de (Ralph Sluiters) Date: Wed, 7 Jan 2004 08:01:57 +0100 Subject: I got the solution [was:Re: Problem: 'Threads' in Python?] References: Message-ID: Simply put the last part in an extra file 'cachedata.py', then use import os os.spawnlp(os.P_NOWAIT, 'python', 'python', 'cachedata.py') to call this as child process and DON'T wait for this process. Ralph From max at alcyone.com Wed Jan 21 22:03:44 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 21 Jan 2004 19:03:44 -0800 Subject: python said : "1, 2, 3, 6, 7, manbo !" References: Message-ID: <400F3D90.2176087B@alcyone.com> - wrote: > Why 5 does not appear ? (this was the source of a deep bug in a 4000+ > lines networked program...) You are iterating over a mutable sequence while you are mutating it. That is a big no-no. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Life is painting a picture, not doing a sum. -- Oliver Wendell Holmes, Jr. From aahz at pythoncraft.com Fri Jan 2 19:16:46 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2004 19:16:46 -0500 Subject: Conditional except: blocks References: Message-ID: In article , Robert Brewer wrote: >Aahz wrote: >> That's pretty sick. If you really need to do that, here's a more >> Pythonic approach: >>=20 >> # This goes at beginning of program >> # or maybe at class/instance initialization >> if trapErrors: >> exceptTuple =3D (Exception,) >> else: >> exceptTuple =3D (None,) >>=20 >> # some time later >> try: >> return nextHandler(args) >> except exceptTuple, exc: >> # Handle exception > >Sure, sure. The point was not so much the JIT tuple-unpacking as it was >the (conditional) use of None in the "except" expression. >BTW, I don't think you need a tuple at all. Might we just as well write: > > if trapErrors: > exceptTuple =3D Exception > else: > exceptTuple =3D None > >? For this purpose, yes. But I figured one might as well make it a bit more generic, just for the purpose of documentation. >FWIW (and just to start a flame war ;) I tend to avoid using a flag >(like 'trapErrors'), only to trigger such an intermediate step as the >above. I get antsy when that intermediate value gets used "some time >later". If I were to do something like the above, it would be put >immediately before the actual use. The other option would be to have >whoever is setting trapErrors (to True or False) instead directly set >exceptTuple to Exception, None, or what-have-you. Sure; exceptTuple is the only part that needs to be generally available. My point was more that by setting exceptTuple early in the script, you clarify what your program is doing. Using a subscript selector in the ``except`` clause is an unPythonic hack, partly because it's less maintainable. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bokr at oz.net Thu Jan 8 21:58:20 2004 From: bokr at oz.net (Bengt Richter) Date: 9 Jan 2004 02:58:20 GMT Subject: Bits from Numbers. References: <3ffcb189$1@nntp0.pdx.net> Message-ID: On Wed, 07 Jan 2004 16:36:43 -0800, sdd wrote: >I am whacking away at some code to view numbers as bit sequences. >While this is not complete, I'd appreciate some feedback from anyone >who is interested in looking at it: > http://members.dsl-only.net/~daniels/bits.html > >As the page describes, bit extract of more than an int's worth of bits >from a long at one go does not yet work. > > >The basic idea is that the (non-complex) python numbers can be >viewed as an infinite binary bit stream: > > ...........000101.11000..... is 5.75 > >There are functions to get the least and most significant bit >numbers, examine a particular bit, and extract a consecutive >chunk of bits. > >At the bottom of the page are links to source archives and windows >installers for 2.2 and 2.3. > >For now, consider this a pre-alpha. I am soliciting comments >on both the definitions and names of the functions provided. > >However, I'd like to point out now that negative integers have >an infinite number of ones _and_ zeros in their expansion above, >so popcount as traditionally defined for negative integers is >unworkable. No time to look now, but maybe http://mail.python.org/pipermail/python-list/2003-December/199683.html will give you something useful? BTW, it proposes a literal string format that takes care of the infinitely repeating sign bit problem (i.e., you don't repeat it, except for representing -1 as '11b' for symmetry with '01b' for +1) but you always have a one or zero leading bit that you can repeat as needed to make whatever width. Regards, Bengt Richter From skip at pobox.com Sat Jan 10 13:48:30 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 12:48:30 -0600 Subject: xml-rpc In-Reply-To: References: Message-ID: <16384.18686.623407.634068@montanaro.dyndns.org> Walt> Curious about why the same very simple xml-rpc demo code should Walt> execute quickly under python2.1 but very slowly under python2.3 Walt> python2.1 ~4 seconds Walt> python2.3 ~24 seconds on the same machine Walt> Is there a well known reason for the difference? Nope. I tweaked your script to contact my XML-RPC server over the net (about 20-30ms ping times between client and server) and just make server.echo() calls. It took between 1.6 and 2.5 seconds real time running python 2.4a0 (aka CVS) on the client and 2.2.3 on the server. Note that the server is in production, so the different times were probably due to transient server load. Skip From fortepianissimo at yahoo.com.tw Sun Jan 4 15:15:10 2004 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 4 Jan 2004 12:15:10 -0800 Subject: codecs packages? Message-ID: I'd like to decode some email headers into unicode, including some Asian DBCS. I've searched several places and they pointed to the Python Codecs project @ SF (http://sourceforge.net/projects/python-codecs/), but I couldn't find anything there. Could someone give me a pointer to any related library? Thanks. From francisgavila at yahoo.com Tue Jan 13 23:03:29 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 13 Jan 2004 23:03:29 -0500 Subject: Myth or Urban Legend? Python => Google [ was: Why learn Python ??] References: <40029dad$0$28706$a729d347@news.telepac.pt><100655fo84c2211@corp.supernews.com><87d69og2jl.fsf@pobox.com> Message-ID: <1009fum3evnc96a@corp.supernews.com> EP wrote in message ... >Is it true that the original Google spider was written in Python? I don't know *what* Google uses Python for, but it uses Python. >It would seem like the poster boy example for using Python in some >respects, if true. Um, nothing new about this: http://python.org Read the top center of the front page.... -- Francis Avila From james at logicalprogression.net Thu Jan 22 05:35:07 2004 From: james at logicalprogression.net (James Henderson) Date: Thu, 22 Jan 2004 10:35:07 +0000 Subject: Assignment to slice In-Reply-To: References: <20040121191546.4975.qmail@web40102.mail.yahoo.com> Message-ID: <200401221035.07776.james@logicalprogression.net> On Thursday 22 January 2004 4:54 am, r.e.s. wrote: > "James Henderson" wrote ... > > JH Assignment to x[-4:-3] is not same as assignment to x[-1:0]: Since this wasn't made clear in r.e.s.'s post I'd just like to point out that the above obervation was in response to the proposal that a negative index "i" was simply a shorthand for "i + len(x)". (len(x) was 3.) James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From rganesan at myrealbox.com Sat Jan 24 11:12:58 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Sat, 24 Jan 2004 21:42:58 +0530 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: >>>>> "Ville" == Ville Vainio writes: >>>>> "Ganesan" == Ganesan R writes: Ganesan> is nearly 6 times slower in python (8 time slower with Ganesan> Python 2.2) using fileinput. Every appears to know that Ganesan> fileinput is slower and avoid it when performance is a Ganesan> concern; but even manually doing the equivalent is slower Ganesan> in python. I've simply switched back to using perl for my > A while back someone fixed his python script to use normal files > instead of stdin, and the Python version proved to be even faster than > the Perl version. Have you tried that? Are you saying that iterating over normal files instead of stdin is faster? I ran some tests just now and it doesn't seem to make any significant difference. On the other hand, my current tests show that python is only 40% slower than perl for IO instead of twice as slow as I mention above. Something has changed for the better in python (or worse in perl!) since I last ran the tests. I am running Debian testing versions of python and perl. I'll run some more tests and share the test scripts and results sometime next week. Ganesan -- Ganesan R From anthony at interlink.com.au Sat Jan 10 22:09:09 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Sun, 11 Jan 2004 14:09:09 +1100 Subject: py2exe, Inno Setup, and tkinter Message-ID: <200401110309.i0B39ARe002821@localhost.localdomain> I'm trying to use py2exe and Inno Setup to build an installer for shtoom, which uses tkinter. If I take the py2exe generated directory, and run the executable from there, it works fine. If I add all the files in the directory to an installer (including the tk-8.4 and tcl-8.4 directories), it builds an installer fine. But when I run the installer, and install to, say c:/Program Files/Shtoom, running the program fails with Traceback (most recent call last): File "", line 78, in ? File "", line 75, in main File "", line 66, in findUserInterface File "", line 33, in tryTkInterface File "shtoom\ui\tkshtoom.pyc", line 23, in main File "shtoom\ui\tkui\main.pyc", line 11, in __init__ File "Tkinter.pyc", line 1564, in __init__ _tkinter.TclError: Can't find a usable init.tcl in the following directories: {c:/Program Files/lib/tcl8.4} {c:/Program Files/lib/tcl8.4} c:/lib/tcl8.4 {c:/Program Files/library} c:/library c:/../tcl8.4.3/library This probably means that Tcl wasn't installed properly. The init.tcl is actually in C:/Program Files/Shtoom/tcl8.4. Why is it not looking in the correct location? How can I fix this? Thanks, Anthony From jorgencederberg at hotmail.com Mon Jan 12 04:09:57 2004 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Mon, 12 Jan 2004 10:09:57 +0100 Subject: CGI module problem: duplicated output In-Reply-To: References: <9smuvv0ou8qpilg9vlpgpqt45apalmur49@4ax.com> Message-ID: Mimal wrote: >> Pardon me for saying so, but I don't believe you. Your script must >> actually look like this: > > > Pardon me too, but I know what my script looks like. I'm not such a > fool! I've tested this script under Windows NT + Python 2.1 and Windows > XP + Python 2.3 with the same result. > > To prove you, I copied YOUR code and pasted to *.py file. Than I made it > executable and run it using console (./cgi.py). This is what it showed: > > Hello, world! > Content-type: text/html > > Hello, world! > Hello, world! > Content-type: text/html > > Hello, world! > > I know it's very strange. I don't get it and that's why I need help. :-) > No it is not strange. What you didn't mention in your first posting is that you named your file cgi.py. Thus, when you run your script, you start of by importing it, and therefore the messages are printed twice. How about renaming it to mimal_cgi.py! Regards Jorgen From loic at yermat.net1.nerim.net Thu Jan 22 12:26:58 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 22 Jan 2004 18:26:58 +0100 Subject: prog/lib to draw graphs In-Reply-To: References: Message-ID: graphivz seems good but it is an external tool... Is there something similar as http://gef.tigris.org for python ? Yermat From harry.g.george at boeing.com Fri Jan 23 04:42:01 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 23 Jan 2004 09:42:01 GMT Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: "Dave Brueck" writes: > Moosebumps wrote: > > So, after reading some messages about os.system, and looking at the popen > > stuff and trying it a bit, I still have not found a way to keep a command > > window open for several commands (on Windows 2000/XP), while seeing the > > normal output in a command window. All I want to do is do what a batch file > > does, but I want to actually have functions and associative arrays and all > > the other niceties of python. > > Can you give an example of what you mean, in Perl as well as what you hoped > would work in Python? I couldn't quite understand what it is that you're trying > to do. > > > What's the deal with that? I thought Python started out as a scripting > > language. And that seems like the most basic thing that a scripting > > language should do. > > Dunno, although MS-DOS shell scripting is certainly a small subset of scripting > in general. Maybe with a concrete example somebody will be able to give you a > hand. > > -Dave > > I wonder if this is miscommunication over "script" vs "shell window". This confused me when trying python scripts in MS Windows after using then in *NIX. Quite often a script will output to stdout. In *NIX the script is usually run from a shell, in which case the output goes to the shell and you can see it. But in Windows there is no automatic shell -- you have to explicitly tell the script where to put the output. Otherwise a DOS shell wakes up long enough to complain and then goes away. (At least that's what I think is happening.) An alternative is to install cygwin and run scripts from the bash shell -- you will see output. Even better, install emacs too, then run scripts from inside am emacs bash shell buffer -- you can then search, edit, print, etc the output. Another alternative is to redirect your script output to a file, and then examine it via notepad or (if linefeeds are screwed up) wordpad. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From gerrit at nl.linux.org Wed Jan 28 04:02:05 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 28 Jan 2004 10:02:05 +0100 Subject: I support PEP 326 In-Reply-To: <20040128041023.2EB9225B353@bonanza.off.ekorp.com> References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> <20040128041023.2EB9225B353@bonanza.off.ekorp.com> Message-ID: <20040128090205.GA3086@nl.linux.org> Anthony Baxter wrote: > >>> len(dir(__builtins__)) > 125 > > That's a _lot_ of stuff in one module. Even if you exclude the 40-odd > exceptions that are there, that's still a lot of guff in one big flat > namespace. Any plans to clean it up in Python 3.0? In my opinion, a lot of builtins could either be deleted or moved into a module: buffer complex -> to math open (use file) long abs -> to math apply -> use extended syntax compile -> to sys divmod -> to math execfile -> to sys filter, reduce -> to functional? intern -> ? map -> use list comp oct/hex -> to math? range/xrange (unify) round -> to math Gerrit. -- 227. If any one deceive a barber, and have him mark a slave not for sale with the sign of a slave, he shall be put to death, and buried in his house. The barber shall swear: "I did not mark him wittingly," and shall be guiltless. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From rmkrauter at yahoo.com Wed Jan 21 14:15:46 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed, 21 Jan 2004 11:15:46 -0800 (PST) Subject: Assignment to slice Message-ID: <20040121191546.4975.qmail@web40102.mail.yahoo.com> I hope this gets tacked on to the original thread. Sorry if it doesn't. I see your point. However I could be wrong, but I don't know if what you say is really the case, since negative indexes are just shorthand for actual positive index = i + len(x), where i is the negative index, and len(x) >= abs(i). e.g. x = [1,2,3,4,5] x[-4] is equivalent to x[-4+len(x)], which is x[1] x[-4:-2] is equivalent to x[(-4+len(x)):(-2+len(x))], which is x[1:3] I contend that my restriction may still hold even in the case of negative indices, since negative indices (which are just convenient shorthand), should map to positive indices. In that case, x = [1,2,3] x[-10:-9] = [54] should return an exception too since, x[-10:-9] = x[-10+len(x):-9+len(x)] == x[-7:-6], which is REALLY out of bounds of x. Instead python will just tack stuff on to the front of the array. Which, I still believe, is totally inconsistent. But what do I know? I have about 5 minutes of python experience. I guess I just don't like that behaviour. At least in perl if I assign something to a list slice: @x[2..3] = (4,5); the list grows, so that the things I inserted are at the indices where I think I inserted them. That is, @x now contains (0,0,4,5). So later if I ask for $x[3], or $x[4], I get back what I put there in the first place. In python this is not true. The indices will change because of the append-like behavior: >> x = [] >> x[2:3] = [4,5] >> x [4,5] That just doesn't seem right. Either always raise an out-of-bounds exception or always grow the list. Python seems to be doing a combination of both, and in an inconsistent way, at that (or, more accurately, in a way that does'nt make sense to me). Oh well. Maybe my problem is that I'm using perl as my model of consistency. Plus, it's a minor issue anyway. I just need to be aware of it, and not try to write perl code in python. I need to learn to write python code in python. Thanks for your input. Rich > This doesn't answer you fully but Python is at least > consistent in that > slicing - as opposed the indexing of your first case - > *never* raises an > IndexError. It's not unique to assignment. "print > x[1000:9000]" works too.> > The fact that slices can extend outside the current > range is useful. > Otherwise you couldn't use them to extend sequences. > Adding to the end > would still be possible with your proposed restriction >on first index., but > what if you wanted to add stuff to the *start* of the > list. Currently this > works: > > >>> x = [1, 2, 3] > >>> x[-10:-9] = [54] > >>> x > [54, 1, 2, 3] > > In this case to be consistent you must insist that the second index exist in > the array, i.e. insist on: > >>> x[-4:-3] = [54] > James > -- > James Henderson, Logical Progression Ltd. > http://www.logicalprogression.net/ > http://sourceforge.net/projects/mailmanager/ > On Wednesday 21 January 2004 5:01 pm, Rich Krauter > wrote: > I do not understand why python behaves the way it does > in the following code: > > Here, Python doesn't like that I'm assigning > out-of-range. OK. That's fine. > > >>> x = [] > >>> x[5] = 3 > > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list assignment index out of range > > However, the following seems very strange. Assigning > to a slice, over non-existent array indexes, sets x[0] > and x[1]. > > >>> x[2:5] = [3,4] > >>> x > > [3,4] > > >>> x[1000:9000] = [5] > >>> x > > [3, 4, 5] > > Why does assigning to a slice of non-existent array > elements fill in the array, starting with the first > empty array position? (Acts like [].append() or > [].extend()?) > > Why not raise an out-of-bounds exception here too? > Wouldn't that be more consistent with the first case, > in which I tried to assign out-of-range, and got an > exception? > > IMO, at least the first index in the slice should be > required to exist in the array. If not, raise an > exception. That way, assigning to the slice fills in > the array in a predicatable way without having to do > len() checks first to ensure that you know where in > the array the slice is actually going to be inserted. > > But I'm sure it is the way it is for a good reason. > Hopefully someone can clue me in. > > Thank you in advance. > > Rich __________________________________ Do you Yahoo!? Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes http://hotjobs.sweepstakes.yahoo.com/signingbonus From ajsiegel at optonline.com Wed Jan 21 21:06:41 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 22 Jan 2004 02:06:41 GMT Subject: [Numpy-discussion] Status of Numeric References: Message-ID: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> On Wed, 21 Jan 2004 16:22:43 -0700, Tim Hochberg wrote: >Arthur wrote: >[SNIP] >> Which, to me, seems like a worthy goal. >> >> On the other hand, it would seem that the goal of something to move >> into the core would be performance optimized at the range of array >> size most commonly encountered. Rather than for the extraodrinary, >> which seems to be the goal of numarray, responding to specific needs >> of the numarray development team's applications. > >I'm not sure where you came up with this, but it's wrong on at least two >counts. Its easy to accept that I am wrong, since I wasn't partiuclarly trying to be right about anything. >The first is that last I heard the crossover point where >Numarray becomes faster than Numeric is about 2000 elements. It would be >nice if that becomes smaller, but I certainly wouldn't call it extreme. >In fact I'd venture that the majority of cases where numeric operations >are a bottleneck would already be faster under Numarray. In my >experience, while it's not uncommon to use short arrays, it is rare for >them to be a bottleneck. Couldn't one argue that - for example - in 3d graphic applications the performance as to short arrays is crucial. Not that I really care to argue. I will be happy (and privileged) to work with whatever is decided and created. Understanding that I am out of my league in trying to understand the implications of the trade-offs involved. But hoping that in fact numarray does come to be accepted as the "standard". > >The second point is the relative speediness of Numeric at low array >sizes is the result that nearly all of it is implemented in C, whereas >much of Numarray is implemented in Python. Good for me. I'll be able to understand more of it. > This results in a larger >overhead for Numarray, which is why it's slower for small arrays. As I >understand it, the decision to base most of Numarray in Python was >driven by maintainability; it wasn't an attempt to optimize large arrays >at the expense of small ones. I was indeed making an assumption here. Ifs its wrong, its indeed wrong. > >> Has the core Python development team given out clues about their >> feelings/requirements for a move of either Numeric or numarray into >> the core? > >I believe that one major requirement was that the numeric community come >to a consensus on an array package and be willing to support it in the >core. There may be other stuff. > > >> It concerns me that this thread isn't trafficked. > >I suspect that most of the exchange has taken place on >numpy-discussion at lists.sourceforge.net. > The original post was a request for feedback from the wider community. My only intent was to feedback. I think the issue is important. For reasons that are non-technical, I believe it much to the best that the community continue to look to one package of the sort as a standard. To me. even better if it makes it into the core distribution. And I could even be wrong about that. Art From max at alcyone.com Tue Jan 13 00:02:22 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 12 Jan 2004 21:02:22 -0800 Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> <4002F93D.298A2394@alcyone.com> Message-ID: <40037BDE.CAFB05A9@alcyone.com> "David M. Cooke" wrote: > Do you mean something like > os.environ['startTime'] = '`rm -rf /`' > ? No, I mean something like os.environ['startTime'] = '"; rm -rf /; : "' The lesson to be learned here is: Do not build shell commands from untrusted inputs. Ever. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ You are free and that is why you are lost. -- Franz Kafka From tim.golden at viacom-outdoor.co.uk Mon Jan 26 04:15:19 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 26 Jan 2004 09:15:19 -0000 Subject: -- Pythonic control of Windows GUI application: tabs and list views Message-ID: >-----Original Message----- >From: zapazap at yahoo.com [mailto:zapazap at yahoo.com] [.. snip explanation of sending messages to Windows controls ..] >For the "List-View" and "Tab" controls then, I expected to find the >constants > > win32con.LVM_GETCHECK > win32con.TCM_GETITEMCOUNT > >corresponding to the distinct messages documented at [3] and [4]. >Unfortunately the module win32com module does not have any LVM_* or >TCM_* attributes, and I have not found reference to such constants in >the Extensions documentation. To answer this question most directly, the TCM_GETITEMCOUNT etc. message constants will ultimately just be numeric values. If win32con doesn't have them (and it doesn't have everything) then just Google around to find out where they're defined. If you already have a recent win32 sdk knocking around, you'll find them in one of the header files (*.h). As a hint from someone who's had to do this quite a lot, Googling for (eg) const TCM_GETITEMCOUNT is likely to get you something useful, as both Delphi & VB have a lot of adherents on the web, and someone in those communities is bound to have done the same kind of thing that you're trying. In this case, the first hit is: http://www.vbaccelerator.com/home/VB/Utilities/ActiveX_Documenter/ActiveX_Do cumenter_Source_zip_cTabCtrl_ctl.asp which seems to have some useful constants. As an aside, have you look at this and related posts by Simon Brunning? I honestly don't know if it's directly of use, but it may throw up some clues. http://www.brunningonline.net/simon/blog/archives/000664.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 usenet_spam at janc.invalid Fri Jan 23 23:32:49 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 24 Jan 2004 04:32:49 GMT Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: "Moosebumps" schreef: > BatchTest.py: > > # the intention is to do the same thing as BatchTest.bat, [...] > # in particular the environment variable is not saved, BatchTest.bat sets the environment variable in the same shell that executes it, BatchTest.py sets the environment variables in a subshell, and the changes made in the subshell are discarded when it terminates. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From michele.simionato at poste.it Thu Jan 15 10:15:55 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Jan 2004 07:15:55 -0800 Subject: super. could there be a simpler super? References: Message-ID: <95aa1afa.0401150715.61e44550@posting.google.com> Kerim Borchaev wrote in message news:... > Hello! > > Always when I use "super" I create a code duplication because class > used as first arg to "super" is always the class where the method > containing "super" was defined in: > ''' > class C: > def method(self): > super(C, self).method() > ''' > > Obviously the methods like the one below doesn't work "right";-) > ''' > def super(self): > super(self.__class__, self) > class C: > def method(self): > super(self).method() > ''' > > Is it possible that such a "super"(deducing class method declaration > context) could appear in Python? > (It seems to me that to implement a simple super something should be > done during "compilation" of class declaration.) > > Best regards, > Kerim mailto:warkid at hotbox.ru ``super`` is one of the trickiest Python constructs. In http://www.python.org/2.2.3/descrintro.html Guido sketches a metaclass solution which however is not quite satisfactory (for one, it does not work with magic methods). Some time ago I went to "fix" autosuper, but that required a major metaclass hacking which was so deep that I have already forgotten what I did ;) Nevertheless, I have still the files around, and my test suite runs okay (this only means that the bugs are smarter than me) so I think I will post the code. If somebody uses it and finds an unexpected behavior, please send me a note. If somebody wants his head to explode, please try to understand what safetype does ;) Here are two examples of usage: # example1.py: the diamond diagram from super import autosuper class A(object): __metaclass__=autosuper def m(self): return "A" class B(A): def m(self): return "B" + self.__super.m() class C(A): def m(self): return "C" + self.__super.m() class D(C, B): def m(self): return "D" + self.__super.m() print D().m() this prints DCBA. #example2.py from super import autosuper class A(str): __metaclass__=autosuper def __new__(cls): obj='A'+cls.__super.__new__(cls) print obj return obj class B(A): def __new__(cls): obj="B" + cls.__super.__new__(cls) print obj return obj class C(A): def __new__(cls): obj="C" + cls.__super.__new__(cls) print obj return obj class D(C, B): def __new__(cls): obj="D" + cls.__super.__new__(cls) print obj return obj D() this prints A BA CBA DCBA Here is the module super.py: # super.py from safetype import safetype # deep magic to avoid metaclass conflicts class _super(object): """Helper descriptor, called by the ``Enable__super`` metaclass which will take care of defining the ``__thisclass__`` attribute; it should not be called directly, unless you really know what you are doing. Notice that this ``_super`` is minimal, i.e. it does not define ``__new__``, `` __init__`` or other special methods; this avoids the problems of the standard ``super``.""" def __get__(self,obj,klass): if obj is None: obj=klass return super(self.__thisclass__,obj) class autosuper(safetype): """Cooperative safe metaclass which defines a private attribute ``__super`` on its instances, containing a reference to the descriptor ``_super``. This enable the cooperative syntax ``obj.__super.methodname`` as sugar for ``super(callingclass,obj).methodname``.""" def __init__(cls,*args): super(autosuper,cls).__init__(*args) if len(args)==1 or args[0]=='superobject': return # do nothing strippedname=args[0].lstrip('_') # if the class name starts with underscores, they must # be stripped; this is how the mangling mechanism works sup=_super(); sup.__thisclass__=cls # trick to avoid __init__ in _super setattr(cls,'_%s__super' % strippedname,sup) Here is the module safetype.py: # safetype.py """Deep, **DEEP** magic to remove metaclass conflicts. ``safetype`` provides the ``safetype`` metaclass, the mother of conflict-free metaclasses. The suggested import syntax for usage in other modules is from safetype import safetype as type If you override ``__new__`` when you derive from ``safetype``, you should do it cooperatively. Example: >>> from safetype import type >>> class M(type): ... def __new__(mcl,*args): ... print 'creating a class from M' ... return super(M,mcl).__new__(mcl,*args) >>> class N(type): ... def __new__(mcl,*args): ... print 'creating a class from N' ... return super(N,mcl).__new__(mcl,*args) >>> class C: ... __metaclass__=M creating a class from M >>> class D: ... __metaclass__=N creating a class from N >>> class E(C,D): ... pass creating a class from M creating a class from N >>> E.__class__ # automagically created >>> E.__metaclass__ # inherited from C """ import sys,sets,types,__builtin__ __type__=__builtin__.type #the aboriginal 'type'; useful if you rebinds 'type' to 'safetype' metadic={} # associates tuple of bases metaclasses to children metaclasses class safetype(type): """Overrides the ``__new__`` method of the ``type`` metaclass, making the generation of classes conflict-proof.""" # Seventeen lines of DENSE code! def __new__(mcl,*args): nargs=len(args) if nargs==1: # works as __builtin__.type return __type__(args[0]) elif nargs==3: # creates the class using the appropriate metaclass n,b,d = args # name, bases and dictionary mb=map(__type__,b) # metaclasses of the bases meta=generatemetaclass([mcl,]+mb) # recursive if mcl is meta: # meta is trivial, dispatch to the default __new__ return super(safetype,mcl).__new__(mcl,n,b,d) elif is_less_specific(mcl,mb): # dispatch to meta.__new__ return meta.__new__(meta,n,b,d) else: # non-trivial metaclass, dispatch to the right __new__ # (it will take a second round) return super(mcl,meta).__new__(meta,n,b,d) else: raise TypeError('%s() takes 1 or 3 arguments' % mcl.__name__) def generatemetaclass(metas): """Given a sequence of metaclasses, removes redundances and, if needed, creates a new metaclass; returns the metaclass and updates the global dictionary.of metaclasses. If the metaclass is already in the dictionary, simply retrieves it.""" metabases=remove_redundant(metas)# metas have the priority if metabases in metadic: # already generated metaclass return metadic[metabases] elif len(metabases)==1: # single metabase meta=metabases[0] else: # multiple metabases metaname=''.join([m.__name__ for m in metabases]) meta=safetype(metaname,metabases,{}) return metadic.setdefault(metabases,meta) def is_less_specific(c,ls): "c is an ancestor of (at least) one class in the list ls." for C in ls: if issubclass(C,c) and C is not c: return True return False def remove_redundant(bases): """Returns a tuple of non-redundant base classes. Given a sequence of base classes, a class is redundant if 1. it is duplicated; 2. it is implied by the others, i.e. it is an ancestor of at least one of the other classes; 3. it is ClassType, the metaclass of old style classes. For instance, if ``C`` is derived from ``B``, in the sequence ``C,B`` the class ``B`` is redundant, since all its features are already provided by ``C``. Therefore ``B`` is removed and ``remove_redundant`` returns the tuple ``(C,)``: >>> class B(object): pass ... >>> class C(B): pass ... >>> import safetype; safetype.remove_redundant([C,B]) (,) """ redundant=sets.Set((types.ClassType,)) # old style metaclass ls=list(bases) for c in bases: if is_less_specific(c,ls) or c in redundant: ls.remove(c) else: # c is a redundant class to be removed if found redundant.add(c) return tuple(ls) From alan.gauld at btinternet.com Thu Jan 22 03:02:13 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2004 08:02:13 GMT Subject: a curious IDLE Error References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> Message-ID: <400f8315.60048965@news.blueyonder.co.uk> On Wed, 21 Jan 2004 21:50:01 -0800, EP wrote: > I opened a new Python shell from the instance of IDLE editor where my > module was open and tried the raw_input(): > > >>> someFile=raw_input("enter: ") > Traceback (most recent call last): > File "", line 1, in ? > someFile=raw_input("enter: ") > TypeError: 'tuple' object is not callable > This is a long shot but is it possible that you used raw_input as the name of a variable somewhere. Thus you are trying to call that variable (which apparently holds a tuple!). Try doing a text search for raw_input in your module code. Just a thought. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From nomail at nospam.net Mon Jan 12 10:55:42 2004 From: nomail at nospam.net (Olaf Meyer) Date: Mon, 12 Jan 2004 15:55:42 GMT Subject: building strings with variable input In-Reply-To: <400273B8.E991F41D@alcyone.com> References: <400273B8.E991F41D@alcyone.com> Message-ID: <2szMb.6443$k4.143679@news1.nokia.com> Erik Max Francis wrote: > Olaf Meyer wrote: > > >>Especially if you have a lot of variable input it makes it hard to >>match >>the variables to the proper fields. From other scripting languanges >>I'm >>used to something like: >> >> $cmd = "$executable -start $startTime -end $endTime -dir $directory" >> >>This makes it very easy to see how the string is actually built. You >>dont't have to worry where which variables go. >> >>Is there a similar way to do this in python? > > > Sure: > > cmd = "%(executable)s -start %(startTime)s -end %(endTime)s -dir > %(directory)s" % locals() > > There are also more expansive solutions such as YAPTU or EmPy. > > Note, however, that what you are trying to do (presuming you're passing > this to os.system or something similar) is potentially a serious > security risk. If the values of the strings you are constructing the > command line are not fully trustworthy, they can be easily manipulated > to make your program execute arbitrary shell commands. > I just found out another way ;-) Using the locals() has the disadvantage that I cannot use more complex variable parameters (e.g. certain values of a dictionary). The following works well: cmd = (executable + " -start " + startTime + " -end " + endTime + " -dir " + options.dir) Olaf From jeremy at zope.com Mon Jan 12 11:26:06 2004 From: jeremy at zope.com (Jeremy Hylton) Date: Mon, 12 Jan 2004 11:26:06 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <9a6d7d9d.0401120658.5b9ee522@posting.google.com> References: <9a6d7d9d.0401120658.5b9ee522@posting.google.com> Message-ID: <1073924765.6341.387.camel@localhost.localdomain> On Mon, 2004-01-12 at 09:58, Aaron Watters wrote: > "Tim Peters" wrote in message news:... > > [Aaron Watters] > > > Does zodb support the strictest isolation levels? > > > > I'm almost certain it doesn't, but I'm not a DB expert. Please take this to > > a ZODB list, as previously suggested. > > > > > If so how? If not what does it support exactly? > > > > I pointed you to Jeremy's relevant blog entry last time... > > Reading the blog it seems you are right. I wish zodb would be > a bit more careful in its claims. When you say "zodb supports > the ACID properties of transactions" this has a precise meaning > which vanishes when you redefine all the letters. Perhaps you could say something about which of the letters you think we've redefined in a confusing way. If you're talking about my blog entry or the zodb programming guide, I wrote the definitions and the text is simply my gloss on the what I thought the standard definitions were. Here's a definition of isolated from Gray & Reuter: "The property that two transactions running in parallel have the illusion that there is no concurrency. It appears that the system runs one transaction at a time. So a transaction is isolated from the uncommitted updates of others (so-called dirty data), and the transaction has repeatable reads. (See also degree 1 isolation, degree 2 isolation, degree 3 isolation.)" In the programming guide, we say "Isolation means that two programs or threads running in two different transactions cannot see each other's changes until they commit their transactions." That strikes me as pretty consistent with the Gray & Reuter definition. In my blog entry (http://www.python.org/~jeremy/weblog/030514.html), I get into the finer details using some terminology from Atul Adya's PhD thesis. The ANSI standard isolation levels don't work for optimistic concurrency control, and Adya fleshes out some levels that makes sense for optimism and looking. > In particular > it suggests that zodb would be good for something like an > accounting or banking application which would require strict > transaction isolation (serializability). The looser definition > could lead to fairly unpleasant difficulties (law suits, jail time...). > Sorry, had to complete my thought on clp. Shane Hathaway posted a nice message about the isolation level supported by zodb last spring. http://mail.zope.org/pipermail/zodb-dev/2003-March/004684.html ZODB does not support full serializability at the moment. The current stable release supports cursor stability and the new development release of ZODB 3.3 + multi-version concurrency control will support snapshot isolation. The remaining obstacle to full serializability is write skew. I think we can address that problem, but it hasn't been a high priority for ZC. Jeremy From francisgavila at yahoo.com Thu Jan 15 14:16:33 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 15 Jan 2004 14:16:33 -0500 Subject: Tcl/Tk Support References: <20040109201513.GC2810@unpythonic.net> Message-ID: <100dpqk1421ohcd@corp.supernews.com> Diego Ribeiro de Andrade wrote in message ... >Yeah! It Works Thanks. > > Everyone else told me that It was native in Python. May I did something >wrong in the installation of Red Hat9? Distros often carve up the as-released packages into more managable chunks for their own packages. Suppose your machine didn't run X--then you'd be complaining about how you had to install tkinter when you didn't need it. :) FWIW, Debian also has tkinter in a separate package. -- Francis Avila From jjl at pobox.com Fri Jan 9 15:11:08 2004 From: jjl at pobox.com (John J. Lee) Date: 09 Jan 2004 20:11:08 +0000 Subject: Python and Jython are kinda different References: <87wu81jjg2.fsf@pobox.com> Message-ID: <8765fkrig3.fsf@pobox.com> Dave Benjamin writes: > In article <87wu81jjg2.fsf at pobox.com>, John J. Lee wrote: > > Dave Benjamin writes: > > [...] > >> Is there anyone here that works on Jython? Do you need help? What kind of > > > > They certainly need help. > > I suppose that was a redundant question. =) Yes, but it has been specifically noted by GvR (as well as the Jythonistas) that Jython is lacking developers ATM. > >> help do you need? What's your estimation of the amount of work needed? Is > > > > Asking on the Jython list seems like a good idea. > > Yes. But I think that c.l.p is an appropriate place to bring this issue up > in general, because if CPython and Jython are truly--as they are often Sure. But the questions you asked can probably be best answered by the core Jython people. > represented in books and tutorials--just two implementations of the Python > language, we all ought to be more concerned with unifying them. I never see > Jython advertised as a limited subset of Python. Well, it's *not* a limited subset of CPython 2.1 (apart from tiny differences). [...] > > PyPy is a research effort, so not immediately useful. It may have big > > payoffs if successful, of course. > > Well, my thinking is that, since it's an implementation of Python written in > Python, many of the new features of CPython that don't require syntactical > or fundamental object-model changes could be ported from PyPy to Jython as a > temporary fix, to be eventually recoded in Java. Library changes don't require PyPy, they already work (most of the time) direct from CPython. It's the fundamentals that take the work. I'm not sure whether there's a third category, as you suggest. I believe GvR said that PyPy might (might!) become a sort of executable standard for Python in the future, though. John From sdeibel at wingide.com Thu Jan 22 09:24:08 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Thu, 22 Jan 2004 09:24:08 -0500 (EST) Subject: a curious IDLE Error In-Reply-To: <5.2.0.9.0.20040122011652.00b7ea80@mail.zomething.com> Message-ID: On Thu, 22 Jan 2004, EP wrote: > At 08:02 AM 1/22/2004 +0000, Alan Gauld wrote: > >On Wed, 21 Jan 2004 21:50:01 -0800, EP wrote: > > > > > I opened a new Python shell from the instance of IDLE editor where my > > > module was open and tried the raw_input(): > > > > > > >>> someFile=raw_input("enter: ") > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > someFile=raw_input("enter: ") > > > TypeError: 'tuple' object is not callable > > > > > > >This is a long shot but is it possible that you used raw_input as > >the name of a variable somewhere. Thus you are trying to call > >that variable (which apparently holds a tuple!). > > > >Try doing a text search for raw_input in your module code. > > > >Just a thought. > > > I thought it might have been something like that as well, but I checked all > my variable names (and I was only importing the string module). > > The strange behavior was that the module worked, just not in an IDLE shell > opened up out of the same instance I created the module in. I'm guessing too (sorry) but it may be that IDLE doesn't have support for properly redirection reads on stdin to the shell? This comes to mind only because we had to write special code to make this happen properly in Wing IDE. Stephan Deibel -- Wing IDE for Python Archaeopteryx Software, Inc Take Flight! www.wingide.com From llothar at web.de Fri Jan 30 20:02:30 2004 From: llothar at web.de (Lothar Scholz) Date: 30 Jan 2004 17:02:30 -0800 Subject: easiest transition for a PHP website to move to Python? References: <6ee58e07.0401300555.12c07aa3@posting.google.com> Message-ID: <6ee58e07.0401301702.42c759f8@posting.google.com> "Diez B. Roggisch" wrote in message news:... > Where exactly is zope not "real" python? Just because it features two > templating-methods that are for good reasons _not_ python embedded into > html, its still a python webapp server. > I never used webware, so I can't compare both, but from what I see it > appears to me like tomcat (or maybe jboss) the python way. No problem with > that. But object-relational-mappers are a PITA if you _must_ use them. ZODB > oth is much more of a object-orientied (not relational, though) database. > And thats what I love about it - simply create objects, and save them, > without the need for prior mapping to anything. Read this http://zope-is-evil-666.idyll.org/ http://www.amk.ca/python/writing/why-not-zope.html http://pywx.idyll.org/advocacy/why-not-zope.html > > For purely content-driven websites, I haven't seen much better solutions > than ZOPE together with some modern CMS, like PLONE or ZMS. Only, as mentionend in other texts, if it is for simple content. Otherwise the ZOPE restrictions are quite strong. From jcarlson at nospam.uci.edu Sat Jan 24 14:39:40 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 24 Jan 2004 11:39:40 -0800 Subject: pty difficulties In-Reply-To: <2e262238.0401240912.1ca6bb74@posting.google.com> References: <2e262238.0401232202.5b21eba8@posting.google.com> <2e262238.0401240912.1ca6bb74@posting.google.com> Message-ID: > I don't think checking for writeable status /should/ help because the > write call I am using blocks. So, if the stream isn't writeable, it > should just block until it is. I think. Hrm. Perhaps you should just leave the sleep in there. One second seems a bit much, but maybe .01 or .001 seconds is sufficient. You could reasonably still get 100K-1M/second. One would hope that would be enough for most tasks. - Josiah From sidharthk at hotmail.com Mon Jan 26 04:01:16 2004 From: sidharthk at hotmail.com (Sidharthk) Date: 26 Jan 2004 01:01:16 -0800 Subject: efficient updating of nested dictionaries References: Message-ID: <8d02ff63.0401260006.1b892fe8@posting.google.com> omission9 wrote in message news:... > I have a dictionary that looks like this > MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO > > I am having a problem updating this with a simple > MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting > into the inner dicts. > Getting the keys of each and iterating through and updating each one is > terribly slow as the number of keys gets bigger and bigger. > What is the bst way to update my nested dicts? Use Tuples MY_DICT[(KEY_X,KEY_Y,KEY_Z)]=FOO Unless for some you need to use nested dicts :) From newsgroups at jhrothjr.com Fri Jan 23 19:18:23 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 23 Jan 2004 19:18:23 -0500 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: <1013ef6ksfsmf16@news.supernews.com> "Amy G" wrote in message news:4GfQb.16187$AA6.14368 at fed1read03... > I have seen something about this beofore on this forum, but my google search > didn't come up with the answer I am looking for. > > I have a list of tuples. Each tuple is in the following format: > > ("data", "moredata", "evenmoredata", "date string") > > The date string is my concern. This is the date stamp from an email. > The problem is that I have a whole bunch of variations when it comes to the > format that the date string is in. For example I could have the following > two tuples: > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 03:15:06") > > I know there is some way to use the date string from each of these to get a > date usable by python, but I cannot figure it out. > I was trying to use time.strptime but have been unsuccesful thus far. > > Any help is appreciated. This is what I use to parse dates of unknown provinance. It's laughably overengineered, and I don't include the day of the week or the time. Given your examples, though, those should be easy enough to deal with. HTH John Roth class DateContainer(object): _typeDict = {} _stringValue = "" _typeDict["stringValue"] = "String" _typeDict["value"] = "String" _value = "" year = 1 month = 1 day = 1 bc = "" def _checkUserFriendlyDate(self, date): # The rules for a user friendly date are: # 1. The year must be at least three digits, including # leading zeroes if necessary. Day and numeric month # may be no longer than 2 digits. # 2. The month may be alphabetic or numeric. If it's # alphabetic, it must be at least three letters long. # 3. The epoch may be ad, bc, bce or ce. If omitted, it's # assumed to be ad. # 4. After removing the year, epoch and an alphabetic month, # the remaining single piece is the day, or the piece that # is greater than 12. # 5. If two pieces remain, the first is the month, the second # is the day. Both are between 1 and 12, inclusive. partList = dateTimeParse(date) if not(2 < len(partList) < 5): raise ValueError, "incorrect part list: %s" % (partList,) bc = self._findBC(partList) if len(partList) != 3: return "too many components in date: '%s'" % date year = self._findYear(partList) month = self._findAlphaMonth(partList) if month != 0: day = partList[0] else: day = self._findDay(partList) if day: month = partList[0] else: month, day = partList year = self._checkNum(year, 4712) day = self._checkNum(day, 31) month = self._checkNum(month, 12) if bc in ("AD", "CE"): bc = "" self.year, self.month, self.day, self.bc = year, month, day, bc return True def _checkNum(self, num, limit): result = int(num) if result > limit: raise ValueError, "number '%s' out of range '%s'" % (num, limit) return result def _findBC(self, partList): for i in range(len(partList)): word = partList[i] if word in ("AD", "BC", "CE", "BCE"): del partList[i] return word # XXX if len(partList > 3): error return "" def _findYear(self, partList): for i in range(len(partList)): word = partList[i] if len(word) > 2 and word.isdigit(): del partList[i] return word raise ValueError def _findAlphaMonth(self, partList): for i in range(len(partList)): word = partList[i] if word.isalpha(): del partList[i] return ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'].index(word[:3]) + 1 return 0 def _findDay(self, partList): for i in range(len(partList)): word = partList[i] if word.isdigit() and int(word) > 12: del partList[i] return word return "" def _getStringValue(self): return self._stringValue def _setStringValue(self, value): self._checkUserFriendlyDate(value) self._stringValue = value _typeDict["stringValue"] = "String" stringValue = property(_getStringValue, _setStringValue, doc="User Friendly Date") def _getValue(self): isoDate = "%04u-%02u-%02u %s" % (self.year, self.month, self.day, self.bc) return isoDate.strip() def checkISODate(self, value): year = self._checkNum(value[:4], 4712) month = self._checkNum(value[5:7], 12) day = self._checkNum(value[8:10], 31) if len(value) > 10: bc = value[11:] if not (bc.upper() in ("AD", "BC", "BCE", "CE")): raise ValueError if bc in ("AD", "CE"): bc = "" self.year, self.month, self.day, self.bc = year, month, day, bc return def _setValue(self, value): self._checkISODate(value) isoDate = "%04u-%02u-%02u %s" % (self.year, self.month, self.day, self.bc) self.stringValue = isoDate return None value = property(_getValue, _setValue, doc = "ISO Standard Format Date") > > From crawley.storm.nonononoemail at ntlworld.com Sat Jan 31 17:31:57 2004 From: crawley.storm.nonononoemail at ntlworld.com (Crawley) Date: Sat, 31 Jan 2004 22:31:57 +0000 Subject: win32com support References: Message-ID: Mark Hammond wrote in news:bvh9f0$1gej$1 at arachne.labyrinth.net.au: > Generally, you can do a QueryInterface for the object. However, if > the object does not support IDispatch, you will haver trouble - we > don't support arbitrary interfaces when calling them, only > implementing them. > > ob = ob._obj_.QueryInterface( > I take it the chances of this working are slim to none ? > > The GUID must be for a type library. If you run "makepy.py -i", then > you will get a list of all valid typelibs you can use, and the params > for it. > Bum! Perhaps I should look at implementing the actual addin in C++ and then embed python into it so that most the work can be done by that. Thanks for your help anyway Rich From swalters_usenet at yahoo.com Sun Jan 11 03:10:50 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 11 Jan 2004 08:10:50 GMT Subject: help with Python Environment For Blind User References: Message-ID: I had a blind friend who swore by vim. It integrated well with his text to speech converter as well as his braille terminal, and provided him lots of facilities to figure out where exactly he was in a file. In fact, poking around in the source, I see that there's several files related to braille encodings and terminals. Look into it. vim can be hard to learn at first, but it may pay off for you in the end. It's a very powerful program, and could make many tools easier for you to use. Sam Walters From jcarlson at nospam.uci.edu Fri Jan 30 17:48:30 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 14:48:30 -0800 Subject: python in dreamweaver In-Reply-To: References: Message-ID: Michel Claveau/Hamster wrote: > Hi ! > > I prepare "template" pages with DM ; in "strategic" position (where i think > put infos later), i put a key-word ; then i save the page. > My web-server (in Python) read the HTML-Page, do multiple search/replace > (key-words by data), then send the page. It would be significantly more Pythonic to have a template similar to the following: template = ''' %(title)s %(menu)s %(body)s ''' output = template%{'title':"this is the title of the web page", 'menu':"this is the menu", 'body':"this is the body"} - Josiah From gerrit at nl.linux.org Mon Jan 19 15:29:33 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 19 Jan 2004 21:29:33 +0100 Subject: Escaping slashes (double backslash plague) In-Reply-To: <400C359B.58CCB134@engcorp.com> References: <400C359B.58CCB134@engcorp.com> Message-ID: <20040119202933.GA10765@nl.linux.org> Peter Hansen wrote: > If so, give up: it's not possible. File names cannot contain a > forward slash, at least on most any operating system which uses slashes > as path separators. (*) > (*) Examples to the contrary, while perhaps interesting, notwithstanding... There is (was?) a bug in I think NFS or SMBFS which allowed the creation of a file with a '/' in it. I heard of someone which had a very tough time in removing it again ;-) open(''.join([chr(i) for i in range(1, 256) if chr(i) != '/']), 'w')-ly y'rs - Gerrit -- 254. If he take the seed-corn for himself, and do not use the yoke of oxen, he shall compensate him for the amount of the seed-corn. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From christian.aastorp.slett.spam at siemens.no.invalid Fri Jan 9 04:20:06 2004 From: christian.aastorp.slett.spam at siemens.no.invalid (Christian Aastorp) Date: Fri, 09 Jan 2004 10:20:06 +0100 Subject: books References: <3FFDC029.AB0A4097@unet.univie.ac.at> Message-ID: On Thu, 08 Jan 2004 20:40:08 GMT, Thomas Mang wrote: >Hello, > >I have programmed mostly in C++ lately, and I want to start learning >Python now. > >Which books would you recommend to buy? > >I am both looking for an introduction into the language, as well as >complete guides. To learn how to think in Python I think the Python Cookbook is very valuable. From jzgoda at gazeta.usun.pl Mon Jan 26 16:16:42 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 26 Jan 2004 21:16:42 +0000 (UTC) Subject: wxpython and wxlocale References: Message-ID: Ya pisze: > Is there any way of telling python that the text of the dialogues is in a > specific language? > And in affirmative case. How is it made? since all the attempts have been > useless. > I think that wxLocale has to be used, but I do not become clear. loc = wx.Locale() loc.Init(wx.LANGUAGE_POLISH) Et voila, your program uses Polish dialogs. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From guido.schimmels at freenet.de Tue Jan 13 18:25:11 2004 From: guido.schimmels at freenet.de (Guido Schimmels) Date: Wed, 14 Jan 2004 01:25:11 +0200 Subject: id3v2 module References: Message-ID: Am Tue, 13 Jan 2004 21:11:11 +0000 schrieb Jarek Zgoda: > Guido Schimmels pisze: > >>> I'd like to know if there is a third-party module for reading/writing >>> id3v2 informations. >>> Thanks >> >> http://id3-py.sourceforge.net/ > > This one is able to read and write only ID3v1.1 tags. O, sorry. Maybe this is what you are looking for then: http://tunetagger.sourceforge.net/snapshots/ From peter at engcorp.com Fri Jan 16 09:23:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Jan 2004 09:23:05 -0500 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> <265368cb.0401151424.3cd7ede6@posting.google.com> Message-ID: <4007F3C9.7BB853A2@engcorp.com> Laurent Therond wrote: > > I forgot to ask something else... > > If a client and a server run on locales/platforms that use different > encodings, they are bound to wrongly interpret string bytes. Correct? Since the byte strings are by definition *encoded* forms of the Unicode data, they definitely need to have a shared frame of reference or they will misinterpret the data, as you surmise. You can't decode something if you don't know how it was encoded. -Peter From markus_wankus at hotmail.com Thu Jan 29 15:12:44 2004 From: markus_wankus at hotmail.com (Markus Wankus) Date: Thu, 29 Jan 2004 15:12:44 -0500 Subject: win32com - .ocx won't Dispatch... References: Message-ID: Open the gen_py'd file 8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py, and do some searching. You should be able to find an obvious main class related to what you are doing (I'm not sure what the .tlb is), and it will say in the comment or docstring that it is a ".", or whatever. That will be what you need to Dispatch. The other option is to use the OLEView tool tiwth MSVC, and look at your EDRE Utility Control. It will say in there somewhere... Markus. On Wed, 28 Jan 2004 19:04:22 -0800, RJ wrote: > Hi, > I've been going over the Quick Start to Client side COM and Python and > many other sources, but cannot find an example that will get my > com/ActiveX .ocx USB device driver imported. > > The Excel and Word examples run fine. > win32com.client.Dispatch("Excel.Application") etc., but how does one > know the (".") to type in? Excel looks only vaguely like > "Excel.Application" in the com browser. > > Firstly, I found the ocx from the Python Object Browser. > I ran makepy.py on EDREUtlX.ocx (USB device driver) which created > 8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5.py > etc. in gen_py\, > but, I cannot find a syntax to get Dispatch to accept it... > > from win32com.client import Dispatch > # failed attempts > Dispatch("EDRE Utility Control") # name in browser > Dispatch('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5}') > Dispatch('{8AA34F82-95C9-11D3-8EB6-00C0DF2247CA}') > Dispatch("8AA34F82-95C9-11D3-8EB6-00C0DF2247CA") > Dispatch("8AA34F82-95C9-11D3-8EB6-00C0DF2247CAx0x3x5") > > all return: > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > line 95, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line > 84, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line > 72, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) > > So, what is the required syntax? > > Thanks, > Ray > > -- -- Markus From bucodi_no_spam at ahoo.fr Tue Jan 13 12:28:13 2004 From: bucodi_no_spam at ahoo.fr (Rony) Date: Tue, 13 Jan 2004 18:28:13 +0100 Subject: Does anyone else not find the fun in programming...? References: Message-ID: Group : comp.lang.python > I find python very effective as a language and can generally project > most of my hazy thoughts into it. But FUN !!! This is work dammit, > I have now ground my teeth down from the number of times I read that > programming is fun. Football (association) is fun, walking along > canals is fun, Arguing about quite how useless the British Government > is fun but programming ? > > Do I need help ? > > (Actually typing this was quite fun, so perhaps) Well I agree... Meeting people, having a drink with them, sex.. is fun Programming is just a job Rony -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi_no_spam at yahoo.fr (delete _no_spam) / | www.bucodi.com - My work \ www.ifrance/karamusic -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From crap at crud.com Tue Jan 13 13:54:27 2004 From: crap at crud.com (Moosebumps) Date: Tue, 13 Jan 2004 18:54:27 GMT Subject: System calls over network References: Message-ID: Windows "at" command, or soon.exe which you can download from the Microsoft website. do a google search on those. I had the exact same question. MB "Gabriel Leblanc" wrote in message news:ed58f15a.0401130950.237a0ea1 at posting.google.com... > Hello, > > I am wondering if there's an easy way to do a system call to a file > that resides on the network. Say for example I would like to call the > batch file which is located at > > \\ComputerName\file.bat > > I tried : > > >>> import os > >>> os.popen("\\ComputerName\file.bat") > > >>> os.popen("\\\\ComputerName\\file.bat") > > > Of course, I replaced ComputerName and file.bat with the correct > paths. > > Any idea ? > > Thanks ! From tcdelaney at optusnet.com.au Sat Jan 10 07:29:38 2004 From: tcdelaney at optusnet.com.au (Tim Delaney) Date: Sat, 10 Jan 2004 23:29:38 +1100 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <3ffff033$0$26117$afc38c87@news.optusnet.com.au> From: "Peter Hansen" > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) I have to say that I do, but I'm also dealing with datasets up to about 500MB in the worst case - but about 10-20MB in the normal case. In most cases, the optimisations are things like only doing a single pass over any file, etc. A naive prototype often doesn't scale well when I need to deal with large datasets. Often using psyco will be sufficient to get me over the hurdle (see the psyco thread) but sometimes not. Tim Delaney From sdeibel at wingide.com Wed Jan 28 13:39:27 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Wed, 28 Jan 2004 13:39:27 -0500 (EST) Subject: Cross Platform Browser Launcher In-Reply-To: <490316A24CC5D411ACD700B0D078F7F003915E28@cseexch01.cse.creoscitex.com> Message-ID: Hi, On Wed, 28 Jan 2004, Pieter Claerhout wrote: > Take a look at the webbrowser module... > http://www.python.org/doc/current/lib/module-webbrowser.html I submitted a patched webbrowser module with substantial improvements a while back. I'm hoping this can make it into Python 2.4 so please try it out: http://python.org/sf/728278 Thanks! Stephan Deibel -- Wing IDE for Python Archaeopteryx Software, Inc Take Flight! www.wingide.com > > Cheers, > > > pieter > > Creo > pieter claerhout | product support prinergy | tel: +32 2 352 2511 | > pieter.claerhout at creo.com | www.creo.com > > IMAGINE CREATE BELIEVE(tm) > > > -----Original Message----- > From: michael at foord.net [mailto:michael at foord.net] > Sent: 28 January 2004 10:18 > To: python-list at python.org > Subject: Cross Platform Browser Launcher > > > I've written a simple application in python with an HTML help file. > > I'm looking for a cross platform way of launching the help file. > > On windows I'd use : > os.system('start help.html') > > Which automatically opens the file with the users browser. > > Is there a cross-platform way of doing the same thing ? > I can do a platform test and use different techniques for different > systems - but I don't know how to achieve the same effect on a Linux > (Unix ? Mac ?) machine..... > > Any help appreciated. > > Fuzzy > > -- > > > 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.voidspace.org.uk/atlantibots/pythonutils.html > Python functions - home of dateutils, ConfigObj, StandOut, CGI-News > and more.... > > -- > > Everyone has talent. What is rare is the courage to follow talent > to the dark place where it leads. -Erica Jong > Ambition is a poor excuse for not having sense enough to be lazy. > -Milan Kundera > -- > http://mail.python.org/mailman/listinfo/python-list > > > From me at privacy.net Mon Jan 26 04:39:09 2004 From: me at privacy.net (Duncan Booth) Date: 26 Jan 2004 09:39:09 GMT Subject: efficient updating of nested dictionaries References: Message-ID: Josiah Carlson wrote in news:bv2e21$j5e$2 at news.service.uci.edu: >> Although, that's probably kind of lame - I bet others will have much >> better suggestions. I'm interested in how other people do this too. >> Rich > > String concatenation is not that lame, but I'd use tuples: > MY_DICT[(KEY_X, KEY_Y, KEY_Z)] = FOO > > Tuples save on string operations. I would omit the extra parentheses here, but its a style thing. MY_DICT[KEY_X, KEY_Y, KEY_Z] = FOO (Note to original poster: I'd also turn off caps-lock) From cmichaelbeck at hotmail.com Wed Jan 28 12:56:27 2004 From: cmichaelbeck at hotmail.com (mike beck) Date: 28 Jan 2004 09:56:27 -0800 Subject: Nested lists or conditional logic? Message-ID: this is not all complex, but as a noob i'm having a hard time getting my head around it. i have a list of items. i need to print the items in batches of x, with a summary line after each complete or partial batch, and a total line at the end of the job. if the list looks like ['line1','line2','line3'], and my ITEMSINBATCH = 1, the output should look like this: line1 ---summary line--- line2 ---summary line--- line3 ---summary line--- ---total line--- if ITEMSINBATCH = 2, the output should look like this: line1 line2 ---summary line--- line3 ---summary line--- ---total line--- i've done the following, which works, but it seems like there must be a better/simpler/faster way to do this with nested loops. ideas? # ---------------------Begin code--------------------- ITEMSINBATCH = 1; ARBITRARYNUM = 51; # create a list to work with myList = ['1']*ARBITRARYNUM; for i in range( len(myList) ): # avoid starting at 0 count = i + 1; print "The item is:",myList[i],'\t',count; # ensure that the batch summary line is printed every ITEMSINBATCH # times but not if the number of items is evenly divisible by # ITEMSINBATCH, in which case both the inner print and the outer # print would execute and we'd get consecutive batch summary lines if ( (count) % ITEMSINBATCH ) is 0 and count != len(myList):: print "-----Add batch summary line-----"; # add a final batch line for those trailing items print "------Add batch summary line------And BTW, i is", count; # and add the final summary line print "------Add file summary------"; # ---------------------End code--------------------- TIA, mike From klapotec at chello.at Fri Jan 16 04:25:39 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 16 Jan 2004 09:25:39 GMT Subject: data structures module References: <92c59a2c.0401152306.1c6a17f5@posting.google.com> Message-ID: <0bbf00pbp7a4ng7ljpd752kr4v4r21kq7v@4ax.com> On 15 Jan 2004 23:06:44 -0800, jcb at iteris.com (MetalOne) wrote: >I am fairly new to Python. >Today, I wanted a priority queue. >I notice that Python does not have any sorted lists. The standard library has modules Queue and bisect - go look them up in the docs (online: http://www.python.org/doc/current/lib/module-Queue.html and http://www.python.org/doc/current/lib/module-bisect.html ). These should be what you're looking for. -- Christopher From robin at jessikat.fsnet.co.uk Mon Jan 12 07:49:18 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 12 Jan 2004 12:49:18 +0000 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <7xbrp9h4xs.fsf@ruckus.brouhaha.com> Message-ID: In article <7xbrp9h4xs.fsf at ruckus.brouhaha.com>, Paul Rubin writes >Robin Becker writes: >> 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. >> >>> from __future__ import division >> >>> eval('1/2') >> 0.5 >> >>> >> I guess I'm 'broken' :) -- Robin Becker From francisgavila at yahoo.com Mon Jan 19 22:53:47 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 19 Jan 2004 22:53:47 -0500 Subject: speedy Python strings? References: Message-ID: <100p9kl96uri9e1@corp.supernews.com> Stuart D. Gathman wrote in message ... ># text = struct.unpack("L", self.buffer[:4]) ># self.buffer = self.buffer[4:] > pos = self.pos > text = struct.unpack("L", self.buffer[pos:pos+4]) > self.pos = pos + 4 In this vein, I would also recommend looking at the array module. You didn't describe the data structure, but if each record is simply a list of 4-byte integers, you could convert the whole record to ints at once like so: record = array.array('L', stringorlist) Then, perform your loops on record, which will be a list-like object supporting item insertion and deletion, and conversion to bytestrings and other Python base types. Or, you could simply use array.array() to implement your buffer more efficiently than continually calling struct. Simply buffer the converted data a chunk at a time, using array. However, I don't think buffering helps much in this case. File operations are already buffered by Python, and most (all?) OSes buffer reads themselves, too. Reading a file is almost always very fast. I would concentrate more on presenting a useful abstraction for your data, rather than worrying about what is essentially an optimization problem. -- Francis Avila From HAALrvanderhWEG at xs4all.nl Thu Jan 22 09:41:49 2004 From: HAALrvanderhWEG at xs4all.nl (Rik van der Helm) Date: Thu, 22 Jan 2004 15:41:49 +0100 Subject: newbie,cgi,os.system,cdrecord References: <400fe08c$0$326$e4fe514c@news.xs4all.nl> Message-ID: <400fe106$0$326$e4fe514c@news.xs4all.nl> Rik van der Helm wrote: > but I get an 'Internal Server Error' of Python I meant Apache ! From peter at engcorp.com Tue Jan 20 11:46:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Jan 2004 11:46:00 -0500 Subject: Delayed evaluation and setdefault() References: <400C25FF.A76B1FEA@engcorp.com> Message-ID: <400D5B48.9F69A788@engcorp.com> Aahz wrote: > > In article <400C25FF.A76B1FEA at engcorp.com>, > Peter Hansen wrote: > >Leo Breebaart wrote: > >> > >> >>> d.setdefault('foo', b()) > >> then b() *does* get executed regardless of whether or not the > >> value it returns is actually used ('foo' was not found) or not > >> ('foo' was found). > >> > >> So I guess my question is twofold: one, do people think > >> differently, and if so why?; and two: is there any elegant (or > >> other) way in which I can achieve the delayed evaluation I desire > >> for setdefault, given a side-effect-having b()? > > > >def lazysetdefault(dict, key, ref): > > if not dict.has_key(key): > > dict[key] = ref() > > return dict[key] > > First of all, Peter made a boo-boo in naming a parameter ``dict``. Oops... I was, uh, writing pseudo-code, not Python! Yeah, that's it... -but-at-least-it-would-have-executed-ly yr's, Peter From tjreedy at udel.edu Fri Jan 9 21:25:02 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Jan 2004 21:25:02 -0500 Subject: displaying extended ASCII from a telnet session References: Message-ID: "Christian Wilcox" wrote in message news:mailman.229.1073667874.12720.python-list at python.org... >I'm trying to programmatically access information from a telnet session which is >normally accessed with a telnet program capable of terminal emulation (currently set at >VT320). The initial login text displays fine, of course, but when I get to the section >which displays extended ASCII characters, Telnet from telnetlib displays the following >garbled mess: There may or may not be any 'extended' chars, but there are 'undisplayable' chars, signaled by most of the '?'s (although a few might be real). The '?' before '[' is the Escape char (what the Esc key on upper left generates.). What follows are VTxxx escape sequences, which often start with [. >?[?40h?[?3l?[0;1m?>?[?1l?[?25l?[?3l?[0;0H?[2J?[?25l?(B??[0;7m?[23B ba6.0 version 03-1993/R1 ?[0m?[0; ..... >Any ideas of a way to decode this information? Since the escape sequences are about visual formating and not about content, you probably do not need to as long as you can recognize and discard what for you may really be noise. To make it easier, you might be able to the the system that you are a really dumb pre-VT100 terminal that only understands control chars and not the newer (as of about 2 decades ago) control sequences. On *nix, this might just mean resetting the TERM environment variable. But some programs might only talk to clients that are VT100 capable. Another route entirely. Terminal and telnet programs often have a script capability with commands like "when you receive 'sometext', send 'mytext'" and others to turn saving to a disk file on and off. Or, if you can install programs on the target, perhaps you can get at the info directly withoug virtual screen scraping and just email yourself a file in the format you want. Terry J. Reedy From computer.problemen at skynet.be Sat Jan 10 14:26:26 2004 From: computer.problemen at skynet.be (broebel) Date: Sat, 10 Jan 2004 20:26:26 +0100 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> <7xfzen3ayb.fsf@ruckus.brouhaha.com> Message-ID: <40005e17$0$6084$ba620e4c@news.skynet.be> If you look at this as a homework or not is of no interest to me but I like the way you explained which way to go to find the resolution. thanks (i solved it in a jiffy now) "Paul Rubin" schreef in bericht news:7xfzen3ayb.fsf at ruckus.brouhaha.com... > That sounds like a homework problem, so rather than write the code for > you, here's a hint -- use another variable, and update it every time > you decide how many coins of any specific size you'll use. From tdelaney at avaya.com Wed Jan 28 18:13:09 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 29 Jan 2004 10:13:09 +1100 Subject: comparing booleans Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE011DB0AE@au3010avexu1.global.avaya.com> > From: Gerrit Holl > > is it proper to compare booleans? It is possible, of course, because > they're compatible with numbers, but booleans aren't truly > numbers. Actually, they *are* really numbers ... >>> isinstance(True, int) True >>> isinstance(False, int) True >>> True == 1 True >>> False == 0 True >>> True == 2 False Note the last case - you can't just compare any true value with True and expect that the comparison will compare True - it must explicitly equal 1 (or True). Likewise with False. However, if `extends` is definitely boolean in your example, then it's perfectly reasonable to do: return cmp(self.extends, other.extends) if you want False to be considered less than True. Tim Delaney From bwglitch at hotpop.com Thu Jan 22 17:49:54 2004 From: bwglitch at hotpop.com (BW Glitch) Date: Thu, 22 Jan 2004 17:49:54 -0500 Subject: Ordered dictionary? In-Reply-To: <09XPb.234$af7.167008@newshog.newsread.com> References: <09XPb.234$af7.167008@newshog.newsread.com> Message-ID: Leif K-Brooks wrote: > Josiah Carlson wrote: > >>> I need to associate a string (key) with an integer (value). A >>> dictionary would do the job, except for the fact that it must be >>> ordered. I also need to look up the value for a specific key easily, >>> so a list of tuples wouldn't work. >> >> >> >> How must the dictionary be ordered? Do you need the keys or the >> values sorted? > > > Sorry for not making that clear, I need it sorted by the order of > insertion. Looks like > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 might do > what I want... That should do. Looks promising, but I think it uses the old style of extending the dictionary (Not that it's bad) ... -- Glitch http://andres980.tripod.com/ One good shot is worth a hundred bad ones! -- Big Shot (G1) From randall at tnr.cc Fri Jan 2 16:30:11 2004 From: randall at tnr.cc (Randall Smith) Date: Fri, 02 Jan 2004 21:30:11 GMT Subject: how to import a module dynamically In-Reply-To: <3ff5dc88$0$318$e4fe514c@news.xs4all.nl> References: <3ff5dc88$0$318$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Randall Smith wrote: > >> How do I import a module when given the module name as input? > > > >> import modname > > > exec "import "+your_module_name > > >> from modname import * > > > exec "from %s import %s" % (your_module_name, your_imported_symbol) > > HTH, > Irmen. > thanks From james at logicalprogression.net Wed Jan 28 12:34:46 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 28 Jan 2004 17:34:46 +0000 Subject: Curious string behavior In-Reply-To: <000001c3e5c3$5a63a8d0$5501a8c0@markxp> References: <000001c3e5c3$5a63a8d0$5501a8c0@markxp> Message-ID: <200401281734.46219.james@logicalprogression.net> On Wednesday 28 January 2004 5:22 pm, mark wrote: > I've encountered an anomaly while using the string module (specifically, > string.split). Here's the snippet: > > import string > > address2 = ' ' > line = 'function, dealer, type, firstname, lastname, vin, blank' > print 'Address2 Type (first check): ', type(address2) > function, dealer, type, firstname, lastname, vin, blank = > string.split(line, ',') > print 'Address2 type (second check): ', type(address2) > > I've extracted this from a larger script, but the error happens roughly > the same way. Now, here's what I would expect to see: > > Address2 Type (first check): > Address2 type (second check): > > Here's what I get instead: > > Address2 Type (first check): > Address2 type (second check): > Traceback (most recent call last): > File > "C:\PROGRA~1\Python\lib\site-packages\Pythonwin\pywin\framework\scriptut > ils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Program Files\Python\test1.py", line 7, in ? > print 'Address2 type (second check): ', type(address2) > TypeError: 'str' object is not callable > > What the heck is going on here? I figure I'm just missing something. You've masked the function "type" with a string called "type", the value of which is " type". James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From rmkrauter at yahoo.com Fri Jan 23 23:33:46 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri, 23 Jan 2004 23:33:46 -0500 Subject: Batch commands on Windows In-Reply-To: References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <1074918825.4458.144.camel@vaio> Each of your system calls spawns it's own separate shell with its own set of environment variables. You probably want to look into os.environ (python) or %ENV (perl) to set your shell variables. On Fri, 2004-01-23 at 23:23, Moosebumps wrote: > > Can you give an example of what you mean, in Perl as well as what you > hoped > > would work in Python? I couldn't quite understand what it is that you're > trying > > to do. > > OK, actually on second test, the problem is mostly with IDLE, but not > totally. When I hit F5 under IDLE, it behaves differently with respect to > the command window then if I just run it by double-clicking on the file. > > Here is an example: > > BatchTest.bat: > > set MYVAR=3 > dir > pause > dir > echo %MYVAR% > pause > > BatchTest.py: > > # the intention is to do the same thing as BatchTest.bat, but it doesn't > work under either IDLE or by double-clicking > # in particular the environment variable is not saved, and it doesn't work > if I replace os.system with os.popen > > import os > > os.system("set MYVAR=3") > os.system("dir") > os.system("pause") > os.system("dir") > os.system("echo %MYVAR%") > os.system("pause") > > BatchTest.pl: > > # this actually does the same thing as Python, I was mistaken. I was > mislead by the IDLE behavior. > > system('set MYVAR=3'); > system('dir'); > system('pause'); > system('dir'); > system('echo %MYVAR%'); > system('pause'); > > The general idea is that it would be nice if there weren't any differences > between the batch file and python. From a practical standpoint, it would > encourage a lot of people to switch from nasty batch files to Python scripts > if you could just surround the entire thing with os.batch(' ') or some > similar sort of mechanical textual substitution. Then you could clean it up > gradually. > > I am aware of os.environ and such, and that is useful, but it's not really > the point. > > Of course I could write a function to take a bunch of strings, write a batch > file, save the working directory, execute it, restore the current directory, > then delete the batch file, but that seems like an awful hack. Though I > probably will do that at some point. > > > > What's the deal with that? I thought Python started out as a scripting > > > language. And that seems like the most basic thing that a scripting > > > language should do. > > > > Dunno, although MS-DOS shell scripting is certainly a small subset of > scripting > > in general. Maybe with a concrete example somebody will be able to give > you a > > hand. > > It is a small subset, but an important subset. Shell scripting started > probably when people got sick of typing the same commands into the prompt. > For a language to really support shell scripting, it should provide a way of > automating the process of typing in the commands. As in, there should be no > difference whether you're actually typing, or you're running the script. > > If there is a way and I don't know about it, I would be happy to hear about > it. But I do think it is a pretty big hole. > > MB > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric.brunel at N0SP4M.com Mon Jan 19 05:38:52 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 11:38:52 +0100 Subject: Looking for very simple general purpose tokenizer References: Message-ID: Maarten van Reeuwijk wrote: > Hi group, > > I need to parse various text files in python. I was wondering if there was a > general purpose tokenizer available. I know about split(), but this > (otherwise very handy method does not allow me to specify a list of > splitting characters, only one at the time and it removes my splitting > operators (OK for spaces and \n's but not for =, / etc. Furthermore I tried > tokenize but this specifically for Python and is way too heavy for me. I am > looking for something like this: > > > splitchars = [' ', '\n', '=', '/', ....] > tokenlist = tokenize(rawfile, splitchars) > > Is there something like this available inside Python or did anyone already > make this? Thank you in advance You may use re.findall for that: >>> import re >>> s = "a = b+c; z = 34;" >>> pat = " |=|;|[^ =;]*" >>> re.findall(pat, s) ['a', ' ', '=', ' ', 'b+c', ';', ' ', 'z', ' ', '=', ' ', '34', ';', ''] The pattern basically says: match either a space, a '=', a ';', or a sequence of any characters that are not space, '=' or ';'. You may have to take care beforehands about special characters like \n or \ (very special in regular expressions) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From aahz at pythoncraft.com Fri Jan 2 19:19:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2004 19:19:55 -0500 Subject: Keyboard browsing (was Re: ANN: Python Language Reference) References: Message-ID: In article , Mark 'Kamikaze' Hughes wrote: >Will Stuyvesant >wrote on 29 Dec 2003 01:09:18 -0800: >> [Aahz] >>> >>> That's why you should use Lynx. Then you don't have any options. ;-) >> >> But isn't Lynx text-only? I want to see the pics! Even though I am >> not the kind of pervert that want to do things to them with the mouse. > > Opera can be completely keyboard-driven. And to search, you can type >/TEXT, just like you would in lynx or any other proper viewing or >editing tool. Really? That's not in my Opera/Linux 6.1. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From shian5.bbs at wretch.csie.nctu.edu.tw Sun Jan 11 09:31:49 2004 From: shian5.bbs at wretch.csie.nctu.edu.tw (¯u¤ß) Date: 11 Jan 2004 14:31:49 GMT Subject: delete file with zipfile Message-ID: <4ADeXb$9SJ@wretch.csie.nctu.edu.tw> ? ???No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster)????? > Hi ! > Please, I beseech you, I beg you, to look at this URL : > http://mclaveau.com/ress/python/zipmci.htm > @-salutations Thanks your share Although i can not read French, i thought Python is our language :D -- ????????????????????????????????????? ?????BLOG http://wretch.twbbs.org/blog ???? ????? ????? ????????????????????????????????????? ????????????????????????????????????? ???????????????????218-166-150-104.HINET-IP.hinet.net? From csgcsg39 at hotmail.com Fri Jan 9 11:06:12 2004 From: csgcsg39 at hotmail.com (CSG) Date: 9 Jan 2004 08:06:12 -0800 Subject: ZSI and faults Message-ID: <592ab9dd.0401090806.30cdbba@posting.google.com> Dear All, I'm very new to python/ZSI and have a (simple) query to ask. I have a simple client: from ZSI.client import Binding fp=open('debug.out','w') b=Binding(url='somewhere',tracefile=fp) print b.connect('usename') fp.close() and a server of from ZSI import * import sys def connect(usename): try: except Exception,e: sys.exit(1) The trouble I'm having is with the . I've tried things like: FaultFromException(e,0).AsSOAP(sys.stdout) or f=Fault() f.code="some message" with no success. Any suggestions Many thanks Colin From tzot at sil-tec.gr Thu Jan 15 04:39:55 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 15 Jan 2004 11:39:55 +0200 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <4003cfeb$0$19263$626a54ce@news.free.fr> Message-ID: On Tue, 13 Jan 2004 12:21:00 +0100, rumours say that Bruno Desthuilliers might have written: > >Woops ! The problem with Perl is actually that it's more or less a >write-only language !-) > I think you mean Perl is a WORN language (Write Once, Read Never). -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From philh at invalid.email.address Mon Jan 12 05:02:08 2004 From: philh at invalid.email.address (phil hunt) Date: Mon, 12 Jan 2004 10:02:08 +0000 Subject: easibox-0.3.0 released Message-ID: I've just released version 0.3.0 of my Easibox program, which is used to automate the creation of archive files (tar, tar.gz, tgz, tar.bz2 and zip formats), typically for open source projects. Version 0.3.0 adds two new features to Easibox: * I've added the ability to make .tar.bz2 archive files. (Suggested by Andr? Simon). * I've included the ability for the project's .easiboxrc file to automatically process archive files after creation, for example by copying them to a web directory. This is described in more detail in my article "New directions for Easibox": Easibox is written in Python and licensed under the GNU General Public License; see file COPYING (which comes with the distribution) for details. Release notes for the latest version of Easibox: The Easibox home page: -- "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 cjensen at soapfire.com Tue Jan 20 17:04:22 2004 From: cjensen at soapfire.com (Christian Jensen) Date: Tue, 20 Jan 2004 22:04:22 GMT Subject: XML-RPC References: Message-ID: Personally, I have gone down this path and have found that using mod_python is a MUCH better way to go. "Jonathan Daugherty" wrote in message news:mailman.557.1074635333.12720.python-list at python.org... > I'm using python 2.3.3 (#2, Jan 4 2004, 12:24:16), [GCC 3.3.3 20031229 > (prerelease) (Debian)], debian unstable. I have written a client and > server program which communicate using the built-in xmlrpclib and > SimpleXMLRPCServer. The server starts up fine, and the client can > connect to it and issue commands (method calls) just fine. However, > after some unknown period of time, the client hangs at the time of the > method call, during which time netstat reports: > > recv send > tcp 307 0 127.0.0.1:9000 127.0.0.1:35496 ESTABLISHED > > Once I break the client and run netstat again, I get: > > tcp 307 0 127.0.0.1:9000 127.0.0.1:35496 CLOSE_WAIT > > And lines such as these hang around in netstat's output for quite some > time (several are there now, left over from attempts to run the client > about 8 hours ago). I haven't been able to identify exactly when this > starts to occur or why. Sometimes it happens soon after starting the > server; sometimes it takes days. > > The server is multi-threaded. The XML-RPC thread is the main thread. > Proper locking mechanisms are used and I have been able to determine > that deadlock is not an issue. > > Does anyone have any ideas? > > Thanks! > > -- > > Jonathan Daugherty > http://www.cprogrammer.org > > "It's a book about a Spanish guy called Manual, you should read it." > -- Dilbert > From bkelley at wi.mit.edu Thu Jan 8 12:39:29 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 08 Jan 2004 12:39:29 -0500 Subject: MySQLDB multiple cursor question In-Reply-To: References: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu> <3ffd7dbe$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3ffd9567$0$559$b45e6eb0@senator-bedfellow.mit.edu> Dennis Lee Bieber wrote: > f The DB-API specifies a common method for accessing data -- this means > "cursors". > > MySQL itself does not implement that type of cursor. > > Therefore, MySQLdb has to emulate cursors locally. That emulation may > be tied to one per connection (or, at least, one active per connection > -- maybe doing a conn.commit()?) [This is all hypothesis at this time] Guess I'll have to crack open the mysqldb source code and fire up a debugger. The main problem with using multiple connections is that I have to cache the user's password in order to repoen the connection which makes me feel very queasy. The error is very reproducible but that fact that it works sometimes and not others means that it is probably a bug in mysqldb. Brian From fumanchu at amor.org Thu Jan 15 01:05:46 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 14 Jan 2004 22:05:46 -0800 Subject: Bug or feature? Message-ID: Alexey Nezhdanov wrote: > Hello. Found a strange python behaivoir while writing some > object. I've > stripped out all other stuff so the problem is stright here: > ================================= > #!/usr/bin/python > > class Object: > def __init__(self,val): > self.val=val > > def Sub(self,delta): > self.val-=delta > return delta > > c=Object(1) > > ### case 1 ### > d=c.Sub(1) > c.val+=d > print 'case A:',c.val > > ### case 2 ### > c.val+=c.Sub(1) > print 'case B:',c.val > ================================= > Case 1 and case 2 prints out different calues (1 and 2 respectively). > Do not know - if this is a bug or feature of python. Disassembly is your friend: >>> def pluseq(inst): ... inst.val += inst.Sub(1) ... >>> dis.dis(pluseq) 2 0 LOAD_FAST 0 (inst) 3 DUP_TOP 4 LOAD_ATTR 1 (val) 7 LOAD_FAST 0 (inst) 10 LOAD_ATTR 2 (Sub) 13 LOAD_CONST 1 (1) 16 CALL_FUNCTION 1 19 INPLACE_ADD 20 ROT_TWO 21 STORE_ATTR 1 (val) 24 LOAD_CONST 0 (None) 27 RETURN_VALUE >>> def subthenplus(inst): ... d = inst.Sub(1) ... inst.val += d ... >>> dis.dis(subthenplus) 2 0 LOAD_FAST 0 (inst) 3 LOAD_ATTR 1 (Sub) 6 LOAD_CONST 1 (1) 9 CALL_FUNCTION 1 12 STORE_FAST 1 (d) 3 15 LOAD_FAST 0 (inst) 18 DUP_TOP 19 LOAD_ATTR 3 (val) 22 LOAD_FAST 1 (d) 25 INPLACE_ADD 26 ROT_TWO 27 STORE_ATTR 3 (val) 30 LOAD_CONST 0 (None) 33 RETURN_VALUE As you can see, the order of evaluation in pluseq() is: load val, call Sub(), add, store result. whereas the order in subthenplus() is: call Sub(), load val, add, store result. ...which explains things a bit. If we had written inst.val = inst.val + inst.Sub(1), the order would be the same as pluseq (but we'd get a binary add instead of inplace). Robert Brewer MIS Amor Ministries fumanchu at amor.org From cfox at cfconsulting.ca Sat Jan 10 16:15:10 2004 From: cfox at cfconsulting.ca (Colin Fox) Date: Sat, 10 Jan 2004 21:15:10 GMT Subject: LC_MONETARY formatting References: <3FFF38DE.1050603@v.loewis.de> Message-ID: On Sat, 10 Jan 2004 16:12:10 +0300, Serge Orlov wrote: >> In my case, I have >> numbers that are always in either Canadian or US dollars, so the dollar >> sign is fine, and the thousands-separator value is fine. > > You should have money class. It should be a subclass of FixedPoint class. > If you want to deal with Canadian or US dollars only it's as simple as: > class Dollars(FixedPoint): > def __init__(self,amount): > super(Dollars,self).__init__(amount) > def __str__(self): > if self < 0: > return locale.format("-$%.2f",-self,True) > else: > return locale.format("$%.2f",self,True) > > > No warranty, of course, that it works and fulfills all your needs. >>>> locale.format("$%.2f",1000000000000,True) > '$1,000,000,000,000.00' Thanks, the locale.format() function indeed does what I need. However, my understanding of it is that it uses the LC_NUMERIC locale info, rather than the LC_MONETARY. For my purposes, this is certainly sufficient. I'd like to use a class, but since this is part of a Zope application, that's a little difficult (and overkill for this particular need). It would be nice if we could have something like: locale.format("%m",1000000,True,locale.LC_MONETARY) though as is indicated in the strfmon docs, it wouldn't be quite so simple (taking into account the different types of currency markers, padding, spacing, etc). cf From max at alcyone.com Sun Jan 4 16:15:37 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 04 Jan 2004 13:15:37 -0800 Subject: Problems compiling python References: Message-ID: <3FF88279.33BF192A@alcyone.com> Florian Lindner wrote: > I want to compile that small python script: ... > bastet:/ # chmod u+x test.pyc > bastet:/ # ./test.pyc > ./test.pyc: line 1: syntax error near unexpected token `;' > '/test.pyc: line 1: `;?? > bastet:/ # > > What is wrong? A compiled Python file (.pyc) is not an executable. (Specifically, in the Unix world, it does not contain a bangpath.) Instead, just pass it as an argument to the Python interpreter: max at oxygen:~/tmp% cat > hello.py print "Hello, world!" ^D max at oxygen:~/tmp% python Python 2.3.3 (#1, Dec 22 2003, 23:44:26) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import py_compile >>> py_compile.compile('hello.py') >>> ^D max at oxygen:~/tmp% ls hello.py* hello.py hello.pyc max at oxygen:~/tmp% rm hello.py max at oxygen:~/tmp% python hello.pyc Hello, world! -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Granted that I must die, how shall I live? -- Michael Novak From shoot at the.moon Thu Jan 8 16:32:47 2004 From: shoot at the.moon (Steve Horsley) Date: Thu, 08 Jan 2004 21:32:47 +0000 Subject: [OT] Database reporting software Message-ID: I have an existing system working on MS Access, and software that regularly logs events into it (and deletes old events after a year). Now need to move to real servers, probably Solaris though possibly Linux. Modifying the software to update the database (maybe mySQL or Oracle) contents is easy enough, but how do I produce reports (statistics and summaries) on the database contents? I could contemplate web based or application based report generation, but are there easy to use draggy-droppy report designing applications around? Just the names would enable me to look them up. I am struggling with OpenOffice.org at the moment, trying to see if it can do what I'm looking for, but it doesn't seem to be able to do GROUP BY and SUM() - simple aggregation stuff. All suggestions would be very welcome. Steve From skip at pobox.com Thu Jan 1 01:02:01 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 1 Jan 2004 00:02:01 -0600 Subject: Python Job Market In-Reply-To: References: Message-ID: <16371.47065.615397.279787@montanaro.dyndns.org> Samuel> |Thus Spake Dave Brueck On the now historical date of Wed, 31 Dec 2003 Samuel> 09:47:31 -0700| >> From what I've seen the market is definitely growing, but if you're >> hunting job listings for an all-Python job the pickings are pretty >> slim. Samuel> *sigh* I know. I didn't ask my question here without first Samuel> searching around to see what was being asked for. It was not Samuel> encouraging. I meant to reply earlier. The slimness of the pickings means if you are adamant about using Python, you may well wind up writing Python programs for application areas you're not particularly interested in. I think I'd rather find something I'm interested in then use Python where possible, like so: >> The easiest way to use Python in your job will probably be if you >> introduce it to the company yourself and then use it as the >> opportunities arise As it turns out my current day job is as essentially a system administrator. I try to turn it into an application programming job at every opportunity, and fortunately my management doesn't really care what I use. Skip From cfox at cfconsulting.ca Fri Jan 9 17:19:09 2004 From: cfox at cfconsulting.ca (Colin Fox) Date: Fri, 09 Jan 2004 22:19:09 GMT Subject: LC_MONETARY formatting Message-ID: Hi, all. This feels like a stupid question to me, but I've scoured the Internet (yes, the whole thing! :) and I can't find a single example of using the locale module to format money. So I have: cash = 12345.6 and the locale is set to "en_CA" (though that doesn't matter, really). I would like to be able to print "$12,345.60" Is there a format string, or function, or *something* that will take advantage of the monetary formatting info in the locale object? Or did they provide all that formatting information just so that I have to write it myself? The only docs on using the locale object contain a single example of comparing two strings. It would sure be nice to see examples of each of the locale features. Any help would be GREATLY appreciated! Thanks, cf From trentm at ActiveState.com Wed Jan 28 16:19:11 2004 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 28 Jan 2004 13:19:11 -0800 Subject: Cross Platform Browser Launcher In-Reply-To: <8089854e.0401280118.2f07fb65@posting.google.com>; from michael@foord.net on Wed, Jan 28, 2004 at 01:18:21AM -0800 References: <8089854e.0401280118.2f07fb65@posting.google.com> Message-ID: <20040128131911.B11615@ActiveState.com> [Fuzzyman wrote] > I've written a simple application in python with an HTML help file. > > I'm looking for a cross platform way of launching the help file. http://www.python.org/doc/current/lib/module-webbrowser.html Cheers, Trent -- Trent Mick TrentM at ActiveState.com From skip at pobox.com Wed Jan 21 19:35:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 21 Jan 2004 18:35:51 -0600 Subject: Secure Voting software In-Reply-To: <20040121174434.28446.00000428@mb-m15.aol.com> References: <20040121174434.28446.00000428@mb-m15.aol.com> Message-ID: <16399.6887.17955.538485@montanaro.dyndns.org> allen> Listening to National Public Radio while reading allen> comp.lang.python. What a life! I just heard a piece on NPR about allen> the security failures of an electronic voting system being allen> developed. I know a voting system could be developed in python. I allen> am working on a simulator myself to run via the web (a personal allen> project only) allen> Are there any features which would make python a viable allen> alternative to develop a real voting system for use in the US? allen> Why or why not? allen> What things must I keep in mind when I design a python allen> application to be secure? allen> Since python is developed using C, can python be free from the allen> buffer overrun problems which plague other C programs? Yes, to a great extent, because you need to find buffer overrun possibilities in the Python interpreter, but not in every Python application. As for voting projects, check out: http://gnosis.python-hosting.com/voting-project/ Python is the development language I believe. I haven't followed it in a couple months. Skip From michael at foord.net Mon Jan 19 07:36:52 2004 From: michael at foord.net (Fuzzyman) Date: 19 Jan 2004 04:36:52 -0800 Subject: Tk Icon - request to Fredrik Lundh Message-ID: <8089854e.0401190436.10f99713@posting.google.com> There is a very interesting (and potentially useful) program on the effbot website - called Tkicon. http://www.effbot.org/downloads/ Unfortuantely the last supported version of python is 2.1 I've seen a few people asking, but never an answer, on Python 2.3 support. So a request to Fredrik to build a 2.3 distribution............ Also in his interesting PDF book "(the eff-bot guide to) The Standard Python Library" http://www.effbot.org/zone/librarybook-index.htm he mentions that you can download the example files... yet the link suggested doesn't point to it and I can't find it... any clues anyone ?? Fuzzball From mcfletch at rogers.com Fri Jan 9 18:19:11 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 18:19:11 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: <026e01c3d702$970ec5a0$6401fea9@YODA> References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> <026e01c3d702$970ec5a0$6401fea9@YODA> Message-ID: <3FFF36EF.90208@rogers.com> Dave Brueck wrote: >Peter wrote: > > ... >>This is my "straw poll" question: >> >> Do you spend a "significant" amount of time actually optimizing your >> Python applications? (Significant is here defined as "more than five >> percent of your time", which is for example two hours a week in a >> 40-hour work week.) >> >> > >Yay, straw poll! ;-) > > Indeed, yay ;) . I am often found optimising. The total time spent on it is probably somewhere around 1-2% of total (after all, I do still *use* Python, it's not like it's killing me). A lot of my projects are speed-sensitive (e.g. OpenGLContext trying to give interactive frame-rates in 3D scenegraph rendering, SimpleParse trying to create really fast parsers, web-sites trying to process 10s of thousands of records into summary views interactively), but I don't think I'm *that* far from the norm in the amount of time spent on optimisation. I'd be surprised if there's not some difference between the experience of library programmers and application programmers in this regard. Library developers tend to need to focus more effort on performance to allow users of the libraries some inefficiencies in their usage. That effort tends to be more in the planning stages, though, making sure you've chosen good algorithms, estimating work-loads and required throughput. You try to make sure the library is robust and fast by designing it that way, not by trying to optimise it after the fact. You plan for worst-case scenarios, and as a result you become "worried" about performance. An application developer is normally going to use optimised libraries and just run with it, only needing to deal with unacceptable performance if it happens to show up in their particular project. Anyway, back to it, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From john at reachin.se Fri Jan 23 05:47:28 2004 From: john at reachin.se (John McLaughlin) Date: 23 Jan 2004 02:47:28 -0800 Subject: Using python as client-side scripting language in IE 6 References: <7eecf173.0312160336.1160a340@posting.google.com> <3FE86415.DA6FFEBC@engcorp.com> Message-ID: <6142447d.0401230247.26670d49@posting.google.com> Hi, Yes I have this working. Do this at your own risk: Add the following to pyscript.py after the AXNotRExec class definition (around line 89): AXRExec = AXNotRExec Then register with python pyscript_rexec.py --debug ^^^^^^ (must be the rexec version). You may have to unregister any other versions first: python pyscript.py --unregister Cheers, -John Peter Hansen wrote in message news:<3FE86415.DA6FFEBC at engcorp.com>... > John Roth wrote: > > > > "popov" wrote: > > > I ran win32comext\axscript\client\pyscript.py and pyscript_rexec.py to > > > register python as a scripting engine. No errors from those scripts. > > > > > > As I understand it and from what I have read in this forum and > > > elsewhere, it should work, but it doesn't: what am I doing wrong ? > > > > I doubt if it will work for a while. It doesn't work on my system > > either, and a quick check of the pyscript_rexec.py module says > > that it will enable Rexec support. Rexec support was removed from > > base Python in release 2.2.3 and later, so I doubt if this is ever > > going to work until ActiveState (or Mark Hammond) changes the > > base code to use Exec instead of RExec. > > I was just trying this myself and had the same lack of results. > I note however that while pyscript_rexec.py uses the Rexec support > and might not work for reasons John describes, pyscript.py claims not > to do that, and seems to be supposed to work. Yet it doesn't.... > > Anyone tried this lately with success? > > For the record, I was trying on a vanilla Win98 machine with Py2.3.2.1 > and the latest win32all as well. (The relevant test scripts execute > okay, showing that the issue is with IE alone, not with the basic > capability that allows ActiveX script hosting with Python.) > > -Peter From skip at pobox.com Wed Jan 28 11:09:25 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 10:09:25 -0600 Subject: isinstance() bug In-Reply-To: References: Message-ID: <16407.57013.866123.204852@montanaro.dyndns.org> Sidharth> python is a dynamic language it figures out where modules are Sidharth> located at run time, it would be expensive to check all paths Sidharth> to see if they ended up at the same file. Maybe not: Help on function abspath in module posixpath: abspath(path) Return an absolute path. Considering all the other stuff import has to do, this seems like only a small extra bit of work. Skip From peter at engcorp.com Mon Jan 26 14:59:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Jan 2004 14:59:53 -0500 Subject: TELNET instead PING References: <5f505344.0401260332.184d4225@posting.google.com> Message-ID: <401571B9.F9DF99D0@engcorp.com> DCK wrote: > > Into group-archive i found most e-mails, which touches PINGing. > In my work i've used TELNET for testing if host is operational. > Sometimes, for unknown reasons, workstation doesn't respond > for PINGing. But in WinNT network, all hosts has a nbsession > listening on port 139. I always use this script instead PING > command (hope, will be usefull for someone :) ): Interesting, but why would you use TELNET for that? Telnet is simply one of many possible protocols, whereas you need only open a socket to the port to see if the host is responding. from socket import * s = socket(AF_INET, SOCK_STREAM) try: s.connect((host, port)) print 'host connected' s.close() except error: print 'host not responding' Should basically do the same job ... -Peter From tomas at fancy.org Thu Jan 15 11:37:12 2004 From: tomas at fancy.org (Tom Plunket) Date: Thu, 15 Jan 2004 08:37:12 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: Peter Ashford wrote: > It would just as dumb as me criticising you for not advancing OS > software - you've never intended to, don't care, so the criticism > would be stupid. Indeed, though, Brandon's mere existence is utterly worthless to all other developers in the world. ...at least using his characterizations of value-adding. -tom! From usenet_spam at janc.invalid Thu Jan 15 23:27:13 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 16 Jan 2004 04:27:13 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: amonroejj at yahoo.com (R. Alan Monroe) schreef: > In article , usenet at janc.cjb.net > wrote: > >>You think "cross-platform" means "it runs out-of-the-box on all >>possible platforms that ever existed, now exist, and will ever exist"? >> >>Please go searching and come back when you find 1 (one) program which >>fits that definition... :-p > > "Hello World"? :^) You know, some early computers couldn't even do things that simple. ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From lists at tomchance.org.uk Sun Jan 18 18:52:12 2004 From: lists at tomchance.org.uk (Tom Chance) Date: Sun, 18 Jan 2004 23:52:12 +0000 Subject: Plotting n-ary trees Message-ID: Hullo, I'm trying to plot a family tree in a way that can be displayed on a web page without recourse to clever javascript. The only solution I can think of is to plot a tree to a JPEG or PNG and embed it in the page, but I can't find any code that will do this, and I've not got the time nor the intelligence to be doing that sort of thing myself ;-) Can anyone suggest anything, other than using graphviz which isn't installed on my host's server. Regards, Tom From enrique.palomo at xgs-spain.com Tue Jan 20 06:04:55 2004 From: enrique.palomo at xgs-spain.com (Enrique) Date: Tue, 20 Jan 2004 12:04:55 +0100 Subject: python As400 Message-ID: <001e01c3df45$3d86ae80$6c010a0a@epalomo> Hello I'm very interested in python for AS/400. I must migrate an application that is running under windows to AS/400. Has anyone worked with python in that platform?? what about performace?? The scripts are basicly of string manipulation and i/o. any kind of information will be welcome. Thanks a lot. Enrique (Madrid) **AVISO DE CONFIDENCIALIDAD** La informaci?n contenida en este mensaje y archivos es privada y confidencial estando dirigida solamente al destinatario. Si Ud. ha recibido esta informaci?n por error, por favor, proceda a su inmediata destrucci?n. Cualquier opini?n o punto de vista contenido en este mensaje corresponde al remitente y necesariamente no representa la opini?n del GRUPO XEROX. From test at test.com Mon Jan 12 11:50:13 2004 From: test at test.com (D) Date: Mon, 12 Jan 2004 16:50:13 GMT Subject: TypeError with genCGI.py Message-ID: <9fAMb.217748$Vu5.16273229@twister.southeast.rr.com> Hello, We are using genCGI.py from the Internet Programming with Python book. We migrated to using Python 2.2.2 from 2.1.3 and we are now getting the following: Unhandled exception encountered. exceptions.TypeError File "/usr/ngasi/contexts/odomain/odomain/cgi-bin/genCGI.py", line 94, in GO form = self.get_form() File "/usr/ngasi/contexts/odomain/odomain/cgi-bin/genCGI.py", line 264, in get_form form = self.get_form_base(self) I notice that the month4.cgi example on the book site gets the same error: http://starship.python.net/crew/aaron_watters/cgi/month4.cgi Does anyone have any idea what the problem is or perhaps have a fix? Thanks, Dan Dan Snider Object Domain Systems Inc. http://www.objectdomain.com dsnider at objectdomain.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gumuz at looze.net Wed Jan 14 10:19:47 2004 From: gumuz at looze.net (Guyon Morée) Date: Wed, 14 Jan 2004 16:19:47 +0100 Subject: wxPython worries References: Message-ID: <40055e11$0$282$4d4ebb8e@news.nl.uu.net> I've got the same worries, but I'm still not really convinced... boa-constructor is nice... but not there yet "James Goldwater" wrote in message news:mailman.352.1074092092.12720.python-list at python.org... > I'm starting a new hopfully-commercial project soon, and I face a > dilemma about whether Python with wxPython would be appropriate. > > The project has 3 main areas: > > a) manipulation of lists and trees, using.. > b) a hopefully dead-sexy gui, all in order to... > c) eventually pump out certain bits of the datastructure over the > network in semi-realtime (< 10ms accuracy or so). > > The target is Win32 for now (98 - XP). Now, if it were up to me, I'd use > Delphi - it's what I know best. But I'm working with a less experienced > developer with whom I have no languages in common. He's keen to get > started on C#, I've toyed with C# and though it looks easy, I don't see > any major gains over what I already know. > > I've read a lot about python and done some mini-stuff in it, and been > impressed with it's ease and conciseness. What worries me is wxPython: > looking at the demo code, it's quite verbose and 'bitty'. I'm also > unclear as to how easy custom controls are to build. > > Am I just being confused by my newbie-ness, or are my initial concerns > justified? What's anybody else's experiences with gui programming in > wxPython like vs a RAD like Delphi or .NET? > > Thanks, > > James. > > From bdusauso at beeznest.NOSPAM.net Tue Jan 13 04:12:40 2004 From: bdusauso at beeznest.NOSPAM.net (Dusausoy Bruno) Date: Tue, 13 Jan 2004 10:12:40 +0100 Subject: id3v2 module Message-ID: Hi, I'd like to know if there is a third-party module for reading/writing id3v2 informations. Thanks From newsgroups at jhrothjr.com Tue Jan 20 11:17:16 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jan 2004 11:17:16 -0500 Subject: personal document mgmt system idea References: Message-ID: <100ql5oc1rctc09@news.supernews.com> I wouldn't put the individual files in a data base - that's what file systems are for. The exception is small files (and by the time you say ".doc" in MS Word, it's now longer a small file) where you can save substantial space by consolidating them. John Roth "Sandy Norton" wrote in message news:b03e80d.0401200538.10fcf33a at posting.google.com... > Hi folks, > > I have been mulling over an idea for a very simple python-based > personal document management system. The source of this possible > solution is the following typical problem: > > I accumulate a lot of files (documents, archives, pdfs, images, etc.) > on a daily basis and storing them in a hierarchical file system is > simple but unsatisfactory: > > - deeply nested hierarchies are a pain to navigate > and to reorganize > - different file systems have inconsistent and weak schemes > for storing metadata e.g. compare variety of incompatible > schemes in windows alone (office docs vs. pdfs etc.) . > > I would like a personal document management system that: > > - is of adequate and usable performance > - can accomodate data files of up to 50MB > - is simple and easy to use > - promotes maximum programmibility > - allows for the selective replication (or backup) of data > over a network > - allows for multiple (custom) classification schemes > - is portable across operating systems > > The system should promote the following simple pattern: > > receive file -> drop it into 'special' folder > > after an arbitrary period of doing the above n times -> run > application > > for each file in folder: > if automatic metadata extraction is possible: > scan file for metadata and populate fields accordingly > fill in missing metadata > else: > enter metadata > store file > > every now and then: > run replicator function of application -> will backup data > over a network > # this will make specified files available to co-workers > # accessing a much larger web-based non-personal version of the > # docmanagement system. > > My initial prototyping efforts involved creating a single test table > in > mysql (later to include fields for dublin-core metadata elements) > and a BLOB field for the data itself. My present dev platform is > windows XP pro, mysql 4.1.1-alpha, MySQL-python connector v.0.9.2 > and python 2.3.3 . However, I will be testing the same app on Mac OS X > and Linux Mandrake 9.2 as well. > > The first problem I've run into is that mysql or the MySQL > connector crashes when the size of one BLOB reaches a certain point: > in this case an .avi file of 7.2 mb . > > Here's the code: > > > > import sys, time, os, zlib > import MySQLdb, _mysql > > > def initDB(db='test'): > connection = MySQLdb.Connect("localhost", "sa") > cursor = connection.cursor() > cursor.execute("use %s;" % db) > return (connection, cursor) > > def close(connection, cursor): > connection.close() > cursor.close() > > def drop_table(cursor): > try: > cursor.execute("drop table tstable") > except: > pass > > def create_table(cursor): > cursor.execute('''create table tstable > ( id INTEGER PRIMARY KEY AUTO_INCREMENT, > name VARCHAR(100), > data BLOB > );''') > > def process(data): > data = zlib.compress(data, 9) > return _mysql.escape_string(data) > > def populate_table(cursor): > files = [(f, os.path.join('testdocs', f)) for f in > os.listdir('testdocs')] > for filename, filepath in files: > t1 = time.time() > data = open(filepath, 'rb').read() > data = process(data) > # IMPORTANT: you have to quote the binary txt even after > escaping it. > cursor.execute('''insert into tstable (id, name, data) > values (NULL, '%s', '%s')''' % (filename, data)) > print time.time() - t1, 'seconds for ', filepath > > > def main (): > connection, cursor = initDB() > # doit > drop_table(cursor) > create_table(cursor) > populate_table(cursor) > close(connection, cursor) > > > if __name__ == "__main__": > t1 = time.time() > main () > print '=> it took total ', time.time() - t1, 'seconds to complete' > > > > > > >pythonw -u "test_blob.py" > 0.155999898911 seconds for testdocs\business plan.doc > 0.0160000324249 seconds for testdocs\concept2businessprocess.pdf > 0.0160000324249 seconds for testdocs\diagram.vsd > 0.0149998664856 seconds for testdocs\logo.jpg > Traceback (most recent call last): > File "test_blob.py", line 59, in ? > main () > File "test_blob.py", line 53, in main > populate_table(cursor) > File "test_blob.py", line 44, in populate_table > cursor.execute('''insert into tstable (id, name, data) values > (NULL, '%s', '%s')''' % (filename, data)) > File "C:\Engines\Python23\Lib\site-packages\MySQLdb\cursors.py", > line 95, in execute > return self._execute(query, args) > File "C:\Engines\Python23\Lib\site-packages\MySQLdb\cursors.py", > line 114, in _execute > self.errorhandler(self, exc, value) > File "C:\Engines\Python23\Lib\site-packages\MySQLdb\connections.py", > line 33, in defaulterrorhandler > raise errorclass, errorvalue > _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone > away') > >Exit code: 1 > > > > My Questions are: > > - Is my test code at fault? > > - Is this the wrong approach to begin with: i.e. is it a bad idea to > store the data itself in the database? > > - Am I using the wrong database? (or is the connector just buggy?) > > > Thanks to all. > > best regards, > > Sandy Norton From miki.tebeka at zoran.com Sun Jan 11 12:36:36 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 11 Jan 2004 09:36:36 -0800 Subject: How to globalize vars ??? References: Message-ID: <4f0a9fdb.0401110936.76e8a2e6@posting.google.com> Hello, Warning: Fix not tested. > def SSInit(SessionDir): global SSDefaultDir # FIX > SSLock() > try: > if SSDefaultDir.strip()=="": > # <- > # UnboundLocalError: local variable 'SSDefaultDir' referenced before assignment > SSDefaultDir=SessionDir > finally: > SSUnlock() > Why ? How to force python to module see his variable ? By definition all new variables are local to their function. HTH. Miki From martin at v.loewis.de Sun Jan 25 13:27:22 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 Jan 2004 19:27:22 +0100 Subject: xrange not hashable - why not? In-Reply-To: References: Message-ID: Gerrit Holl wrote: > why is an xrange object not hashable? Because they don't have a notion of equality beyond identity. Regards, Martin From no at spam.invalid Thu Jan 15 15:02:46 2004 From: no at spam.invalid (Russell E. Owen) Date: Thu, 15 Jan 2004 12:02:46 -0800 Subject: Tcl/Tk Support References: <20040109201513.GC2810@unpythonic.net> Message-ID: In article , "Diego Ribeiro de Andrade" wrote: >Yeah! It Works Thanks. > > Everyone else told me that It was native in Python. May I did something >wrong in the installation of Red Hat9? I doubt you did anything wrong. RH9 seems to come with a python that has no Tkinter support, despite the fact that RH9 also includes tcl/tk. Personally I think it's good that Python has more than one GUI option, but a pity that it has no "native" GUI library that is sufficiently tightly integrated that a programmer can assume it will be present in any python installation. Tkinter is the closest thing Python has to such a standard, in that a source build automatically builds Tkinter if tcl/tk is available. But some OS vendors seem fond of leaving it out anyway (it is also missing in MacOS X). -- Russell From jcarlson at uci.edu Tue Jan 20 20:18:19 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 17:18:19 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> <20040120135921.1C3F.JCARLSON@uci.edu> <400c5790_1@newsfeed.slurp.net> <20040120150005.1C48.JCARLSON@uci.edu> <400c6146_1@newsfeed.slurp.net> Message-ID: <20040120171127.0606.JCARLSON@uci.edu> Here is an example set of interactions I did with my command line: Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\>cd "Documents and Settings" C:\Documents and Settings>cd jcarlson C:\Documents and Settings\jcarlson>cd Desktop C:\Documents and Settings\jcarlson\Desktop>cd .. C:\Documents and Settings\jcarlson>cd \ C:\>d: D:\>c: C:\> I hope that is enough of an example for you to figure out what is going on. As to which path you need to change to, it is wherever you decided to uncompress Spambayes. A few things to note. On Windows 2000/xp: C:\Documents and Settings\\Desktop is the default location of your desktop. c:\Documents and Settings\\My Documents is the default location of your 'My Documents' folder.. If this isn't enough, then Jeebus help you. - Josiah > I think that may be my problem. I am not sure how to change the path to > where the setup.py file is... > > > > That didnt work either and the file assoc. are correct. > > > > > > > If you are in windows and your associations are correct, try: > > > > setup.py install > > > > Steps for you to help us help you: > > 1. Open up a console. > > 2. Change to the proper path. > > 3. Run (without the single quotes) > > 'python setup.py install' > > if that doesn't work, try > > 'setup.py install' > > 4. Copy and paste the output in a message here. > > > > - Josiah > > > From gerrit at nl.linux.org Sat Jan 10 11:57:02 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 10 Jan 2004 17:57:02 +0100 Subject: De Zen van VDVL's Python In-Reply-To: <10009bujbbsn8b5@corp.supernews.com> References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com> <3fff1245@usenet01.boi.hp.com> <400018e8$0$294$ba620e4c@news.skynet.be> <10009bujbbsn8b5@corp.supernews.com> Message-ID: <20040110165702.GB17806@nl.linux.org> Francis Avila wrote: > Guido van Rossum created Python, and is currently its BDFL (Benevolent > Dictator For Life). He's Dutch. It's a sort of an inside joke that Python > makes sense if you're dutch (type 'import this' into an interactive Python > prompt). So he'r really the VDVL, Verlichte Despoot Voor het Leven :) Shouldn't the Zen of Python be translated? De Zen van Python, door Tim Peters vrij vertaald door ondergetekende Mooi is beter dan lelijk. Expliciet is beter dan impliciet. Simpel is beter dan complex. Complex is beter dan gecompliceerd. Plat is beter dan genest. Dun bezaaid is beter dan dicht bezaaid. Leesbaarheid telt. Speciale gevallen zijn niet speciaal genoeg om de regels te overtreden. Maar de praktijk gaat voor de zuiverheid. Foutmeldingen horen nooit genegeerd worden. Behalve expliciet. Weersta de verleiding tot raden bij onduidelijkheden. Er hoort een - bij voorkeur slechts een - duidelijke oplossing te zijn. Maar die lijkt misschien niet meteen duidelijk voor niet-Nederlanders. Beter nu dan nooit. Maar vaak is nooit beter dan *nu meteen*. Als het moeilijk is uit te leggen, is het een slecht idee. Als het makkelijk is uit te leggen, is het misschien een goed idee. Namespaces zijn een ... goed idee -- daar doen we er meer van! groetjes, Gerrit :). -- 185. If a man adopt a child and to his name as son, and rear him, this grown son can not be demanded back again. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From mwh at python.net Tue Jan 13 06:38:37 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 11:38:37 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <877jzwg1v2.fsf@pobox.com> <1006h25r6623m45@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: > In article <877jzwg1v2.fsf at pobox.com>, John J. Lee wrote: > . > [pages of marvelously > precise analysis] > . > . > >Eiffel: Design by contract. The book to read is Meyer's "Object- > > Oriented Software Construction". Full of interesting stuff, if you can > > stand his self-importance ;-). > . > . > . > Mostly I'm writing just to applaud--this post had a lot > of value to it. The largest quibble I could find in its > scores of lines was the failure to mention that *OOSC* > is valuable reading for OO programmers working in *any* > language, not just Eiffel. *OOSC* is like *SICP* in > that regards; it towers not just over the competition, > but also any apparent limit imposed by its language of > expression. I would also say that OOSC is one of those books that's at least as interesting when it's *wrong* than when it's right. Cheers, mwh -- You sound surprised. We're talking about a government department here - they have procedures, not intelligence. -- Ben Hutchings, cam.misc From CousinStanley at hotmail.com Fri Jan 16 17:16:00 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 16 Jan 2004 15:16:00 -0700 Subject: py2exe 0.5.0 (finally) released References: Message-ID: | http://starship.python.net/crew/theller/py2exe Thomas .... This is my first attempt at running any version of py2exe .... Using .... Win98_SE Python 2.3 Enthought Edition py2exe 0.50 The samples hello.py and test_wx.py in the simple folder function as expected when run as python scripts .... setup.py goes through the motions and creates the build and dist directories and the following files are produced in .... /simple/dist .... hello.exe library.zip python23.dll w9xpopen.exe wxc.pyd wxmsw24.dll _sre.pyd hello.exe will not run .... Could not locate script resource: The following Traceback from setup.py indicates that unicows.dll seems to be missing .... python setup.py py2exe > py2exe_simple.txt Traceback (most recent call last): File "setup.py", line 34, in ? console = ["hello.py"], File ".\distutils\core.py", line 149, in setup File ".\distutils\dist.py", line 907, in run_commands File ".\distutils\dist.py", line 927, in run_command File "K:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 197, in run self.create_binaries(py_files, extensions, dlls) File "K:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 391, in create_ binaries arcname, target.script) File "K:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 566, in build_e xecutable add_resource(unicode(exe_path), script_bytes, u"PYTHONSCRIPT", 1, True) RuntimeError: this function requires unicows.dll in the Python directory on Win 95/98/Me I found one version of unicows.dll that was previously installed with another program, OE-Quote-fix, and stuck it in the Python folder, but then Python page faulted from setup.py .... Will a different/current version of unicows.dll in the Python folder alieviate this problem ???? -- Cousin Stanley Human Being Phoenix, Arizona From omission9 at invalid.email.info Sun Jan 25 21:33:11 2004 From: omission9 at invalid.email.info (omission9) Date: Mon, 26 Jan 2004 02:33:11 GMT Subject: efficient updating of nested dictionaries Message-ID: I have a dictionary that looks like this MY_DICT[KEY_X][KEY_Y][KEY_Z]=FOO I am having a problem updating this with a simple MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting into the inner dicts. Getting the keys of each and iterating through and updating each one is terribly slow as the number of keys gets bigger and bigger. What is the bst way to update my nested dicts? From exarkun at intarweb.us Fri Jan 30 13:40:44 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Fri, 30 Jan 2004 13:40:44 -0500 Subject: Tcp/ip programs in python In-Reply-To: References: Message-ID: <20040130184044.GA30420@intarweb.us> On Fri, Jan 30, 2004 at 06:27:45PM -0000, M.Dikmen wrote: > Do you now a source about socket programming in python? or some source > codes, demo programs? i really need them > In order of increasing relevance: http://www.google.com/ http://www.vex.net/parnassus/ http://www.twistedmatrix.com/ Jp From merkosh at hadiko.de Tue Jan 20 19:14:51 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Wed, 21 Jan 2004 01:14:51 +0100 Subject: always the same object (2) Message-ID: Hi, sorry for the lack of source code. Here again: I use struct.unpack() to unpack data from a binary file and pass the returned tuple as parameter to __init__ of a class that's supposed to handle the data: class DataWrapper(): data = { } def __init__(self, arg): #arg will contain a tuple data['var1'], data['var2'] = arg result = [ ] while not : data = struc.unpack("4s4s", f.read(8)) record = DataWrapper( data ) # pass tuple from unpack result.append( record ) Then "result" contains a list with different objects, but the strings in data['var1'] and data['var2'] are all the same. Any ideas how to avoid this? Thanks again Ciao Uwe From sombDELETE at pobox.ru Sat Jan 24 13:00:17 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 24 Jan 2004 21:00:17 +0300 Subject: Perl vs. Python for text manipulation References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <871xpp1i8r.fsf@pobox.com> Message-ID: "Aahz" wrote in message news:buu7pq$i67$1 at panix1.panix.com... > In article , Serge Orlov wrote: > >"Ganesan R" wrote in message news:ou4qulnwy0.fsf at andlx-anamika.cisco.com... > >> > >> fileinput is not optimized yet, at least I don't remember any mails > >> about fileinput in python-devel since python 2.3 was released. I > >> know that it is slow. for line in file: does seem to be optimized > >> though. The last time I ran the tests python was definitely twice as > >> slow (which was before python 2.3 was officially released); now it > >> appears to be only about 40% slower. I need to revisit these crude > >> benchmarks. > > > >Since this problem is not IO bound but rather python internals bound, > >it makes sense to try psyco. > > Pysco won't help and might actually make things worse. Sorry, I was dreaming :) I was dreaming about the day when psyco can recognize the file use pattern and optimize the hell out it. Of course this optimization is not there at this time. > At this point, > Perl's speed advantage should come from two and only two sources: Perl > optimizes the snot out of platform I/O (so these speed tests don't apply > to a platform Perl hasn't been ported to), and Perl does not use the > thread-safe forms of I/O. Python does a fair amount of internal caching > to make up for that, and the file object is already written in C. I'm not sure I understand what does it mean "optimize the snot out of platform I/O"? You just use the bare bones non-caching API and do your own simple caching doing as little as possible. This will allow programs that work with files as streams (read sequentially a lot from one file, write sequentially to another) to run at top speed. Other access patterns may suffer but not very much. As for threads, is it required that after one thread .write() the other thread can immediately .read() what the first thread wrote? If not, threads can have separate caching. After all, doing I/O on the same file from multipile threads is uncommon so it can suffer. 99+ percent of I/O in the world is done from one thread, why should it suffer? -- Serge. From claird at lairds.com Thu Jan 15 08:16:35 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 15 Jan 2004 13:16:35 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <878yka2sze.fsf@pobox.com> <100bbekd61fbl53@corp.supernews.com> Message-ID: <100d4ljnic3l465@corp.supernews.com> In article , JanC wrote: >claird at lairds.com (Cameron Laird) schreef: > >>>Not sure what the goals were, but I'm not sure they were to compete >>>with Netscape and IE. CNRI funding -- "R" for research -- seems to > >> Certainly not the *original* goal, because Grail antedated those >> latecomers. > >My copy of Netscape 0.94beta for Windows has a file date of 1994-11-22. > >And from the Grail docs: >"Grail was started in August 1995 as a quick and dirty demo. It quickly >became a serious project, as witnessed by the release of version 0.2 in >November 1995, and again by the planned release of version 0.3 (currently >in beta) in June 1996." . . . Yikes! Good research--and I'm always in favor of that. I apologize for my error. It's certainly disquieting; I had such a strong memory that Grail was around in mid-'94 that I didn't verify the facts. What *was* I thinking about? Thanks for correcting the mistake. -- Cameron Laird Business: http://www.Phaseit.net From mwh at python.net Mon Jan 19 06:24:23 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 19 Jan 2004 11:24:23 GMT Subject: Where to post an article? References: <4f0a9fdb.0401181356.79a1ec87@posting.google.com> Message-ID: miki.tebeka at zoran.com (Miki Tebeka) writes: > Hello All, > > I have a little article I'd like to publish. > It's about how to use Python to repidly develop an assembler (2.5 days in my case). > > Can you recommend a site/paper to publish it? > > And yes, I have a web page... Well, how about there? Or you could try interesting pyzine.com in it... Cheers, mwh -- Linux: Horse. Like a wild horse, fun to ride. Also prone to throwing you and stamping you into the ground because it doesn't like your socks. -- Jim's pedigree of operating systems, asr From jepler at unpythonic.net Thu Jan 29 09:14:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 29 Jan 2004 08:14:49 -0600 Subject: popen2 with large input In-Reply-To: References: Message-ID: <20040129141449.GA18498@unpythonic.net> The connection to the child process created by the popen family have some inherent maximum size for data "in flight". I'm not sure how to find out what that value is, but it might be anywhere from a few bytes to a few K. So tr starts to write its output as it gets input, but you won't read its output before you've written all your output. If the size of tr's output is bigger than the size of the buffer for tr's unread output, you'll deadlock. As an aside, the particular problem you pose can be solved with Python's str.translate method. If the actual goal is to "work like tr", then use that instead and forget about popen. Anyway, to solve the popen2 problem, you'll need to write something like this: [untested, and as you can see there's lots of pseudocode] def getoutput( command, input ): r, w = popen2(command) rr = [r]; ww = [w] output = [] set r and w nonblocking while 1: _r, _w, _ = select.select(rr, ww, [], 0) if _w: write some stuff from input to w if nothing left: w.close(); ww = [] if _r: read some stuff into output if nothing to read: handle the fact that r was closed if w was closed: break else: probably an error condition return "".join(output) You could also write 'input' into a temporary file and use commands.getoutput() or os.popen(.., "r"). Jeff From nomail at nospam.net Mon Jan 12 04:51:48 2004 From: nomail at nospam.net (Olaf Meyer) Date: Mon, 12 Jan 2004 09:51:48 GMT Subject: Python 2.3.3 compilation problems an HP-UX In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Olaf Meyer wrote: > >>I'm having some problems compiling Python 2.3.3 on HP-UX (B.11.00). >>I've tried sevral different options for the configure script (e.g. >>enabling/disabling gcc, aCC) but I always get the same problem during >>the final linking stage. Several PyThread_* symbols are undefined (for >>details see the output below). > > > I'd suggest that you look at the recent threads about compiling for > HP-UX on python-dev. It's starting to look like a SIG might be a good > way to go. Thanks for pointing me there. It seems that there's some clean-up needed for HP-UX. Luckily compiling 2.2.1 works fine for me, so I think I'll stick with it until the 2.3 versions compile with HP-UX 'out-of-the-box' ;-) Olaf From aahz at pythoncraft.com Tue Jan 27 20:13:52 2004 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2004 20:13:52 -0500 Subject: Upgrading to Python 3.0 Questions References: Message-ID: In article , Zachary wrote: > >I've heard some rumors about Python 3.0. I am wondering what sort of >upgrading I'll have to do, as I have also heard people on this group >asking us to use certain modules or operators or whatever. Is it a >major sort of upgrade? What would I need to do to prepare for it? Rumors are the only thing available at this point. Don't worry about it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From jzgoda at gazeta.usun.pl Fri Jan 23 14:54:23 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 23 Jan 2004 19:54:23 +0000 (UTC) Subject: wxPython question References: <5sKcnU3qx-sP1Y3dRTvaKA@news.rockefeller.edu> Message-ID: Chad Haynes pisze: > Is there a way to change the background color of a wxCheckBox in > wxPython? Using the SetBackgroundColor function will change the > background of any label attached to the checkbox, but I want to change > the color of the actual box. I think that its color depends on GUI toolkit. At least native Win32 checkbox control don't allow such manipulation. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From gerrit at nl.linux.org Wed Jan 7 09:29:43 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 7 Jan 2004 15:29:43 +0100 Subject: Pre-PEP: Dynamically evaluating default function arguments In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE010633FF@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE010633FF@au3010avexu1.global.avaya.com> Message-ID: <20040107142943.GA2283@nl.linux.org> Delaney, Timothy C (Timothy) wrote: > IMO it's not a waste of time for this PEP to be written. Unfortunately, not many people are willing to formally document something that they would like to see when the guaranteed result is that it will be rejected. PEP 313? :) Gerrit. -- 203. If a free-born man strike the body of another free-born man or equal rank, he shall pay one gold mina. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From grelens at NOSPAMyahoo.NOTNEEDEDfr Sat Jan 17 05:30:09 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Sat, 17 Jan 2004 11:30:09 +0100 Subject: help with cr in reg exp... Message-ID: <4009126a$0$22321$626a54ce@news.free.fr> hello, i had a trouble with re that i didn't understand (this is a silly example to show, to parse html i use sgmllib) : having this string : >>> s = """
help """ why do i get : >>> p = re.compile("(?=|)"); p.findall(s) [] while i was expected this kind of behaviour : ['form name="test" method="post" action="test.php">\n\n
\nhelp'] which what i nearly get with : >>> p = re.compile("(?=|)"); p.findall(s.replace('\n', '')) ['

help '] it looks like \n isn't matched by . (dot)* in my re while i though (and need) it should, i must be missing something. thanks! From mcfletch at rogers.com Thu Jan 29 20:00:41 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 29 Jan 2004 20:00:41 -0500 Subject: Easy way to make EXEs... In-Reply-To: References: <4017C45F.D7501215@engcorp.com> Message-ID: <4019ACB9.60605@rogers.com> Xero Limit 126 wrote: ... >SystemExit: usage: setup [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] >...] > or: setup --help [cmd1 cmd2 ...] > or: setup --help-commands > or: setup cmd --help > >error: no commands supplied >-------------------------- > > setup.py requires that you specify which command, such as "install", "bdist_wininst", or in your case "py2exe" you want to run. Distutils (the source of the setup.py functionality) is a large package with many operations beyond creating an exe. Try: python setup.py py2exe And see if that gets you farther. Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From Pekka.Pessi at nokia.com Sat Jan 3 11:33:33 2004 From: Pekka.Pessi at nokia.com (Pekka Pessi) Date: Sat, 03 Jan 2004 18:33:33 +0200 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: "Moosebumps" writes: >mystruct x = { 3, 5.0f }; >mystruct y = { 5, 15.0f }; >These are just "data". Obviously in python you could just write an init >function like this: >x.a = 3; >x.b = 5; >y.a = 5; >y.b = 15; >And that would work fine, but the programmer in me says that that's a pretty >inelegant way to do it. Why execute code when all you need is to put data >in the program? This depends what you plant to do. Easiest way to initialize the __dict__ is with code something like this: class AnyStruct: def __init__(self, **kw): self.__dict__.update(kw) The ** in the __init__ signature means that it puts all named arguments in the dictionary kw. You can then use your structure class like this: x = AnyStruct(a = 3, b = 5) Of course, this is "nice" trick to utilize whenever you initialize an instance. If you have some mandatory argument, you can require that callers sets them with class MyStruct: def __init__(self, a, b, **kw): self.a = a self.b = b self.__dict__.update(kw) then x = MyStruct(3, 5) does same as x = MyStruct(a = 3, b = 5) but the latter is a bit more readable. --Pekka From newsgroups at jhrothjr.com Sat Jan 3 08:08:01 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Jan 2004 08:08:01 -0500 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Sean R. Lynch" wrote in message news:LmmdnUn4seDeGWuiXTWc-w at speakeasy.net... [...] > Does anyone think I'm going in completely the wrong direction here? Am I > missing anything obvious? Yes, you're missing something really obvious. Multi-level security is a real difficult problem if you want to solve it in a believable (that is, bullet-proof) fashion. The only way I know of solving it is to provide separate execution environments for the different privilege domains. In the current Python structure, that means different interpreters so that the object structures don't intermix. If you have separate domains, then the only support needed is to remove privileged modules from the built-ins, and virtualize import so that it won't load modules that aren't on the approved list for that domain. You also, of course, need some form of gate between the untrusted and trusted domains. Once that's done, there's no reason to layer additional complexity on top, and there is no reason to restrict any introspection facilities. John Roth From peter at engcorp.com Fri Jan 16 09:21:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Jan 2004 09:21:46 -0500 Subject: Binary strings, unicode and encodings References: <265368cb.0401151138.37a3a47b@posting.google.com> <4006F13C.7D432B98@engcorp.com> <265368cb.0401151419.7663823e@posting.google.com> Message-ID: <4007F37A.6D26C83@engcorp.com> Laurent Therond wrote: > > So, your test revealed that StringIO converts to byte strings. > Does that mean: > - If the input string contains characters that cannot be encoded > in ASCII, bencode_rec will fail? Yes, if your default encoding is ASCII. > Yet, if your locale specifies UTF-8 as the default encoding, it should > not fail, right? True, provided you are actually creating UTF-8 strings... just sticking in a character that has the 8th bit set doesn't mean the string is UTF-8 of course. > Hence, I conclude your test was made on a system that uses ASCII/ISO > 8859-1 as its default encoding. Is that right? Correct, Windows 98, sys.getdefaultencoding() returns 'ascii'. > > > c) It depends on the system locale/it depends on what the site module > > > specifies using setdefaultencoding(name) > > > > Yes, as it always does if you are using Unicode but converting to byte strings > > as it appears StringIO does. > > Umm...not sure here...I think StringIO must behave differently > depending on your locale and depending on how you assigned the string. It's always possible that StringIO takes locale into account in some special way, but I suspect it does not. As for "how you assigned the string" I'm not sure I understand what that might mean. How many ways do you know to assign a string in Python? -Peter From mir4uu at yahoo.com Mon Jan 5 07:34:28 2004 From: mir4uu at yahoo.com (mir nazim) Date: 5 Jan 2004 04:34:28 -0800 Subject: Help: wxPython tutorials Message-ID: <425cc8d1.0401050434.235ca633@posting.google.com> hi, i am in urgent need of a good refrence material for wxPython. goo docs will also do.(i already have wxWindows library refrence. but it is too hectic for me to traverse throught it). please help. From syver at inout.no Fri Jan 16 11:16:21 2004 From: syver at inout.no (Syver Enstad) Date: 16 Jan 2004 17:16:21 +0100 Subject: Very strange unicode behaviour Message-ID: Here's the interactive session Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ord('\xe5') 229 >>> '\xe5'.find(u'') -1 >>> 'p\xe5'.find(u'') UnicodeError: ASCII decoding error: ordinal not in range(128) >>> 'p\xe4'.find(u'') -1 >>> 'p\xe5'.find(u'') UnicodeError: ASCII decoding error: ordinal not in range(128) >>> print '\xe5' ? >>> print 'p\xe5' p? >>> 'p\xe5' 'p\xe5' >>> def func(): ... try: ... '\xe5'.find(u'') ... except UnicodeError: ... pass ... >>> func() >>> for each in range(1): ... func() ... UnicodeError: ASCII decoding error: ordinal not in range(128) >>> It's weird that \xe5 throws and not \xe4 but even weirder that the exception is not cleared so that the loop reports it. Is this behaviour the same on Python 2.3? From skip at pobox.com Wed Jan 14 11:57:54 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 10:57:54 -0600 Subject: Safe prime numbers in Python In-Reply-To: <16389.28642.425686.771599@montanaro.dyndns.org> References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au> <4005725d$1@nntp0.pdx.net> <16389.28642.425686.771599@montanaro.dyndns.org> Message-ID: <16389.29970.183928.30299@montanaro.dyndns.org> Ack... I'm an idiot: Skip> def safe_primes(last=1): Skip> last = long((last-1)/2) # assuming future float division... should be last = (last-1)//2 # doh! Skip> while True: Skip> last = gmpy.next_prime(last) Skip> other = last * 2 + 1 Skip> if gmpy.is_prime(other): Skip> yield other Skip From swalters_usenet at yahoo.com Sun Jan 11 02:43:14 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 11 Jan 2004 07:43:14 GMT Subject: what is best for web development?? References: Message-ID: |Thus Spake ketulp_barod On the now historical date of Sat, 10 Jan 2004 03:58:09 -0800| > i am developing a web application and i am really confused on what > should i use. should i use just python and use the cgi module availabe. > Or should i use application like WebWare.Also there is PSP available. I > am really confused and need help Follow the advice given elsewhere in this thread, but also look at PHP, which is another web-programming language. It's not difficult to pick up if you have a grounding in C, and understand HTML, but it does have its issues. It is best for getting web pages to talk to databases. The nicest thing about it is that it was developed *for* creating dynamic web-pages, so it has a good tool-box for that sort of thing. HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From davidb at mcs.st-and.ac.uk Tue Jan 13 17:35:13 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 13 Jan 2004 14:35:13 -0800 Subject: Help in unwrapping a PyObject* returned by an embedded Python function References: <200401120930.i0C9UTmq032356@se-126.se.wtb.tue.nl> Message-ID: <4de76ee2.0401131435.3d66be95@posting.google.com> Read Roberts wrote in message news:... [Returning a string/tuple to a C function] > In fact, I did try all combinations of > > in the Python call-back function : > return myString > return (myString) > > and, in the C calling function, > > PyArg_ParseTuple(pyStringResult, "s", myString) > PyArg_ParseTuple(pyStringResult, "(s)", myString) I'm guessing here but, if you want to pass tuples around, have you tried using the second form of each of the above with the following correction to the Python code? return (myString,) > Also, the Python documentation (and other working code examples I > have) indicate that 'PyArg_ParseTuple', unlike BuildValues, always > assumes the arguments are supplied in a argument tuple, even if there > is only one argumen. Maybe. I haven't really thought about it. > I speculate that an argument list object, as required by > PyArg_ParseTuple, is not in fact a simple tuple., and that > PyArg_ParseTuple cannot be used to parse a regular tuple. Any idea if > this is correct? I think that there's been a misunderstanding. Since your original message, and some unavailable reply were quoted below your last message, I think I can see where it happened. > >In comp.lang.python, you wrote: > > > >> Why does PyArg_ParseTuple fail to parse a return value which is a > >> tuple? > >> > >> However, the following does not work: > >> from Python callback function: return (myString) > >> in calling C function: > >> if (!PyArg_ParseTuple(pyStringResult, "s", name)) { > >> dbprintf(4, "c: failed to parse return value\n"); > >> PyErr_Clear(); > >> } > >> PyArg_ParseTuple fails, and returns NULL. How come? By the > >> documentation, I would think that PyArg_ParseTuple would parse any > >> Python tuple object. I don't know whether it does or not, but you have returned a string! This happened because you need to use a trailing comma within the brackets. This tells the interpreter that the return value is not simply a string enclosed in brackets. You can see this from the following output from an interactive session in Python: >>> "string" 'string' >>> ("string") 'string' >>> ("string",) ('string',) In your original example, you returned a string and converted it successfully to a char pointer. Presumably, you wanted a more general solution in order to catch any non-string objects returned and turned to PyArg_ParseTuple. Maybe you could put the returned object in a tuple and call PyArg_ParseTuple on the result, but there's surely an easier way to check the validity of the return value. Hope this helps, David From raneb at slingshot.co.nz Mon Jan 26 14:28:28 2004 From: raneb at slingshot.co.nz (Rane Bowen) Date: Tue, 27 Jan 2004 08:28:28 +1300 Subject: Optional Parameters in python COM References: Message-ID: "Rane Bowen" wrote in message news:bv1rek$oof$1 at lust.ihug.co.nz... > Hi, > > I am using python with a makepy generated wrapper on a COM application. One > of this object's methods has 3 parameters, two of which are optional. > If I call the method with just the non-optional parameter, or all three > parameters, it works. If I call it with the first two parameters, I get the > following error: > > (-2147352567, 'Exception occurred.', (0, 'Amphora.Session.1', 'A bad > parameter was passed to the method', None, 0, -1610547133), None) > > I have tried calling the method by using the names of the optional > parameters, and I have also tried using pythoncom.Missing and > pythoncom.Empty for the non essential parameter. I have also edited the > generated .py file so that it contains the following: > > defaultNamedOptArg=pythoncom.Empty > defaultNamedNotOptArg=pythoncom.Empty > defaultUnnamedArg=pythoncom.Empty > > But this has not made any difference! Any help would be very much > appreciated. > > Cheers, > > Rane > > From JoeyTaj at netzero.com Thu Jan 8 10:42:14 2004 From: JoeyTaj at netzero.com (Paradox) Date: 8 Jan 2004 07:42:14 -0800 Subject: Calling a function dynamically Message-ID: <924a9f9c.0401080742.39eba581@posting.google.com> I would like to call a function whose name I supply at runtime. Something like this but it didn't work functionName = 'run' instance = ClassDef() args = [1, 2] #want the dynamic equivalant of #instance.run(*args) #This didn't work cause there was no __call__ attribute. Why? value = instance.__call__[functionName](*args) Thanks Joey From ad at ad.nl Sun Jan 11 08:31:33 2004 From: ad at ad.nl (duikboot) Date: Sun, 11 Jan 2004 14:31:33 +0100 Subject: Oracle to Mysql (dates) Help please Message-ID: Hi all, I'm trying to export a view tables from a Oracle database to a Mysql database. I create insert statements (they look alright), but it all goes wrong when I try to execute them in Mysql, because the dates must have quotes on each side. I just don't know how make the dates right. Well I'll just show you the code and some insert statements it generates. Could anyone please help me? Thanks, Arjen ####Code#### import cx_Oracle tabellen=["machine"] con_oracle=cx_Oracle.connect("bla/bla") c_oracle=con_oracle.cursor() import MySQLdb my=MySQLdb.Connect("localhost", db="bla") my_mysql=my.cursor() for tabel in tabellen: print tabel c_oracle.execute("select * from %s" % tabel) a_oracle=c_oracle.fetchone() #file=open("%s.sql" % tabel, 'w') while a_oracle != None: b=str(a_oracle) ins="insert into %s values %s;\n" % (tabel, b) #file.write(ins) my_mysql.execute(ins) #print ins a_oracle=c_oracle.fetchone() file.close() con_oracle.close() my.close() ##insert statement### insert into machine values ('230KM', ' ', '230KM', 1980-01-01 00:00:00, 2035-01-01 00:00:00, 1, 100, 'asap', 'NO', 0, 0, 'corrugator', 2003-12-04 06:00:00, 1970-01-01 01:00:00, ' ', 'normal', 0.0, 0.0, 7, ' ', ' ', 'normal', ' ', ' ', 'A', 2003-12-04 09:42:14, 82766); From max at alcyone.com Fri Jan 23 05:47:19 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 23 Jan 2004 02:47:19 -0800 Subject: private class members and hasattr References: Message-ID: <4010FBB7.B4692922@alcyone.com> Dragos Chirila wrote: > Why hasattr method doesn't return 1(true) for private member '__prop3' > ?? > > I tested it with Python 2.2.1 and 2.1.3 . Because a prefix double underscore (without a suffixed double underscore, anyway) mangles the identifier with the intention of it being private. That is to say, trying to access a __private name from another class is a good indication that you're doing something you're not supposed to be doing. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I do not promise to consider race or religion in my appointments. I promise only that I will not consider them. -- John F. Kennedy From peter at engcorp.com Thu Jan 8 10:09:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Jan 2004 10:09:49 -0500 Subject: PRE-PEP: new Path class References: <1073567709.3ffd57dda8cb0@mcherm.com> Message-ID: <3FFD72BD.780554D8@engcorp.com> Gerrit Holl wrote: > > Michael Chermside wrote: > > I agree... paths should be immutable. > > > > Instead of .normalize_inplace() which changes the behavior of the > > Path, how about .get_normalized_string() (please find a better name) > > which allows access to the normalized version without mutating the > > Path object? (Or perhaps it should be .get_normalized_Path()... I'm > > not sure.) > > If we make it immutable, we can simply do path.normalize(), which > returns the normalized path. Or am I overlooking something? I haven't been following (either discussion) closely, but this sounds similar to some posts I read about a discussing involved a .reverse() method, and the apparent conclusion that .reversed() [note the 'd'] was more appropriate as it didn't imply that the object was being modified in-place, but that it was returning a reversed version of itself. Same thing could apply here... -Peter From simonb at NOTTHISBIT.webone.com.au Mon Jan 19 19:09:20 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Tue, 20 Jan 2004 11:09:20 +1100 Subject: Pyrex and numarray References: Message-ID: On Mon, 19 Jan 2004 19:33:28 +0100, Marco Bubke wrote: > Hi > > I have tried to include numarray in Pyrex but I get allways this error: > > Traceback (most recent call last): > File "gears.py", line 9, in ? > import gl > File "/home/marco/projects/test_pyrex/gl.pyx", line 40, in gl > ctypedef class numarray.NumArray [object PyArrayObject]: > ValueError: numarray.NumArray does not appear to be the correct type > object > Yes, i had that problem. Here is what I'm using now: ctypedef class numarray._numarray._numarray [object PyArrayObject]: # Compatibility with Numeric cdef char *data cdef int nd #cdef int dimensions[MAXDIM], strides[MAXDIM] cdef int *dimensions, *strides cdef object base cdef PyArray_Descr *descr cdef int flags # New attributes for numarray objects cdef object _data # object must meet buffer API cdef object _shadows # ill-behaved original array. cdef int nstrides # elements in strides array cdef long byteoffset # offset into buffer where array data begins cdef long bytestride # basic seperation of elements in bytes cdef long itemsize # length of 1 element in bytes cdef char byteorder # NUM_BIG_ENDIAN, NUM_LITTLE_ENDIAN cdef char _aligned # test override flag cdef char _contiguous # test override flag cdef extern from "numarray/libnumarray.h": void import_libnumarray() object NA_NewAll( int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable ) object NA_NewAllStrides( int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, int byteorder, int byteoffset, int aligned, int writeable ) object NA_New( void* buffer, NumarrayType type, int ndim,... ) object NA_Empty( int ndim, maybelong* shape, NumarrayType type ) object NA_NewArray( void* buffer, NumarrayType type, int ndim, ... ) object NA_vNewArray( void* buffer, NumarrayType type, int ndim, maybelong *shape ) object NA_InputArray (object, NumarrayType, int) object NA_OutputArray (object, NumarrayType, int) object NA_IoArray (object, NumarrayType, int) object PyArray_FromDims(int nd, int *d, int type) object NA_updateDataPtr(object) object NA_getPythonScalar(object, long) object NA_setFromPythonScalar(object, int, object) #object NA_getPythonScalar(PyArrayObject, long) #object NA_setFromPythonScalar(PyArrayObject, int, PyArrayObject) object PyArray_ContiguousFromObject(object op, int type, int min_dim, int max_dim) #cdef void*NA_OFFSETDATA(object) void*NA_OFFSETDATA(_numarray) int NA_nameToTypeNo (char*) Simon. -- Simon Burton, B.Sc. Licensed PO Box A66 ANU Canberra 2601 Australia Ph. 02 6249 6940 http://arrowtheory.com From r.s at ZZmindspring.com Wed Jan 21 23:54:43 2004 From: r.s at ZZmindspring.com (r.e.s.) Date: Thu, 22 Jan 2004 04:54:43 GMT Subject: Assignment to slice References: <20040121191546.4975.qmail@web40102.mail.yahoo.com> Message-ID: "James Henderson" wrote ... JH Assignment to x[-4:-3] is not same as assignment to x[-1:0]: JH JH >>> x = [1, 2, 3] JH >>> x[-4:-3] = [56] JH >>> x JH [56, 1, 2, 3] JH >>> x = [1, 2, 3] JH >>> x[-1:0] = [56] JH >>> x JH [1, 2, 56, 3] JH JH Although x[-4:-3] and x[-1:0] both evaluate to the same JH thing (an empty list). JH I would be interested to hear what anyone else has to say JH about this. Here's my beginner's take on "slice indices" ... Since len(x)==3, *only* the values -1, -2, and -3 are shorthand, standing for 2, 1, 0 resp.; i.e., only -1, -2, ..., -len(x) are shorthand, and any other negative integer is equivalent to 0; any positive integer values > len(x) are equivalent to len(x). So, x[-4:-3] stands for x[0:0], while x[-1:0] stands for x[2:0]. Both x[0:0] and x[2:0] are empty lists, but x[0:0] is located "just before x[0]" whereas x[2:0] is located ""just before x[2]", and the assignments amount to insertions at the resp. locations. I trust someone will correct me if I'm wrong, but it seems to me a simpler restatement of what's in the Python Reference Manual. --r.e.s. From davecook at nowhere.net Sat Jan 24 06:24:44 2004 From: davecook at nowhere.net (David M. Cook) Date: Sat, 24 Jan 2004 11:24:44 GMT Subject: Python & Databases ? References: <4011bcd6$0$4051$afc38c87@news.optusnet.com.au> Message-ID: In article <4011bcd6$0$4051$afc38c87 at news.optusnet.com.au>, Peter Moscatt wrote: > Will Python work with any of the databases like MySQL... ? Yes, very nicely indeed. You can use mysqldb or one of the object-relational mappers that support mysql, like sqlobject or middlekit. Dave Cook From candiazoo at comcast.net Thu Jan 22 20:44:27 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 23 Jan 2004 01:44:27 GMT Subject: Seem to be having trouble with Python/Bethon. Message-ID: >>> class foo(BWindow.BWindow): .. pass .. Traceback (most recent call last): File "", line 1, in ? TypeError: base is not a class object Not entirely sure what the message means (beyond the obvious that it does not believe the class is a class, so to speak). (Btw, I did previously import BWindow). Anyone here have BeOS experience with Python? The "rest" of python works fine. I've built and added packages to it and am in the process of coding an application which I will, eventually, want a front end for. Thanks! Mike From jsbenson at bensonsystems.com Thu Jan 15 14:15:47 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 15 Jan 2004 11:15:47 -0800 Subject: I come not to bury C++, but to praise it... Message-ID: <0bf601c3db9b$fb7ccda0$8d09500a@jsbwxp3> I give up! Enough already! Maybe C++ will make my teeth brighter and my socks whiter, and remove the yellowish wax buildup on the kitchen floor! :^) I read Koenig's C Traps and Pitfalls years ago; it's been one of my favorite programming language books for a long time, so I'm predisposed to set a certain store by the following pronouncement: Message: 6 Date: 15 Jan 2004 02:37:32 +0000 From: jjl at pobox.com (John J. Lee) Subject: Re: I come not to bury C++, but to praise it... To: python-list at python.org Message-ID: <87wu7uq6mr.fsf at pobox.com> Content-Type: text/plain; charset=us-ascii "Andrew Koenig" writes: > "John Benson" wrote in message > news:mailman.337.1074032524.12720.python-list at python.org... > > > I got into Python because I took one look at C++ and saw all the > > handwaving in the introductory O'Reilly book to the effect that > > "everything looks sweet now, but wait until these snazzy little > > features interact..." and then started casting around for another > > road to OOP. > > Perhaps you should cast around for a different C++ book while you're > at it, too -- maybe the one you found isn't well suited to your > particular learning style. Andrew's own "Accelerated C++" is good (written with Barbara Moo). :-) John (end quote) It took years to get IT managers to feel comfortable with software development in C as opposed to COBOL. I suppose I may still be haunted by that; it just seems that advocating C++ raises the bar even more for the maintenance programmers that get stuck with my code. Python is a whole different story, since the rapidity with which I can field a serviceable prototype changes the economics completely. But again, this may be more an artefact of my personal experience than a Universal Truth. From manoj at cs.uoregon.edu Fri Jan 30 12:55:38 2004 From: manoj at cs.uoregon.edu (Manoj K Pandey) Date: Fri, 30 Jan 2004 09:55:38 -0800 (PST) Subject: Source specific multicast implementation.. Message-ID: hi All, Do we have Source Sepcific Multicast, SSM implemented in python... Does anyone have any API for it, which they would like to share? thnx in advance, manoj ****************************** Manoj Pandey, PhD student, #207C, Network Research Lab, Deschutes, Computer and Information Science, University of Oregon, Phone# 541-346-0892 [Office], www.cs.uoregon.edu/~manoj ****************************** From hans at zephyrfalcon.org Sun Jan 25 19:06:31 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun, 25 Jan 2004 19:06:31 -0500 Subject: xrange not hashable - why not? In-Reply-To: <20040125144724.GA13741@nl.linux.org> References: <20040125144724.GA13741@nl.linux.org> Message-ID: <40145A07.2070906@zephyrfalcon.org> Gerrit Holl wrote: > Hi, > > why is an xrange object not hashable? > I was trying to do something like: > > comments = { > xrange(0, 4): "Few", > xrange(4, 10): "Several", > xrange(10, 100): "A lot", > xrange(100, sys.maxint): "Can't count them"} > for (k, v) in comments.items(): > if n in k: > commentaar = v > break So far, everybody who replied seems to agree or assumes that xrange indeed isn't hashable. However: 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 sys >>> comments = { ... xrange(0, 4): "Few", ... xrange(4, 10): "Several", ... xrange(10, 100): "A lot", ... xrange(100, sys.maxint): "Can't count them"} >>> comments {xrange(4): 'Few', xrange(4, 10): 'Several', xrange(100, 2147483647): "Can't count them", xrange(10, 100): 'A lot'} Sure enough, that dict works. Let's try something else then: >>> a = xrange(10) >>> b = xrange(20) >>> hash(a), hash(b) (7774576, 7775104) It seems that xrange objects do have a hash value. The other part of the code works as well: >>> n = 3 >>> for k, v in comments.items(): ... if n in k: ... commentaar = v ... break ... >>> commentaar 'Few' I don't really see what the problem is...? -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From hokiegal99 at hotmail.com Mon Jan 5 16:17:58 2004 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 05 Jan 2004 16:17:58 -0500 Subject: local interpreter remote machines Message-ID: This may not be possible, but I thought I'd ask anyway. Could I get the below code to run on a Python server where other machines would connect to it (say thru the Web) and get details of *their* system instead of the system details of the machine that the interpreter is running on? Any ideas? Thanks!!! import os import socket x = os.uname() y = socket.gethostbyaddr(x[1]) print print "This is the connecting machine's os:", x[0] print "This is the connecting machine's os version:", x[2] print "This is the connecting machine's IP address:", y[2] print From idbaxter at semdesigns.com Sat Jan 10 14:10:30 2004 From: idbaxter at semdesigns.com (Ira Baxter) Date: Sat, 10 Jan 2004 13:10:30 -0600 Subject: scanning c-code References: Message-ID: <40004ca7$7@giga.realtime.net> "tm" wrote in message news:btj4oo$g58$1 at piggy.rz.tu-ilmenau.de... > I have to to scan c-code, look for a c-struct variable(declaration) and > represent the struct in a tree-graphic. > Are there modules for scanning c-code and graphictools for the > representation stuff. > What would you advise as a starting point... I wouldn't specifically recommend python for this. This is really a job for a parsing engine. (To the extent that python has good parsing tools and good C definitions, it might be an OK answer.) Getting parsing tools in python is likely possible. Getting a good C definition, however, is harder. You might consider an engine designed to parse languages that has a good C definition. GNU C is one example. Another is http://www.semanticdesigns.com/Products/FrontEnds/CFrontEnd.html -- Ira D. Baxter, Ph.D., CTO 512-250-1018 Semantic Designs, Inc. www.semdesigns.com ----== 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 skip at pobox.com Mon Jan 26 15:15:00 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 26 Jan 2004 14:15:00 -0600 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <40156FB6.F71C19B0@engcorp.com> References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> Message-ID: <16405.30020.406117.575663@montanaro.dyndns.org> Josiah> http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html Peter> I'm sorry, really, to bring this up, but as a Canadian I might be Peter> a little thick on this point, so help me out: was that site Peter> hacked? Or is this for real? I'm a natural-born American and I wondered the same thing. This is what you get when the electorate chooses the "leader of the free world" because "he seems like such a nice fellow" or "he's a regular guy" Pardon me, but I don't want "a regular guy" in this particular position. I want the god damned smartest, most capable person we can find. Hmmm... If we're electing the "leader of the free world", maybe the entire free world ought to be able to vote. Imagine the primary season running up to that election! Skip From aathan-python-5923 at cloakmail.com Mon Jan 5 21:35:26 2004 From: aathan-python-5923 at cloakmail.com (Andrew Athan) Date: Mon, 5 Jan 2004 21:35:26 -0500 Subject: Repost: Can't sys.exit() from SIGTERM handler? In-Reply-To: <20040106013708.GD5514@unpythonic.net> Message-ID: Yes, but it gets stranger (see below). It seems if I try to catch exceptions from within the SIGTERM handler, they are instead caught by the main program. Perhaps this is because a second signal is raised from within the SIGTERM handler and python doesn't handle nested signals well? --------------------------------------------------------- So #1: But first, the "simple" question: It seems really onerous to have to explicitly trap SystemExit and re-raise everywhere in my program, just so I can make sure that proper exit handlers (atexit(), etc.) are called. What is the idiom to "force" and exit while still "properly" shutting down the interpreter? ---------------------------------------------------------- #2 Now the hard question... It seems my problem is caused by my atexit() handler. It is meant to kill the children, and then os.waitpid() for them to make sure they are dead. I added this because killing the python process was not reliably killing the children (this surprised me since I thought the shell sent the signal to all processes in a process group??!!! perhaps cdparanoia has some incorrect exception handling which causes it not to reliably die on SIGTERM) I attribute my woes to the atexit() handler because when I changed my code to explicitly call the function I register with atexit() (called killChildren()) from within my SIGTERM handler, then the behavior got even weirder. The code I have basically looks something like this (pseudocode) childrenList=[] def sigterm(a,b): killChildren() childrenList=[] sys.exit() def sigchild(a,b): pass def killChildren(): try: os.kill(pid,signal.SIGTERM) os.waitpid(pid,0) pass: pass signal.signal(sigchild,signal.SIGCHILD) signal.signal(sigterm,signal.SIGTERM) childrenList.append(fork(...)) sys.atexit(killChildren) ... while 1: try: foo=read() except Exception,e: print 'Here: %s'%e pass If I send a SIGTERM, then I occasionally get 'Here: [Errno 10] No child processes' printed out!!! Stranger still, if I leave the normal atexit() handler alone by doing this instead: def sigterm(a,b): sys.exit() then *no* exception is printed out and the program keeps running. I *still* don't get anything printed even if I explicitly catch SystemExit within the while 1: loop and print a debug statement. The only conclusion I can draw is that (a) atexit's exception handling is strange and/or (b) if the child is still running when I os.kill() it in in the atexit() handler that occurs after the sys.exit() in, the SIGCHILD that gets raised as a result of the kill() is interfering in some very strange way. HELP! Any comments? Thanks, A. -----Original Message----- From: Jeff Epler [mailto:jepler at unpythonic.net] Sent: Monday, January 05, 2004 8:37 PM To: Andrew Athan Cc: python-list at python.org Subject: Re: Repost: Can't sys.exit() from SIGTERM handler? If I had to guess, I'd bet you had a blanket exception handler somewhere. sys.exit merely raises SystemExit, and if this exception propogates all the way back up, Python treats it specially by exiting instead of printing the exception's traceback. :r term.py import os, signal, time, sys, traceback def sigterm(a, b): print "sigterm" sys.exit() signal.signal(signal.SIGTERM, sigterm) os.system("(sleep 1; kill %s) &" % os.getpid()) print "Sleeping (should be killed)" try: time.sleep(2) except SystemExit: traceback.print_exc() raise print "sleep finished (!?)" :r!python -u term.py Sleeping (should be killed) sigterm Traceback (most recent call last): File "term.py", line 14, in ? time.sleep(2) File "term.py", line 5, in sigterm sys.exit() SystemExit From gherron at islandtraining.com Mon Jan 5 12:26:14 2004 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 5 Jan 2004 09:26:14 -0800 Subject: Get UID of username In-Reply-To: References: Message-ID: <200401050926.14167.gherron@islandtraining.com> On Monday 05 January 2004 09:20 am, Florian Lindner wrote: > Hello, > how can I find out the UID of a username on a linux system? > Thx, > Florian Try the pwd module: >>> import pwd >>> pwd.getpwnam('gjh') ('gjh', 'x', 500, 500, 'Gary Herron', '/home/gjh', '/bin/bash') Gary Herron From webmaster at beyond-thoughts.com Fri Jan 9 12:06:03 2004 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 09 Jan 2004 18:06:03 +0100 Subject: PRE-PEP: new Path class; mutability, __hash__, __eq__, __cmp__ In-Reply-To: <6qad4xmjsd.fsf@salmakis.intevation.de> References: <3FFA7E82.4020609@beyond-thoughts.com> <3FFC9209.7060703@beyond-thoughts.com> <6qad4xmjsd.fsf@salmakis.intevation.de> Message-ID: <3FFEDF7B.6050501@beyond-thoughts.com> Bernhard Herzog wrote: > Christoph Becker-Freyseng writes: > > >>So for __eq__ it follows naturaly >>def __eq__(self, other): >> FIXME: isinstance checking >> return (str(self.normalized()) == str(other.normalized())) >>It cares about nonexistent paths, too. (The samefile-solution won't --- >>we might code a special case for it ...) > > > What exactly does normalized() do? If it's equivalent to > os.path.normpath, then p1 == p2 might be true even though they refer to IMO yes. > different files (on posix, a/../b is not necessarily the same file as > b). OTOH, if it also called os.path.realpath too to take symlinks into > account, __eq__ would depend on the state of the filesystem which is > also bad. > > IMO __eq__ should simply compare the strings without any modification. > If you want to compare normalized paths you should have to normalize > them explicitly. I agree with that. While it would be nice if __eq__ could match such things it is ambiguous. So better let __eq__ be a bit strict than faulty. Christoph Becker-Freyseng From dave at pythonapocrypha.com Fri Jan 9 17:47:41 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 9 Jan 2004 15:47:41 -0700 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <026e01c3d702$970ec5a0$6401fea9@YODA> Peter wrote: > Iwan van der Kleyn wrote: > > > > In other words: it would be nice if Python on average would run faster > > so the need for optimisation would lessen. > > I disagree with the above. My opinion has long been that Python runs > adequately fast and that few people should need to spend much time on > optimization. Maybe that sort of view should be put to the test. > > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) Yay, straw poll! ;-) I program in Python full-time and each spend approximately zero hours optimizing. In the past two years I can think of two instances in which I went into heavy optimization mode: one was for a web server that needed to handle hundreds of requests per second and the other was a log processor that needed to parse and process several gigabytes of log data per hour. In the server I added a tiny C extension to make use of the Linux sendfile API, all the other optimizations were algorithmic. In the log processor all the optimizations ended up being either algorithmic or doing fewer dumb things (like recomputing cacheable data). From peter at engcorp.com Wed Jan 21 09:23:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Jan 2004 09:23:36 -0500 Subject: Tutorial/Docs on threading with Python? References: Message-ID: <400E8B68.1D509128@engcorp.com> Andreas Neudecker wrote: > > I would like to learn how to do threading with Python. I have not done > threading before can anyone suggest URLs where I could find > understandable information on that? (I am using Python for approx. 1 > year now, previous programming experiences lie back a long time). http://www.google.com/search?q=python+threading+tutorial Check out the fifth link, Aahz's page. -Peter From dallasm at aiinet.com Fri Jan 23 18:10:47 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Fri, 23 Jan 2004 18:10:47 -0500 Subject: help with unittest Message-ID: > if __name__ == '__main__': > #unittest.main() > suite = > unittest.defaultTestLoader.loadTestsFromNames(['myTestCase2.te > stTrue']) > unittest.TextTestRunner().run(suite) > Not quite an asnswer to the question, but why not do it this way If __name__ = '__main__': suite = unittest.makeSuite(myTestCase2, 'testTrue') unittest.TextTestRunner().run(suite) ? --- Dallas S. Mahrt From me at privacy.net Mon Jan 26 12:40:49 2004 From: me at privacy.net (Duncan Booth) Date: 26 Jan 2004 17:40:49 GMT Subject: Single and double asterisks preceding variables in function arguments References: Message-ID: anton muhin wrote in news:bv3gdg$ms0sn$1 at ID- 217427.news.uni-berlin.de: > Stephen Boulet wrote: >> I've run across code like "myfunction(x, *someargs, **someotherargs)", >> but haven't seen documentation for this. >> >> Can someone fill me in on what the leading * and ** do? Thanks. >> >> Stephen > > See item 7.5 in Language Reference. In short: * declaries list of > additional parameters, while ** declares map of additional parameters. > Try somehting like: > > def foo(*params): print params > > and > > def bar(**params): print params > > to find out details. I may be wrong, but I think the OP was asking about calling functions rather than defining them. The '*' and '**' before arguments in function calls are described in section 5.3.4 of the language reference but, so far as I know, isn't explained clearly in any of the more 'user level' text. There is a brief mention in the library reference under the documention of 'apply'. In a call of the form: myfunction(x, *someargs, **someotherargs) the sequence 'someargs' is used to supply a variable number of additional positional arguments. 'someotherargs' should be a dictionary and is used to supply additional keyword arguments. From astrand at lysator.liu.se Tue Jan 6 16:44:04 2004 From: astrand at lysator.liu.se (Peter Astrand) Date: Tue, 6 Jan 2004 22:44:04 +0100 (CET) Subject: PEP 324: popen5 - New POSIX process module In-Reply-To: <16E1010E4581B049ABC51D4975CEDB8803060D8E@UKDCX001.uk.int.atosorigin.com> Message-ID: On Tue, 6 Jan 2004, Moore, Paul wrote: > > 1) Should popen5 support a string argument on Windows? > > > > and > > > > 2) Should popen5 support a string argument on UNIX? > > > > You seems to have made up your mind about case 1, and even thinks that > > this should be "recommended". I'm not that sure. > > Using a list works most of the time, but can break in subtle, and surprising > ways. I have coded "Algorithm A in reverse" a number of times, and *always* > managed to construct a program that "broke". With Windows GUI programs > (not the key use case for this module, I admit) it's not remotely hard to > construct a broken example :-( Ok, lets support case 1 then. Currently, I also think that we should support case 2 as well, using Algorithm A. We need to document that single quote escaping are not supported, though. > > The only drawback with "process" is that it is already in use by > > http://starship.python.net/~tmick/#process. > > Ah. I wasn't aware of that module. I wasn't either, until I was about to announce the PEP. That's why there's no reference to Trent's module in the PEP (yet). >I wonder whether Trent would be willing > to combine his code and yours somehow, and donate the name? I have contacted Trent; let's give hime some time to respond. -- /Peter ?strand From francisgavila at yahoo.com Sun Jan 11 14:20:59 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 11 Jan 2004 14:20:59 -0500 Subject: Variable Scope 2 -- Thanks for 1. References: <10038cpbu23hv93@corp.supernews.com> Message-ID: <10038irlidciha2@corp.supernews.com> Francis Avila wrote in message <10038cpbu23hv93 at corp.supernews.com>... >Jens Thiede wrote in message ... >>OK, thanks for sorting that out, but what do I replace in the >>following to avoid referancing: >> >>x = [[0]*5]*5 >>x is [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] >> >>and after >> >>x[0][0] = 1; >>x is [[1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0]] > >Ah, the joy of list comprehensions! > >>>> x = [ [ 0 for i in range(5)] for j in range(5)] In my enthusiasm for list comprehensions I went too far. The inner loop comp is unnecessary because ints are immutable. So [ [0]*5 for i in range(5) ] is enough. -- Francis Avila From jjl at pobox.com Mon Jan 19 20:43:44 2004 From: jjl at pobox.com (John J. Lee) Date: 20 Jan 2004 01:43:44 +0000 Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> Message-ID: <87r7xv9yy7.fsf@pobox.com> Just want to state explicitly from the outset that this is all intended as friendly argument. Personally, I take it as a compliment when somebody takes me seriously enough to argue with me ;-) Wayne Folta writes: > I think one problem here is that somehow I left a paragraph out of my > original posting. After years and years of Perl use, I evaluated Ruby > and Python and have adopted Python. Ruby intrigues me, but it's not > what I will use to get things done. I thought that as a newcomer to > both, I though I might have a different perspective from people who > were native users, hence my posting. Great. I don't think that makes any difference to what I said, though: the correctness or otherwise of your statements is not dependent on which language you happen to like best. > I can see that without that info, it may have appeared that I was > possibly advocating Ruby over Python, which would be inappropriate in > a Pyton forum. I apologize for the confusion! Absolutely not! I see nothing even faintly wrong with arguing in favour of Ruby in comp.lang.python. Go ahead! In return, I'll tell you off if I think what you say is wrong or poorly reasoned :-) > > Well, that's not exactly a huge leap given any knowledge of how the > > internet works. I'm not sure that Python's docs should be in the > > business of educating people about that... > > There's no necessary connection between the protocol stack and > software packages. It's good and sensible that POP3 is built on > socket, but it could be based on my_sockets or _socket or who knows > what. I'm not asking that the entire protocol stack be documented, and > it's not as if "obvious" things aren't documented in detail elsewhere > in Python. (For example, there's an entire paragraph on socket's > gethostname(). I could rhetorically say this is so obvious it should > be replace with "returns host name" or "see GETHOSTNAME(3)"?) I see your point, though I think there's an significant difference in degree here. Still, perhaps it's useful (while timeouts aren't directly supported by clients of the socket module) to point people to the socket module docs for the default timeout setting. Try writing a doc patch and submitting it to SF. [...] > > ...but the fact that there is no timeout support in client modules of > > the socket module is a known bug: > > This is a bug? I guess it can cause problems in the underlying > package, Sorry, I was following the sloppy practise of using the word "bug" to cover all sins. By "bug" here I mean "gross missing feature" -- something that really should be there, but nobody has got round to implementing yet. I didn't mean that socket or its client modules behave incorrectly according to their docs (apart from raising socket.timeout, of course!). > but I sure hope that the exception is handled and then > re-raised as timeout_proto or something distinct from error_proto. I ATM, client modules know nothing about socket timeouts, AFAIK, so socket.timeout is never caught. Not sure whether it's best to just let socket.timeout propagate, or wrap it in an error_proto (if the latter, a subclass certainly sounds like a good idea). [...] > From an external viewpoint I don't see that much difference between > "fixing" this bug and simply documenting the other exceptions you > might see from underlying packages. set_timeout() methods (or similar) need to be added to these modules. [...about "Real OO"...] > languages like Python) and said that. I'm making no statement about > reality, but simply about what advocates mantras are. (Or actually, as > I carefully said, "might be".) > > (Actually, now that I reread it, I should've said "pure OO", which I > believe is more reflective of their statements. And this has some > basis in fact, I believe, if you look at the v1 of Ruby and Python and > what is first-class and what is not.) I don't know what "pure OO" is either! > > I don't see how a missing feature in Python reveals any difference in > > culture between Python and Ruby, other than perhaps that the Ruby > > people like implementation inheritance more than the people who > > designed the Python standard library. > > You have taken my observation and transformed it into ignorance on my > part In saying "...I'm not sure that Python's docs should be in the business of educating people about that..." I wasn't trying to imply that you're uneducated! I assumed you simply failed to make the "obvious" (or not) connection from timeouts to the socket module, and made the point that the documentation cannot and should not attempt to solve all such problems. > and a supposed bug on Python's part. Once you've done that, yes, > it is no longer illuminative. My point was simply that there are no .set_timeout() methods in the client modules of socket because nobody has yet got round to it, not because of some deliberate design decision... > Again, as you yourself say, they chose to subclass protocol services > off of a class 'protocol' and Python did not. In fact, Python chose to > not subclass POP3 from anything. Why? Because of the culture, in my > opinion. Ruby emphasizes OO and that it's "pure OO" (their opinion) > and so an implementation that involves a Smalltalk-ish subclassing of > everything recommends itself. ...oh, I see. Yes, that's a substantive difference in design, I agree (and perhaps in culture -- I wouldn't know, not having used Ruby). (Mind you, it's far from obvious that it's good OO design to have every class that uses sockets inherit from a socket class, let alone that it's a requirement for "pure OO" (which remains undefined). Does "pure OO" mean simply "using inheritance a lot"? Hmm, I didn't mean to get into this debate: I just wanted to point out the lack of meaning in saying "Real OO" without defining what you mean.) > Python has a different culture where such strict tree-like class > structure does not recommend itself. Python's "batteries included" > philosophy resulted in a more straightforward and (mostly) better > documented way to do it. > > Intellectually, I prefer Ruby. Ruby and Smalltalk intrigue me. But the > "pure OO" approach (my words this time) is annoying, and even at some > point inconsistent, as I mentioned in my paragraph about 0.step(). I > feel like Python has got the right balance where it's OO and pretty > much fully so, but not fanatically so. And it's what I've adopted. [...] I'm not competent enough to make judgements on these issues, I think: they're quite subtle. I certainly agree that such decisions about language and library design should be made on the basis of pragmatic design informed by a good understanding of underlying principles, not on some blinkered notion of "purity", but I've not much idea where Ruby fits on that scale, so I'll shut up :-) John From a at a.invalid Thu Jan 8 18:00:47 2004 From: a at a.invalid (Timo Virkkala) Date: Fri, 09 Jan 2004 01:00:47 +0200 Subject: Cheetah - Test suite failures In-Reply-To: References: Message-ID: Joe Francia wrote: > You also may want to post this question to the Cheetah list: > http://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss Thanks, I'll do that.. -- Timo Virkkala From mcfletch at rogers.com Wed Jan 21 16:48:27 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 21 Jan 2004 16:48:27 -0500 Subject: Nokia prefers Python In-Reply-To: References: Message-ID: <400EF3AB.9050601@rogers.com> Robin Becker wrote: >This might be the start of a success story. Says Nokia prefers Python! > >http://www.theregister.co.uk/content/64/35040.html >-ringing-ly yrs- >Robin Becker > > Oh, neat. Someone was looking for a series 60 developer a few months ago and wandered into the PyGTA meeting (well, wandered with some prodding :) ). Maybe she knew something we didn't. Wonder what the process is for getting access to the dev kit? I suppose I'd have to buy a phone/N-gage first :) . Python on a cell-phone... what a wonderful world :) , Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From martin at v.loewis.de Sat Jan 3 19:14:52 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sun, 04 Jan 2004 01:14:52 +0100 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: References: Message-ID: <3FF75AFC.3020204@v.loewis.de> Peter Astrand wrote: > I don't agree. I have used all of the existing mechanism in lots of apps, > and it's just a pain. There are lots of functions to choose between, but > none does what you really want. So enhance them, instead of replacing them. >>> - Cross-process exceptions: Exceptions happening in the child >>> before the new process has started to execute are re-raised in >>> the parent. >>> >>This is a bug in popen2, IMO. Fixing it is a good thing, but does not >>require a new module. > > "Fixing popen2" would mean a break old applications; exceptions will > happen, which apps are not prepared of. I find that an acceptable incompatibility, and it will likely break no existing application. Applications usually expect that the program they start actually exists; it is a good thing that they now can detect the error that the missing/non-executable application. Errors should never pass silently. >>> - A hook for executing custom code between fork and exec. This >>> can be used for, for example, changing uid. >> >>Such a hook could be merged as a keyword argument into the existing >>API. > > > Into which module/method/function? For example, popen2.popen2, as argument preexec_fn. > There is no one flexible enough. The > case for redirecting only stderr is just one example; this is simple not > possible with the current API. Can you elaborate? What is the specific problem, how does your preexec function look like, and how is it used with popen5. I can then show you how it could be used with popen2, if that was enhanced appropriately. >>> - All combinations of file descriptor redirection is possible. >>> For example, the "python-dialog" [2] needs to spawn a process >>> and redirect stderr, but not stdout. This is not possible with >>> current functions, without using temporary files. >> >>Sounds like a new function on the popen2 module. > > > To support all combinations, 12 different functions are necessary. Who > will remember what popen2.popen11() means? Why is that? Just add a single function, with arguments stdin/stdout/stderr. No need for 12 functions. Then explain the existing functions in terms of your new function (if possible). >>> - Support for connecting several subprocesses (shell "pipe"). >> >>Isn't this available already, as the shell supports pipe creation, >>anyway? > > > With popen5, you can do it *without* using the shell. Why is that a good thing? > There's already a bug about this; bug 788035. This is what one of the > comment says: > > "But this whole popen{,2,3,4} section of posixmodule.c is so fiendishly > complicated with all the platform special cases that I'm loath to touch > it..." > > I haven't checked if this is really true, though. You really should work with the existing code base. Ignoring it is a guarantee that your PEP will be rejected. (Studying it, and then providing educated comments about it, might get you through) I think this is the core problem of your approach: You throw away all past history, and imply that you can do better than all prior contributors could. Honestly, this is doubtful. The current code is so complicated because implementing pipes is complicated. > Well, I don't see how this could be done easily: The current API is not > flexible enough, and some things (like cross-process exceptions) breaks > compatibility. I never said it would be easy. However, introducing a new popen module is a major change, and there must be strong indications that the current API cannot be enhanced before throwing it away. There should be one-- and preferably only one --obvious way to do it. As for breaking compatibility: This is what the PEP should study in detail. It is sometimes acceptable to break compatibility, if applications are likely to be improved by the change. *Any* change can, in principle, break compatibility. Suppose I had an application that did from popen5 import open This application might break if your proposed change is implemented, as a new module is added. So you can't claim "I will break no programs". > Writing a good popen module is hard. Providing cross-platform support (for > Windows, for example) is even harder. Trying to retrofit a good popen > implementation into an old API without breaking compatibility seems > impossible to me. I'm not prepared to try. So I continue to be -1 with your PEP. Regards, Martin From syver at inout.no Fri Jan 16 11:39:32 2004 From: syver at inout.no (Syver Enstad) Date: 16 Jan 2004 17:39:32 +0100 Subject: Very strange unicode behaviour References: Message-ID: I have seem to isolate the behaviour: >>> chr(127).find(u'') 0 >>> >>> chr(128).find(u'') -1 >>> UnicodeError: ASCII decoding error: ordinal not in range(128) >>> Observe that the exception is first thrown on after execing a blank line, after calling find on a non ASCII string. I'll test this on 2.3 when I get home from work. From __peter__ at web.de Fri Jan 2 11:57:16 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jan 2004 17:57:16 +0100 Subject: Passing to a function -- object and method names (or references) References: <3ff595e2.67831682@news.iprimus.ca> Message-ID: Midas wrote: > I'm including code, for cut/paste, to better explain my question. I create > a Car object then I call some of its methods. No problem. Then I try to > pass, to a function, the name of the Car object and the name of one of its > methods. I found one way to get this to work but can someone show me a > more orthodox way? Is there a way using references to the object and > somehow the method? You can access attributes with the getattr() builtin. carGas = getattr(car, "gas") You can refer to a method either directly fun = car.drive fun(123) or via getattr(): fun = getattr(car, "drive") fun(321) I've modified your example to demonstrate this. class NoGas(Exception): pass class Car: def __init__(self): self.milespergallon = 25.0 self.gas = 20 self.travelled = 0 def drive(self, miles): newGas = self.gas - miles/self.milespergallon if newGas < 0: self.travelled += self.milespergallon*self.gas self.gas = 0 raise NoGas("%s miles travelled. No more gas" % self.travelled) self.travelled += miles self.gas = newGas def printAttr(obj, attrname): "Demo for accessing an attribute by its name" print attrname, "=", getattr(obj, attrname) def callMethod(obj, methodname, *args): """ Demo for calling a method determined by its name. An arbitrary number of arguments is just passed through to the method. """ method = getattr(obj, methodname) print "calling", methodname method(*args) def callMethod2(method, *args): """ Demo for calling a method reference. The method is is generated by obj.method in the calling code. Of course you can pass function references as well """ method(*args) def someFunction(): print "Welcome to the Python Motorshow" callMethod2(someFunction) car = Car() printAttr(car, "gas") callMethod(car, "drive", 10) printAttr(car, "gas") while True: printAttr(car, "travelled") callMethod2(car.drive, 100) Note that my car will not travel as far as yours as it is less satisfied with negative amounts of gas :-) Peter From newsgroups at jhrothjr.com Wed Jan 21 16:34:26 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 21 Jan 2004 16:34:26 -0500 Subject: Redefining __call__ in an instance References: <73b00f0c.0401151529.676347b6@posting.google.com> <73b00f0c.0401211013.29b5718a@posting.google.com> Message-ID: <100ts518i4qvqe7@news.supernews.com> "Robert Ferrell" wrote in message news:73b00f0c.0401211013.29b5718a at posting.google.com... > Jason Mobarak wrote in message news:... > > def firstFunc (s, word='up'): > > print "foo" > > > > class callNoWork(object): > > def __new__ (cls): > > cls.__call__ = firstFunc > > return object.__new__(cls) > > > > callNoWork()() > > > > # Dunno if you've read this, but it explains this: > > # http://python.org/2.2.1/descrintro.html > > Thanks for the pointer. I had read this a while ago, it didn't all > sink in, and I'd forgotten about it. That was exactly the info that I > needed. In particular, it says that __call__ is a static method, so > it is not possible to define that differently for each instance. > > The code above was a good reminder for me, but because __call__ is a > static method, any new instantiation redefines __call__ for all > existing instances. Huh, what? __call__() is *not* a static method. It's a perfectly ordinary instance method, and there is nothing in the document above that says anything different. What it is is a static *attribute.* That's a different animal entirely. Static attributes cannot be overridden by defining them in an instance. The entire issue is that old style and new style classes treat a __call__ method in an instance differently. New style classes ignore it, old style classes use it. John Roth > > Thanks for the pointer, > -robert From __peter__ at web.de Sat Jan 31 12:58:36 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 31 Jan 2004 18:58:36 +0100 Subject: problem with weakref.proxy References: Message-ID: Peter Otten wrote: > I'd recommend being lazy and using a WeakValueDictionary instead of > building the machinery on your own. Your code would then look similar to If you want to keep your original design, just use ref instead of proxy: import weakref class GOb: __olist=[] def c_show_all(): print "all GObs, sorted by priority:" for i in GOb.__olist: i().show() def proxy_callback(x): print "weakref.proxy callback" GOb.__olist.remove(x) proxy_callback=staticmethod(proxy_callback) c_show_all=staticmethod(c_show_all) def __init__(self, name="GOB", priority=0): self.priority=priority self.name=name ref=weakref.ref(self, GOb.proxy_callback) GOb.__olist.append(ref) GOb.__olist.sort(lambda x, y: cmp(x(), y())) def __del__(self): print "Destruktor called for GOB " + self.name def show(self): print self.name + " " + str(self.priority) def __cmp__(self, other): if self.priority < other.priority: return -1 elif self.priority == other.priority: return 0 else: return 1 if __name__ == '__main__': a=GOb("T1", 0) b=GOb("T2", 2) c=GOb("T3", 1) GOb.c_show_all() print "delete T1:" del a GOb.c_show_all() The line that failed in your original version is GOb.__olist.remove(x) because x is found in __olist by comparing against the list items - and the proxy automatically delegates this to the no longer existing object. With ref you have to explicitly dereference by calling (as seen in __olist.sort() in the __init__() method). As that step is not performed by the list.remove() method, only ref instead of GOb instances are compared and the callback succeeds. Peter From fuka at fuxoft.cz Sun Jan 4 13:31:34 2004 From: fuka at fuxoft.cz (Frantisek Fuka) Date: Sun, 04 Jan 2004 19:31:34 +0100 Subject: Progress indicator during FTP upload Message-ID: My application uses ftplib to upload files to remote server. What is the cleanest way to provide progress indicator for long files? What exactly should I override in the ftplib (I am not very proficient in the FTP protocol)? Thanks -- Frantisek Fuka (yes, that IS my real name) (and it's pronounced "Fran-tjee-shek Foo-kah") ---------------------------------------------------- My E-mail: fuka at fuxoft.cz My Homepage: http://www.fuxoft.cz My ICQ: 2745855 From R.Brodie at rl.ac.uk Fri Jan 23 12:09:54 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 23 Jan 2004 17:09:54 -0000 Subject: Sending Through ^] Through telnetlib References: Message-ID: "John Abel" wrote in message news:mailman.687.1074866920.12720.python-list at python.org... > I have written a script that makes a telnet connection, runs various > commands, and returns the output. That was the easy bit :) However, to > close the session, I need to send ^] followed by quit. Are you sure that just calling close() isn't what you want? It would be unusual to send ^]quit on the wire. From bignose-hates-spam at and-benfinney-does-too.id.au Tue Jan 27 20:13:56 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Jan 2004 12:03:56 +1050 Subject: Running python automatically in the background References: <1e4e0378.0401271729.3ea6b5c2@posting.google.com> Message-ID: On 27 Jan 2004 17:29:53 -0800, Alfred wrote: > i'm trying to figure out if there is some easy way to run a python > script in the background _without_ specifying "&" in a linux > enivornment. > > script.py & That's how you tell any POSIX-compatible shell (like bash) to execute a command as a background job. Why is that not acceptable? > been looking around but couldn't find any docs to support a > possibility. Perhaps if you explain what it is you're trying to achieve, we can offer a better solution. -- \ "We used to laugh at Grandpa when he'd head off and go fishing. | `\ But we wouldn't be laughing that evening when he'd come back | _o__) with some whore he picked up in town." -- Jack Handey | Ben Finney From christian.eslbauer at liwest.at Sat Jan 3 09:19:17 2004 From: christian.eslbauer at liwest.at (EsC) Date: Sat, 3 Jan 2004 15:19:17 +0100 Subject: SMTP - Topic & add files Message-ID: <1073137983.983243@news.liwest.at> Hy! probably a dummy question, but i don't know how to set a Topic-Text and add Files to an email ... i use the SMTPLIB module and the function/method: .sendmail(from,to,msg) but how can i set a topic Text? is there an other function/method, or must it be encoded within the message-text? thanks for your help EsC From jcarlson at nospam.uci.edu Wed Jan 28 10:12:47 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 28 Jan 2004 07:12:47 -0800 Subject: I support PEP 326 In-Reply-To: References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> <20040128041023.2EB9225B353@bonanza.off.ekorp.com> <20040128090205.GA3086@nl.linux.org> Message-ID: Skip Montanaro wrote: > >> That's a _lot_ of stuff in one module. Even if you exclude the 40-odd > >> exceptions that are there, that's still a lot of guff in one big flat > >> namespace. > > Gerrit> Any plans to clean it up in Python 3.0? > > Yes, there has been some discussion about this on python-dev. It doesn't > appear a PEP's been written yet. > > Skip Hey Skip, I know you commented on the flat namespace of __builtin__, but I've not seen any comments on PEP 326. Don't feel like you need to answer, but what are your feelings on it (even if you hate the PEP and give it a -1, you'll not hurt my feelings)? - Josiah From aahz at pythoncraft.com Sun Jan 18 10:22:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 18 Jan 2004 10:22:17 -0500 Subject: Python used in Freedom Force References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> <4006911e$0$327$e4fe514c@news.xs4all.nl> Message-ID: In article , Alan James Salmoni wrote: > >Perhaps all this stuff could be put onto the "Python Success Stories" >part of the python.org website? It's not public, but if the language >is clearly being used... Currently, due to the load on the webmasters and the available time, http://www.pythonology.com/ is better maintained. Send e-mail to the pythonology webmaster to get something included. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From hwlgw at hotmail.com Fri Jan 16 06:36:06 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 16 Jan 2004 03:36:06 -0800 Subject: Printing to console, no scroll References: <20040114190048.06766.00000030@mb-m21.aol.com> Message-ID: > I use it on my os2 2.1 laptop for which I don't have curses or tkinker libs. Do you also know how to get it to work on a Windows XP laptop? I tried cmd.exe and command.com, but they don't so ansi. From amy-g-art at cox.net Wed Jan 21 20:41:56 2004 From: amy-g-art at cox.net (Amy G) Date: Wed, 21 Jan 2004 17:41:56 -0800 Subject: Side note: Praise to the contibuters to this group Message-ID: I just wanted to take a second and thank all of the contributors to this awesome newsgroup. I am subscribed to a whole bunch of newsgroups for work as well as personal use. Of all of the groups, I find this one to have the most thorough responses and the most helpful members. I have personally only been programming in python for a little over 2 months, but have already received phenomenal aide from the brainiacs who lurk about. So, thank you. Thank you to all who have helped me, and to all who have helped others to better understand this awesome programming language. From jjl at pobox.com Tue Jan 13 13:02:35 2004 From: jjl at pobox.com (John J. Lee) Date: 13 Jan 2004 18:02:35 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> <87d69og2jl.fsf@pobox.com> Message-ID: <873cajafr8.fsf@pobox.com> "Derek" writes: [...] > Point taken. I once worked on a project where we implemented a > production system in C++ and then implemented it again in Python for > QA purposes. It took about 150k lines of C++ code and 10k lines of > Python. Python took less code because so many modules are bundled > with the language, but the C++ system ran many times faster. It's all > about picking the right tool for the job. Well, that's a banal truism obscuring the fact that, for the great majority of projects, optimisation does not require implementation of the *entire* system in a language like C++. The sum of C++ and Python is greater than the parts. John From dsarrazinNOSPAMPLEASE at cyberus.ca Mon Jan 12 05:41:01 2004 From: dsarrazinNOSPAMPLEASE at cyberus.ca (Denis Sarrazin) Date: Mon, 12 Jan 2004 05:41:01 -0500 Subject: Division oddity References: <7at3005sjtd6clgfm6e7v1gq83ohlrc2td@4ax.com> <6b2dnS9lM559YpzdRVn-ig@comcast.com> Message-ID: Thanks. I'd not realized that we could test out new changes to Python within existing Python code. Cool. -D Le Mon, 12 Jan 2004 02:49:45 -0700, Jason Mobarak a ?crit : >Please note: "from __future__ import division", see PEP 238 which >changes the behavior of the divisino operator. From frithiof.jensen at removethis.ted.ericsson.dk Mon Jan 12 05:52:10 2004 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Mon, 12 Jan 2004 11:52:10 +0100 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: "Samuel Walters" wrote in message news:pan.2004.01.11.06.08.18.867825 at yahoo.com... > As I see it, when one considers which language is best for one's needs, > one considers a couple of things: > > 1) Does the language have the semantics I want. > 2) Does the language have the primitives I need. > 3) Can I *easily* build any missing or suboptimal primitives. > True. > One would assume that Fortran has the proper semantics for numerical > processing because it seems to have been wildly successful for a long > period of time. That, in my opinion, is wrong: Fortran is successful because it was there first! There exists a very large set of actively supported and proven libraries, NAG f.ex., which nobody will ever bother to port to another language just for the sake of it, and Fortran has been around for so long that it is well understood how best to optimise and compile Fortran code. It is easy enough to link with NAG if one needs to use it. > Fortran naturally comes with the primitives for numerical processing, > because numerical processing is its stated goal. ("FORmula TRANslation") ...or maybe the name sounded cool ;-) > Whether one uses Fortran, Python, or any other language, all primitives > are eventually implemented in either C or assembly. At some point or > another, we end up scraping bare metal and silicon to get our answers. Exactly - Fortran in itself does not do something that another language cannot do as well. It is just the case that Fortran is better understood when applied to numering processing than other languages because more "numerics" people used it than any other language. On DSP architectures, f.ex., I doubt that one would have better performance using Fortran in comparison with the C/C++ tools, DSP's usually ship with - because DSP's were "born" when C/C++ was hot. A lot of real, serious DSP work is done in Mathlab - thus skipping the issue of language choice and getting right onto getting the job done. This is good IMO. From jepler at unpythonic.net Tue Jan 27 11:37:04 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 27 Jan 2004 10:37:04 -0600 Subject: Problem with RE matching backslash In-Reply-To: <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> References: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> Message-ID: <20040127163703.GM18498@unpythonic.net> On Tue, Jan 27, 2004 at 03:31:24PM +0000, Ladv?nszky K?roly wrote: > Thanks for your quick and very helpful reply, Peter. > What is still not clear to me is why the search examples work and yield > 'm'. Because the first pattern, which you wrote as "\\m", will match a lone 'm'. So 'match' fails, because m is not in the first position. But 'search' succeeds at index 1. Jeff From Pieter.Claerhout at Creo.com Wed Jan 28 08:13:11 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 28 Jan 2004 14:13:11 +0100 Subject: Oracle beginner problem: can't connect to Oracle using cx_Ora cle Message-ID: <490316A24CC5D411ACD700B0D078F7F003915E2E@cseexch01.cse.creoscitex.com> http://www.google.be/search?ie=utf-8&oe=utf-8&hl=nl&q=ORA-12514&btnG=google This google search will give you lot's of clues. Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Aurelio Martin [mailto:amartin at wpsnetwork.com] Sent: 28 January 2004 13:55 To: python-list at python.org Subject: Re: Oracle beginner problem: can't connect to Oracle using cx_Oracle Benson, John wrote: > Hi, I'm a non-Oracle guy just starting to use Python to explore Oracle. > I enclose the Python command prompt log for the usage example further > down with only the user, password and host names changed to keep me out > of trouble. But first, I'd like to point out that I'm able to logon to > myhost, and get into the following via SQL*Plus using myuser/mypassword > > Oracle8i Enterprise Edition Release 8.1.7.3.0 - Production > With the Partitioning option > JServer Release 8.1.7.3.0 - Production > > (end quote of Unix box SQL*Plus stuff) > > so I know that myuser/mypassword works for SQL*Plus on the myhost Unix > box. > > I downloaded the cx_Oracle Python interface to Oracle(r) Version: 4.0 > Date: December 17, 2003 Win32 binary for Oracle 8i, Python 2.) and > proceeded to exercise the usage example: > > PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] > on win32. > Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - > see 'Help/About PythonWin' for further copyright information. > >>>>import cx_Oracle >>>>connection = cx_Oracle.connect("myuser/mypassword at myhost") > > Traceback (most recent call last): > File "", line 1, in ? > DatabaseError: ORA-12514: TNS:listener could not resolve SERVICE_NAME > given in connect descriptor > I think it's a problem with the connection data in your Windows PC. You have tested a local connection ( user/password ) on the Unix host with SQL*Plus. Have you tried a remote connection ( user/password at host ) from your Windows PC with SQL*Plus ? I think you will find the same problem if you try it with SQL*Plus. Probably the connection data in your TNSNAMES.ORA file is not correct. Hope this helps Aurelio -- http://mail.python.org/mailman/listinfo/python-list From dave at boost-consulting.com Sun Jan 4 08:11:42 2004 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 04 Jan 2004 08:11:42 -0500 Subject: Advanced (?) compiling, freezing, translating Python References: <312735AC.3841CC26.0331AA34@netscape.net> Message-ID: luszczek1 at netscape.net writes: > Hi, > > here's my problem: > > - I know it will take me 10 times as long to write a code in C than in > Python > - I need the speed of the C version > - my program cannot depend/require on Python > interpreter/libraries/modules > > Is there a way to write Python program that almost looks like (say) C > and then transoform it into C. Transformation should be intelligent - > I don't want dynamic objects with dictionaries of methods. I'm willing > to provide type descriptions so when I say: > myList = [0] * 100 > > I get in C: > int *myList; > myList = calloc(100, sizeof(int)); > > I'm aware of projects like Pyrex, Psyco, and Pypy but their scope is > too broad: they are about Python in its entirety and dynamism. I think you're underestimating the actual scope of what you're trying to describe... but anyway, here's another one you probably aren't interested in because it's too broad ;-) http://felix.sf.net -- Dave Abrahams Boost Consulting www.boost-consulting.com From gandalf at geochemsource.com Fri Jan 30 02:23:26 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 30 Jan 2004 08:23:26 +0100 Subject: wxNotebook question References: <5.2.0.4.0.20040129151313.02127918@blue-cove.com> Message-ID: <401A066E.2080604@geochemsource.com> > > >> How can I hide/show a page (wxNotebookPage) invisible of a >> wx.wxNotebook instance? >> There is a GetPage() method which returns a wxNotebookPage but I >> could not find >> any documentation in the help about this class. > > > I use: > C:\Python23\Lib\site-packages\wxPython\docs\wx.chm > always, but > http://www.orbtech.com/www/wx/epydoc/ > is great, and shows inherited properties Thanks, epydoc is the best. (Note: I meant wxNotebookPage, there is no doc about wxNotebookPage in the wx.chm) >> I thought there will be a 'SetVisible' >> or 'SetTabvisible' method but it seems to be a proxy for the root >> control on that page. >> So I cannot even get method names by dir(self.notebook.GetPage(0)). > > > Check the "Show()" method > Show (self, show) > (inherited from Window ) Thanks. I was blind. I searched the docs but I looked for 'Visible' only. Bad habit from a Delphi programmer. :-) G -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryangrow at yahoo.com Fri Jan 23 14:05:41 2004 From: ryangrow at yahoo.com (Ryan Grow) Date: Fri, 23 Jan 2004 11:05:41 -0800 (PST) Subject: fcntl O_NDELAY constant not found in python 2.3 on linux Message-ID: <20040123190541.31213.qmail@web21206.mail.yahoo.com> Hi, I'm trying to use fcntl to set an existing file descriptor to be nonblocking. This contrived example exhibits the behavior of python that is preventing me from doing this: import os, fcntl, FCNTL file = open("/tmp/testfd.txt", 'w') fd = file.fileno() fl = fcntl.fcntl(fd, FCNTL.F_GETFL) fcntl.fcntl(fd, FCNTL.F_SETFL, fl | FCNTL.O_NDELAY) print "Made it!" When I run this in the following environment, it works fine: Linux Kernel 2.4.7-10 python 2.1.1 [rgrow at linux01 python]$ /usr/bin/python2.1 ./testfcntl.py Made it! However, when I run this with either python 2.3.2 or 2.3.3, I get the following output: [rgrow at linux01 python]$ python ./testfcntl.py /usr/local/lib/python2.3/FCNTL.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) Traceback (most recent call last): File "./testfcntl.py", line 6, in ? fcntl.fcntl(fd, FCNTL.F_SETFL, fl | FCNTL.O_NDELAY) AttributeError: 'module' object has no attribute 'O_NDELAY' What is the correct way that I should be making this kind of a call in 2.3 to both avoid the deprecation warning as well as the attribute error? Thanks, Ryan __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From amartin at wpsnetwork.com Wed Jan 28 07:55:22 2004 From: amartin at wpsnetwork.com (Aurelio Martin) Date: Wed, 28 Jan 2004 13:55:22 +0100 Subject: Oracle beginner problem: can't connect to Oracle using cx_Oracle In-Reply-To: References: Message-ID: Benson, John wrote: > Hi, I'm a non-Oracle guy just starting to use Python to explore Oracle. > I enclose the Python command prompt log for the usage example further > down with only the user, password and host names changed to keep me out > of trouble. But first, I'd like to point out that I'm able to logon to > myhost, and get into the following via SQL*Plus using myuser/mypassword > > Oracle8i Enterprise Edition Release 8.1.7.3.0 - Production > With the Partitioning option > JServer Release 8.1.7.3.0 - Production > > (end quote of Unix box SQL*Plus stuff) > > so I know that myuser/mypassword works for SQL*Plus on the myhost Unix > box. > > I downloaded the cx_Oracle Python interface to Oracle(r) Version: 4.0 > Date: December 17, 2003 Win32 binary for Oracle 8i, Python 2.) and > proceeded to exercise the usage example: > > PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] > on win32. > Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - > see 'Help/About PythonWin' for further copyright information. > >>>>import cx_Oracle >>>>connection = cx_Oracle.connect("myuser/mypassword at myhost") > > Traceback (most recent call last): > File "", line 1, in ? > DatabaseError: ORA-12514: TNS:listener could not resolve SERVICE_NAME > given in connect descriptor > I think it's a problem with the connection data in your Windows PC. You have tested a local connection ( user/password ) on the Unix host with SQL*Plus. Have you tried a remote connection ( user/password at host ) from your Windows PC with SQL*Plus ? I think you will find the same problem if you try it with SQL*Plus. Probably the connection data in your TNSNAMES.ORA file is not correct. Hope this helps Aurelio From eric.brunel at N0SP4M.com Tue Jan 20 03:59:16 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Tue, 20 Jan 2004 09:59:16 +0100 Subject: Tk Icon - request to Fredrik Lundh References: <8089854e.0401190436.10f99713@posting.google.com> <8089854e.0401200031.445728d9@posting.google.com> Message-ID: Fuzzyman wrote: > Eric Brunel wrote in message news:... > >>Fuzzyman wrote: >> >>>There is a very interesting (and potentially useful) program on the >>>effbot website - called Tkicon. >>> >>>http://www.effbot.org/downloads/ >>> >>>Unfortuantely the last supported version of python is 2.1 >>>I've seen a few people asking, but never an answer, on Python 2.3 >>>support. >> >>This utility should not be needed anymore if you're using a recent version of >>tcl/tk: the method wm_iconbitmap on toplevel's, that didn't work on earlier >>versions of tk on Windows, now works without problem. You should specifiy a .ico >>or .icr file name as its argument. See the documentation for the corresponding >>tk command at: >>http://www.tcl.tk/man/tcl8.3/TkCmd/wm.htm#M15 >> > > > Hmmm..... reading the documentation makes things less clear :-) > > How about : > > test = tkinter.Toplevel(wm_iconbitmap='test.ico') Nope: test = Tkinter.Toplevel() test.wm_iconbitmap('test.ico') All tcl/tk wm commands map to the corresponding wm_... *method* on Tkinter objects. It indeed takes some time to get used to... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From francisgavila at yahoo.com Thu Jan 22 15:24:24 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 22 Jan 2004 15:24:24 -0500 Subject: performing action on set of charecters References: Message-ID: <1010ce6opqvuv13@corp.supernews.com> jeff wrote in message ... >hiya, > >Ive a load of binary in a file. Its 3 bit (2^3) and i wanna convert it >to an integer. > >ive tried using theintergar = string.atoi(thebinary, 2), but that >doesnt take it as 3 bit binary > >it has no spaces it it, so im a bit stuck as to how to do this with >python, > >cheers > >greg Three bit binary?! Whoever designed that format is a sadomasochist. You're going to have to separate out the bits in the byte stream (so that each bit is a byte--use strings), take three-bit groupings, and multiply to convert to integer. If this is a single, isolated three-bit integer, your approach will involve shifting. If it's a continuous stream, without any padding, you can work in groups of 24 bits (4 bytes), which gives you 8 3-bit ints. There are many different approaches, but all will be painful. I don't think it would be much easier in C, either (bit manipulation is often a little easier in C compared to Python, albeit more dangerous). Search this group. Not too long ago there was talk of a module for working with binary which you might find helpful. -- Francis Avila From vscan at vdr.ma Thu Jan 29 05:30:11 2004 From: vscan at vdr.ma (vscan at vdr.ma) Date: Thu, 29 Jan 2004 10:30:11 +0000 (WET) Subject: VIRUS IN YOUR MAIL Message-ID: <20040129103011.5D317ADFC1C@xfusion.intranet> V I R U S A L E R T Our viruschecker found the I-Worm.Mydoom virus(es) in your email to the following recipient(s): -> nondmatherr at amstex.tex -> postfix at vdr.ma Please check your system for viruses, or ask your system administrator to do so. For your reference, here are the headers from your email: ------------------------- BEGIN HEADERS ----------------------------- Received: from python.org (unknown [192.168.0.119]) by xfusion.intranet (Postfix) with ESMTP id C630BADFC06 for ; Thu, 29 Jan 2004 10:30:10 +0000 (WET) From: python-list at python.org To: nondmatherr at amstex.tex Subject: HI Date: Thu, 29 Jan 2004 10:29:46 +0000 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0003_211518AE.BC08BBF0" X-Priority: 3 X-MSMail-Priority: Normal Message-Id: <20040129103010.C630BADFC06 at xfusion.intranet> -------------------------- END HEADERS ------------------------------ From max at alcyone.com Fri Jan 9 04:11:44 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 09 Jan 2004 01:11:44 -0800 Subject: user/passwd entry References: Message-ID: <3FFE7050.DAC170F0@alcyone.com> John Smith wrote: > I'm wondering how to enter the user and password for a site over http? > What's the module that I should use: urllib, htmllib, HTMLParser, > httplib? > What are the classes I should call, etc? Thanks for any help. It depends on exactly how you're entering the password. If it's just part of a form, then you'd do it through normal CGI means. If it's actually HTTP authentication, then you can do that by subclassing urllib.URLopener. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ No one should have to dance backward all their lives. -- Jill Ruckelshaus From sambo at void.com Fri Jan 23 12:33:40 2004 From: sambo at void.com (sambo) Date: Fri, 23 Jan 2004 09:33:40 -0800 Subject: Assignment to slice References: <20040121130236.D8E3.JCARLSON@uci.edu> Message-ID: <40115AF4.4070709@void.com> Rich Krauter wrote: > I'm just surprised that nobody thinks it's unusual. > > >>> x = [] > >>> x[4] = 5 > Python says "Wrong! Can't do that! I'm quitting now!" > >>> x = [] > >>> x[4:5] = [1,2,3,4,5] > Python says "Ok. Cool. Those indices don't exist in x so I'll just > stick your list at the beginning, > and the indices you used in the slice have nothing to do with where > the elements end up, > since they don't exist in the list anyway." > > To me that doesn't look much different than if python were to do this: > (not real code obviously) > > >>> x = [] > >>> x[4] = 5 > >>> x > [5] > Python says "Well, x[4] doesn't exist so you must have meant x[0]." > > > That would make no sense. So why does it make sense to do that same > exact thing if you're > assigning to a slice, instead of an element? > > That's what I see as inconsistent; not that python does not behave > just like perl. I'm sure that > a little more time will reveal this 'inconsistency' as a shortcoming > in the wiring of my brain, and > not a weird python idiosyncrasy. It's cool to hear other people's take > on it. > Thanks alot. > Rich > > Well one might argue, I suppose, that the key word here is LIST - good for storing strings not so for numeric data/matrixes. Imagine my surprise when I was trying to find my numeric command line arguments with int() only to find int( "string" ) != 0 but an exception is raised instead. Cheers From NAIGIMSESRIMAIL at gims.com Tue Jan 27 07:20:36 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Tue, 27 Jan 2004 14:20:36 +0200 Subject: ALERT - GroupShield ticket number OA1720_1075206030_ESRIMAIL_3 w as 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: ciwwy at aol.com Sent: -1211817472,29615281 Subject: Error Attachment Details:- Attachment Name: ATT12795.txt File: ATT12795.txt 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: 1863 bytes Desc: not available URL: From maxm at mxm.dk Mon Jan 19 07:18:57 2004 From: maxm at mxm.dk (Max M) Date: Mon, 19 Jan 2004 13:18:57 +0100 Subject: Does anyone else not find the fun in programming...? In-Reply-To: References: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> <400a7a92$0$205$edfadb0f@dread12.news.tele.dk> Message-ID: <400bcb2b$0$180$edfadb0f@dread12.news.tele.dk> Dave Benjamin wrote: > So, a data-flow style more or less... that seems to be a useful model for > music software. Have you ever played around with Max? No. I tried c-sound, and while it was interesting, it was really cumbersome at the level I am interested in. > Yeah, makes perfect sense to me. Do you have any Python-generated songs > available? Sounds really cool. Nothing I will release. Mostly pre-studies. > The thing I was working on was a probabilistic beat generator, based on > statistics of when a certain drum would hit in a beat for a selection of hip > hop songs. I was trying to capture the "feel" rather than the exact sequence > of sounds. That is a good way to go. Bayes networks for rythmical patterns. regards Max M From Kyler at Lairds.com Tue Jan 20 18:48:55 2004 From: Kyler at Lairds.com (Kyler Laird) Date: Tue, 20 Jan 2004 18:48:55 -0500 Subject: calling Pyrex results from C In-Reply-To: <20040120172733.GA7666@titan.progiciels-bpi.ca> References: <20040120172733.GA7666@titan.progiciels-bpi.ca> Message-ID: <20040120234855.GV22782@jowls> On Tue, Jan 20, 2004 at 12:27:33PM -0500, Fran?ois Pinard wrote: > There is some magic needed to establish Python context, not much. > Hoping that it will help, here is a template I use when generating > Pyrex main programs. Paul started me on this path and you've given me exactly what I need to keep going. Thank you! --kyler From mark at mceahern.com Sun Jan 4 22:45:56 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 04 Jan 2004 21:45:56 -0600 Subject: Why does this fail? In-Reply-To: References: Message-ID: <1073274355.12941.27.camel@dev.internal> On Sun, 2004-01-04 at 20:58, Dave Murray wrote: [...] > I have found the library for html/sgml to be not very robust. Big .php and > .html with lot's of cascades and external references break it very > ungracefully (sgmllib.SGMLParseError: expected name token). I'd suggest using htmllib. // m From mike at triplepc.com Sat Jan 10 14:21:29 2004 From: mike at triplepc.com (Michael T. Babcock) Date: Sat, 10 Jan 2004 14:21:29 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: References: Message-ID: <400050B9.5070904@triplepc.com> > > >From: "Peter Hansen" > >I have to say that I do, but I'm also dealing with datasets up to about >500MB in the worst case - but about 10-20MB in the normal case. > I have one customer for whom I'm writing software to parse large (~1GB) Quark Express documents and for the initial months of the project, optimization was a large piece of the coding process. Rewriting and rewriting to get the information I needed as quickly as possible. Considering the initial version of the program took all night to parse the file and I'm down to about 40 minutes now, its been quite a ride. That said, over the entire length of the project, about 80-90% of my time will be straight user interface coding with very little (or no) time spent on optimization, so my net optimization time by the end of the project will be quite low again. This is similar to a comment made by someone else re: library programmers now that I think about it. -- Michael T. Babcock http://www.fibrespeed.net/~mbabcock/code From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Jan 5 17:27:04 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 05 Jan 2004 23:27:04 +0100 Subject: local interpreter remote machines In-Reply-To: References: Message-ID: <3ff9e4b8$0$318$e4fe514c@news.xs4all.nl> hokieghal99 wrote: > This may not be possible, but I thought I'd ask anyway. Could I get the > below code to run on a Python server where other machines would connect > to it (say thru the Web) and get details of *their* system instead of > the system details of the machine that the interpreter is running on? > Any ideas? If you also have Python running on the other machine, you can do this very easily with Pyro: http://pyro.sourceforge.net (no network programming necessary at all). Essentially you create an object on the remote machine that contains a method with the code you want to execute, and you call that object -using Pyro- as if it was located on your own computer. But this only works if you have a supported Python version running on the remote machine, and that you are allowed to connect to that machine over the network. You can even create some python code on your local machine, and actually submit that to the other machine, let it deal with it, and then get the results back. But only do this if you know that no unauthorised user can do this, because this is a security risk. --Irmen de Jong. From mwh at python.net Wed Jan 14 06:47:03 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 14 Jan 2004 11:47:03 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: Jacek Generowicz writes: > Samuel Walters writes: > > > because there seem to be many more introductory tutorials and a lot of > > advice that one should learn Scheme, then move to Common Lisp. > > Careful. If you were to make such a suggestion on comp.lang.lisp, then > you'd be likely to be told that learning Scheme first will cause you > irreversible brain damage. Of course, now that He Whose Name Must Not > Be Mentioned is no longer posting there, Heeeeeeeeee's back! Cheers, mwh -- MAN: How can I tell that the past isn't a fiction designed to account for the discrepancy between my immediate physical sensations and my state of mind? -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From nicholas_wieland at yahoo.it Fri Jan 2 21:34:55 2004 From: nicholas_wieland at yahoo.it (Nicholas Wieland) Date: Sat, 03 Jan 2004 03:34:55 +0100 Subject: new style shelve implementation Message-ID: I'm using the shelve module for a program I'm writing, and reading the source I've noted that shelve doesn't use new style classes. Well, this is the first time I use *seriously* new style classes (I work primarly on Zope and Python 2.1), so the result is probably far from production code, but after half an hour of hacking my Shelf class seems to work like the original one (much more than what I expected...) :) class Shelf (dict): def __init__ (self, dict, protocol = None, writeback = False, binary = None): self.dict = dict if protocol is not None and binary is not None: raise ValueError, "can't specifiy both 'protocol' and 'binary'" if binary is not None: warnings.warn ("The 'binary' argument to Shelf() is deprecated", PendingDeprecationWarning) protocol = int (binary) if protocol is None: protocol = 0 self.protocol = protocol self.writeback = writeback self.cache = {} def __repr__ (self): dummy = dict () for k in self.keys (): dummy [k] = self [k] return repr (dummy) def keys (self): return self.dict.keys () def __len__ (self): return len (self) def has_key (self, key): return self.dict.has_key (key) def __contains__ (self, key): return self.has_key (key) def get (self, key, default = None): if self.has_key (key): return self.dict [key] return default def __getitem__ (self, key): try: value = self.cache [key] except KeyError: f = StringIO (self.dict [key]) value = Unpickler (f).load () if self.writeback: self.cache [key] = value return value def __setitem__ (self, key, value): if self.writeback: self.cache [key] = value f = StringIO () p = Pickler (f, self.protocol) p.dump (value) self.dict [key] = f.getvalue () def __delitem__ (self, key): del self.dict [key] try: del self.cache [key] except KeyError: pass def close (self): self.sync () try: self.dict.close () except AttributeError: pass self = None def __del__ (self): self.close () def sync (self): if self.writeback and self.cache: self.writeback = False for key, entry in self.cache.iteritems (): self.dict [key] = entry self.writeback = True self.cache = {} if hasattr (self.dict, "sync"): self.sync () Everything else is like the original one, I've just added a totally unpythonic implementation of the __repr__ method and removed the UserDict dependency. IMVHO if UserDict is going to be removed it's good to start removing it from the python library. On the other hand, this is just a dirty hack, so every comment is deeply appreciated. Happy new year, nicholas From todcsmith at yahoo.com Fri Jan 16 18:45:38 2004 From: todcsmith at yahoo.com (todd smith) Date: 16 Jan 2004 15:45:38 -0800 Subject: problems with os.path.isdir on windows shares (i've read the FAQ) Message-ID: <4489035c.0401161545.75b63ce@posting.google.com> having some strange problems with Python2.3 on windowsXP. im trying to access shares and the os.path.isdir function _always_ returns false even though the directories are there and i can os.chdir, os.listdir it in the python shell. i've followed the FAQs rule of putting the trailing '\\' on the share name with no luck heres my sessioin: >>> os.path.isdir('\\\\ren\\backup\\') False >>> os.chdir('\\\\ren\\backup\\') >>> os.getcwd() '\\\\ren\\backup' >>> os.listdir(os.getcwd()) ['ssbackup-16-1-2004.ssa', 'ssbackuptest-14-1-2004.ssa', 'tmp'] From t-meyer at ihug.co.nz Thu Jan 29 18:39:25 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 30 Jan 2004 12:39:25 +1300 Subject: Pythonwin - breaking out of infinite loop In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1304D0B9E8@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13046778AF@its-xchg4.massey.ac.nz> > How do I stop a Python program running in PythinWin? I would > expect to be able to use CTR-C or CTRL-break etc. If you right-click on the PythonWin icon in the tray, one of the items is "Break into running code". This will sometimes do it for you, and is probably your best chance. (It does break into "while True: pass", for example). =Tony Meyer From peter at engcorp.com Mon Jan 5 17:30:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Jan 2004 17:30:40 -0500 Subject: explicit variable declaration References: Message-ID: <3FF9E590.7EE65247@engcorp.com> Michel Claveau/Hamster wrote: > > Hi ! > > "Variable" is a bad word - beurk ! - In Python there are ref-on-objects ; > it's without interest with declaration (explicit). I'm not sure how helpful that is to a newbie, and in any case I've been using Python for a reasonably long time now and I definitely refer to those babies as variables.... with no ill effects to date. -Peter From c at c.com Wed Jan 14 10:16:45 2004 From: c at c.com (chris) Date: Wed, 14 Jan 2004 15:16:45 -0000 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Brandon J. Van Every" wrote in message news:bu2pim$d3pa0$1 at ID-207230.news.uni-berlin.de... > > "Dan Olson" wrote in message > news:pan.2004.01.14.04.32.52.403279 at fakeemail.com... > > On Tue, 13 Jan 2004 19:00:43 -0800, Brandon J. Van Every wrote: > > > > > I'm curious what sky is going to fall if I don't follow your advice? > > > > It's just advice. I think it would have been smoother for everyone if > > you'd followed it, but apparently you prefer to piss on my advice so > > that's cool too. > > You have some deep-seated need for smootheness? I see no a priori value in > smoothness. > And that is I think the base of all of your problems. (sorry, long-term lurker feels urge to put in my 2c) MrJeff From wilkSPAM at OUTflibuste.net Sat Jan 10 10:33:15 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sat, 10 Jan 2004 16:33:15 +0100 Subject: Asynchronous HTTP server in standard library ? References: Message-ID: <87eku76cp0.fsf@blakie.riol> "Pierre Quentel" writes: > Python standard library provides two modules for asynchronous socket > programming : asyncore and asynchat. Several web servers have been built > upon these modules (medusa being the best-known I suppose) and are famous > for their performance level > > Unfortunately no example of use is provided in the standard library (whereas > the more "classic" SocketServer is illustrated by BaseHTTPServer, > SimpleHTTPServer, etc). I think it would be useful if Python came with a > simple HTTP server written with these modules, to help beginners understand > how use them > > I've written one, which handles GET and POST requests. It's inspired by (and > partly copied from) the http subset of medusa, only reduced to less than 200 > lines. It's called SimpleAsyncHTTPServer and published on Active State > Python Cookbook > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259148 > > Any thoughts ? I think you'll be welcome in the web-sig !!! http://python.org/sigs/web-sig/ -- Wilk - http://flibuste.net From db3l at fitlinxx.com Tue Jan 27 17:31:04 2004 From: db3l at fitlinxx.com (David Bolen) Date: 27 Jan 2004 17:31:04 -0500 Subject: wxpython and wxlocale References: Message-ID: "Ya" writes: > This is my code: > The button of "OK" is not translated. > What is wrong ? I believe this was discussed recently on the wxPython list. Under Windows, wxMessageDialog creates a native Windows dialog, so wxPython/wxWindows is not in control of the basic dialog buttons (such as OK). They are therefore under control of the OS as far as internationalization goes, and will only obey the system settings. So if you need to operate in a localized setting other than that of the host operating system, I'm guessing you're best bet is to make your own dialog box rather than using wxMessageDialog. To add to the complexity (if I recall correctly), wxMessageDialog is implemented by wxWindows itself under Linux/GTK, so you don't see the same problem there. Clearly not an ideal situation, but one of the wrinkles that comes from trying to use native widgets on a platform when available. The wxPython list is probably a better place to get further details. -- David From maarten at remove_this_ws.tn.tudelft.nl Thu Jan 15 06:04:23 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Thu, 15 Jan 2004 12:04:23 +0100 Subject: Newbie: how to write modules without C Message-ID: I want to extend python with a framework for reading, manipulating and visualising CFD data. Basically I want to have an environment in which I can quickly and interactively produce results, and Python with SciPy seems to be an ideal start. However, the only references I can find about writing modules talk about using C, and that's exactly what I DON'T want to do. I don't need any low-level operations, just handy classes that understand my file-format and wrap SciPy features etc. So my questions are: 1) Is it necessary to resort to C when writing modules or can you use normal Python? 2) How do you load a Python script into a python session? 3) Can various python scripts be combined into a module? Thanks in advance! -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From linda at acm.org Thu Jan 29 22:22:52 2004 From: linda at acm.org (linda at acm.org) Date: Thu, 29 Jan 2004 22:22:52 -0500 Subject: (no subject) Message-ID: <200401300322.i0U3MoYT002606@mxzilla7.xs4all.nl> The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment. -------------- next part -------------- A non-text attachment was scrubbed... Name: body.zip Type: application/octet-stream Size: 0 bytes Desc: not available URL: From skip at pobox.com Sat Jan 31 10:48:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 31 Jan 2004 09:48:17 -0600 Subject: timeit In-Reply-To: References: Message-ID: <16411.52801.42668.236157@montanaro.dyndns.org> Duncan> This is possibly a stupid question, but I need to get this Duncan> working quickly, and I guess I'm just too tired / pressured to Duncan> see what I'm doing wrong. Import the subtract module in a setup arg to your Timer() constructor: tim = timeit.Timer(setup-'import subtract', stmt=s) Skip From secchi at sssup.it Thu Jan 22 05:54:59 2004 From: secchi at sssup.it (Angelo Secchi) Date: Thu, 22 Jan 2004 11:54:59 +0100 Subject: Importing database: newbie issue Message-ID: <20040122115459.0da97bfb.secchi@sssup.it> Hi, I have a database with a fixed format structure (i.e. i know the starting point and the length of each of the field composing the database) and I would like to extract from it only few fields (ex the one starting from the 32nd position with length 12...). What is the best way to do that? Thanks a From arsanalytica at yahoo.com Wed Jan 21 14:45:52 2004 From: arsanalytica at yahoo.com (Dan) Date: 21 Jan 2004 11:45:52 -0800 Subject: WSDL tools/problems (Salesforce.com) Message-ID: <8e198b65.0401211145.71d8bc85@posting.google.com> Salesforce.com has what looks to be a nice SOAP interface (see http://www.sforce.com) which I would like to access via Python. I am currently trying to use the newest release of ZSI (1.4.1) to process our Salesforce WSDL file but have run in to problems (see below). *Any* suggestions on alternative approaches, or how to get this approach to work will be appreciated. Also please note, since I am new to both Python and ZSI, that this is may be something really obvious. Thanks in advance, Dan Here is an example: >>> from ZSI.wstools.WSDLTools import * >>> w=WSDLReader() >>> w.loadFromURL('http://gothamanalytics.com/Ex/enterprise.wsdl') Traceback (most recent call last): File "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python23\Lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 592, in run exec cmd in globals, locals File "C:\Documents and Settings\Dan\Desktop\Python\sforce.py", line 3, in ? w.loadFromURL('http://gothamanalytics.com/Ex/enterprise.wsdl') File "C:\Python23\Lib\site-packages\ZSI\wstools\WSDLTools.py", line 37, in loadFromURL wsdl.load(document) File "C:\Python23\Lib\site-packages\ZSI\wstools\WSDLTools.py", line 195, in load binding.load(operations) File "C:\Python23\Lib\site-packages\ZSI\wstools\WSDLTools.py", line 488, in load mbinding.load_ex(GetExtensions(item)) File "C:\Python23\Lib\site-packages\ZSI\wstools\WSDLTools.py", line 609, in load_ex ob = SoapBodyBinding(use, namespace, encstyle, parts) File "C:\Python23\Lib\site-packages\ZSI\wstools\WSDLTools.py", line 780, in __init__ raise WSDLError( WSDLError: The parts argument must be a sequence. >>> From martin at v.loewis.de Fri Jan 9 18:17:53 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 10 Jan 2004 00:17:53 +0100 Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3FFF36A1.40303@v.loewis.de> Brian Kelley wrote: > Essentially, everything looks like this > _("STRING") > > I got to thinking that this is python, I shouldn't have to do this. Why > not have a mechanism to capture this data at compile time? Precisely because it is Python you should have to do this. The language that looks like line noise is a different one... Explicit is better than implicit. Simple is better than complex. > Which is just a subtype of string. When python parses this it adds it > in an entry in the internationalization table. (essentially a > dictionary) It also addes it as an entry to the standard gettext > mechanism to indicate strings that need to be localized. When the > string is created, if a value exists in the international table for the > given string, the string is converted to the current locale. Using what textual domain? > Now, I don't know if this is a good idea or not, and I may be > reinventing some wheels, but it has some appealing characteristics and > ties in with the gettext system really well. Of course, I'm a bit leary > with changing the python parser but I was uncomfortable with the two > step process of writing the code, then passing it through a source > analyzer so that it could be internationalized. What is your problem with that technique? You have to extract the strings *anyway*, because the translators should get a list of the strings to translate, and not need to worry with your source code. > So, am I being silly, redundant or just plain different? I do wonder what kind of application are you looking at. How many strings? How many different translators? How often do the strings change? Are the strings presented to the immediate user of the application sitting in front of the terminal where the application is running, or are there multiple simultaneous accesses to the same application, e.g. through a Web server? Regards, Martin From cndistin at aol.com Tue Jan 6 10:22:32 2004 From: cndistin at aol.com (Cndistin) Date: 06 Jan 2004 15:22:32 GMT Subject: help needed with class and method confusion Message-ID: <20040106102232.19889.00002028@mb-m01.aol.com> First I am sorry for the title but I an newbie enough to now know how to better word it. The problem part of my code is class Application: class Moon: def __init__(self, name): self.name = name def __init__(self): self.moons = [] names = ["Io", "Europa", "Ganymeade"] for name in names: setattr(self, name, Moon(name)) I would like to somehow get self.moons to equal [self.Io, self.Europa, self.Ganymeade]. I had hoped on using self.moons as an iterant in "for" loops to be able to alter each in turn. Thanks in advance for any possible help. From jeremy at zope.com Mon Jan 12 11:39:17 2004 From: jeremy at zope.com (Jeremy Hylton) Date: Mon, 12 Jan 2004 11:39:17 -0500 Subject: Databases: Which one's right for me? In-Reply-To: <878ykf71g6.fsf@pobox.com> References: <4378fa6f.0401091717.1ae63541@posting.google.com> <878ykf71g6.fsf@pobox.com> Message-ID: <1073925556.6341.403.camel@localhost.localdomain> On Sat, 2004-01-10 at 19:50, John J. Lee wrote: > Rene Pijlman writes: > > > Marc: > > >Basically I need a db that will travel with my executable script and > > >faithfully store and edit the data needed in that script. > > > > Have a look at ZODB. > > > > Introduction: > > http://www.python.org/workshops/2000-01/proceedings/papers/fulton/zodb3.html > > Which doesn't have a built-in query system, so isn't a database in the > same way as a relational DB like Postgres or Oracle. It's more like > BSDDB + pickle. A database is a lot more than a query system, although for some applications query support is very important. Zope has a custom query system, called the catalog, that is built on top of ZODB. Whether ZODB sans a builtin query system is suitable really depends on the application. Jeremy From kelianichols at ssdd.nrl.navy.mil Mon Jan 5 15:49:02 2004 From: kelianichols at ssdd.nrl.navy.mil (nuvodido) Date: Mon, 05 Jan 2004 20:49:02 -0000 Subject: ASCII characters in my hex output Message-ID: I am using pyserial to work with a device on my serial port. the output is a mixture of ASCII and hex: Ex. '\x10\x00*' I need conver the \x00* nuber in to decimal. Is there way to convter this value striat forward? Thanks in advance Kelia Nichols ______________________________________ No trees were killed in the sending of this message. However a large number of electrons were terribly inconvenienced. From nospam at steve.com Wed Jan 14 11:21:31 2004 From: nospam at steve.com (Steve) Date: Thu, 15 Jan 2004 03:21:31 +1100 Subject: Time diff Message-ID: <40056c83$1@clarion.carno.net.au> Hi, I have two time strings: 2004-01-14 19:17:37, and 2004-01-15 01:45:33 How can I find out the number of minutes/seconds between the two times in python? Thanks !! Steve From news at badblocks.de Sat Jan 31 14:19:36 2004 From: news at badblocks.de (Walter Haslbeck) Date: Sat, 31 Jan 2004 20:19:36 +0100 Subject: problem with weakref.proxy References: Message-ID: <8nbte1-iia.ln1@smell.butthole.homeunix.net> Peter Otten <__peter__ at web.de> wrote: > If you want to keep your original design, just use ref instead of proxy: Thanks! Thats what I was looking for! And: after I posted the original article I tried another method: I didn't use weakref, but put a real reference of the instance into __olist and checked in c_show_all with sys.getrefcount() if the object is referenced by other names. If not, I removed the object from __olist[]. Well, that worked. But I like the weakref.ref method much more! Walter From spam-trap-095 at at-andros.demon.co.uk Sun Jan 4 10:26:41 2004 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 4 Jan 2004 15:26:41 +0000 Subject: Sending e-mail with python 1.5.2 Message-ID: I am writing a CGI script on an account that only has Python 1.5.2. It's principal purpose is to take some user input from a form, do some manipulation and return some information to the user. However, I would also like it to send some information to an e-mail account (behind the scenes). The e-mail could be quite simple, but I wouldn't rule out wanting to send a pickled object or two. Now if I was using a recent Python I would just use the email package, but I don't think it's compatible with v1.5.2. I know I have access to the sendmail binary, so something should be possible. Any pointers gratefully received. -- Andrew McLean From xpythonist at yahoo.com.br Fri Jan 23 10:25:44 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Fri, 23 Jan 2004 12:25:44 -0300 (ART) Subject: file open problem In-Reply-To: <20040123143808.80139.qmail@web14702.mail.yahoo.com> Message-ID: <20040123152544.60161.qmail@web21503.mail.yahoo.com> Are you sure that the file c:\temp\pytest.txt exists in your laptop's hard disk? --- Neil MacGaffey escreveu: > Hi - I'm new to python and am stymied by something > that should be simple. The file open command below > works fine on my desktop machine, but I cant get it > to > work on my laptop. Since using Python on my laptop > is > realistically the only way I'm going to find the > time > to learn Python, this is a big problem for me. > Here's > what I'm up against: > > PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond > (mhammond at skippinet.com.au) - see > 'Help/About PythonWin' for further copyright > information. > >>> fobj = open(r'c:\temp\pytest.txt','r') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: > 'c:\\temp\\pytest.txt' > > The laptop is a Sony VIAO that's about 2 years old. > Its running Windows 2000, SP4. The desktop is an > older machine, but with the same Windows > environment. > I've obtained a fresh download of Python 2.3.3 and > the > Win32 extension and have re-installed both a couple > of > times with no apparent problems. I also tried > dropping back to Python 2.3.2, but had same result. > Any ideas as to what I should be looking at on this > laptop that might be causing the problem? > > Thank you > Neil > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. > Try it! > http://webhosting.yahoo.com/ps/sb/ > > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis! http://br.geocities.yahoo.com/ From mac-gs-bounces at ghostscript.com Thu Jan 29 23:37:24 2004 From: mac-gs-bounces at ghostscript.com (mac-gs-bounces at ghostscript.com) Date: Thu, 29 Jan 2004 20:37:24 -0800 Subject: Your message to mac-gs awaits moderator approval Message-ID: Your mail to 'mac-gs' with the subject test 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://www.ghostscript.com/mailman/confirm/mac-gs/812fd23cd4fae011f66b2bea2cdf585e583184c4 From james at logicalprogression.net Wed Jan 21 12:42:07 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 21 Jan 2004 17:42:07 +0000 Subject: Assignment to slice In-Reply-To: <20040121170142.55936.qmail@web40104.mail.yahoo.com> References: <20040121170142.55936.qmail@web40104.mail.yahoo.com> Message-ID: <200401211742.07507.james@logicalprogression.net> On Wednesday 21 January 2004 5:01 pm, Rich Krauter wrote: > I do not understand why python behaves the way it does > in the following code: > > Here, Python doesn't like that I'm assigning > out-of-range. OK. That's fine. > > >>> x = [] > >>> x[5] = 3 > > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list assignment index out of range > > However, the following seems very strange. Assigning > to a slice, over non-existent array indexes, sets x[0] > and x[1]. > > >>> x[2:5] = [3,4] > >>> x > > [3,4] > > >>> x[1000:9000] = [5] > >>> x > > [3, 4, 5] > > Why does assigning to a slice of non-existent array > elements fill in the array, starting with the first > empty array position? (Acts like [].append() or > [].extend()?) > > Why not raise an out-of-bounds exception here too? > Wouldn't that be more consistent with the first case, > in which I tried to assign out-of-range, and got an > exception? > > IMO, at least the first index in the slice should be > required to exist in the array. If not, raise an > exception. That way, assigning to the slice fills in > the array in a predicatable way without having to do > len() checks first to ensure that you know where in > the array the slice is actually going to be inserted. > > But I'm sure it is the way it is for a good reason. > Hopefully someone can clue me in. > > Thank you in advance. > > Rich This doesn't answer you fully but Python is at least consistent in that slicing - as opposed the indexing of your first case - *never* raises an IndexError. It's not unique to assignment. "print x[1000:9000]" works too. The fact that slices can extend outside the current range is useful. Otherwise you couldn't use them to extend sequences. Adding to the end would still be possible with your proposed restriction on first index., but what if you wanted to add stuff to the *start* of the list. Currently this works: >>> x = [1, 2, 3] >>> x[-10:-9] = [54] >>> x [54, 1, 2, 3] In this case to be consistent you must insist that the second index exist in the array, i.e. insist on: >>> x[-4:-3] = [54] James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From Tobias.Windeln at gmx.de Fri Jan 9 08:37:54 2004 From: Tobias.Windeln at gmx.de (Tobias Windeln) Date: Fri, 09 Jan 2004 14:37:54 +0100 Subject: Object-based inheritance in Python In-Reply-To: References: Message-ID: Alexander Schmolck wrote: > Tobias Windeln writes: > > >>Maybe there is a way to hand over self to the delegatee object. > > [...] > > >>class Child: >> def __init__(self, delegatee): >> self.__dict__['delegatee'] = delegatee > > > Can't you just use this pattern: > > self.__dict__['delegatee'] = delegatee(self) This results in: AttributeError: Delegatee instance has no __call__ method Here is the solution by Hans Nowaks (http://zephyrfalcon.org/download/selfish-0.4.2.zip): ################################################################## import new import types __version__ = "0.4.2" __author__ = "Hans Nowak" __license__ = "python" __cvsid__ = "$Id: selfish_v2.py,v 1.3 2003/09/22 04:30:50 hansn Exp $" def rebind(method, obj): return new.instancemethod(method.im_func, obj, obj.__class__) class SelfObject: def __init__(self): pass def __setattr__(self, name, value): if name.endswith("_p"): assert isinstance(value, SelfObject), \ "Only SelfObjects can be used for inheritance" if isinstance(value, types.FunctionType): m = new.instancemethod(value, self, self.__class__) self.__dict__[name] = m elif isinstance(value, types.UnboundMethodType): self.__dict__[name] = rebind(value, self) elif isinstance(value, types.MethodType): self.__dict__[name] = rebind(value, self) else: self.__dict__[name] = value def __getattr__(self, name): if name in self.__dict__.keys(): # seems superfluous; if the attribute exists, __getattr__ # isn't called return self.__dict__[name] else: # scan "ancestors" for this name... # left-right based on name, depth first items = self.__dict__.items() items.sort() for attrname, obj in items: if attrname.endswith("_p"): try: z = obj.__getattr__(name) except AttributeError: pass else: if isinstance(z, types.MethodType): z = rebind(z, self) return z raise AttributeError, name Object = SelfObject() From guettli at thomas-guettler.de Tue Jan 6 03:17:33 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 06 Jan 2004 09:17:33 +0100 Subject: tuple.__hash__() Message-ID: Hi! Can someone point me to the documentation of tuples __hash__ method? I want to unique a list of tuples. Since __hash__ returns a 32 bit integer, there could be a situtation where two different tupples return the same value. >>> t1=(1, 2, 3) >>> t1.__hash__() -821448277 >>> t2=(1, 2, 3) >>> t2.__hash__() -821448277 Is there a dictionary type which uses __cmp__() like btrees in the standard library? thomas From swalters_usenet at yahoo.com Fri Jan 9 16:02:38 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 09 Jan 2004 21:02:38 GMT Subject: displaying extended ASCII from a telnet session References: Message-ID: |Thus Spake Christian Wilcox On the now historical date of Fri, 09 Jan 2004 11:04:27 -0600| > I'm trying to programmatically access information from a telnet session > which is normally accessed with a telnet program capable of terminal > emulation (currently set at VT320). The initial login text displays > fine, of course, but when I get to the section which displays extended > ASCII characters, Telnet from telnetlib displays the following garbled > mess: > Any ideas of a way to decode this information? Tell us a bit more detail on your problem, such as what program/system are you trying to get to access what program/system. Unless you correct me, I'll assume that you're trying to get a python program that may or may not be on a linux/unix computer to access a telnet resource that you normally use a vt320 emulator to access. The information you seek has to do with termcap, termio and (tangently) curses. Each terminal defines a set of codes and capabilities using a termcap file (on *nix, at least.) Those capabilities are stored in the termcap database. Your terminal program is not properly decoding these codes and control sequences. Specifically, the codes like ?[?40h are control sequences. and the long lines of q's are where the server told the terminal to use line-drawing characters rather than normal characters. You, of course, only see q's because you aren't decoding the stream. Read up on the matter here: http://www.gnu.org/software/termutils/manual/termcap-1.3/html_chapter/termcap_4.html#SEC23 and here: http://www.gnu.org/software/termutils/manual/termcap-1.3/html_chapter/termcap_toc.html But don't necessarily try to get a deep understanding of each element. Just try to get an overview so that you have a grasp on the issues involved. There are probably better manuals on this stuff, but these are the definitive manuals. Once you've done that and told us more about your problem, we'll be able to have a much more informative discussion of how to resolve this issue. HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From pln at cosmic.stanford.edu Wed Jan 14 18:28:21 2004 From: pln at cosmic.stanford.edu (Patrick L. Nolan) Date: Wed, 14 Jan 2004 23:28:21 +0000 (UTC) Subject: Tkinter: disable menu items while running Message-ID: We have a Tkinter application which has a menubar with cascade submenus. I would like to start the program with one of the submenu items state=DISABLED, then change it to state=NORMAL at a later time. I hope I just missed something obvious, because I can't figure out how to change its state. The problem comes about because the menu bar is built by several add_cascade() calls. Each of the cascades, in turn, has several add_command() calls. If the cascade in question was, say, an object named Cas, then I could call Cas.entryconfigure(). However, I don't know how to get ahold of the objects created by add_cascade() or add_command(). Do they live somewhere accessible? -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From harry.g.george at boeing.com Thu Jan 15 08:40:44 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 15 Jan 2004 13:40:44 GMT Subject: keeping Python code properly indented References: <3064b51d.0401151125.711ade4c@posting.google.com> Message-ID: beliavsky at aol.com writes: > How do you keep Python code properly indented as you modify it? I use > an Emacs-type editor that has a Python mode, so the initial indenting > is easy. If I later want to put a 'for' loop (or an 'if' statement) > around a bunch of code, I find myself going through the body of the > loop, manually re-indenting to keep the nested loops correct. There > should be a better way. > > I think that having a 'for' loop end with a matching 'next' statement, > as done in (for example) Basic, is a safer and clearer way of writing > loops, although some Python programmers consider this a 'feature' > rather than a 'bug'. You do not need to "go through the body, manually re-indenting". In emacs, block select everything to be indented and then do the right shift in one step. That action is in the python-mode.el's added menu, and it is available as keystrokes ("C-c >" by default). Similarly for undenting. Is there a safety concern which requires solution through closure markers? It is a potential problem, but isn't worth closure markers in the language. The main solution is to not let indenting get out of whack in the first place: a) Have a rigorous newbie setup process to assure the editor does 4-char hard spaces (no tab chars), and understands python-mode indenting. See: http://www.python.org/peps/pep-0008.html b) During development, run unittest-based regression tests every minute or so. A messed-up indent will either fail to compile or will fail a test. This enforces the indents and that becomes valued a language feature when doing code reviews. c) Immediately fix indents if problems are detected. d) Keep the code under revision control, so older (known good) code can be recovered. (If you can't assure a-d, then there are bigger problems than language features.) Finally, if you really think you need closure markers, do so with comments instead of language changes: if x > y: z=0 #end if You will still be forced to get the indenting right, but at least you will have clues for recovering mangled indenting. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From adolfo at linuxmail.org Mon Jan 26 17:41:31 2004 From: adolfo at linuxmail.org (Adolfo) Date: 26 Jan 2004 14:41:31 -0800 Subject: Free Python Class Online ! Message-ID: <91de052a.0401261441.28fec693@posting.google.com> Hi, I just found out about a free Python class online You can register here: http://www.icanprogram.com/registration_python.html And join the class mailing list here: ican05py-subscribe at yahoogroups.com Adolfo Santa Barbara, CA From crap at crud.com Fri Jan 23 23:23:40 2004 From: crap at crud.com (Moosebumps) Date: Sat, 24 Jan 2004 04:23:40 GMT Subject: Batch commands on Windows References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: > Can you give an example of what you mean, in Perl as well as what you hoped > would work in Python? I couldn't quite understand what it is that you're trying > to do. OK, actually on second test, the problem is mostly with IDLE, but not totally. When I hit F5 under IDLE, it behaves differently with respect to the command window then if I just run it by double-clicking on the file. Here is an example: BatchTest.bat: set MYVAR=3 dir pause dir echo %MYVAR% pause BatchTest.py: # the intention is to do the same thing as BatchTest.bat, but it doesn't work under either IDLE or by double-clicking # in particular the environment variable is not saved, and it doesn't work if I replace os.system with os.popen import os os.system("set MYVAR=3") os.system("dir") os.system("pause") os.system("dir") os.system("echo %MYVAR%") os.system("pause") BatchTest.pl: # this actually does the same thing as Python, I was mistaken. I was mislead by the IDLE behavior. system('set MYVAR=3'); system('dir'); system('pause'); system('dir'); system('echo %MYVAR%'); system('pause'); The general idea is that it would be nice if there weren't any differences between the batch file and python. From a practical standpoint, it would encourage a lot of people to switch from nasty batch files to Python scripts if you could just surround the entire thing with os.batch(' ') or some similar sort of mechanical textual substitution. Then you could clean it up gradually. I am aware of os.environ and such, and that is useful, but it's not really the point. Of course I could write a function to take a bunch of strings, write a batch file, save the working directory, execute it, restore the current directory, then delete the batch file, but that seems like an awful hack. Though I probably will do that at some point. > > What's the deal with that? I thought Python started out as a scripting > > language. And that seems like the most basic thing that a scripting > > language should do. > > Dunno, although MS-DOS shell scripting is certainly a small subset of scripting > in general. Maybe with a concrete example somebody will be able to give you a > hand. It is a small subset, but an important subset. Shell scripting started probably when people got sick of typing the same commands into the prompt. For a language to really support shell scripting, it should provide a way of automating the process of typing in the commands. As in, there should be no difference whether you're actually typing, or you're running the script. If there is a way and I don't know about it, I would be happy to hear about it. But I do think it is a pretty big hole. MB From mbabcock at fibrespeed.net Fri Jan 9 13:35:08 2004 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 09 Jan 2004 13:35:08 -0500 Subject: displaying extended ASCII from a telnet session In-Reply-To: References: Message-ID: <3FFEF45C.3060607@fibrespeed.net> > > >Controls?[39C?(0?x?[15;5Hx?[68Cx?[16;5Hmqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq >x?(B??[60CChoice:s?[56C?(0?x?[1D?[1B(0?x?[1D?[1B ?[5C?(0?x?[1D?[1B > >Any ideas of a way to decode this information? > > Terse answer: Read up on VT100 emulation. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From pythongnome at hotmail.com Fri Jan 23 08:13:27 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 23 Jan 2004 13:13:27 GMT Subject: C compilers Message-ID: I realize that this is a Python newsgroup, but do any of you know any good C/C++ compilers?? I'm interested in imbedding C with Python. Thanks From mersmann at szut.uni-bremen.de Sat Jan 3 11:32:07 2004 From: mersmann at szut.uni-bremen.de (Frank) Date: 3 Jan 2004 08:32:07 -0800 Subject: Integer math question Message-ID: <3987e01c.0401030832.114c6f2a@posting.google.com> Hi, can anybody help with the following problem? In C++ i = 5 / 10 and i = -5 / 10 both have the same result 0. In python i = 5 / 10 gives me 0 as expected, but i = -5 / 10 gives -1 as result. Is this a feature or a bug? I remember Delphi gave me the same result as C++. TIA, Frank From __peter__ at web.de Tue Jan 13 14:18:54 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Jan 2004 20:18:54 +0100 Subject: Make a function call itself after set amount of time References: Message-ID: Bart Nessux wrote: > Bart Nessux wrote: >> How do I make a function call itself every 24 hours. Also, is there a >> way to start the program automatically w/o depending on the OS functions >> like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and >> xp. Below is an example of what I'm trying to do. [...] > I figured it out. I added this to the function definition: > ipconfig_email() Note that Python has a limit for nesting functions: >>> depth = 0 >>> def callself(): ... global depth ... depth += 1 ... callself() ... >>> try: ... callself() ... except RuntimeError, e: ... print "depth", depth ... print e ... depth 999 maximum recursion depth exceeded >>> 999/365.25 2.7351129363449691 This means that your app will probably crash in less than three years. Would that be a problem on W2K ? If so, a loop could go much longer: while True: ipconfig_email() Seriously, you should reconsider the OS features. Peter From martin at v.loewis.de Fri Jan 9 18:27:26 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 10 Jan 2004 00:27:26 +0100 Subject: LC_MONETARY formatting In-Reply-To: References: Message-ID: <3FFF38DE.1050603@v.loewis.de> Colin Fox wrote: > So I have: > > cash = 12345.6 > > and the locale is set to "en_CA" (though that doesn't matter, really). > > I would like to be able to print "$12,345.60" > > Is there a format string, or function, or *something* that will take > advantage of the monetary formatting info in the locale object? No. > Or did > they provide all that formatting information just so that I have to write > it myself? Yes. Use locale.localeconv() to find the relevant parameters. Make sure you understand that using 'currency_symbol' presents a problem if the amount you have is already in some currency. Printing the same value in different locales using the na?ve formatting algorithm is likely to produce incorrect results, as you have to apply some exchange rate, which varies from day to day, and from trading place to trading place. IOW, LC_MONETARY is useless for financial applications - if the amount is in ?, using the locale's currency symbol would be wrong. Regards, Martin From andrew-pythonlist at puzzling.org Sat Jan 31 20:35:15 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 1 Feb 2004 12:35:15 +1100 Subject: Python vs. Io In-Reply-To: <20040131203802.GA1664@intarweb.us> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> <20040131203802.GA1664@intarweb.us> Message-ID: <20040201013515.GA19909@frobozz> On Sat, Jan 31, 2004 at 03:38:02PM -0500, Jp Calderone wrote: > On Sat, Jan 31, 2004 at 12:20:52PM -0800, Daniel Ehrenberg wrote: > > > > What are you talking about? There's tons of new "magical syntax" in > > Python. Examples for "magical syntax" features that don't work on > > 1.5.2 include: [...] > > > * * and ** in function declarations > > Yep. * and ** in function _calls_ is new in 2.0, but in declarations was already there in 1.5.2: bash-2.05b$ python1.5 Python 1.5.2 (#0, Jul 5 2003, 11:45:08) [GCC 3.3.1 20030626 (Debian prerelease)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> def f(*args, **kwargs): ... print args, kwargs ... >>> f('a', 'b', 'c', x=1, y=2, z=3) ('a', 'b', 'c') {'z': 3, 'x': 1, 'y': 2} >>> -Andrew. From martin at v.loewis.de Sat Jan 3 07:09:48 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 03 Jan 2004 13:09:48 +0100 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: Sean R. Lynch wrote: > If you know of a location where the known shortcomings of rexec are > documented, please let me know. So far I've only seen a couple examples > and a lot of people saying "it's not secure so let's disable it." The biggest problem is that new-style classes are both available through the type() builtin, and callable to create new instances. For example, if you have managed to open a file object f, then type(f)("/etc/passwd").read() lets you access a different file, bypassing all machinery that may have been designed to prevent that from happening. Of course, for the specific case of file objects, there is additional machinery preventing that from happening, but in the general case, there might be more problems in that area. For example, object.__subclasses__() gives you access to quite a lot of stuff. Regards, Martin From __peter__ at web.de Wed Jan 28 08:35:01 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Jan 2004 14:35:01 +0100 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain wrote: > Does Python have something similar to Tcl style tracing? That is, the > ability to call a subroutine when a variable is written to or read from? Would it be sufficient to keep track of attribute changes? Then you could try something like class TraceChanges(object): def __init__(self, name, onChange): # bypass the tracking mechanism object.__setattr__(self, "name", name) object.__setattr__(self, "changed", onChange) def __setattr__(self, name, value): object.__setattr__(self, name, value) self.changed(self, name, value) def changed(sender, name, value): # could also be a method of TraceChanges print "%s.%s changed to %s --> updating canvas" % (sender.name, name, value) rectangle = TraceChanges("rectangle", changed) rectangle.color = "blue" text = TraceChanges("text", changed) text.color = "red" text.font = "Helvetica" Peter From jcarlson at uci.edu Mon Jan 19 21:43:14 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 19 Jan 2004 18:43:14 -0800 Subject: stack-like file object References: <400be8f3_2@nova.entelchile.net> Message-ID: <20040119183719.ABC4.JCARLSON@uci.edu> Rodrigo, > I need to implement a stack on a file. > The idea is to have a big list, and put part of his head on the disk. The > model of access to the file is like a stack (read in order only the tail, > write only at the tail). > How could I create this, knowing that I need to pickle arbritary objects ? While I don't condone the use of files as stacks, the below should work for you. It doesn't reduce in size when an object is removed, but as long as you don't try to share the stack between processes or threads, it should work fine. - Josiah import cPickle import struct import os class filestack: def __init__(self, filename): try: os.remove(filename) except: pass self.fn = filename self.f = open(filename, 'wb+') self.s = len(struct.pack('!i', 0)) def __del__(self): self.f.close() del self.f os.remove(self.fn) def append(self, data): st = cPickle.dumps(data) self.write(st) self.write(struct.pack('!i', len(st))) def pop(self): posn = self.f.tell() if posn <= 0: raise IndexError self.f.seek(posn-self.s) s = struct.unpack('!i', self.f.read(self.s)) self.f.seek(posn-self.s-s) ret = cPickle.loads(self.f.read(s)) self.f.seek(posn-self.s-s) return ret From jerf at jerf.org Sat Jan 17 22:27:41 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 18 Jan 2004 03:27:41 GMT Subject: Inserting while itterating References: Message-ID: On Wed, 14 Jan 2004 09:43:01 +0100, Thomas Guettler wrote: > Hi, > > Simple excerise: > > You have a sorted list of integers: > l=[1, 2, 4, 7, 8, 12] > > and you should fill all gaps: > > result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > How would you code this? > > Constrain: The original list should be changed, > don't create a copy. > > thomas l[:] = [x for x in range(l[0], l[-1] + 1)] If you care about timing, you'll want to compare against Peter Abel's solution; I would not guarantee which is faster. All I can tell you is which makes more sense to me when I read it. Actually, maximal readability is l[:] = [x for x in range(min(l), max(l) + 1)] but that will *certainly* be less efficient if you know the list is sorted then my first post. From josecarlos at siadv.com Fri Jan 23 07:50:00 2004 From: josecarlos at siadv.com (José Carlos) Date: Fri, 23 Jan 2004 13:50:00 +0100 Subject: Server and Client Socket problem Message-ID: Hi. I am starting a server socket program. I send data from client socket but the server don?t recived anything. This is my python code: Server: import socket def run(): servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) servidor.bind(('localhost', 6969)) servidor.listen(1) while 1: (conexion, direccion) = servidor.accept() datos = conexion.recv(4069) print "Servidor Recibe", datos if datos == "quit": servidor.close() break run() Client: import socket def run(): cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cliente.connect(('localhost', 6969)) except: print "No he podido Conectar con el Servidor" return datos = '12345678' cliente.send(datos) #cliente.close() run() I am a new python user. what can i do? Thank you. Regards. Jos? Carlos From sinzcere at hotmail.com Mon Jan 5 19:10:21 2004 From: sinzcere at hotmail.com (J) Date: 5 Jan 2004 16:10:21 -0800 Subject: Quck question Message-ID: <3125790e.0401051610.5e24de28@posting.google.com> I have the following information in a file : r1kcch Serial0/0/0 propPointToPointSerial Mon Jan 5 13:15:03 PST 2004 InOctets.1 0 Mon Jan 5 13:15:05 PST 2004 OutOctets.1 0 I want to be able to extract each line into a comma delimited list. Bellow i am trying to print out my list print currentList but nothing is comming out. I added a line after print test to make sure the file has the information. Can someone help me with this? #Read a file true = 1 in_file = open("test.txt","r") text = in_file.read() while true: in_line = in_file.readline() if in_line == "": break currentList = string.split(in_line,",") #print out the contents of the current list print currentList #make the inline stop reading in_line = in_line[:-1] in_file.close() From wcitoan at NOSPAM-yahoo.com Wed Jan 14 18:44:43 2004 From: wcitoan at NOSPAM-yahoo.com (W. Citoan) Date: Wed, 14 Jan 2004 23:44:43 -0000 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <4004EC9E.1E2E2893@alcyone.com> Message-ID: ["Followup-To:" header set to comp.games.development.programming.misc.] On Wed, 14 Jan 2004 14:16:02 +0000 (UTC), Bent C Dalager wrote: > > It is, never the less, worth pointing out. It would seem that Brandon > entered the scene with an idea that OSS developers might be incredibly ^^^^^^^^^^^^^^ > useful to him for some reason or other. Other game developers might > very well have the same idea. When Brandon finds out that this is not > the case and describes in some detail why OSS won't do the job for ^^^ > him, than this can certainly be useful for other game developers to > learn so that don't have to spend 6 months figuring out the exact same > thing themselves. > > The conclusion may seem obvious to _you_ but this is no guarantee that > everyone else also possesses this knowledge. OSS is being hailed as ^^^ > the second coming, and it comes as no surprise therefore that some > people might be deluded into thinking they could harness this power to > cure cancer overnight or land a man on Mars by 2005. OSS developers != OSS While "OSS is being hailed as the second coming", nobody is claiming that people you aren't paying are going to do what you want, when you want, and how you want. That was Brandon's complaint. People develop OSS for their own reasons (personal or corporate). They don't do it to provide free labor for the asking. Anyone who doesn't see that as obvious is severely lacking in common sense. - W. Citoan -- A bore is someone who persists in holding his own views after we have enlightened him with ours. From __peter__ at web.de Thu Jan 8 08:12:20 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Jan 2004 14:12:20 +0100 Subject: Chaning self? References: <4f0a9fdb.0401080457.3d60adb5@posting.google.com> Message-ID: Subclassing won't work here, because the long type is immutable :-( Peter From peter at engcorp.com Tue Jan 27 17:12:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Jan 2004 17:12:07 -0500 Subject: makeExe.py References: Message-ID: <4016E237.97F88A36@engcorp.com> Premshree Pillai wrote: > > Peter wrote: > > if you're interested > > in integrating the > > changes, and maintaining it, I'll forward our own > > script which you can > > pull apart and reuse as required... > > I'd be interested in that. Attached below. Use for any purpose, no warranty. :-) (The "batchutil" at the end stuff is not really necessary, but is handy for us to put Python code inside ".bat" files without having to hardcode the actual path anywhere. Basically it finds the .bat file wherever it is in the path and executes it as a Python file. I should probably post that sometime too....) -Peter ------------------start of py2exe.bat------------------- @goto dos # setup.py from distutils.core import setup import py2exe import sys import os import getopt from StringIO import StringIO def usage(): print 'Usage: py2exe [-i path] mainmodule.py' sys.exit(0) if __name__ == '__main__': opts, args = getopt.getopt(sys.argv[1:], 'h?qi:') quiet = False for opt,val in opts: if opt in ['-?', '-h']: usage() elif opt in ['-q']: quiet = True elif opt in ['-i']: abspath = os.path.normpath(os.path.abspath(val)) if abspath not in sys.path: if not quiet: print 'Appending to sys.path: %s' % abspath sys.path.append(abspath) if len(args) != 1: usage() mainScript = args[0] if mainScript.endswith('.py'): # get part before the .py baseName = os.path.splitext(mainScript)[0] # fake command line arguments sys.argv[1:] = ['py2exe'] # install redirector for output if quiet: print 'Running...' sys.stdout = StringIO() sys.stderr = StringIO() try: result = setup( name=baseName, scripts=[mainScript] ) finally: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ # quick hack which I hope checks that the run succeeded, at least partially # result should be an instance of distutils.dist.Distribution which has a have_run attribute if hasattr(result, 'have_run'): print '\nDone. Look in dist/%s folder for the executable(s).' % baseName else: usage() ''' :dos @echo off set argv=%0 :getargs set argv=%argv% %1 shift if not %1.==. goto getargs call python -c "import batchutil; batchutil.runme()" %argv% rem ''' ---------------end of file----------------------------------- From eddie at holyrood.ed.ac.uk Mon Jan 19 12:51:24 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 19 Jan 2004 17:51:24 +0000 (UTC) Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: cartermark46 at ukmail.com (Mark Carter) writes: >I'm experimenting with learning a functional language; and I know >almost zero about Scheme. I find it very difficult to understand the >structure of what's going on. I downloaded Standard ML (the New Jersey >offering), and find myself more inclined to dig into ML deeper; rather >than Scheme. ML does, at first glance, seem more readable. It's probably a lot more important to stretch yourself out in that direction than to worry about which flavour. >I suppose that Schemers and Lispers take the attitude that a lack of >syntax is an advantage, because you can ultimately program in any >paradigm you wish. It's "just" a case of writing code that implements >the paradigm. I have also heard claims that the existence of >parantheses in s-exprs is a red herring as far as readability is >concerned. The supposed unreadability is a complete nonsense, you quickly don't notice the parentheses and rely mostly on the indentation. I think I'll start looking for another project I can do in Scheme, it's been ages. >Non Schemers/Lispers, on the other hand, presumably think that a >spoonful of syntactic sugar helps the medicine go down. >I suspect that if there really was One Obviously Right Way To Do It, >then we'd all be using it. No silver bullet, and all that. >I am sure, though, that there will be many people who disagree with my >sentiments. Who cares eh? The important thing is to get the message through to the few who can think for themselves and give them a chance to rise above the mediocrity. Somehow I'm reminded of a sequence in a novel I was reading at the weekend: Q:"Do you exercise?" A:"Only restraint!" From eddie at holyrood.ed.ac.uk Tue Jan 20 12:07:25 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 20 Jan 2004 17:07:25 +0000 (UTC) Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> Message-ID: Wayne Folta writes: >Intellectually, I prefer Ruby. Ruby and Smalltalk intrigue me. But the >"pure OO" approach (my words this time) is annoying, and even at some >point inconsistent, as I mentioned in my paragraph about 0.step(). I >feel like Python has got the right balance where it's OO and pretty >much fully so, but not fanatically so. And it's what I've adopted. Python: because everything's not an object ? From jzgoda at gazeta.usun.pl Fri Jan 16 18:41:56 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 16 Jan 2004 23:41:56 +0000 (UTC) Subject: RDFLib site down? Message-ID: Is here somebody that could confirm how long rdflib.net site is down (OK, "unavailable")? Should I try to find somebody with working version of RDFLib, or is it only temporary problem? -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From amk at amk.ca Wed Jan 21 07:47:10 2004 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 21 Jan 2004 06:47:10 -0600 Subject: Pyrex without Python (was Re: calling Pyrex results from C) References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> Message-ID: On Tue, 20 Jan 2004 22:15:18 -0500, Fran?ois Pinard wrote: > Maybe the fact that one can build and debug prototypes in Python, with > the agenda of later transforming them into C, somehow, without rewriting > so much of them, for environments where the whole of Python, for various > reasons, is not welcome. At work I've done a much simpler version of this. We produce code for mathematical algorithms or state machines that runs inside the Linux kernel; code can be written either in C or in a tiny subset of Python (basically, assignments, if...elif...else and for loops -- I forget if 'while' is implemented or not). Instead of using Pyrex, I just use the compiler package to get an AST for a chunk of Python code, and then have a code generator that walks over the AST and produces C code. The nice thing is that the code generator knows the C-level types of variables, so if a and b are arrays, a = a + b generates a 'for' loop in the C code. In theory you could test them in Python, too, letting you debug problems before having to compile C code and insert it into the kernel. A long-term pipe dream is to look at code and figure out which cases to test; for example, if x is an input parameter and you have the statement 'if 0 Message-ID: "r.e.s." wrote: >I have no PYTHONPATH nor any other python-related environment >variables, yet everything seems fine. (I'm using PythonWin >with winxp.) As long as modules are loaded through PythonWin, >is PYTHONPATH unnecessary? Or am I missing something? On Windows, the initial value of PYTHONPATH is stored in the registry: HKEY_LOCAL_MACHINE\ SOFTWARE\ Python\ PythonCore\ 2.3\ PythonPath -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From none at none.com Wed Jan 14 12:52:29 2004 From: none at none.com (Derek) Date: Wed, 14 Jan 2004 12:52:29 -0500 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> Message-ID: "Cameron Laird" wrote: > > >I also use C++ and Python as my main languages and I agree > >with your comments. However, I don't agree that Python is > >inherently "safer" than C++. At best I see it as a tie. > >For example, C++ let's you corrupt memory among other > >"unsafe" things, most of which can be avoided by using > >standard containers, smart pointers, etc. Python lets you > >do "unsafe" things such as passing an object to a function > >when it makes no sense to do so, which can lead to nasty > >runtime surprises. > > We disagree on some matters. > > I *do* regard Python as inherently safer than C++, and > much more so. My aim for now is not to persuade you to my > view, but only to make it explicit. Memory management, and > mismanagement, as mundane as it is, is so poorly applied > in so much of the C++ code I see, that it swamps all other > dimensions of comparison between the two languages. I > quite agree with you that competent C++ programmers should > exploit smart pointers and so on. My experience is that, > somehow, C++ as it's generally practiced appears to have > barriers to their use. I see your point and -- despite my original post -- I agree with it. Reflecting on my own experience with C++, I agree that C++ does not seem to make writing safe code as easy as it should, at least for the uninitiated. Standard containers (eg, vector, list, map, etc.) don't get used as much as they should. Robust smart pointers (eg, boost::shared_ptr) seem to get used even less. In terms of memory management, Python does seem safer. > I don't understand your last sentence, and, given my own > focus on reliability, I very much want to understand it. > Are you alluding precisely to Python's dynamic typing, and > observing that, as earlier is better, C++'s compile-type > checks beat Python's run-time checks? Yes, I prefer compile-time checks to run-time checks. I don't know which method is "better" by any objective measure, but I prefer to know if there is a problem as early as possible. It's not hard to make a change in Python that will go unnoticed until much later, and in the real world test suites often don't have enough coverage to catch every runtime error up front. From malcolmny_1 at lycos.com Sun Jan 25 14:43:18 2004 From: malcolmny_1 at lycos.com (malcolm) Date: 25 Jan 2004 11:43:18 -0800 Subject: Guardian: open source is a throwback says Jack Schofield Message-ID: <64cff82f.0401251143.328388bd@posting.google.com> Why you can't get something for nothing Jack Schofield Jan 22 2004 [..] "There are also undoubted benefits from running open source software, though the financial ones can be small or even negative. Companies are bound to be tempted by the idea of getting something for nothing .." "The facility to fix bugs yourself and to modify programs also sounds attractive. However, fixing bugs is not practical for most companies, and modifications can be positively dangerous. If you are really going to do these things, you need to hire several reliable programmers with kernel-level skills" "Indeed, the whole progress of commercial computing has been from expensive hand-written, bug-ridden, company-specific programs to cheaper but more powerful off-the-shelf packages. From that point of view, open source is a throwback." - http://www.guardian.co.uk/online/story/0,3605,1127802,00.html From eurleif at ecritters.biz Thu Jan 22 15:18:25 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 22 Jan 2004 20:18:25 GMT Subject: Ordered dictionary? Message-ID: I need to associate a string (key) with an integer (value). A dictionary would do the job, except for the fact that it must be ordered. I also need to look up the value for a specific key easily, so a list of tuples wouldn't work. From bombeiro03 at yahoo.com Wed Jan 14 10:34:20 2004 From: bombeiro03 at yahoo.com (Stefan Zollinger) Date: Wed, 14 Jan 2004 16:34:20 +0100 Subject: Reading pipes from curses applications Message-ID: Hi I'm working on a "telnet" server which should serve piped output from curses based applications. So far it works fine with plain text, but it looks like stdin.readline() scrambles the control characters of curses applications. Does anyone know a way to work around this? Thanks for help, Stefan From lance.ellinghaus at eds.com Wed Jan 21 08:36:11 2004 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Wed, 21 Jan 2004 08:36:11 -0500 Subject: Do (USA) Python conferences require a coast? Message-ID: <1093E8BAEB6AD411997300508BDF0A7C18D09DC7@USHEM204> How about one in Dallas, TX? It is central to the country and a really nice place! :) Lance Ellinghaus EDS - TWAI Operations Special Projects Phone: 214-922-6458 Work Cell: 972-877-0409 Nextel Private ID: 142*52*5511 Personal Cell: 940-597-4755 -----Original Message----- From: python-list-bounces+lance.ellinghaus=eds.com at python.org [mailto:python-list-bounces+lance.ellinghaus=eds.com at python.org] On Behalf Of codeapocalypse at msn.com Sent: Wednesday, January 21, 2004 3:22 AM To: python-list at python.org Subject: Re: Do (USA) Python conferences require a coast? > I'd vote for Chicago. Of course, technically speaking we're on a coast > also. It should be just about the easiest city to get to from anywhere in > the US though. Given recent weather conditions, I'd think everyone would jump at the idea of coming out here, to sunny Southern California for a conference... (I missed the Long Beach conference, and D.C. is just so far away...and much colder, brrr. :) -- http://mail.python.org/mailman/listinfo/python-list From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Jan 26 10:11:10 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 26 Jan 2004 16:11:10 +0100 Subject: makeExe.py References: Message-ID: Hi ! And more : Negative indices are your Positive friends. ;-) From hasan at slac.stanford.edu Tue Jan 27 22:23:16 2004 From: hasan at slac.stanford.edu (Adil Hasan) Date: Tue, 27 Jan 2004 19:23:16 -0800 Subject: Problem connecting to https using ZSI (openssl problem) - python2.3 Message-ID: Hello, I'm having problems trying to use ZSI to connect to a https url. I give the command and I get prompted for my X509 cert pass-phrase, but the program dies with an openssl error. Here's my code: from ZSI import * u='' n='https://shahzad.fnal.gov/edg-voms-admin/uscms/services/VOMSAdmin' b = Binding(url=u,ns=n, ssl=1, \ host='shahzad.fnal.gov',port=8080, \ cert_file='/home/hasan/.globus/usercert.pem', \ key_file='/home/hasan/.globus/userkey.pem') b.listCAs() The traceback I get is: Enter PEM pass phrase: Traceback (most recent call last): File "", line 1, in ? File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", line 28, in __call__ requesttypecode=TC.Any(self.name, aslist=1)) File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", line 131, in RPC self.Send(url, opname, obj, **kw) File "/usr/local/python2.3/lib/python2.3/site-packages/ZSI/client.py", line 184, in Send self.h.connect() File "/usr/local/python2.3/lib/python2.3/httplib.py", line 961, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) File "/usr/local/python2.3/lib/python2.3/socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol') Any ideas about this? Does anyone know how to solve this problem? I have seen one post here with a similar problem, but haven't seen any resolution. Help! thanks, adil From goodger at python.org Fri Jan 23 12:10:14 2004 From: goodger at python.org (David Goodger) Date: Fri, 23 Jan 2004 12:10:14 -0500 Subject: PyCon2004 - Where to stay, which airport? In-Reply-To: References: Message-ID: <40115576.3020100@python.org> Another option is to stay at a hostel. Beds at the Washington International Student Center (http://www.washingtondchostel.com/) go for $22/night, and there's at least one private room for $55/night. Breakfast & kitchen facilities included. It's located in the Adams-Morgan area ("on the hippest street in town"), near the Dupont Circle metro station, about 3 km (2 miles) from PyCon (GWU). Open to anyone, not just for students. I just made my reservation, knowing that I'm not going to be spending much time in the room anyhow. -- David Goodger From python-list at frenchfriedhell.com Sun Jan 18 23:38:07 2004 From: python-list at frenchfriedhell.com (python-list) Date: Sun, 18 Jan 2004 23:38:07 Subject: threads and loops Message-ID: <20040118233807.29489.qmail@serversys852.com> Hello, I posted this to the tutor list, but didn't get any responses, unless my email client really messed up. So I'll try here. I'm starting to work with threads, but I'm a little confused. I think I understand the concepts, but not the controls. Why doesn't something like this work: ############# import threading def counter(x): while tEvent.isSet(): x+=1 print x def tStart(): tEvent.set() if counterThread.isAlive(): counterThread.join() else: counterThread.start() def tStop(): tEvent.clear() counterThread=threading.Thread(target=counter, args=(1,)) tEvent=threading.Event() ##################### After that I have controls setup for a Tkinter box with two buttons, one has tStart as it's command value, and the other tStop. When I run the program, it starts fine, and then the loop stops when I press 'stop', but when I try to press 'start' again, I get an error: ########### Exception in Tkinter callback Traceback (most recent call last): File "C:\myweb\python\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\myweb\python\SNC\Script1.py", line 14, in tStart counterThread.start() File "C:\myweb\python\lib\threading.py", line 404, in start assert not self.__started, "thread already started" AssertionError: thread already started ############ Because my 'while' func depends on the flag, when the flag is false, and it stops, the thread should die, right? And why the need for the extra comma in the args value when defining my instance? -Stryder -------------- next part -------------- An HTML attachment was scrubbed... URL: From richardshea at fastmail.fm Wed Jan 14 15:44:11 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 14 Jan 2004 12:44:11 -0800 Subject: Accessing "GIS (ESRI shape file)" files from Python ? References: Message-ID: <282f826a.0401141244.5a92629a@posting.google.com> Thanks to all for the pointers to Thuban and Openev I will be checking both out. regards richard shea. From lubowiecka at go2.pl Mon Jan 26 02:08:39 2004 From: lubowiecka at go2.pl (Sylwia) Date: 25 Jan 2004 23:08:39 -0800 Subject: problems with registering PythonService.exe Message-ID: Hi! I have the following problem :( After registering the "PythonService.exe" executable... C:\Python23\Lib\site-packages\win32>PythonService.exe -register I got the following error message: ============================================================================== "Registering the Python Service Manager... Fatal Python error: PyThreadState_Get: no current thread This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information." ============================================================================== What may be wrong ?:( I have win32all-157 installed on my computer... I will be grateful for any hints. Thank you in advance, Sylwia From just at xs4all.nl Mon Jan 5 11:32:52 2004 From: just at xs4all.nl (Just) Date: Mon, 05 Jan 2004 17:32:52 +0100 Subject: PRE-PEP: new Path class References: Message-ID: In article , "John Roth" wrote: > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q > > Frankly, I like the idea. It's about time that all of the file > and directory stuff in the os module got objectified > properly (or at least with some semblance of OO propriety!) > > In the issues section: [ snipping those points where I agree with John ] > 4) Should path expose an iterator for listdir(?) > > I don't see why not, as long as the path is to a > directory. _An_ iterator, sure, but not __iter__. How about path.listdir()? :) __iter__ could also iterate over the path elements, so it's ambiguous at least. > 15. Should files and directories be the same > class. > > Probably not. While they share a lot of common > functionality (which should be spelled out as an > interface) they also have a lot of dissimilar > functionality. Separating them also makes it easy > to create objects for things like symbolic links. But what about paths for not-yet-existing files of folders? I don't think you should actually _hit_ the file system, if all your doing is path.join(). Just From http Thu Jan 15 15:26:33 2004 From: http (Paul Rubin) Date: 15 Jan 2004 12:26:33 -0800 Subject: python & mathematical methods of picking numbers at random References: Message-ID: <7xd69largm.fsf@ruckus.brouhaha.com> Bart Nessux writes: > I am using method 'a' below to pick 25 names from a pool of 225. A > co-worker is using method 'b' by running it 25 times and throwing out > the winning name (names are associated with numbers) after each run > and then re-counting the list and doing it all over again. > > My boss thinks that 'b' is somehow less fair than 'a', Both are the same, as you can see by calculating the probability of any given name being selected. What is the application, and the computer environment? You may also need to worry about correlations in the underlying Mersenne Twister PRNG. If the application is something where randomness is very important (you're picking winners for a big lottery or something) then you should use a better RNG. From jsbenson at bensonsystems.com Thu Jan 15 13:36:50 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 15 Jan 2004 10:36:50 -0800 Subject: best book: aint no such thing, and encouragement for old coots Message-ID: <0bc301c3db96$8aa3e500$8d09500a@jsbwxp3> Hi, I see a lot of posts asking about "the best Python book." In my experience, there is no such thing, but there are a lot of good books that will help you along in different ways, and at different times. First of all, I'd like to clarify my position on learning: I subscribe to the adobe hacienda school of autodidactic technology, to wit: "If you throw enough adobe at the side of the hacienda, some of it will stick" At one time or another, I've dipped into the various O'Reilly Python books, Grayson's Python and Tkinter Programming, and Christopher's Python Programming Patterns. They're all good, but I need to see the same difficult or complex thing presented various times in various contexts to really get comfortable with it. Hence the multiple viewpoints of multiple books, and I will also read an individual book more than once, interspersed with other volumes. Enough adobe ends up adhering to my mental hacienda so that I can accomplish things in Python. And now, some encouragement for old techies who have considered going into management with writing cool software is enough: My formal education in data processing stopped with Advanced Data Structures back in the eighties, and I coasted along doing journeyman programming in various COBOLs, Cs and proprietary languages. Of course, I stayed reasonably current with stuff like Dijkstra's Structured Programming, DeMarco's Structured Analysis, Date's Relational Database and other flavors of business software technology which were my stock in trade, but otherwise I avoided the paradigm of the week. Then I ran into Python about two years ago and all of a sudden there was OOP, functional programming, aspect-oriented programming and other stuff that I had maybe heard about but hadn't actually worked with, all staring back at me from the pages of Python books and the mailing list. It's been pretty much a process of creative destruction: starting all over, but from a higher and clearer conceptual vantage point. And, of course, I didn't really forget all the other stuff, I just pushed it into the background long enough to get a new appreciation of it from this new point of view. In summary, I'd like to recommend getting into Python as a rather easy and fun way to talk the talk and walk the walk nowadays; it's been a very rewarding and refreshing software engineering update. From jcarlson at nospam.uci.edu Sat Jan 31 12:35:09 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 31 Jan 2004 09:35:09 -0800 Subject: PEP 327: Decimal Data Type In-Reply-To: References: Message-ID: > If I needed more than that, I'd use a rational type - I speak from > experience as I set out to write a base N float library for C++ once > upon a time and ended up writing a rational instead. A rational, BTW, > isn't too bad to get working but that's as far as I got - doing it > well would probably take a lot of work. And if getting Base N floats > working was harder than for rationals, getting them to work well would > probably be an order of magnitude harder - for no real benefit to 99% > or more of users. I also wrote a rational type (last summer). It took around 45 minutes. Floating point takes a bit longer to get right. > Just because a thing can be done, that doesn't make it worth doing. Indeed :) - Josiah From aahz at pythoncraft.com Mon Jan 26 09:33:05 2004 From: aahz at pythoncraft.com (Aahz) Date: 26 Jan 2004 09:33:05 -0500 Subject: Class returning None ? References: <2r4Rb.286342$e6.11127748@twister2.libero.it> Message-ID: In article , Cliff Wells wrote: > >from exceptions import Exception >class SomeError(Exception): pass BTW, there's no need to do this. ``Exception`` lives in the built-in namespace. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From Pieter.Claerhout at Creo.com Thu Jan 15 05:47:10 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 15 Jan 2004 11:47:10 +0100 Subject: is it possible to create a win binary file from .py files ? Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D9D@cseexch01.cse.creoscitex.com> Take a look at: - py2exe: http://starship.python.net/crew/theller/py2exe/ - McMillan's installer: http://www.mcmillan-inc.com/install1.html - cx_Freeze: http://starship.python.net/crew/atuining/cx_Freeze/index.html Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: stephane ancelot [mailto:sancelot at free.fr] Sent: 15 January 2004 11:25 To: python-list at python.org Subject: is it possible to create a win binary file from .py files ? Hi, I am new to python and I would like to know if there are some ways to provide a binary file as target . Because my projects may contain lot of py files and I do not want to provide source files . for maintenance puproses it is too easier for me to send only one file to my customer. Best Regards Steph -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Thu Jan 22 14:19:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Jan 2004 14:19:29 -0500 Subject: Nokia prefers Python References: Message-ID: <40102241.E4A38F73@engcorp.com> Stephan Deibel wrote: > > Anyone happen to have a contact at Nokia that might be willing and able > to write up a Python Success Story based on this? Or know of someone > else that might? > > http://pythonology.org/success Maybe it's a bit soon to call it a "success"? It sounds like it's just in evaluation at this stage... -Peter From andrew.henshaw at gtri.gatech.edu Sun Jan 25 23:31:42 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Sun, 25 Jan 2004 23:31:42 -0500 Subject: Text Animation References: <7b454334.0401242038.11404dac@posting.google.com> Message-ID: <101961fon94ml81@corp.supernews.com> Fazer wrote: > Hello, > > I was wondering if anyone has done any simple text-based animation? > > I mean things such as text-based pre-loaders. One example would be > when you use the *nix utility called `wget.` You get that fancy " > ====> " type of animation as you download a large file. Or maybe even > a rotating " | " that I have seen before in some installation > programs. > > Any ideas how these effects can be achieved? > > Thanks a lot! > > Faizan I use this: ################################### import sys class Spinner: SYMBOLS = '|/-\\' def __init__(self): self.index = 0 def __call__(self): sys.stdout.write(Spinner.SYMBOLS[self.index]+'\b') self.index = (self.index+1) % len(Spinner.SYMBOLS) ################################### And call it like this: ################################### if __name__ == '__main__': import time spin = Spinner() for i in range(100): spin() time.sleep(0.1) ################################### This looks fine under the Win2K cmd window; but, as pointed out in another reply, you may need to turn off the cursor. I just tested it under Konsole on Linux, and the block cursor doesn't allow the effect to show. --Andy From tjreedy at udel.edu Sun Jan 11 20:43:14 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Jan 2004 20:43:14 -0500 Subject: Python installation breaks Outlook Express References: Message-ID: "M. Laymon" wrote in message news:t2k3001mc170t3vdkk7f0mftcjlptkdo6a at 4ax.com... > I just installed Python 2.3.3 under Windows XP professional. After I > did, my wife tried to access her email using Outlook Express and got > the error messages: ... > Since the only thing I had done recently was to install Python. I > used system restore to go back to the point before installing Python. > After I did, Outlook started working again. Has anyone else seen this > behavior ? I find errors with either the mail service or Windows to be fairly common. Server errors tend to disappear by waiting. Windows glitches disappear (often) by rebooting. I recently 'fixed' a problem with OE on XPHome that way. Did you try reinstalling to see if coincidence was just that? Terry J. Reedy From artur_spruce at yahoo.com Thu Jan 8 14:32:23 2004 From: artur_spruce at yahoo.com (AdSR) Date: 8 Jan 2004 11:32:23 -0800 Subject: MySQLDB multiple cursor question References: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu> <3ffd7dbe$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Brian Kelley wrote: > Brian Kelley wrote: > > I am trying to use threads and mysqldb to retrieve data from multiple > > asynchronous queries. > > > > My basic strategy is as follows, create two cursors, attach them to the > > appropriate databases and then spawn worker functions to execute sql > > queries and process the results. > > The problem goes away if I have only one cursor per connection and just > use multiple connections. This seems like a bug but I don't know for sure. > > Brian See PEP 249, read about the "threadsafety" global variable. HTH, AdSR From bkelley at wi.mit.edu Mon Jan 12 09:20:30 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Mon, 12 Jan 2004 09:20:30 -0500 Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <4002acc9$0$564$b45e6eb0@senator-bedfellow.mit.edu> Neil Hodgson wrote: > Brian Kelley: > > >>I made a new python string type and got enough working on the parser to >>accept >> >>string = i"whatever" > > > I would not like to see strings gain more interpretation prefix > characters without very strong justification as the combinational growth > makes code interpretation more difficult. The "i" would need to be used in > conjunction with the "u" or "U" Unicode prefix and possibly the "r" or "R" > raw prefix. > > The order of interpretation here is reasonably obvious as the > internationalization would be applied after the treatment as Unicode and > raw. However, when used in conjunction with other proposed prefix characters > such as for variable interpolation, the ordering becomes more questionable. If the gettext mechanism is followed, it would make sense that i"whatever" would be a special form of unicode so multiple prefixes might not be necessary. That being said, after some of the preceding discussions, I'm not sure that introducing a new built-in datatype would be that useful. I'm leaning toward something like: string = international("whatever") Which would be a bit more typing but would allow international(r"whatever") I think that we've pretty much beaten this topic into the ground though, it's time to finish coding up the data type and see how it works. Thanks for your input. Brian From lvraab at earthlink.net Sat Jan 10 10:18:56 2004 From: lvraab at earthlink.net (Lucas Raab) Date: Sat, 10 Jan 2004 15:18:56 GMT Subject: Writing Files Message-ID: What is the best way to go about writing to files?? Whenever I insert a statement to write results to a file there's nothing in it. Any suggestions?? TIA From martin at v.loewis.de Tue Jan 6 23:52:31 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 07 Jan 2004 05:52:31 +0100 Subject: Getting strange characters in the command prompt In-Reply-To: <56f42e53.0401061704.523f394@posting.google.com> References: <56f42e53.0401061704.523f394@posting.google.com> Message-ID: <3FFB908F.9010208@v.loewis.de> sebb wrote: > # -*- coding: cp1252 -*- > print "? ? ?" > > ... and I run it in the windows command prompt, I get strange > characters I didn't ask for. > [...] > Can anyone help we with that problem? As Irmen explains, this is because cmd.exe uses code page 850 (on your installation). You should write print u"? ? ?" Regards, Martin From eric.brunel at N0SP4M.com Mon Jan 19 04:29:57 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 10:29:57 +0100 Subject: Using python for _large_ projects like IDE References: <930ba99a.0401180625.5863acd4@posting.google.com> Message-ID: Sridhar R wrote: > Hi, > > I am a little experienced python programmer (2 months). I am somewhat > experienced in C/C++. I am planning (now in design stage) to write an > IDE in python. The IDE will not be a simple one. I had an idea of > writing the IDE in C/C++, as it is a big project, bcoz of the > following > > 1. if python is used, then the memory required for running the IDE > will be high. It's quite hard to tell, since I've never seen anybody writing a significant application *both* in C/C++ and Python to compare their memory usage... I'd say memory usage depends a lot more on the design than on the language used. Python does introduce an extra cost in memory consumption, but the larger the application, the less you'll notice it. > 2. if pure python is used, the IDE will be slower. An application coded in Python will actually be slower than the same application coded in C/C++. I won't repeat what others have already said about what *looks* slow to a user. > I'm not sure whether they are true. > > Then I thought of using python for 90% of the code and using C for > other performance critical part. But the problem is in identifying > the performance critical code. People suggest to start with pure > python and then _recode_ the performance critical code after profiling > the original code. But I fear whether there will be a conflit in say > data structures. Not yet expert in extending/embedding python. We did just that for quite a big application and it works like a charm: the critical code is usually one that does many calculations and it's usually quite easy to isolate this part in a module handling only base types. And even if it's not true, as somebody already said, it's easier to handle Python objects at C level that it may seem at first sight. > Are there any ways to forsee the performance critical parts? I really think you shouldn't care; remember, "premature optimization is the root of all evil" ;-) > Also, any suggestions on reducing memory usage of big applications > written in python? Design them keeping this problem in mind if you really have to. But... "premature optimization ...". You'll always be able to make compromises on a well designed application afterwards to reduce memory usage; it's indeed a lot easier than to maintain an application originally badly designed for bad reasons (e.g. reduce memory consumption). HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From bug-gs-bounces at ghostscript.com Fri Jan 30 12:50:17 2004 From: bug-gs-bounces at ghostscript.com (bug-gs-bounces at ghostscript.com) Date: Fri, 30 Jan 2004 09:50:17 -0800 Subject: Your message to bug-gs awaits moderator approval Message-ID: Your mail to 'bug-gs' 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://www.ghostscript.com/mailman/confirm/bug-gs/c960d6e9894865ef4d202f7847e966da960da673 From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Mon Jan 12 11:48:52 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 12 Jan 2004 18:48:52 +0200 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: >>>>> "Jacek" == Jacek Generowicz writes: Jacek> Lest Derek give the impression that Lisp is in any way a Jacek> "toy" language, or that it somehow sacrifices practicality Jacek> for elegance, I feel honour bound to point out that it is Jacek> actually the most powerful and expressive programming Jacek> language known to man, and excells in solving problems Jacek> which are often considered too hard to be solved in other Jacek> languages. Python will catch up Real Soon Now - there are so many Python+Lisp projects in the works, soon we can implement all the impossible tasks in the world by combining development speed of Python with macro magic of Lisp for that final, "impossible" leap :-). Jacek> -- Greenspun's Tenth Rule of Programming: Jacek> Greenspun's Tenth Rule of Programming: "Any sufficiently Jacek> complicated C or Fortran program contains an ad-hoc, Jacek> informally-specified, bug-ridden, slow implementation of Jacek> half of Common Lisp." At least they should have implemented scheme instead. -- Ville Vainio http://www.students.tut.fi/~vainio24 From sombDELETE at pobox.ru Sun Jan 4 19:46:16 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 5 Jan 2004 03:46:16 +0300 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "John Roth" wrote in message news:vvh75ienj7g244 at news.supernews.com... > > "Serge Orlov" wrote in message > news:bta2ng$16v7$1 at nadya.doma... > > > > "John Roth" wrote in message > news:vvg0h93ue63c0b at news.supernews.com... > > > > > > One problem I've been playing around with is: how would you > > > implement something functionally equivalent to the Unix/Linux > > > chroot() facility? The boundaries are that it should not require > > > coding changes to the application that is being restricted, and it > > > should allow any and all Python extension (not C language > > > extension) to operate as coded (at least as long as they don't > > > try to escape the jail!) Oh, yes. It has to work on Windows, > > > so it's not a legitimate response to say: "use chroot()." > > > > I don't see any unsolvable problems. Could you be more specific > > what is the problem? (besides time, money, need to support > > alternative python implementation, etc...) > > Well, I don't see any unsolvable problems either. The biggest > sticking point is that the Unices use hard links to create > a directory tree that has the necessary programs availible. > Windows does not have this capability, so an implementation > would have to build a virtual directory structure, intercept all > paths and map them to the virtual structure backwards and > forwards. > > The reason I find it an interesting problem is that I can't see > any way to do it with the kind of "generic" facility that was > in the Python Restricted execution facility, at least without a > complete redesign of the file and directory functions and > classes in the os module. Without that, it would > require code in the C language implementation modules. > Right now the file and directory management modules are a > real mess. Right, you can do it with a custom importer and wrapper functions over all file and directory functions. But that's a mess over a mess and any mess is *bad* for security. The way out the mess is probably filepath object that should consolidate all access to files and directories. If you wanted to make a point that std library should be designed with security in mind I agree with you. One step in that direction is to design everything OO. OO design plays nice with capabilities. -- Serge. From kristian.ovaska at helsinki-nospam.fi.invalid Thu Jan 15 07:00:33 2004 From: kristian.ovaska at helsinki-nospam.fi.invalid (Kristian Ovaska) Date: Thu, 15 Jan 2004 12:00:33 GMT Subject: super. could there be a simpler super? References: Message-ID: Kerim Borchaev : > Is it possible that such a "super"(deducing class method declaration > context) could appear in Python? > (It seems to me that to implement a simple super something should be > done during "compilation" of class declaration.) The document "Unifying types and classes in Python 2.2" by Guido probably answers your question. Quote from http://www.python.org/2.2.3/descrintro.html#cooperation regarding super: "It would be nice if we didn't have to name the class explicitly, but this would require more help from Python's parser than we can currently get. I hope to fix this in a future Python release by making the parser recognize super." -- Kristian Ovaska - http://www.cs.helsinki.fi/u/hkovaska/en/ From theller at python.net Wed Jan 21 13:33:13 2004 From: theller at python.net (Thomas Heller) Date: Wed, 21 Jan 2004 19:33:13 +0100 Subject: py2exe 0.5.0 (finally) released References: <8a27e309.0401201304.7ee860b0@posting.google.com> <1ebr001fkuq85al2i8c26ejceu8qvedmdb@4ax.com> <8a27e309.0401210959.22a2cacb@posting.google.com> Message-ID: ny_r_marquez at yahoo.com (R.Marquez) writes: > Wolfgang Strobl wrote >> icon_resources works for me, like so: >> >> setup( windows = ["wxKnife.py", >> {"script":"wxKnife.py","icon_resources":[(1,"images/app2.ico")]}], >> console=["installed_updates.py","installed_sw.py"], >> data_files=[("images",["images/app2.ico",]),] >> ) > > That worked. I see that I need to visit the wiki page now. Thank you. > > -Ruben It is also in the samples\advanced, although commented out. Thomas From ramen at lackingtalent.com Sat Jan 10 01:54:00 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 10 Jan 2004 06:54:00 -0000 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: Message-ID: In article , Robert Brewer wrote: >> Do you spend a "significant" amount of time actually >> optimizing your Python applications? (Significant is >> here defined as "more than five percent of your time", >> which is for example two hours a week in a 40-hour >> work week.) > > No, I don't. The big object server I'm working on now for four months > (which actually *has* some performance requirements) has had _one_ > optimization round. I noticed some slowness, profiled the problem down > to the DB layer, and solved it by switching my ADO recordset to > read-only. That cut the load time of objects to 1/3 of what it was > before the optimization. All the other operations to get that data laid > out on a web page were insignificant in comparison. That's generally been my experience as well. > Generally, I tend to "worry" far more about interface design (for both > users and developers) than performance. Thank you! I couldn't say it better. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From nekiv at start.no Mon Jan 26 08:16:43 2004 From: nekiv at start.no (Olav) Date: 26 Jan 2004 05:16:43 -0800 Subject: Py2exe and WMI module Message-ID: <697d8a6c.0401260516.40e51096@posting.google.com> I'm having a problem when I try to make a standalone installation of a Python program using Tim Goldens WMI-module. The py2exe produce the exe-file as expected, but it fails to execute. I have run makepy manually on one all of the above libraries. Microsoft WMI Scripting Library WMI ADSI Extension Type Library WMICntl Type Library test-fail.py (my script) ----------------------- import wmi ----------------------- setup.py (my setupscript) ----------------------- # setup.py from distutils.core import setup import py2exe setup(console=["test-fail.py"]) ----------------------- Output from exe-file: Traceback (most recent call last): File "test-fail.py", line 1, in ? import wmi File "wmi.pyc", line 132, in ? File "win32com\client\gencache.pyc", line 527, in EnsureDispatch File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass KeyError: '{D2F68443-85DC-427E-91D8-366554CC754C}' Anyone? regards Olav From stuart at bmsi.com Mon Jan 19 22:02:31 2004 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 19 Jan 2004 22:02:31 -0500 Subject: speedy Python strings? References: Message-ID: On Tue, 20 Jan 2004 01:43:24 +0100, Uwe Mayer wrote: > class myFile(file): > def read(self, *args): > ... # self.buffer += file.read(self, *args) # not this self.buffer = self.buffer[self.pos:] + file.read(self, *args) self.pos = 0 > ... > > and after reading information from the buffer I remove the read part from > it: > # text = struct.unpack("L", self.buffer[:4]) # self.buffer = self.buffer[4:] pos = self.pos text = struct.unpack("L", self.buffer[pos:pos+4]) self.pos = pos + 4 -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From mmoum at woh.rr.com Wed Jan 14 19:13:33 2004 From: mmoum at woh.rr.com (DoubleM) Date: Thu, 15 Jan 2004 00:13:33 GMT Subject: Tkinter: modal ok in windows, but not in Linux Message-ID: Hi, I'm running Python2.3.3c1 on Mandrake 9.1 The following code is designed to bring up a window with a button labeled "popup". Clicking on the popup buttons triggers a secondary window with a button labeled "ok". The second window is supposed to be modal - it should not be possible to reset the focus back to the first window or close the first window without first closing the second. The program works just fine in Windows XP home, but in Linux I can close the first window while the second one is still active. This seems to be a bug, or am I doing something wrong. I searched google for Tkinter Linux modal, but found nothing relevant. Thanks for your help. Here's the code, copied and pasted from IDLE. ############################# from Tkinter import * makemodal = 1 def dialog(): win = Toplevel() Label(win, text = "Secondary").pack() Button(win, text = "Ok", command = win.destroy).pack() if makemodal: win.focus_set() win.grab_set() win.wait_window() print "dialog exit" root = Tk() Button(root, text = 'popup', command = dialog).pack() root.mainloop() ################################# Mike mmoum-xxxspam.woh.rr.com -- Remove -xxxspam to reply From alan.gauld at btinternet.com Thu Jan 8 17:04:08 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Jan 2004 22:04:08 GMT Subject: OT: What is Mac OS X? References: Message-ID: <3ffdd365.360302036@news.blueyonder.co.uk> On 8 Jan 2004 15:55:37 -0500, aahz at pythoncraft.com (Aahz) wrote: > http://www.kernelthread.com/mac/osx/ > > Good technical summary for all the Macaholics here. I agree, and as someone who got is first Mac at exactly the same date as the author I'll add one extra observation. Multi button mice for Mac are not only available but they actually work as you would expect (including the scrollwheels!) with the standard Mac applications as well as with X windows ones... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From peter at engcorp.com Wed Jan 28 09:14:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 09:14:16 -0500 Subject: Upgrading to Python 3.0 Questions References: Message-ID: <4017C3B8.8E3E3642@engcorp.com> Zachary wrote: > > I've heard some rumors about Python 3.0. I am wondering what sort of > upgrading I'll have to do, as I have also heard people on this group asking > us to use certain modules or operators or whatever. > Is it a major sort of upgrade? What would I need to do to prepare for it? All available information about Python 3.0 is very clearly posted on the www.python.org site right under "Python versions" in the "Python 3.0" link. -Peter From nosmapplease at somewhere.com Sat Jan 31 18:25:51 2004 From: nosmapplease at somewhere.com (Psymaster) Date: 31 Jan 2004 23:25:51 GMT Subject: Problems embedding Python Message-ID: I've tried running scripts from the embedded interpreter but it doesn't work. If I try the same scripts as strings to interpret it works. Here is my program: #include #include "Python.h" int main(int argc, char *argv[]) { FILE *script = fopen("c:/c.py", "r"); Py_Initialize(); PyRun_SimpleFile(script, "c.py"); Py_Finalize(); return 0; } c.py contains just a simple print statement. This compiles and links under MSVC 6 but when run crashes. Any help? From paul at prescod.net Wed Jan 21 04:24:41 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 21 Jan 2004 01:24:41 -0800 Subject: Weaver/Yarn Pattern in Python In-Reply-To: <20040121062432.GA6158@ics.uci.edu> References: <20040121062432.GA6158@ics.uci.edu> Message-ID: <400E4559.3020704@prescod.net> I've tried to understand your problem statement in detail but it is alot to keep in the head in pure abstraction (i.e. I don't have your specific problem and haven't worked on this complicated a tree walker in a while if ever). Also, I think there may have been some typos that are making it harder to understand. For instance, is visitB supposed to be syntactically identical to visitA except it calls weaveB's instead of weaveA's? Is this the boilerplate that offends you? But maybe I can help anyhow. Here's some code from your post: > class Weaver: > "A special visitor which weaves yarns" > def __init__(self, yarns): > self.yarns = yarns > def visitA(self, a): > for y in self.yarns: > y.weaveA_First(a) > for i, k in enumerate(a.kids): > for y in self.yarns: > y.weaveA_Before(a, i) > k.accept(self) > for y in self.yarns: > y.weaveA_After(a, i) > for y in self.yarns: > y.weaveA_First(a) > def visitB(self, b): > for y in self.yarns: > y.weaveA_First(b) > for y in self.yarns: > y.weaveA_First(b) I'm going to presume that visitB was supposed to be more like: > def visitB(self, b): > for y in self.yarns: > y.weaveB_First(b) > ... identical to visitA except A's swapped for B's ... If it isn't identical to visitA (except for the B) then I don't know what the boilerplate is. Also, you end visitA with a weaveA_First but you probably mean weaveA_Last. If I'm understanding right, I think each yarn has a two-D matrix of methods: A B C D .... First Before After Last And then you've got another dimension for the yarns (that varies at runtime) There are many ways to represent these axes in Python: self.yarns[0]["A"]["First"] self.yarns[0]["A", "First"] self.yarns[0]["A_First"] self.yarns[0]["A"].First() class Weaver: "A special visitor which weaves yarns" def __init__(self, yarns): self.yarns = yarns def visit(self, a): for y in self.yarns: y.threads[a.type].First(a) for i, k in enumerate(a.kids): for y in self.yarns: y.threads[a.type].Before(a, i) k.accept(self) for y in self.yarns: y.threads[a.type].After(a, i) for y in self.yarns: y.threads[a.type].Last(a) Now a yarn becomes essentially a holder for a dictionary of what I've called threads (that'll confuse your co-workers!). And a thread works with a particular node type, doing the First, Before, After and Last for it. The "thread" looks something like: class X_Yarn_A_thread: self.type == "A" def First(self, arg): assert arg.type == self.type return self.first(arg) def Before(self, arg): assert arg.type == self.type return self.before(arg) The asserts may be useless considering how bullet-proof the Weaver code should be...you dispatch on a.type so how could a thread end up with the wrong type? Hacking together method names with strings is only ever a sort of syntactic sugar for some other design that uses dictionaries "properly". Remember that Python has at its core a similar feature set to Scheme and Lisp which are famously "flexible" and "powerful" and yet do not do any name manging weirdness. It's great that Python allows that name manging stuff but if you feel you HAVE to use it then you probably aren't thinking in terms of higher order functions or objects in contrainers as you could/should. You should think about hwo to do things without method-name hacking before deciding that that's a better solution for some reason of expedience or usability. Paul Prescod From giva at users.sourceforge.net Thu Jan 8 11:35:21 2004 From: giva at users.sourceforge.net (Gisle Vanem) Date: Thu, 8 Jan 2004 17:35:21 +0100 Subject: Module depends tool Message-ID: <3ffd87c4$1@news.broadpark.no> Is there a tool to show which dynamic modules (*.pyd/*.dll) a script depends on w/o running it? And the path(s) where python would have loaded it from. Something like Cygwin's cygcheck does for PE modules. G:\Programfiler\Python.23\Lib\site-packages>cygcheck pcapy.pyd Found: .\pcapy.pyd pcapy.pyd g:\Mingw32\bin\wpcap.dll f:\windows\System32\ADVAPI32.DLL f:\windows\System32\ntdll.dll f:\windows\System32\KERNEL32.dll f:\windows\System32\RPCRT4.dll f:\windows\System32\msvcrt.dll f:\windows\System32\USER32.dll f:\windows\System32\GDI32.dll f:\windows\System32\WS2_32.DLL f:\windows\System32\WS2HELP.dll f:\windows\System32\python23.dll f:\windows\System32\SHELL32.dll f:\windows\System32\SHLWAPI.dll -- Gisle V. # rm /bin/laden /bin/laden: Not found From cygnus at cprogrammer.org Sat Jan 24 08:48:34 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sat, 24 Jan 2004 08:48:34 -0500 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> Message-ID: <20040124134834.GA13149@mail.theserver.ath.cx> I propose a perl-vs-python at lists.sourceforge.net list. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From python at quixs.com Sun Jan 18 09:15:44 2004 From: python at quixs.com (Lars Heuer) Date: Sun, 18 Jan 2004 15:15:44 +0100 Subject: Webbrowser and Mozilla control on linux In-Reply-To: <1d17eeb7.0401171633.170e313a@posting.google.com> References: <1d17eeb7.0401171633.170e313a@posting.google.com> Message-ID: <929559882.20040118151544@quixs.com> Hi Jay, > If anyone can share some samples, or point me to a good > reference with browser control details, I'd much appreciate Documancer, a wxPython app uses Mozilla to display pages (using wxMozilla). Documancer: http://documancer.sf.net/ wxMozilla: http://wxMozilla.sf.net/ HTH, Lars From hilfmir at gmx.at Tue Jan 13 11:55:59 2004 From: hilfmir at gmx.at (mzo) Date: 13 Jan 2004 08:55:59 -0800 Subject: Cannot press OK in Windows Print Dialog / How can i print in Windows ? Message-ID: <2d0e7cf4.0401130855.d55d411@posting.google.com> Hello I want to use the Standard Windows Common Dialog, because i want a orginal Windows Look and Feel in a pyGTK - GUI. I use Python 2.3 with PythonWin GUI Extension and Win32 Extension. ColorSelectionDialog, FileSelectionDialog, FontSelectionDialog work well, but PrintDialog do not work. I have made a small example: ----------------------------- import win32ui import gtk dllhandle = win32ui.LoadLibrary("C:\\WINNT\\SYSTEM32\\COMDLG32.DLL") pcd = win32ui.CreatePrintDialog(1538, gtk.FALSE, win32ui.PD_NOPAGENUMS|win32ui.PD_PAGENUMS|win32ui.PD_SELECTION|win32ui.PD_SHOWHELP|win32ui.PD_PRINTTOFILE|win32ui.PD_ALLPAGES, None, dllhandle ) res = pcd.DoModal() ----------------------------- This Example load the Print Dialog/ Print Setup but if i press OK nothing do (The dialog do not close, like expected). I can the Window only close with Cancel and get "2" back. Whats?s wrong ? How can i get the Settings and print with this settings after the dialog ? A not so important question is, how i can connect a Help-message to the Help button in the Print Dialog ? The Pythonwin-Printdialog (from pywin.mfc import dialog) use the CreatePrintDialog but i do not know whats pinfo. Where can i get pinfo (need to call this function). The Head of PrintDialog is: ----------------------------------------- class PrintDialog(Dialog): " Base class for a print dialog" def __init__(self, pInfo, dlgID, printSetupOnly = 0, flags=(win32ui.PD_ALLPAGES| win32ui.PD_USEDEVMODECOPIES| win32ui.PD_NOPAGENUMS| win32ui.PD_HIDEPRINTTOFILE| win32ui.PD_NOSELECTION), parent=None, dllid=None): ------------------------------- Thanks martin From Kyler at news.Lairds.org Mon Jan 19 23:12:09 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 20 Jan 2004 04:12:09 GMT Subject: efficent test for array with only one value? References: <00ird1-dmd.ln1@jowls.lairds.org> Message-ID: <25mud1-s1m.ln1@jowls.lairds.org> Robert Kern writes: > >>> from Numeric import * > >>> a = ones((3,5)) > >>> equal.reduce(a.flat) >1 > >>> a[0,3] = 0 > >>> equal.reduce(a.flat) >0 > >>> >Ufuncs are wonderful things. Yeah, but they also don't work for this. First, I'm guessing that reduce will not stop immediately when equal encounters a False. (It doesn't do "and".) Also, it just plain doesn't work. >>> import Numeric >>> a = Numeric.zeros((3,5)) >>> Numeric.equal.reduce(a.flat) 0 >>> Numeric.equal.reduce([0,0,0,0,0,0,1]) 1 --kyler From M.Waack at gmx.de Thu Jan 8 16:19:30 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Thu, 08 Jan 2004 22:19:30 +0100 Subject: scanning c-code References: Message-ID: <24u0d1-g04.ln1@valpo.de> tm wrote: > I have to to scan c-code, look for a c-struct variable(declaration) > and represent the struct in a tree-graphic. > Are there modules for scanning c-code and graphictools for the > representation stuff. > What would you advise as a starting point... www.doxygen.org and graphviz (the latter is used by the former). Mathias From nospam at no.spam Sat Jan 17 04:08:56 2004 From: nospam at no.spam (Andrae Muys) Date: Sat, 17 Jan 2004 19:08:56 +1000 Subject: Suggested generator to add to threading module. In-Reply-To: References: <7934d084.0401152058.164a240c@posting.google.com> Message-ID: <4008fba9@duster.adelaide.on.net> Aahz wrote: > In article <7934d084.0401152058.164a240c at posting.google.com>, > Andrae Muys wrote: > >>Found myself needing serialised access to a shared generator from >>multiple threads. Came up with the following >> >>def serialise(gen): >> lock = threading.Lock() >> while 1: >> lock.acquire() >> try: >> next = gen.next() >> finally: >> lock.release() >> yield next > > > I'm not sure this is generic enough to go in the standard library. > Usually, I'd recommend that someone wanting this functionality consider > other options in addition to this (such as using Queue.Queue()). While I fully appreciate the importance of a Queue.Queue in implementing a producer/consumer task relationship, this particular function provides serialised access to a *passive* data-stream. With the increasing sophistication of itertools and I feel there maybe an argument for supporting shared access to a generator. Anyway I thought it was worth offering as a possible bridge between the itertools and threading modules. If I'm mistaken, then it's no major loss. Andrae From mwh at python.net Wed Jan 21 15:12:18 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 21 Jan 2004 20:12:18 GMT Subject: SystemError while execing bad code References: Message-ID: Gerrit Holl writes: > Hi, > > I found a cool way to trigger a SystemError: How about marshal.loads('0') ? > >>> exec CodeType(0,0,0,0,"",(),(),(),"","",0,"") > XXX lineno: 0, opcode: 0 > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/", line 0, in > File "/usr/lib/python2.2/site-packages/", line 0, in > SystemError: unknown opcode [snippety] > But I guess this is a case of "so don't do it" :-)? Definitely. It's easy enought to crash the interpreter this way (think LOAD_CONST 30000, for just one easy way). Cheers, mwh -- Very clever implementation techniques are required to implement this insanity correctly and usefully, not to mention that code written with this feature used and abused east and west is exceptionally exciting to debug. -- Erik Naggum on Algol-style "call-by-name" From tjreedy at udel.edu Fri Jan 2 00:12:38 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jan 2004 00:12:38 -0500 Subject: question: Python or Lua for rejuvenation of old PCs? References: Message-ID: <8oKdneXkV7RcYGmiRVn-hQ@comcast.com> "John Benson" wrote in message news:mailman.16.1072987285.12720.python-list at python.org... > I suppose that my question is best phrased as this: What is a comfortable > minimum RAM size that a PC needs to have to comfortably run modern Python > for non-memory-intensive applications (i.e. no big database crunching or > other thrashy stuff). I'm thinking about just polling sensors and actuating > control devices over RS-232/RS-485/LAN and doing some chitchat between the > nodes over the LAN. Based on the response, I'll draw the line between my Lua > machines and my Python machines. I did my first useful Python work with old DOS version on a 4 MB machine. Disk memory size and running RAM memory size are different issues. I have read that Lua beats Python on minimal disk footprint but have no idea of running size. On Windows, Python.exe is very small but does import several modules, though I believe it could be built to require less. Terry J. Reedy From adonisv at REMOVETHISearthlink.net Sun Jan 4 14:52:32 2004 From: adonisv at REMOVETHISearthlink.net (Adonis) Date: Sun, 04 Jan 2004 19:52:32 GMT Subject: Tkinter.Menu() Question Message-ID: <4a_Jb.8099$6B.48@newsread1.news.atl.earthlink.net> I wish to create a popup menu from a list, when it is created they all show the same label from the list: Months = [0, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def _Menu_Click(self, month): print month menu = Menu(fraMain, tearoff=0) for Month in Months[1:]: menu.add_command(label=Month, command=lambda : _Menu_Click(Month)) When the menu calls _Menu_Click(...) it always prints 'December' Now my understanding is the when an object is created and it is replicated, whichever of the modified replications affects all of the objects, being that they are just mere references to the original (my wording might be off, correct me if I am wrong). How do I avoid this for what I am trying to achieve? Any help is greatly appreciated. Adonis From arjen.dijkstraNoSpam at hccnet.nl Fri Jan 16 07:50:05 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Fri, 16 Jan 2004 13:50:05 +0100 Subject: Setting Window Size using Pack Under Tkinter References: <8089854e.0401160134.5674a86c@posting.google.com> Message-ID: <4007de09$0$151$e4fe514c@dreader5.news.xs4all.nl> from Tkinter import * gui=Tk() ####code#### gui.geometry("+%d+%d" %(300, 100)) gui.resizable(0,0) if __name__=='__main__': gui.mainloop() "Fuzzyman" schreef in bericht news:8089854e.0401160134.5674a86c at posting.google.com... > I'm having trouble implementing my GUI using Tkinter...... > I've been working through the Tkinter tutorials from 'Programming > Python' and am generally happy enough with the functionality and feel > of the results *but* - I can't see how to set the size of the root > window (or any top level window) and to stop it being resized........ > > Thanks for any help. > > Fuzzyman > > > -- > > YAPLP > Yet Another Python Links Page > http://www.voidspace.org.uk/coollinks/python_links.shtml > > Python Utils > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > -- > > 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.atlantibots.org.uk > http://groups.yahoo.com/group/atlantis_talk/ > Atlantibots - stomping across the worlds of Atlantis. > --- > 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 elainejackson7355 at home.com Thu Jan 29 12:58:45 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 29 Jan 2004 17:58:45 GMT Subject: conditional expression sought Message-ID: If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without evaluating any other B_i. This is such a useful mode of expression that I would like to be able to use something similar even when there is an i with bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious reasons. Does anybody know a good way to express this? Any help will be mucho appreciado. Peace From simonb at NOTTHISBIT.webone.com.au Wed Jan 14 19:50:41 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Thu, 15 Jan 2004 11:50:41 +1100 Subject: Cyclic garbage collection and segfaults... References: Message-ID: > Can anyone explain what I'm doing wrong? Or perhaps suggest a better > solution to my "real" problem, if I'm approaching the problem completely > wrong :-) > > Yours, > /mailund In my extensions python seems to segfault in the GC most of all... Just yesterday I removed a malloc that was (why??) causing a segfault. Have you seen pyrex ? It's absolutely brilliant. Take 2 hours to try it out if you have the time. Simon. From claird at lairds.com Wed Jan 14 11:05:59 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 14 Jan 2004 16:05:59 -0000 Subject: I come not to bury C++, but to praise it... References: Message-ID: <100aq779r2h2c9e@corp.supernews.com> In article , Derek wrote: . . . >I also use C++ and Python as my main languages and I agree with your >comments. However, I don't agree that Python is inherently "safer" >than C++. At best I see it as a tie. For example, C++ let's you >corrupt memory among other "unsafe" things, most of which can be >avoided by using standard containers, smart pointers, etc. Python >lets you do "unsafe" things such as passing an object to a function >when it makes no sense to do so, which can lead to nasty runtime >surprises. > > We disagree on some matters. I *do* regard Python as inherently safer than C++, and much more so. My aim for now is not to persuade you to my view, but only to make it explicit. Memory management, and mismanagement, as mundane as it is, is so poorly applied in so much of the C++ code I see, that it swamps all other dimensions of comparison between the two languages. I quite agree with you that competent C++ programmers should exploit smart pointers and so on. My experience is that, somehow, C++ as it's generally practiced appears to have barriers to their use. I don't understand your last sentence, and, given my own focus on reliability, I very much want to understand it. Are you alluding precisely to Python's dynamic typing, and observing that, as earlier is better, C++'s compile-type checks beat Python's run-time checks? -- Cameron Laird Business: http://www.Phaseit.net From jjl at pobox.com Fri Jan 23 07:32:04 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 12:32:04 +0000 Subject: Help and optimization hints, anyone? References: Message-ID: <87d69a6e2j.fsf@pobox.com> Kim Petersen writes: > I've worked on this table object a bit too long - and seem to have > stared too long at the code. Can someone see where it goes wrong in > the insertrow function? I made a few comments before I realised it was a Tkinter question, so no answer, sorry! Just some style hints. BTW, it's very helpful to mention in the subject line when a particular GUI toolkit is involved (or when any other large library is a central part of the question, for that matter). > Also optimization hints and alternatives will be greatly appreciated. > > > #!env python > # > # created: "15:19 20/01-2004" by Kim Petersen > # > # $Id$ > # > import Tkinter > > class UserDict: Bad name -- UserDict is a standard library module. In 2.2 or newer, you can subclass dict. In 2.3, you also have the option of subclassing UserDict.DictMixin. If you just want to implement part of the maping interface, just call your class something other than UserDict -- say SimpleDefaultDictBase. > defaults={} > def __init__(self,inherit=None): > if not inherit: > self.inherit=[] > else: > self.inherit=inherit > self.dict=self.defaults.copy() > > def __setitem__(self,name,value): self.dict[name]=value > > def __getitem__(self,name): > if not self.dict.has_key(name): > for dict in self.inherit: dict is also a bad name -- this is the name of the builtin dictionary type, which you've just clobbered (in the local scope). > if dict.has_key(name): > return dict[name] > raise KeyError,"%s not found" % (name,) > return self.dict[name] > > def haskey(self,name): return self.dict.has_key(name) Did you really mean to call it that? The dict interface has a method .has_key(), not .haskey(). > class Cell(UserDict): > defaults={"width": 0,"height": 0,"text": '',"color": "black","background": "white", > "widgets": None} [...] Haven't read much further, but it looks like you might be better off using attribute access rather than indexing. In 2.2, use properties. Earlier, use __setattr__ / __getattr__ (make sure you read the docs). John From jjl at pobox.com Tue Jan 6 13:49:45 2004 From: jjl at pobox.com (John J Lee) Date: Tue, 6 Jan 2004 18:49:45 +0000 (GMT) Subject: Why does this fail? In-Reply-To: <16378.58491.796532.530331@montanaro.dyndns.org> References: <878yklavnx.fsf@pobox.com> <16378.58491.796532.530331@montanaro.dyndns.org> Message-ID: On Tue, 6 Jan 2004, Skip Montanaro wrote: [...] > John> http://wwwsearch.sf.net/bits/clientx.html > > A possible addition to your "Embedded script is messing up my web-scraping" > section: Wasn't there mention of the Mozilla project's standalone > JavaScript interpreter (don't remember what it's called) recently alongside > some Python interface? (Just finished updating that page a few seconds ago, BTW.) I don't remember that, other than PyXPCOM (linked to from that page -- at least, it is now ;-) and my own http://wwwsearch.sf.net/python-spidermonkey http://wwwsearch.sf.net/DOMForm Be warned, all my JavaScript-support code is very alpha (DOMForm itself shouldn't be anywhere near so bad, but still very early alpha). John From xerolimit126 at earthlink.net Tue Jan 27 19:56:13 2004 From: xerolimit126 at earthlink.net (Xero Limit 126) Date: Wed, 28 Jan 2004 00:56:13 GMT Subject: Easy way to make EXEs... Message-ID: Okay, I am completely new to Python, and I really dont understand much, but I was wondering how to make a python script/program into a standalone .EXE? I dont understand py2exe at all, so if someone could tell me or find me an easy (For a newbie) to convert Python scripts to EXEs, please let me know! Thanks for any help! From jcarlson at nospam.uci.edu Fri Jan 30 22:10:07 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 30 Jan 2004 19:10:07 -0800 Subject: Python vs. Io In-Reply-To: <711c7390.0401301726.3e38da27@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: > I'm not sure how to tell you this so I'll just give a heavily > commented example (comments in Io are with #, //, or /* */) > > parentProto := Object clone //makes parentProto a new object > //:= is used for creating new variables > parentProto shared := 5 //parentProto's new slot shared holds 5 > parentProto different := 6 > parentProto sum := method(shared + different) //self isn't necessary > write("parentProto's sum: ", parentProto sum, "\n") > x := parentProto clone //essentially new instance of parentProto > y := parentProto clone > x different = 2 //just updating slots is done with =. > y different = 3 > write("first x sum ", x sum, "\n", > "first y sum ", y sum, "\n") > parentProto shared = 7 //should show up on all clones > write("later x sum", x sum, "\n", > "later y sum", y sum, "\n") > > Does that illustrate it well? I know the difference between := and = > is annoying, but you'll get used to it, and it allows really cool > things to be done with scopes and inheretance. > > Daniel Ehrenberg After looking at your sample code, I couldn't help but say 'ick'. Maybe it is my C and Python background, but just putting a space between an object and its properties looks ugly. The use of method() also makes my skin crawl. It is cool that you dig on Io, and I wish you the best. - Josiah From peter at engcorp.com Fri Jan 9 09:42:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 09:42:04 -0500 Subject: Debugging Python References: Message-ID: <3FFEBDBC.2F9DFD03@engcorp.com> Ashley Lloyd wrote: > > What do people generally use to debug their Python programs? I haven't seen > anything out there that walks through the code, but perhaps I'm looking in > the wrong places? When I need to, which is rare, I either use print statements (a very solid technology dating from, oh, last century sometime ;-), or the Python debugger module: pdb. Actually, all I ever do with pdb is this: # this is just before the code that I think is failing import pdb pdb.set_trace() # code that I'm about to trace through goes here And about the only features of pdb I've had to use are "r", "n", and the ability to inspect arbitrary variables. I'm not sure about others, but when I design and code using test-driven development (TDD), I tend not to need to debug almost ever. The need to debug is usually when you aren't sure where a typo, or logic error, or other mistake has actually occurred. When using TDD, it's exceedingly rare that when a test fails, I don't know exactly where the problem is without having to resort to traditional (slow, tedious, annoying) debugging. -Peter From bkelley at wi.mit.edu Sun Jan 11 16:51:12 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Sun, 11 Jan 2004 21:51:12 GMT Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> <40011315.7070000@v.loewis.de> <8EeMb.24302$5V2.36981@attbi_s53> Message-ID: Martin v. L?wis wrote: > I'm uncertain how this relates to the internationalization tables > you are proposing, but please recognize that a single application > may have *multiple* such tables, called "textual domains". To > find a translation, you not only need the message id, but you > also need the textual domain. I understand this. I was just curious whether this should be internal or external to python. Various comments have indicated that it really doesn't matter. This might be a red-herring to the current discussion, let's forget that I mentioned parsing at all :) >>This should tranparent to Gui Widgets and the like so you can place >>i"Message" in a list box, it will automatically get internationalized >>but when you get the result of the user selected, it still can be used >>to dictionary look ups exactly the same as the original i"Message". > > > Using what textual domain? As I understand it, it doesn't matter. I have been wrong before though. The textual domains are set by setting the locale and what I considered the "neat" part was that the dictionary look ups are independent of textual domain. That is, you could switch textual domains on the fly and not affect dictionary look-ups. I don't think that with the original gettext system that this would work. That is as I understand it, if you changed the locale you need to call the _() function again which means that any previous dictionaries would need to be re-created with the new string values. > xgettext.py already performs very simple parsing of source files, > to extract messages. Why reinvent the wheel? I agree with this. I just initially didn't like the idea of using an independent source code analyzer. Let's assume that I will start with xgettext and modify that instead. >>In either case, I far prefer using internation("This is good") over >>the _("This is good") function call. > > > So do call it internation(), or internationalization() or something > else. It is just a function: Ahh, but mine isn't a function, it is a subclass of string. So my version of gettext, calling _("Hello") doesn't return the current localized string, it returns a string object that looks up on the fly the current localization for the purposes of printing, essentially str operations. Your comments about looking at the thread state are quite useful, I might play with that. Again, if I am reinventing the wheel on this, I apologize. And again, thanks for bearing with me. Brian From LittleDanEhren at yahoo.com Sat Jan 31 21:35:39 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 31 Jan 2004 18:35:39 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> <711c7390.0401311134.26cd0a11@posting.google.com> Message-ID: <711c7390.0401311835.240e6e41@posting.google.com> > Okay. So, if I set 'self id', like so > > self id := allocated > > and want to update it later in the same block I can use > > id = "updated self 'id' slot value" > > But, if I later use > > id := "set new local 'id' slot value" Yes, but code like that is confusing and shouldn't be used unless you need to. > > in the same block I get a new local variable. Is that how it works? > Or does the first use of a slot determine its assignment scope > for the duration of the block? > > self a := "unchanged" > a := "changed" > write("self a is ", self a) # changed or unchanged? unchanged. If you want to learn more about Io, you should probably join the Io mailing list instead of bothering the whole usenet thread. Its website is http://groups.yahoo.com/group/iolanguage/ . Daniel Ehrenberg From miki.tebeka at zoran.com Wed Jan 28 02:44:19 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 27 Jan 2004 23:44:19 -0800 Subject: Tcl style traces References: <40171be5$0$1742$5a62ac22@freenews.iinet.net.au> Message-ID: <4f0a9fdb.0401272344.3464cfd5@posting.google.com> Hello Derek, > Does Python have something similar to Tcl style tracing? That is, the > ability to call a subroutine when a variable is written to or read from? Not that I know of. The only way I can think you'll be able to pull this one is by using pdb. Just set breakpoints where the variable can change a give as a condition a function that prints the value of the variable and returns 0. HTH. Miki From pf_moore at yahoo.co.uk Thu Jan 22 14:08:33 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Thu, 22 Jan 2004 19:08:33 +0000 Subject: Program Python in VIM References: <871xpsc5zf.fsf@tulip.whu.ca> Message-ID: Peter Wu writes: > I'm giving vim a try to program Python. The following are the steps I > follow to code/test a python program. > > vi test.py > [key in some python code] > :wq > :!python test.py > > > Is there any other way? I don't want to type 'python test.py' every time > I've made any modifications. In Emacs, I can simply fire C-c C-c to fire > the python interpreter. Thanks! There's always :map ^C^C :w^M:!python %^M which makes C-c C-c write the file and then run it in Python. Paul. -- This signature intentionally left blank From martin at v.loewis.de Mon Jan 19 01:31:31 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 19 Jan 2004 07:31:31 +0100 Subject: time module question In-Reply-To: References: Message-ID: Jeff Seale wrote: > How would one go about writing a program which included a clock that > updated itself? Right now I'm able to display the time in a text widget in > the window but I can't get it to update. In your GUI library, find the mechanism to produce delayed/timed events. Then, in the event callback, update the text of the widget. Regards, Martin From sombDELETE at pobox.ru Mon Jan 19 16:38:51 2004 From: sombDELETE at pobox.ru (Serge Orlov) Date: Tue, 20 Jan 2004 00:38:51 +0300 Subject: stack-like file object References: <400be8f3_2@nova.entelchile.net> Message-ID: "Rodrigo Benenson" wrote in message news:400be8f3_2 at nova.entelchile.net... > Hi, > I need to implement a stack on a file. > The idea is to have a big list, and put part of his head on the disk. The > model of access to the file is like a stack (read in order only the tail, > write only at the tail). Why don't you use a collection of file organized as stack in one directory or in many directories if your underlying file system cannot effectively support many files in one directory. If your pickles are small (much less than block size of the file system) you can keep several of them in one file about the size of the block size. Since the files will be small you can simply rewrite them competely each time you need change them. -- Serge. From mnations at airmail.net Tue Jan 27 13:43:04 2004 From: mnations at airmail.net (Marc) Date: 27 Jan 2004 10:43:04 -0800 Subject: Confusing problem between Tkinter.Intvar() and self declared variable class References: <4378fa6f.0401261709.664ca799@posting.google.com> Message-ID: <4378fa6f.0401271043.5183d0c3@posting.google.com> Thanks Peter. That worked great! I was able to shoe horn that into my main program with hardly any changes at all, and it was exactly what I was looking for. I was afraid my post was a little confusing, so I started another thread on the general subject of Tk support for pickling. But basically you answered both questions with one shot. Thanks again, Marc From theller at python.net Thu Jan 29 09:59:49 2004 From: theller at python.net (Thomas Heller) Date: Thu, 29 Jan 2004 15:59:49 +0100 Subject: crc-16 References: <40191E1D.D912C1BB@engcorp.com> Message-ID: <1xpihkbe.fsf@python.net> Peter Hansen writes: > eugene wrote: >> >> I looked for a crc-16(crc 16) function to use but couln't find one >> that worked: >> >> This one is working .. >> >> def crc16(s): > [snip] > > > Since eugene started the thread, I'll continue it by posting one that we've > been using. [code snipped] Since you didn't post the unit tests, the code seems incomplete. >From a TDD kind of view, at least. I'm disappointed of you . Thomas From godoy at ieee.org Thu Jan 15 08:21:14 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 15 Jan 2004 11:21:14 -0200 Subject: wxwindows question References: Message-ID: On Tuesday 13 January 2004 11:31 Jason Tesser wrote in : > I am looking into using wxwindows for a gui to develop applications. > The > Apps need to be cross-platform Mac, Windows, Linux. I work > For a bible college and will be developing applications ranging from > online > Registration to business office software. My question is what is > your guys > Experiences with wxwindows/python? What is the best tool that is > stable > I can use? I am looking into using wxDesigner with maybe Wing or > Komodo. > What do you guys think? I'm used to use wxGlade to create GUIs, but you can do it with other tools as well. A friend of mine likes more BOA Constructor. But my development platform is Linux... With regards to wxPython, I'm all for it. This a very good GUI and the fact of it having native look on the OSs you cited above is a plus: users won't be surprised with a new look in your application and everything will be where they are used to get it. You can take a look at GNUMed for a nice design using wxPython. See you, -- Godoy. From aa at bb.cc Tue Jan 27 10:31:24 2004 From: aa at bb.cc (Ladvánszky Károly) Date: Tue, 27 Jan 2004 15:31:24 GMT Subject: Problem with RE matching backslash References: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> Message-ID: <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> Thanks for your quick and very helpful reply, Peter. What is still not clear to me is why the search examples work and yield 'm'. K?roly From jacek.generowicz at cern.ch Tue Jan 13 06:15:28 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2004 12:15:28 +0100 Subject: Python Optimization References: <84fc4588.0401130249.e6ad2bf@posting.google.com> Message-ID: pythonguy at Hotpop.com (Anand Pillai) writes: > Interesting article in Kansas State University website > on Python internals. Thought I should post it here. > > http://www.cis.ksu.edu/VirtualHelp/Info/develop/cmu-user.info.Source_Optimization.html Methinks you are confusing Python (the language created by Guido van Rossum) with Python (the compiler of the CMUCL implementation of Common Lisp). Let's play spot-the-python: [xxx jacek] cmucl CMU Common Lisp 18e-small, running on xxx With core: /afs/cern.ch/sw/lisp/i386_linux24/cmucl-18e-small/lib/cmucl/lib/lisp.core Dumped on: Mon, 2003-12-01 12:51:47+01:00 on vmetrt1 See for support information. Loaded subsystems: Python 1.1, target Intel x86 CLOS 18e (based on PCL September 16 92 PCL (f)) * From ramen at lackingtalent.com Thu Jan 22 02:24:49 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 22 Jan 2004 07:24:49 -0000 Subject: Does anyone else not find the fun in programming...? References: <4004f5ac$0$69931$edfadb0f@dread12.news.tele.dk> <400a7a92$0$205$edfadb0f@dread12.news.tele.dk> <400bcb2b$0$180$edfadb0f@dread12.news.tele.dk> Message-ID: In article <400bcb2b$0$180$edfadb0f at dread12.news.tele.dk>, Max M wrote: > Dave Benjamin wrote: > >> So, a data-flow style more or less... that seems to be a useful model for >> music software. Have you ever played around with Max? > > No. I tried c-sound, and while it was interesting, it was really > cumbersome at the level I am interested in. Yeah, CSound is theoretically amazing but practically useless for me. ;) But I've had a few friends swear by it. I played around with Max a little bit in an electronic studio class, and found it very interesting. It's the only thing I've ever seen that was worthy of the name "graphical programming languaeg". A language you could program in entirely with a mouse, and it was actually useful. My teacher used it to do MIDI routing and later to create an algorithmic music installation in a musem. For the sake of keeping this on-topic, and because it actually sounds like a neat idea, I think it'd be cool to develop something like Max (or jMax - is that project still alive?) for Python. What's the best way of interfacing Python with real-time MIDI? >> Yeah, makes perfect sense to me. Do you have any Python-generated songs >> available? Sounds really cool. > > Nothing I will release. Mostly pre-studies. Hehe... >> The thing I was working on was a probabilistic beat generator, based on >> statistics of when a certain drum would hit in a beat for a selection of hip >> hop songs. I was trying to capture the "feel" rather than the exact sequence >> of sounds. > > That is a good way to go. Bayes networks for rythmical patterns. Interesting idea. -- .:[ dave benjamin (rameny sp00) -:- spoomusic.com -:- ramenfest.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From nathan at visi.com Tue Jan 13 20:20:26 2004 From: nathan at visi.com (Nathan Mates) Date: 14 Jan 2004 01:20:26 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: <4004995a$0$539$a1866201@newsreader.visi.com> In article , Brandon J. Van Every wrote: >I'm also starting to downright despise Linuxers. If I see another >project that's "cross-platform, so long as your platform is Linux," >I'm going to cut someone's head off. While I agree with that statement in the abstract (and can remember when it was SunOS being the platform of choice), I would like to point out that FreeBSD has reached over 10,000 ports. (See the counter at http://www.freshports.org/categories.php ) For those that don't run FreeBSD (or *BSD in general), a port is a piece of software designed to be built completely from source on a local machine. Packages are pre-built binaries. So, it the fine FreeBSD folks can manage to make "Linux-only" apps build fine from source, maybe you can too. The rest of your pissy "I can't CVS commit back" comments, well, start your own darn project on http://sourceforge.net/ . Once it's available for others, it's got a chance of being used widely. But, I suspect your motive was to be a freeloader and not contribute back. Nathan Mates -- <*> Nathan Mates - personal webpage http://www.visi.com/~nathan/ # Programmer at Pandemic Studios -- http://www.pandemicstudios.com/ # NOT speaking for Pandemic Studios. "Care not what the neighbors # think. What are the facts, and to how many decimal places?" -R.A. Heinlein From mwh at python.net Wed Jan 14 06:30:26 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 14 Jan 2004 11:30:26 GMT Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> <400413E0.5C691A56@engcorp.com> <4004452C.47DB4C4@engcorp.com> Message-ID: Peter Hansen writes: > Michael Hudson wrote: > > > > Peter Hansen writes: > > > > > Tim Rowe wrote: > > > > > > > > Well, the documentation for "input()" says "Equivalent to > > > > eval(raw_input(/prompt/))". Perhaps it should say "/Usually/ > > > > equivalent...." > > > > > > I remember reading that too, and just assumed that at this point > > > it was in fact *implemented* that way, as a simple alias. Maybe > > > it should be... > > > > http://www.python.org/sf/876178 > > > > Ideas on how to write a testcase welcome. > > Are there any test cases which verify behaviour both in the presence > and absence of certain "from __future__ import" statements? Yes. > My first thought would have been simply to write two test files, > one of which imports from __future__ and the other which does not, > and check that in both cases input(x) == eval(raw_input(x)). > > Or is the issue how to test when the input comes from stdin? In > that case, doesn't faking sys.stdin work as usual? Oh, probably... Cheers, mwh -- I'll write on my monitor fifty times 'I must not post self-indulgent wibble nobody is interested in to ucam.chat just because I'm bored and I can't find the bug I'm supposed to fix'. -- Steve Kitson, ucam.chat From rick_muller at yahoo.com Tue Jan 13 11:44:41 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 13 Jan 2004 08:44:41 -0800 Subject: Python bindings for the Gnu Multiprecision library Message-ID: <5eb8fb88.0401130844.6054b2d7@posting.google.com> I just discovered the python bindings for the Gnu Multiprecision library available at http://gmpy.sf.net. The release notes say that it only works for Python 2.3, but I successfully got it to work on Python 2.2. Way, way cool. For example, the following is an implementation of the Lucas-Lehmer test for Mersenne primes: def lucas(p): "Test whether 2^p-1 is a Mersenne prime" s = 4 val = pow(2,p)-1 for i in range(3,p+1): s = (s*s-2)%val return not s Using normal python long integers, this routine is an interesting toy, but not much else. However, with the gmpy libraries, you can grind away until your Powerbook G4 burns your lap: def lucas_gmp(p): "Test whether 2^p-1 is a Mersenne prime" from gmpy import mpz s = mpz('4') val = pow(2,p)-1 for i in range(3,p+1): s = (s*s-2)%val return not s Way to go, Alex and Gustavo (and anyone else involved)! From claird at lairds.com Sun Jan 18 16:34:41 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 18 Jan 2004 21:34:41 -0000 Subject: Fw: PDF library for reading PDF files References: Message-ID: <100luvhbh3vr75d@corp.supernews.com> In article , Harald Massa wrote: >> I am looking for a library in Python that would read PDF files and I >> could extract information from the PDF with it. I have searched with >> google, but only found libraries that can be used to write PDF files. > >reportlab has a lib called pagecatcher; it is fully supported with python, >it is not free. > >Harald ReportLab's libraries are great things--but they do not "extract information from the PDF" in the sense I believe the original questioner intended. As Andreas suggested, he's probably best off using existing stand-alone applications as separate processes, controlled from Python. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Mon Jan 12 09:26:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Jan 2004 09:26:35 -0500 Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> <3fffbe99.486050433@news.blueyonder.co.uk> Message-ID: <4002AE9B.C51448FB@engcorp.com> Alan Gauld wrote: > > On Fri, 9 Jan 2004 10:29:46 GMT, Harry George > wrote: > > > I'm not sure about others, but when I design and code using test-driven > > > development (TDD), I tend not to need to debug almost ever. > > > told him almost exactly what you said: If you are doing test-based > > (whether or not it is with someojne else and thus Agile), you don't > > get into those grim debug sessions that are part of life in C/C++ > > land. > > Interesting comments. How do people generally perform these tests > then? My primary test tool, for low level testing, is usually the > debugger. Batch mode debugging is something I've been doing since > I worked on VAX/VMS systems and its seems as natural as breathing > to me. Its easy to save a test session and run it later etc. How > else do you test code at a low level? > > Or does using the debugger as a test harness not count as > debugging? The debugger-as-test-harness does not count as testing, anyway, at least not in the Agile sense. The tests *must* be automated, and run very frequently (constantly) or you can't be very agile. As others have said, the unittest is the key (in Python) or at least the de facto standard. I would not agree that using it is "tedious" at all, however, as it takes me only about twenty seconds to start a new test file and that's *without* using a template. Running the tests is also not tedious, at least not if you invest a few hours in a simple utility that automates even the run-all-tests functionality. I just type "unit -a" and all tests in all subfolders are immediately run, without output going to a log file for later analysis in case there are failures. -Peter From luszczek1 at yahoo.com Sat Jan 10 12:25:49 2004 From: luszczek1 at yahoo.com (Piotr Luszczek) Date: Sat, 10 Jan 2004 09:25:49 -0800 (PST) Subject: Bruce Eckel example / CGI server for localhost for Windows XP possible? In-Reply-To: Message-ID: <20040110172549.5263.qmail@web60902.mail.yahoo.com> --- Will Stuyvesant wrote: > Is there anybody who can provide simple example code > like found in > Fredrik Lundh's Python Standard Library book for > setting up a CGI > server for localhost with Python? Perhaps the > examples that are > available work on linux, but not on my Windows XP > laptop with Python > 2.3.3: GET works and the first POST works too, > subsequent POSTs crash. This is simple: http://www.geocities.com/luszczek1/httpd_py.html and seems to work with multiple POSTs. But it doesn't seem to be able to handle file upload correctly. At least as this script is concerned: def main(): form = cgi.FieldStorage() fc = form.getvalue("fc", "") print "Content-type: text/html\r\n\r\n", print "" if fc: print "File", repr(fc), str(dir(fc)) fc = form["fc"] print "
"
        print fc.file.value
        print "
" __________________________________ Do you Yahoo!? Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes http://hotjobs.sweepstakes.yahoo.com/signingbonus From michele.simionato at poste.it Mon Jan 12 10:41:19 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 12 Jan 2004 07:41:19 -0800 Subject: slots , setattr, metaclass References: Message-ID: <95aa1afa.0401120741.6a7ae7c9@posting.google.com> "Roman Yakovenko" wrote in message news:... > Hi. I have small problem and I don't know solution. > The problem: every class imported from some module X should not allow to > be modified > ( modified == adding or deleting new class attributes ). I think you may be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 (uses setattr, metaclasses, no slots). Michele From giles_brown at hotmail.com Mon Jan 26 15:45:00 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 26 Jan 2004 12:45:00 -0800 Subject: python service running on Win Xp, but failing on Win NT Workstation :( References: Message-ID: <57de9986.0401261245.461e481@posting.google.com> "Ringwraith" wrote in message news:... > "The Purge Log Files Service service failed to start due to the following > error: > The service did not respond to the start or control request in a timely > fashion. > > Timeout (120000 milliseconds) waiting for service to connect. " > > > > Any ideas what could caused the problem? No idea what caused the problem. I would suggest you "import win32traceutil", stick some print statements in early on in your code and start the "Trace Collector Debugging tool" from the Tools menu of PythonWin. Hth, Giles From crap at crud.com Sat Jan 10 04:30:48 2004 From: crap at crud.com (Moosebumps) Date: Sat, 10 Jan 2004 09:30:48 GMT Subject: Setting up test for XML-RPC Message-ID: I'm trying to test out Python XML-RPC for the first time, and can't find anything that executes a call end to end. I thought that I would use SimpleXMLRPCServer to run a simple server on localhost, and xmlrpclib to run a client that connects to it, but they don't seem to register the same functions. The server test code registers 'pow' and 'add' (in the Python 2.3 distribution) but the client seems to call "print server.examples.getStateName(41)". It doesn't seem like they were meant to work together as a unit test, although that would seem logical. Can anyone help me just get a single XML-RPC call to execute (and I want to see both the client and server code)? I have googled extensively and haven't come up with anything. Also -- I'm investigating this for a nightly build process involving many machines. There is going to be a master machine that sends requests to 20 other machines to build things. They're just a bunch of Windows XP machines, with almost no software on them. What software would I need to install to run XML-RPC servers on them to receive requests? Just Python and a web server like Apache? If there are any other _very_ lightweight RPC mechanisms, I would appreciate hearing about them. I am writing some build scripts in Python, and while I could for example schedule a task on 20 machines separately, it would be nicer to have a master machine control when the build happened, etc. and be able to manage dependencies by waiting for a return result, etc. All I want to do is execute a python function on a remote machine and get a result back. It is all done in a local, secure environment. Thanks for all the previous responses to my questions -- this newsgroup has been very helpful. MB From slukas5 at poczta.onet.pl Thu Jan 15 06:46:07 2004 From: slukas5 at poczta.onet.pl (slukas) Date: Thu, 15 Jan 2004 12:46:07 +0100 Subject: MySQLdb Message-ID: Hello Sorry for my English. I want add the new record to Mysql database. When I use my script I got an exception "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 12: ordinal not in range(128). When I add line sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout) to my script i see the var on the screen but I can't add var to database. Any idea? Thanks! Lukas From ykingma at accessforall.nl Mon Jan 5 16:24:25 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 05 Jan 2004 22:24:25 +0100 Subject: Scoped Lock References: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl> Message-ID: <3ff9d591$0$15165$e4fe514c@dreader14.news.xs4all.nl> Marco Bubke wrote: > Ype Kingma wrote: > >> Marco Bubke wrote: >> >>> Hi >>> >>> There is the Lock object in the threading module. >>> But there is no medode there I could aquire a scoped >>> lock like: >>> >>> mutex = threading.Lock() >>> my_lock = mutex.scoped_acquire() # maybe scoped_lock() >>> #now this stuff is locked >>> >>> del mylock >>> >>> #the lock is released. >>> >>> def do_domething: >>> my_lock = mutex.scoped_acquire() >>> #now this stuff is locked >>> #the lock is released after its out of scope >>> >>> >>> I have written this my own but I'm not sure there is a drawback >>> because its looks so convinent. So I wonder why its not in >>> the module? >> >> Some reasons: >> - What should happen when an exception happens during the locked stuff? >> - It is possible pass a reference to the lock during the locked stuff, >> so although the lock goes out of local scope, there still might be >> a reference to it. >> - The moment that __del__() is called is not guaranteed. >> >> You can also do it like this: >> >> mutex = threading.Lock() >> mutex.acquire() >> try: >> # now this stuff is locked >> finally: >> mutex.release() # explicit is better than implicit > > This does not look nice to me. There should be something me easily. An elegant and easier way has been designed, see PEP 310, mentioned in another post in this thread: http://www.python.org/peps/pep-0310.html However, one normally does not use locks so often that the lightly verbose idiom needed to use them becomes a problem. Regards, Ype From no.spam Sun Jan 4 16:10:12 2004 From: no.spam (Christophe Delord) Date: Sun, 4 Jan 2004 22:10:12 +0100 Subject: Progress indicator during FTP upload References: Message-ID: <20040104221012.0cc111a3.no.spam@box> On Sun, 04 Jan 2004 19:31:34 +0100, Frantisek Fuka wrote: > My application uses ftplib to upload files to remote server. What is > the cleanest way to provide progress indicator for long files? What > exactly should I override in the ftplib (I am not very proficient in > the FTP protocol)? > Hello, To update my web site I wrote a script in wich I have overriden ftplib.FTP to print a dot when a block of bytes is sent. Here is my dot_FTP class : class dot_FTP(ftplib.FTP): def storbinary(self, cmd, fp, blocksize=8192): ''' Store a file in binary mode.''' self.voidcmd('TYPE I') conn = self.transfercmd(cmd) while 1: buf = fp.read(blocksize) if not buf: break conn.send(buf) sys.stdout.write('.') sys.stdout.flush() conn.close() return self.voidresp() I just took the code of storbinary in ftplib.py and added the wanted output. Christophe. From eelgueta at navix.cl Tue Jan 27 17:30:05 2004 From: eelgueta at navix.cl (Eduardo Elgueta) Date: 27 Jan 2004 14:30:05 -0800 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <3b3f63ed.0401271430.27d9202c@posting.google.com> Michael and the rest, Your analogy is very good. I think of C++ as an enigmatic and temperamental cat, and I think of Python as last generation language. I mean, it's ok if in C/C++ you can't get an instance name (another reason not to use it). But why not in Python? (I use it a lot) An object can have many references to it? Ok, give me the name of the instance I'm using to refer to it: x.__instance_name__ --> "x" foo.__instance_name__ --> "foo" Or the first it finds, if it's not obvious: self.__instance_name__ --> whatever it finds first (I'll be carful not to referentiate the instance twice, I promise) I've never ran into a software design/engineering book saying "storing an instance name is forbidden under penalty of death." I don't want to flame anyone. It's just I'm so lazy I wanted to save myself a parameter in my html generation class, using the instance name as the html object name: python: pass = Input(...) : pass.render(page_buffer) html: : : Oh well! Regards, Ed. Michael Hudson wrote in message news:... > engsolnom at ipns.com writes: > > > What I'd like to do is display is the instance name. Is it hiding > > somewhere? > > From http://www.amk.ca/quotations/python-quotes/page-8.html: > > The same way as you get the name of that cat you found on your > porch: the cat (object) itself cannot tell you its name, and it > doesn't really care -- so the only way to find out what it's > called is to ask all your neighbours (namespaces) if it's their > cat (object)... > > ....and don't be surprised if you'll find that it's known by many > names, or no name at all! > > -- Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I > get the name of a variable from C++ when I have the PyObject*?" > > One of my favourite Python quotes... > > Cheers, > mwh From aahz at pythoncraft.com Mon Jan 5 15:40:32 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Jan 2004 15:40:32 -0500 Subject: prePEP "Decimal data type" v0.2 References: Message-ID: In article , Batista, Facundo wrote: > >http://www.taniquetil.com.ar/facundo/python/prePEP-Decimal-0.2.html Overall, looks good. I think the biggest point of disagreement still is the behavior of Decimal interacting with floats. I hope more people will comment once you get a PEP number. One major correction: "Rationale" means "reason"; "rational" refers to fractions. Several times you use "rationale" when you mean "rational". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From james at eccehomo.co.uk Wed Jan 14 16:41:26 2004 From: james at eccehomo.co.uk (James Goldwater) Date: Wed, 14 Jan 2004 21:41:26 +0000 Subject: wxPython worries In-Reply-To: <9d1c4d6d.0401141221.22c587f5@posting.google.com> References: <9d1c4d6d.0401141221.22c587f5@posting.google.com> Message-ID: <4005B786.6000805@eccehomo.co.uk> It's not the RADdish-ness (is that a word?) - drag'n'drop, property assignment etc - that concerns me, it's the ease of gui building - by hand is fine (oh how I've come to 'love' Java's layout managers...) Custom controls is the biggie then. I think I'll have a punt at building a custom control in wxPython to see if it's even feasible. Anybody want an arbitrary-angled triangular-wedge button? (My first custom control in Delphi version 1, all those years back...) PT wrote: >>What worries me is wxPython: >>I'm also >>unclear as to how easy custom controls are to build. > > > None of the Python GUI toolkits support making good custom controls as > well as Java and .NET do. TKinter is probably the best Python option > for that. If you are comfortable with Windows programming though, > wxPython will not be too difficult. > > >>Am I just being confused by my newbie-ness, or are my initial concerns >>justified? What's anybody else's experiences with gui programming in >>wxPython like vs a RAD like Delphi or .NET? > > > If you want something similar to Delphi or .NET, then you would > probably like QT Designer much better than the wx options. See > BlackAdder (Win, $$) or eric3 (Linux, free): > http://www.thekompany.com/products/blackadder/ > http://www.die-offenbachs.de/detlev/eric3.html > > If money isn't an issue though, just stick with Visual Studio and C# > and let the other guy do most of the work. -- James Goldwater I.T. Consultant 020 8949 7927 (mobile 078 999 55 265) GPG Key: A2137B98 (pgp.mit.edu) From robin at jessikat.fsnet.co.uk Fri Jan 9 09:30:47 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 9 Jan 2004 14:30:47 +0000 Subject: Twisted or Medusa or Zope References: <425cc8d1.0401070808.14690325@posting.google.com> <3FFD7159.55630AE0@engcorp.com> <6AlLb.134$hd.7718@news2.e.nsc.no> <3FFEB6D6.BF92551E@engcorp.com> Message-ID: <+vXesJAXsr$$EwJL@jessikat.fsnet.co.uk> In article <3FFEB6D6.BF92551E at engcorp.com>, Peter Hansen writes .. ... >enlighten me. > >Thomas, you're completely ON track here... I just wanted to emphasize that >Twisted is much more polished and sophisticated. I'd even have to say, >as a programmer using them, that Twisted does actually provide a simpler and >cleaner API. It and Medusa are much closer in concept than either is to >Zope, though, as you say. > >-Peter In another thread http://snakelets.sf.org was mentioned. -- Robin Becker From Yomanium at Yomanium.com Thu Jan 15 09:08:42 2004 From: Yomanium at Yomanium.com (Yomanium Yoth Taripoät II) Date: Thu, 15 Jan 2004 15:08:42 +0100 Subject: TUPLE & LIST Message-ID: <%7xNb.55$Uw3.50@newsr2.u-net.net> HI, 1) what are the differences between list and tuple? 2) how to concatenate tuple and list? no method, no op?rator? 3) im looking the fucking manual, and cant add value in my tuple, when it already created :/ how to do it? thx. From adonisv at REMOVETHISearthlink.net Sun Jan 4 16:25:11 2004 From: adonisv at REMOVETHISearthlink.net (Adonis) Date: Sun, 04 Jan 2004 21:25:11 GMT Subject: Tkinter.Menu() Question References: <4a_Jb.8099$6B.48@newsread1.news.atl.earthlink.net> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:bt9v6d$s3n$07$1 at news.t-online.com... > Adonis wrote: > > > I wish to create a popup menu from a list, when it is created they all > > show the same label from the list: > > > > Months = [0, 'January', 'February', 'March', 'April', 'May', 'June', > > 'July', 'August', 'September', 'October', 'November', > > 'December'] > > > > def _Menu_Click(self, month): > > print month > > > > menu = Menu(fraMain, tearoff=0) > > > > for Month in Months[1:]: > > menu.add_command(label=Month, command=lambda : _Menu_Click(Month)) > > > > When the menu calls _Menu_Click(...) it always prints 'December' > > > > Now my understanding is the when an object is created and it is > > replicated, whichever of the modified replications affects all of the > > objects, being that they are just mere references to the original (my > > wording might be off, correct me if I am wrong). How do I avoid this for > > what I am trying to achieve? > > (I made some bogus changes so I could ensure it works) > > from Tkinter import * > > Months = [0, 'January', 'February', 'March', 'April', 'May', 'June', > 'July', 'August', 'September', 'October', 'November', > 'December'] > > root = Tk() > > class DontCare: > def _Menu_Click(self, month): > print month > dc = DontCare() > > mb = Menubutton(root, text="so what") > mb.pack() > menu = mb["menu"] = Menu(mb, tearoff=0) > > > for Month in Months[1:]: > menu.add_command(label=Month, command=lambda m=Month: dc._Menu_Click(m)) > > root.mainloop() > > Note how the instance (dc) is provided with the method (_Menu_Click) in the > lambda (in your real code you will most likely have to replace dc with > self). The real trick is to provide the loop variable Month as the default > value for m in the lambda. m will be bound to the same string as Month when > the lambda is *created*. If you don't do this, the value of the variable > Month will be looked up when the lambda is *called*, which will be always > "December" after the for loop is terminated. > > Peter Thanks a million, works like a charm. Adonis From aaron at reportlab.com Mon Jan 5 13:26:20 2004 From: aaron at reportlab.com (Aaron Watters) Date: 5 Jan 2004 10:26:20 -0800 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: <9a6d7d9d.0401051026.775d9ef3@posting.google.com> lipp at epost.de (Wolfgang Lipp) wrote in message news:... > hi, > > ....when i create > a database, populate it, commit, and then re-open it, i get a nasty > xsdb.xsdbExceptions.RollBackError.... Thank you very much for finding this problem! Double apologies: Sorry that I made this bug and sorry that I didn't respond to your message earlier. I decided take a different approach than the one you suggested that fixes the problem systematically (and required a lot of changes and testing). Basically I hadn't considered the possibility that a program might open two direct connections to a database within the same minute (because my machine is so slow :( ). If you do make very fast connections I added the ability to clear out all the timestamp information using a special keyword argument to the connection initializer. Here is the test case (fastconnect.py): === "test connecting and then reconnecting to a database quickly" def test(filename="data/fastconnect.dat"): import time now = time.time() from xsdb.KISSBaseHierarchy import xsdb print "testing fast reconnection" connection = xsdb(filename, startup=1) t = connection.transaction() t.add("object1", "this is the object") t.commit() t = connection.transaction() t.add("object2", "this is the other object") t.commit() connection = None # must clear the connection for fast reconnect! connection = xsdb(filename, startup=0, clear=1) print "fast reconnect completed in ", time.time()-now if __name__=="__main__": test() === If you omit the "clear=1" above you get the exception you reported. I just uploaded a new file release which includes this and a number of other bugfixes, enhancements, doc changes, etcetera. Get it at: http://xsdb.sourceforge.net -- Aaron Watters === You can't talk to a man When he don't wanna understand -- Carole King From mcfletch at rogers.com Sun Jan 4 16:30:50 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 04 Jan 2004 16:30:50 -0500 Subject: Launching pdb from within a script In-Reply-To: References: Message-ID: <3FF8860A.4070509@rogers.com> Peter Otten wrote: >Graham Nicholls wrote: > > ... >>But pdb complains that there are no such variables. It may be that I had >>to add some incantation around the script startup - I just can't remember >>(and its frustrating!). >> >> ... >-> Pdb().set_trace() >(Pdb) abc >*** NameError: name 'abc' is not defined >(Pdb) u > > This is the key line, 'n' would work as well. The reason your variables weren't being found is that you were still inside the call to set_trace(). You need to return from that (either by going "u"p to the calling context, or to the "n"ext instruction, which returns to the calling context by finishing the set_trace() call). Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mcherm at mcherm.com Fri Jan 30 10:06:21 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 30 Jan 2004 07:06:21 -0800 Subject: [Python-Dev] PEP 327: Decimal Data Type Message-ID: <1075475181.401a72ed15fc5@mcherm.com> Facundo Batista writes: > I'm proud to announce that the PEP for Decimal Data Type is now published > http://www.python.org/peps/pep-0327.html VERY nice work here. Here's my 2 cents: (1) You propose conversion from floats via: Decimal(1.1, 2) == Decimal('1.1') Decimal(1.1, 16) == Decimal('1.1000000000000001') Decimal(1.1) == Decimal('110000000000000008881784197001252...e-51') I think that we'd do even better to ommit the second use. People who really want to convert floats exactly can easily write "Decimal(1.1, 60)". But hardly anyone wants to convert floats exactly, while lots of newbies would forget to include the second parameter. I'd say just make Decimal(someFloat) raise a TypeError with a helpful message about how you need that second parameter when using floats. (2) For adding a Decimal and a float, you write: I propose to allow the interaction with float, making an exact conversion and raising ValueError if exceeds the precision in the current context (this is maybe too tricky, because for example with a precision of 9, Decimal(35) + 1.2 is OK but Decimal(35) + 1.1 raises an error). I suppose that would be all right, but I think I'm with Aahz on this one... require explicit conversion. It prevents newbie errors, and non-newbies can provide the functionality extremely easily. Also, we can always change our minds to allow addition with floats if we initially release with that raising an exception. But if we ever release a version of Python where Decimal and float can be added, we'll be stuck supporting it forever. Really, that's all I came up with. This is great, and I'm looking forward to using it. I would, though, be interested in a couple more syntax-related details: (a) What's the syntax for changing the context? I'd think we'd want a "pushDecimalContext()" and "popDecimalContext()" sort of approach, since most well-behaved routines will want to restore their caller's context. (b) How about querying to determine a thread's current context? I don't have any use cases, but it would seem peculiar not to provide it. (c) Given a Decimal object, is there a straightforward way to determine its coefficient and exponent? Methods named .precision() and .exponent() might do the trick. -- Michael Chermside From bkelley at wi.mit.edu Thu Jan 15 10:45:52 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 15 Jan 2004 10:45:52 -0500 Subject: Why gmp is not in the standard library? In-Reply-To: References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Message-ID: <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> Michael Hudson wrote: > miki.tebeka at zoran.com (Miki Tebeka) writes: > > >>Hello All, >> >>On a different thread Skip wrote: >> >>>Yes, you're right. Starting at 2**1000 I found three safe primes quite >>>quickly. Using my version I gave up waiting after seeing one safe prime >>>float by. >> >>Which made me think why Python don't use gmp as it's primary math >>package - we'll get fast results, a lot of number types and much more. >> >>Can't think of any reason why Python is implementing its own long >>numbers... This discussion partly happened a couple of years ago when mxNumber was released from egenix. Here is a google link: http://mail.python.org/pipermail/python-list/2001-April/040453.html >>Can you enlighten me? > > > Licensing? IIRC, GMP is GPL. So is bsddb and that is included with python. Anyway, gmp is LGPL'd not GPL'd. > Also, possibly, portability. GMP is incredibly portable, it does have one large flaw for use with python: Q: I get a Segfault/Bus error in a program that uses GMP to calculate numbers with several hundred thousand digits. Why? A: GMP allocates most temporaries on the stack, and some machines give user programs very little stack space by default. See setrlimit(2) for information on how to increase the stack allocation. You can also change it from the shell (using ulimit or limit depending on the shell). You can also configure with --disable-alloca to instead allocate temporaries using malloc, but that will make the library run somewhat slower. Brian From here at there.org Sun Jan 4 06:32:11 2004 From: here at there.org (The_Incubator) Date: Sun, 04 Jan 2004 03:32:11 -0800 Subject: Scripting C++ Game AI object using Python Generators Message-ID: As the subject suggests, I am interested in using Python as a scripting language for a game that is primarily implemented in C++, and I am also interested in using generators in those scripts... Initially I was justing looking at using Python for some event scripting. So basically an event would trigger an object to run the appropriate Python script, which would be run in it's entirety and return control to the C++ code. After looking at the Python docs and a few articles I've found, I'm really excited by the idea of using Python generators as micro-threads for game AI. I've been playing around writing play Python applications with classes that use generators as update methods, and it's cool as hell. I've also managed to write a C++ program with an embedded Python interpreter than runs a script, and I've used the Boost Python library to expose some C++ functions to Python. Where I would like to go from there is to be able to associate a Python script with a C++ object, so that on every frame update I could run the Python script (which would have functionality implemented as a generator) until it yields, then move on to updating the next object, and on the next frame, have the generator continue from where it left off. I haven't really attempted this yet, because I'm not quite sure where to start. I'm not sure how to have a Python script persistently attached to a C++ object so that execution can be returned to C++ from a yield and continue where it left off on the following update cycle. I am beginning to suspect, based on the docs and articles I've read, that to get this sort of functionality I should be looking at exporting all my C++ objects to Python, and then using Python as the glue to write the main loop of the application, calling out to the C++ objects as required. Is this assumption correct, or can I get the functionality I want while still keeping this a C++ application? Should I be looking at writing the AI modules as Python objects and attaching these to my C++ objects at runtime? Initially I was just looking for something to use for simple scripting, and we were planning to do a custom scripting language, but I know just enough about language design and implementation to be very weary of having to maintain our own language when there are proven embeddable languages out there than are more powerful (and if I wanted to stick with simple I'd use Lua, which was just a breeze to embed). But the more I look at Python, the more ambitious I'm getting about how much we could potentially do by using Python at least as a scripting language and possible as glue... however, I'm not necessarily sure we need all this functionality (generators included), but that doesn't mean I don't want it, and I do like the idea of having more power and flexibility than is strictly necessary, so that we will have the power to do things we didn't necessarily plan for or expect. We are using Gamebryo as our rendering library, so that is a major constraint. That is very much a C++ library, so this is very much a C++ application. I am also a bit concerned about scaring other developers on my team... We need a scripting language, and everyone can deal with that as long as we pretend that the scripting language is a separate thing for designers, but I'm afraid if I start suggesting the programmers write our main application in Python and export the C++ code, I'm in danger of becoming a heretic ;) I'm not even sure if that's practical, given our C++ middleware and performance concerns, but that's why I'm posting here, to get some assistance from the experts. Thanks in advance for any advice Nick From jjl at pobox.com Fri Jan 16 10:53:43 2004 From: jjl at pobox.com (John J. Lee) Date: 16 Jan 2004 15:53:43 +0000 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> <8765ferltj.fsf@pobox.com> Message-ID: <87zncnzy7s.fsf@pobox.com> "Andrew Koenig" writes: > > The argument runs like this: If you don't have near-100% test > > coverage, you are missing many bugs that static typechecking will not > > catch. So don't do that (the fact that it's perfectly feasible to > > have near-100% coverage, when given support from bosses where > > relevant, has been repeatedly demonstrated recently). OTOH, if you do > > have 100% coverage, the set of bugs that *are* caught by the static > > typechecks, but *not* by the tests is usually very small, in practice. > > There is a subtle fallacy in this argument, at least in the context of C++ > and Python, namely that there is a significant category of errors that > static type checking (as C++ and some other languages do it) can detect but > can escape even 100% test coverage. It may be subtle, but it's also the starting point for most of these debates. > Before you get out your flame-thrower, please hear me out -- I am not saying OK... :-) > that this reasoning applies to all errors, or even a majority of them, but > only to a significant category. That category consists of programs where > the types of key objects are not known when the program is written, but are > known when the program is compiled. Agreed. [...snip example...] > In practice, C++ programmers often solve such problems by using templates, > which defer type checking until the last possible moment during the > compilation process. In effect, the compiler looks at each call to our > hypothetical sort function, and verifies that the type assumptions that the > sort function makes are valid in the context of that particular call. The > result is that the compiler can detect type errors that would show up in a > dynamically typed environment only if the function were tested with the > specific types that revealed the error. Yes. > The price one pays for this extra checking, of course, is that one cannot > call such a sort function with an argument with a type that is known only at > run time. But in practice, there are many cases where being able to defer > type checking until the end of compilation is just as useful as being able > to defer it until run time. I believe that many people who dislike static > type checking are unaware of this distinction. I do like static type checking. I *don't* like the price that C++ makes me pay for it in terms of lines of code and inflexibility. When comparing Python and C++, the longer, more inflexible programs required to solve problems in C++ introduce more bugs than its static typechecking system removes. It's a shame some tiny fraction of the trillion dollars recently allocated to George Bush's electoral campaign <0.2 wink> can't be diverted to experiments to test this hypothesis (but I guess those dollars are mostly fictional anyway ;-). So, I think the various interface proposals that have been made for Python are interesting. Also, it seems attractive to have static type inference wedged into Python somehow (not holding my breath: I don't even know if that idea really makes any sense in the context of Python). But I see Python in its current state as a safer language than C++. Alex Martelli goes much further than I do: http://www.google.com/groups?selm=ft6tb.21351%249_.767461%40news1.tin.it&rnum=1 [...] > I see static typing > as a theoretically-interesting field of no real applicability to my > work. If I felt otherwise about it, I would most likely be coding > in Haskell or some kind of ML, of course -- nobody's come and FORCED > me to choose a dynamically-typed language, you know? And perhaps he's right: my attraction to static type inference in a Python-like language is both theoretical and almost maximally vague (and my grasp of the issues is weaker than Alex's), and I don't have any decent ML or Haskell experience with to compare with my Python experience... See also the couple of posts near this article in the exchange between Alex and David Abrahams (same one I posted in a followup to Cameron earlier): http://www.google.com/groups?selm=pNfIa.206219%24g92.4232233%40news2.tin.it&rnum=2 John From JimJJewett at yahoo.com Tue Jan 20 14:10:54 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 20 Jan 2004 11:10:54 -0800 Subject: __init__(self, *args, **kwargs) - why not always? References: Message-ID: I'm still not sure I understand the objection, as I would still have wanted the extension even in your examples. So I've gone into a bit more detail, and generalized the replacement. Is there any reason not to replace replace: class SubClass(BaseClass): def __init__(self, [what you used to take]): BaseClass.__init__(self, [what you used to send]) with: class SubClass(BaseClass): def __init__(self, [what you used to take], *args, **kwargs): BaseClass.__init__(self, [what you used to send], *args, **kwargs) on a near-global basis? Gerrit Holl wrote in message news:... > A subclass may be a specialized case, e.g.: > class Tree: > def __init__(self, evergreen=False): > ... > class Spruce(Tree): > def __init__(self): > Tree.__init__(self, True) I do understand that you will sometimes need to modify the argument (or keywords) based on your subclass' needs. My question is about unexpected input -- which you might get if the base class is later enhanced. What is wrong with the following: class Spruce(Tree): "Spruce are evergreen." def __init__(self, *args, **kwargs) eg = kwargs.pop('evergreen', True) Tree.__init__(self, eg, *args, **kwargs) or class Spruce(Tree): "Spruce are always evergreen, you annoying user!" def __init__(self, *args, **kwargs) kwargs['evergreen'] = True Tree.__init__(self, *args, **kwargs) These will work even if tree is later enhanced to keep track of which trees need extra attention. class Tree: def __init__(self, evergreen=False, healthy=True): ... > or the other way around, e.g. > class Enemy: > def __init__(self, pos): > ... > class ShootingEnemy(Enemy): > def __init__(self, pos, bullets): > Enemy.__init__(pos) > ... > In both cases I don't want to BaseClass.__init(self, *args, **kwargs)... class ShootingEnemy(Enemy): def __init__(self, pos, bullets, *args, **kwargs): Enemy.__init__(self, pos, *args, **kwargs) indicates that the base class also needed to see position. This wouldn't take any special thought that wasn't already required by passing position in your original example. And again, it would remove some fragility in case the Enemy class is later extended to indicate which army it is from, or what type of unit. -- -jJ Take only memories. Leave not even footprints. From crescent_au at yahoo.com Thu Jan 29 21:57:26 2004 From: crescent_au at yahoo.com (Ben) Date: 29 Jan 2004 18:57:26 -0800 Subject: python in dreamweaver References: Message-ID: "Michel Claveau/Hamster" wrote in message news:... > Hi ! > > Yes ! > > I do. How to do???? From swalters_usenet at yahoo.com Mon Jan 5 12:34:03 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 17:34:03 GMT Subject: How to control a console based program from Python References: Message-ID: |Thus Spake Will Stuyvesant On the now historical date of Sat, 03 Jan 2004 02:24:32 -0800| > I never used the popen or popen2 libraries but it is my understanding > that they can capture the output of console based programs. Is it also > possible to send keystrokes to console base programs? > > I would like to program a Python program that can play for instance the > tty version of nethack 3.4.3 on Windows, simulating a human player: for > nethack it would not be possible to know if a human or a computer > program is playing it. It is a console based program, it accepts > keystrokes and outputs characters on the (Windows) console box. I did > see that WConio can read characters from the screen, perhaps I can use > that, have to experiment with it some more. But how to send keystrokes? > Any help and ideas are much appreciated. And a happy new year of > course! The fact that you're on a microsoft box makes the issue of console-based programs significantly more sticky than it would be on a *nix system. You may know this already, but in case you don't, here's a bit of technical info to get you oriented. Unix was, early on, designed around the idea of pipes. Pretty much every program reads from stdin and writes to stdout. Thus, there's a constant flow of data into the program and a constant flow out. On *nix systems, a terminal pushes your keystrokes to stdin, and interprets the results it gets from stdout. (This description is oversimplified, but it will do.) The results contain certain codes that, depending on the terminal, move the cursor around, change colors and such. A good resource on all this is: http://www.faqs.org/docs/artu/index.html Even if you're not that interested in unix stuff, it's a good read because Python inherits a lot of the unix philosophy. MS-DOS, and hence microsoft console programs, were based on an entirely different philosophy, that of CP/M. Whereas Unix was designed for big computers with many users running many programs at once, CP/M was designed for computers with one user running only one program. CP/M simply abstracted the low-level hardware calls through the use of interrupts. Interrupts are called interrupts because they do exactly that: they interrupt the entire computer, run some low-level code, then return control to the (one and only) program running. I don't think pipes were ever part of CP/M, but at some point they were grafted onto MS-DOS. (This was probably to make some grumpy unix wizards complain less vocally about having to write code for single user machines.) Almost nothing useful is done with pipes in MS-DOS. When you run a console program in Windows, it's a special program that pretends to be the old Dos system. Apropos Docs: http://www.wkonline.com/d/CPM.html http://www.wkonline.com/d/MS-DOS.html Chances are that the nethack you're running displays to the screen via these crufty old Dos interrupts. While it is possible to "steal" these interrupts (and snag their data) I don't know of any libraries that would let you do that, I wouldn't try it unless you've got some serious sorcery in you. To give you an idea of how complex it is, somewhere around here, I've got a manual on all those interrupts and I think it's about 6 inches thick and involves manipulating the processor registers directly. You can probably find some c code to do that, but umm... I dunno. I always just inlined assembly when I was working with MS-Dos. (;Please, god no ABEND NOW! MOV AH,4Ch MOV AL,01h INT 21h ;*weeps* Fifteen years later, and I still remember that. ) http://users.win.be/W0005997/GI/dosref.html If you *really* want to try making a robot that plays nethack, I suggest installing cygwin, which gives you a unix environment on top of your windows system, then compiling nethack for it and *then* you'll have access to proper pipes. Besides, you'll get to dabble a bit in *nix land. You might like it. http://www.cygwin.com/ Sam Walters p.s. You might try taking this to the python-tutor list. You will probably get more answers to questions like this. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From jjl at pobox.com Sat Jan 3 18:56:21 2004 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2004 23:56:21 +0000 Subject: Keyboard browsing (was Re: ANN: Python Language Reference) References: Message-ID: <87k748powq.fsf@pobox.com> Gabriel Genellina writes: > At 2/1/2004 19:19, you wrote: > > > > Opera can be completely keyboard-driven. And to search, you can type > > >/TEXT, just like you would in lynx or any other proper viewing or > > >editing tool. > > > >Really? That's not in my Opera/Linux 6.1. > > That really cool feature appeared in v7.20. But Ctrl-F = search in > page works from prehistoric ages :) Mozilla also has / for incremental search. And most have ALT- and ALT- for history navigation, and tab, space and return for other navigation (though I'm never sure if I should hit tab or return...). John From exarkun at intarweb.us Mon Jan 12 14:48:57 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 12 Jan 2004 14:48:57 -0500 Subject: Using switches with exec? In-Reply-To: <20040112170718.38245.qmail@web8310.mail.in.yahoo.com> References: <20040112170718.38245.qmail@web8310.mail.in.yahoo.com> Message-ID: <20040112194857.GA10477@intarweb.us> On Mon, Jan 12, 2004 at 05:07:18PM +0000, Premshree Pillai wrote: > --- "Diez B. Roggisch" wrote: > > > I need to run a Python program dynamically within > > > another program. I am using exec for the purpose. > > Is > > > there a way to pass parameter switches to exec? > > > > You can pass a globals-dictionary to exec, which can > > hold the switches > > values. > > > > Diez > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Could you please elucidate with a sample script. > Suppose I need to pass the switch "-w" to the > dynamically loaded code (using eval()/exec()). > Any help is appreciated. > Options aren't typically passed to "code". They're passed to the main function of a program. For example: def main(argv): o = GameOptions() o.parse(argv[1:]) ... If your code is structured like this, you can avoid using eval() and exec altogether and simply import and call the main function: from foo import main main(['progname', '-w']) Hope this helps, Jp From jcarlson at nospam.uci.edu Sat Jan 31 13:27:45 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 31 Jan 2004 10:27:45 -0800 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia In-Reply-To: <2da21d6c.0401310807.671be3b7@posting.google.com> References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: > produced demo output that clearly demonstrates the viability of > my approaches, which I've been showing to potential licensees and > investors. This demo output is currently being generated through Hey Stan, I don't suppose you'd post a link to a bit of demo output? - Josiah From elainejackson7355 at home.com Fri Jan 9 13:43:28 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 09 Jan 2004 18:43:28 GMT Subject: Pesky reverse() References: <3t3svvs7ni8l8jnn1l1v60oogirqoaa85f@4ax.com> Message-ID: >>> list1=[1,2,3] >>> list2=list1[:] ## "cloning" >>> list1.reverse()==None 1 >>> list1 [3, 2, 1] >>> list2 [1, 2, 3] wrote in message news:3t3svvs7ni8l8jnn1l1v60oogirqoaa85f at 4ax.com... | | I need to use the built-in method 'reverse', but notice strange behavior. | Foe example: | | print my_list.reverse() doesn't work. | | new_list = my_list.reverse() doesn't work. | | my_list.reverse() | print my_list does work. (displays reversed list) | | But I want both a 'forward' and 'reverse' list: | | new_list = my+list # should save a 'forward' copy, right? Nope | my_list.reverse() actually reverses both copies, since Python is a bit too | helpful sometimes, and I understand why. | | So the question is, how do I get a forward and reverse list? | | Thanks......Norm. | | From paul at prescod.net Sat Jan 24 16:19:08 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 24 Jan 2004 13:19:08 -0800 Subject: Perl vs. Python for text manipulation In-Reply-To: <1013o27e3nb141@corp.supernews.com> References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <1013o27e3nb141@corp.supernews.com> Message-ID: <4012E14C.9020102@prescod.net> Cameron Laird wrote: > ... > The comparison with Perl in particular interests me. I > often encounter characterizations of Perl (or Ruby--I > regard them as equivalent in this dimension) as the par- > agon of text manipulation. It's not, of course, as Icon > conclusively demonstrates, at least for me; but I don't > even see Perl as distinctly superior to Python in text > mangling. I recognize that Python REs can feel a bit > cumbersome, in comparison to Perl, because they essenti- > ally demand the extra step of explicit compilation. Is > that all that people mean, though, when they talk about > Perl's superiority for text mangling? Is there more to > it? Here's an anecodotal sample where I think that the Perl and Python are roughly the same. I translated the Perl to Python. Note that the Python is a little more complicated primarily because of Python string interpolation and not regular expressions. http://www.cs.sfu.ca/~cameron/REX.html # REX/Perl 1.0 # Robert D. Cameron "REX: XML Shallow Parsing with Regular Expressions", # Technical Report TR 1998-17, School of Computing Science, Simon Fraser # University, November, 1998. # Copyright (c) 1998, Robert D. Cameron. # The following code may be freely used and distributed provided that # this copyright and citation notice remains intact and that modifications # or additions are clearly identified. $TextSE = "[^<]+"; $UntilHyphen = "[^-]*-"; $Until2Hyphens = "$UntilHyphen(?:[^-]$UntilHyphen)*-"; $CommentCE = "$Until2Hyphens>?"; $UntilRSBs = "[^\\]]*](?:[^\\]]+])*]+"; $CDATA_CE = "$UntilRSBs(?:[^\\]>]$UntilRSBs)*>"; $S = "[ \\n\\t\\r]+"; $NameStrt = "[A-Za-z_:]|[^\\x00-\\x7F]"; $NameChar = "[A-Za-z0-9_:.-]|[^\\x00-\\x7F]"; $Name = "(?:$NameStrt)(?:$NameChar)*"; $QuoteSE = "\"[^\"]*\"|'[^']*'"; $DT_IdentSE = "$S$Name(?:$S(?:$Name|$QuoteSE))*"; $MarkupDeclCE = "(?:[^\\]\"'><]+|$QuoteSE)*>"; $S1 = "[\\n\\r\\t ]"; $UntilQMs = "[^?]*\\?+"; $PI_Tail = "\\?>|$S1$UntilQMs(?:[^>?]$UntilQMs)*>"; $DT_ItemSE = "<(?:!(?:--$Until2Hyphens>|[^-]$MarkupDeclCE)|\\?$Name(?:$PI_Tail))|%$Name;|$S"; $DocTypeCE = "$DT_IdentSE(?:$S)?(?:\\[(?:$DT_ItemSE)*](?:$S)?)?>?"; $DeclCE = "--(?:$CommentCE)?|\\[CDATA\\[(?:$CDATA_CE)?|DOCTYPE(?:$DocTypeCE)?"; $PI_CE = "$Name(?:$PI_Tail)?"; $EndTagCE = "$Name(?:$S)?>?"; $AttValSE = "\"[^<\"]*\"|'[^<']*'"; $ElemTagCE = "$Name(?:$S$Name(?:$S)?=(?:$S)?(?:$AttValSE))*(?:$S)?/?>?"; $MarkupSPE = "<(?:!(?:$DeclCE)?|\\?(?:$PI_CE)?|/(?:$EndTagCE)?|(?:$ElemTagCE)?)"; $XML_SPE = "$TextSE|$MarkupSPE"; sub ShallowParse { my($XML_document) = @_; return $XML_document =~ /$XML_SPE/g; } =============== import re class recollector : def __init__(self): self.res={} def add(self, name, reg ): self.res[name] = reg % self.res collector = recollector() a = collector.add a( "TextSE" ,"[^<]+" ) a( "UntilHyphen" ,"[^-]*-" ) a( "Until2Hyphens" ,"%(UntilHyphen)s(?:[^-]%(UntilHyphen)s)*-" ) a( "CommentCE" ,"%(Until2Hyphens)s>?" ) a( "UntilRSBs" ,"[^\\]]*](?:[^\\]]+])*]+" ) a( "CDATA_CE" ,"%(UntilRSBs)s(?:[^\\]>]%(UntilRSBs)s)*>" ) a( "S" ,"[ \\n\\t\\r]+" ) a( "NameStrt" ,"[A-Za-z_:]|[^\\x00-\\x7F]" ) a( "NameChar" ,"[A-Za-z0-9_:.-]|[^\\x00-\\x7F]" ) a( "Name" ,"(?:%(NameStrt)s)(?:%(NameChar)s)*" ) a( "QuoteSE" ,"\"[^\"]*\"|'[^']*'" ) a( "DT_IdentSE" ,"%(S)s%(Name)s(?:%(S)s(?:%(Name)s|%(QuoteSE)s))*" ) a( "MarkupDeclCE" ,"(?:[^\\]\"'><]+|%(QuoteSE)s)*>" ) a( "S1" ,"[\\n\\r\\t ]" ) a( "UntilQMs" ,"[^?]*\\?+" ) a( "PI_Tail" ,"\\?>|%(S1)s%(UntilQMs)s(?:[^>?]%(UntilQMs)s)*>" ) a( "DT_ItemSE" ,"<(?:!(?:--%(Until2Hyphens)s>|[^-]%(MarkupDeclCE)s)|\\?%(Name)s(?:%(PI_Tail)s))|%%%(Name)s;|%(S)s" ) a( "DocTypeCE" ,"%(DT_IdentSE)s(?:%(S)s)?(?:\\[(?:%(DT_ItemSE)s)*](?:%(S)s)?)?>?" ) a( "DeclCE" ,"--(?:%(CommentCE)s)?|\\[CDATA\\[(?:%(CDATA_CE)s)?|DOCTYPE(?:%(DocTypeCE)s)?" ) a( "PI_CE" ,"%(Name)s(?:%(PI_Tail)s)?" ) a( "EndTagCE" ,"%(Name)s(?:%(S)s)?>?" ) a( "AttValSE" ,"\"[^<\"]*\"|'[^<']*'" ) a( "ElemTagCE" ,"%(Name)s(?:%(S)s%(Name)s(?:%(S)s)?=(?:%(S)s)?(?:%(AttValSE)s))*(?:%(S)s)?/?>?" ) a( "MarkupSPE" ,"<(?:!(?:%(DeclCE)s)?|\\?(?:%(PI_CE)s)?|/(?:%(EndTagCE)s)?|(?:%(ElemTagCE)s)?)" ) a( "XML_SPE" ,"%(TextSE)s|%(MarkupSPE)s" ) a( "XML_MARKUP_ONLY_SPE" ,"%(MarkupSPE)s" ) def lexxml(data, markuponly=0): regex = re.compile(collector.res["XML_SPE"]) return regex.findall(data) (I stripped a few features out of the Python code to make it equivalent. If it doesn't run as written above you can see the original here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65125) Paul Prescod From steve at ferg.org Thu Jan 15 12:47:20 2004 From: steve at ferg.org (Stephen Ferg) Date: 15 Jan 2004 09:47:20 -0800 Subject: traceback as string References: Message-ID: I haven't been using this function for very long, but it seems to work. You pass it the exception object, and it returns a string. =================================================== def exception_format(e): """Convert an exception object into a string, complete with stack trace info, suitable for display. """ import traceback info = "".join(traceback.format_tb(sys.exc_info()[2])) return str(e) + "\n\n" + info ==================================================== Here's an example of how to use it. ================================================== try: main1() except Exception, e: print exception_format(e) ==================================================== From piedmontbiz at aol.com Wed Jan 14 19:00:48 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 15 Jan 2004 00:00:48 GMT Subject: Printing to console, no scroll References: Message-ID: <20040114190048.06766.00000030@mb-m21.aol.com> > > >"Totte Karlsson" writes: > >> Hi, >> How can I print to the console without having it scrolling to a new line >for >> each print statement? >> I want to print a count down in the console, but for each count it scrolls >> the screen (of course). >> >> Is there another way? >> ===== Here is some code i got off the web. I use it on my os2 2.1 laptop for which I don't have curses or tkinker libs. I mostly use the color functions and move as a analog to turbo pascal/basic gotoxy. # begin code #!/usr/bin/env python ''' ansi.py ANSI Terminal Interface (C)opyright 2000 Jason Petrone All Rights Reserved Color Usage: print RED + 'this is red' + RESET print BOLD + GREEN + WHITEBG + 'this is bold green on white' + RESET Commands: def move(new_x, new_y): 'Move cursor to new_x, new_y' def moveUp(lines): 'Move cursor up # of lines' def moveDown(lines): 'Move cursor down # of lines' def moveForward(chars): 'Move cursor forward # of chars' def moveBack(chars): 'Move cursor backward # of chars' def save(): 'Saves cursor position' def restore(): 'Restores cursor position' def clear(): 'Clears screen and homes cursor' def clrtoeol(): 'Clears screen to end of line' ''' ################################ # C O L O R C O N S T A N T S # ################################ BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' WHITE = '\033[37m' RESET = '\033[0;0m' BOLD = '\033[1m' REVERSE = '\033[2m' BLACKBG = '\033[40m' REDBG = '\033[41m' GREENBG = '\033[42m' YELLOWBG = '\033[43m' BLUEBG = '\033[44m' MAGENTABG = '\033[45m' CYANBG = '\033[46m' WHITEBG = '\033[47m' def move(new_x, new_y): 'Move cursor to new_x, new_y' print '\033[' + str(new_x) + ';' + str(new_y) + 'H' def moveUp(lines): 'Move cursor up # of lines' print '\033[' + str(lines) + 'A' def moveDown(lines): 'Move cursor down # of lines' print '\033[' + str(lines) + 'B' def moveForward(chars): 'Move cursor forward # of chars' print '\033[' + str(lines) + 'C' def moveBack(chars): 'Move cursor backward # of chars' print '\033[' + str(lines) + 'D' def save(): 'Saves cursor position' print '\033[s' def restore(): 'Restores cursor position' print '\033[u' def clear(): 'Clears screen and homes cursor' print '\033[2J' def clrtoeol(): 'Clears screen to end of line' print '\033[K' # ======end code======= allen From grahamd at dscpl.com.au Tue Jan 13 05:39:48 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 13 Jan 2004 02:39:48 -0800 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) wrote in message news:<10064loqc7sd7e3 at corp.supernews.com>... > In article <7xisjh1e3i.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > . > . > . > >I'd say don't bother with C++ unless you're working on a big > >multi-person project. Its design will make no sense to you unless > >you've faced the problems that come up in those projects. Otherwise > >it's a big mess. > . > . > . > And if you *are* working on a big multi-person project, and you > choose C++, you're likely to end up with ... a big mess. > > I get to say so. I'm fond of C++, and have seen plenty of pro- > jects which rely on it. I've also seen the teams assigned to > such projects ... Would agree that more often than not it is the programmers working on the project. I have met very very few programmers who I thought had what it takes to develop decent C++ code which is understandable and maintainable. Part of the problem though is not the programmers but the C++ libraries they have to work with. Even though the STL may be the "standard template library", it is pretty dangerous stuff. Your average programmer however will tell you it is wonderful stuff and never understand its danger and how one can so easily create huge disasters with it. Part of the utility of Python is thus not so much the language itself, but the availability of useful modules to go with it. I wouldn't say all the Python modules are perfect, some could certainly have done with a bit more thought, but it certainly gives a Python programmer a head start over a C++ programmer. From jl at windsmith.net Tue Jan 13 09:28:09 2004 From: jl at windsmith.net (John Lull) Date: 13 Jan 2004 08:28:09 -0600 Subject: Multithreaded COM server problem... References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> Message-ID: <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com> Mark Hammond wrote (with possible deletions): > John Lull wrote: ... > > Unfortunately, this one has to be a local server since it's providing shared > > access to a pool of hardware devices from multiple distributed clients. I've > > carefully reviewed chapters 5 & 12, and appendix D, and wasn't able to find > > anything addressing threading models in the local server in detail. If I've > > missed something, I'd be grateful for any additional hints. > > The problem is that your client code is not running a message loop. If > you change the loop of your client test code to something like: > > for i in range(delay)*10: > time.sleep(0.1) > pythoncom.PumpWaitingMessages() > > It works as you expect. A better choice would probably be > win32event.MsgWaitForMultipleObjects, but that depends on what your app > really does. > > Mark. I presume you meant my server code. This still leaves all calls to the server running in a single thread, however. If I insert a call to PumpWaitingMessages() in a short operation, and it happens to start a long operation, the result of that short operation will be delayed until the long operation completes. This will make my server unusable. I think I really need a server with at least requests from different clients running in separate threads. I tried changing win32com.server.localserver to do: sys.coinit_flags = 0 instead of: sys.coinit_flags = 2 At first glance this seems to do what I want -- requests to the server seem to run from a thread pool. However, I also get intermittent (but frequest) startup errors, with a Microsoft Visual C++ Runtime Library error dialog (during pythoncom.PumpMessages but before my server module gets imported) reporting: Runtime Error! Program: c:\Apps\Python2.2\pythonw.exe abnormal program termination When I click OK, my client application reports (reformatted for posting): Traceback (most recent call last): File "D:\Cust\Kinetics\comThreads\test20.py", line 7, in ? app=Dispatch('PyComThreads.Application') File "C:\Apps\Python2.2\lib\site-packages\win32com \client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName( dispatch,userName,clsctx) File "C:\Apps\Python2.2\lib\site-packages\win32com \client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Apps\Python2.2\lib\site-packages\win32com \client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2146959355, 'Server execution failed', None, None) I do *not* seem to get this error if the server is already running because of a request from another process. If I'm not able to track down the cause of this error, is there some way I can (during object creation) create a new thread to handle all requests on the new object? I know how to create the thread, what I don't know is how I would tell the COM mechanism to route all requests on the new object to the message pump in the new thread. Thanks for your assistance. Regards, John From rnd at onego.ru Mon Jan 5 04:08:33 2004 From: rnd at onego.ru (Roman Suzi) Date: Mon, 5 Jan 2004 12:08:33 +0300 (MSK) Subject: Is it bug or feature in sre? Message-ID: I've accidentally tried on of my programs written for Python 1.5 and encountered this: Python 2.3.1 (#1, Sep 25 2003, 10:15:04) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 ...... >>> re.compile("(?P[A-Z]*)?") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/sre.py", line 179, in compile return _compile(pattern, flags) File "/usr/local/lib/python2.3/sre.py", line 229, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat I wonder why I can't do this? I guess it's of terrible style, but is this behaviour intentional or not? Probably it is good idea to mention this in Python update path documents. Otherwise some old programs will mysteriously fail. Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From fBechmann at web.de Sat Jan 17 09:22:28 2004 From: fBechmann at web.de (Frank Bechmann) Date: 17 Jan 2004 06:22:28 -0800 Subject: [OT] AS/400 References: <4005cd03@news.mt.net.mk> Message-ID: OS-wise an incredible innovative and visionary machine, programming-wise you had .NET (read as: multi-language runtime-environment) since more than a decade. unequaled productivity for business application development with the usual triple dialog-processing - business logic - database. if only it had more cool ILE-languages than RPG, CL, Cobol and a poorly supported C/C++. btw.: there is even a python port for the AS/400, but even if CL as ugly as a nightmare it can't be beaten in terms of productivity on an AS/400. From cappy2112 at yahoo.com Sun Jan 25 01:04:23 2004 From: cappy2112 at yahoo.com (Tony C) Date: 24 Jan 2004 22:04:23 -0800 Subject: pyMagick vs PIL Message-ID: <8d3e714e.0401242204.38c9c0e@posting.google.com> I've used Image Magick before, and I'm happy with it. When I searched for Python extensions for Image Magick, I found an unsupported (an old) version of pyMagick. I'm wondering if this was very popular, or if the author just didn't have time to continue supporting it. I'd like to hear from someone who used pyMagick and PIL, for some comparative opinions. thanks From tim.golden at viacom-outdoor.co.uk Fri Jan 23 11:31:55 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 23 Jan 2004 16:31:55 -0000 Subject: File Install Program Using Python? Message-ID: >From: CB Hamlyn [mailto:cbh at newenglandhomes.net] ... >Anyway, I want to create an installation program that takes a >folder and all >it's sub-folders and copies them from a compressed form into the proper >directory. Basically a simplified version InstallSheild or whatever. ... >Any help would be appreciated. > >Thanks >CB Hamlyn > You want to be looking at the zipfile and/or gzip and/or bz2 modules: http://www.python.org/doc/current/lib/module-bz2.html http://www.python.org/doc/current/lib/module-gzip.html http://www.python.org/doc/current/lib/module-zipfile.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 mark at mceahern.com Mon Jan 19 12:17:43 2004 From: mark at mceahern.com (Mark McEahern) Date: Mon, 19 Jan 2004 11:17:43 -0600 Subject: ConfigParser - setting the order of options in a section In-Reply-To: References: Message-ID: <1074532662.5354.48.camel@dev.internal> On Mon, 2004-01-19 at 09:24, S.Ramaswamy wrote: > I am trying unsuccessfully to set the order of options [...] Sections and options are internally stored by ConfigParser in dictionaries. I think the idea is that, as far as ConfigParser is concerned, the order of sections and options within a section is unimportant. So if it *is* important to you, you're going to have to do the ordering yourself. Also, in your code, you seem to treat comments as if they were options, setting them with set(). As far as I can tell, ConfigParser doesn't provide anyway for you to associate a comment with an option. What I'd do is provide your own write function or writer object that does what you want it to do. Cheers, // m From mwh at python.net Tue Jan 13 05:59:48 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 13 Jan 2004 10:59:48 GMT Subject: setproctile()? References: Message-ID: Wilfredo S?nchez writes: > Is there a way to set the kernel's notion of a python process' name > on Unix such that, for example, ps shows what I specify? No. I seem to remember than last time this went around it was decided that it was too hard to do portably, but that's just possibly flaky memory. You might want to consult the python-dev archives. Cheers, mwh -- /* I'd just like to take this moment to point out that C has all the expressive power of two dixie cups and a string. */ -- Jamie Zawinski from the xkeycaps source From miki.tebeka at zoran.com Mon Jan 19 17:21:02 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 19 Jan 2004 14:21:02 -0800 Subject: ConfigParser - setting the order of options in a section References: Message-ID: <4f0a9fdb.0401191421.36060536@posting.google.com> Hello, > I am trying unsuccessfully to set the order of options using the > set(section,option,value) method ( Python 2.2.2) and writing to a > file. But the options always appear in a random order. I had the same problem. Just hand written the file myself, the syntax of the .cfg files is *very* simple and by iterating over the sections/values it's very easy to generate the "right" output file. HTH. Miki From bkelley at wi.mit.edu Fri Jan 9 12:02:36 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 09 Jan 2004 12:02:36 -0500 Subject: Python And Internationalization maybe a pre-pep? Message-ID: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> I have been using gettext and various utilities to provide internationalization for a wxPython application and have not really been liking the process. Essentially it uses a macro-style notation to indicate which strings should be internationalized. Essentially, everything looks like this _("STRING") A good description of this system is located here http://wiki.wxpython.org/index.cgi/Internationalization I got to thinking that this is python, I shouldn't have to do this. Why not have a mechanism to capture this data at compile time? I made a new python string type and got enough working on the parser to accept string = i"whatever" Which is just a subtype of string. When python parses this it adds it in an entry in the internationalization table. (essentially a dictionary) It also addes it as an entry to the standard gettext mechanism to indicate strings that need to be localized. When the string is created, if a value exists in the international table for the given string, the string is converted to the current locale. The locale is set through the standard locale module. When this happens, all internationalized strings, when used, are converted to their international representations (using unicode if necessary) automagically through the gettext system. Hopefully I'm not reinventing the wheel but one nice thing about this system is that after some slight code modifications to the python sources declaring exception error messages to be international, I now have a nice dictionary of error messages that need to be localized. These would be localized in the standard way using gettext tools. Now, I don't know if this is a good idea or not, and I may be reinventing some wheels, but it has some appealing characteristics and ties in with the gettext system really well. Of course, I'm a bit leary with changing the python parser but I was uncomfortable with the two step process of writing the code, then passing it through a source analyzer so that it could be internationalized. Of course I have some issues, like if you use an international string in a dictionary and the internal value changes based on the locale bad things happen. This requires that the locale be set only once at the beginning of the application otherwise undesirable events occur :) What I would like is something like import internationalization and then at compile time strings like i"whatever" would be analyzed but would be normal strings without "import internationalization" So, am I being silly, redundant or just plain different? Brian From fumanchu at amor.org Sat Jan 3 18:40:55 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 3 Jan 2004 15:40:55 -0800 Subject: Recurring dates module [was: Project dream] Message-ID: > eltronic at juno.com wrote: > > a timer capable of alarms or starting programs with > > various ways of specifying the event, weekly monthly > > don't start untill, stop after date, user defined, etc. Then I responded: > I've been needing to write this, as well, for my own apps. Here is a > first attempt (*very* alpha); feedback/additions appreciated. > > http://www.aminus.org/rbre/python/recur.py > http://www.aminus.org/rbre/python/test_recur.py I updated this today, including time functions in addition to the date functions and generally "filling in the corners". I also included an interval calculation function for e.g., threading.Timer. Finally, I wrapped the bare generator functions in a Recurrence class. I'm now using it for my object server, and it seems to be working well. Again, any feedback appreciated, especially from Skip M. (who's worked on this problem before, it seems ;). Robert Brewer MIS Amor Ministries fumanchu at amor.org From piedmontbiz at aol.com Wed Jan 21 17:44:34 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 21 Jan 2004 22:44:34 GMT Subject: Secure Voting software Message-ID: <20040121174434.28446.00000428@mb-m15.aol.com> Listening to National Public Radio while reading comp.lang.python. What a life! I just heard a piece on NPR about the security failures of an electronic voting system being developed. I know a voting system could be developed in python. I am working on a simulator myself to run via the web (a personal project only) Are there any features which would make python a viable alternative to develop a real voting system for use in the US? Why or why not? What things must I keep in mind when I design a python application to be secure? Since python is developed using C, can python be free from the buffer overrun problems which plague other C programs? allen From op73418 at mail.telepac.pt Thu Jan 15 09:15:29 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 15 Jan 2004 14:15:29 +0000 Subject: super. could there be a simpler super? References: Message-ID: <3u7d00tr6088nceeajqr9m2j2t2vatta5a@4ax.com> On Thu, 15 Jan 2004 11:50:57 +0300, Kerim Borchaev wrote: >Hello! > > Always when I use "super" I create a code duplication because class > used as first arg to "super" is always the class where the method > containing "super" was defined in: > ''' > class C: > def method(self): > super(C, self).method() > ''' > > Obviously the methods like the one below doesn't work "right";-) > ''' > def super(self): > super(self.__class__, self) > class C: > def method(self): > super(self).method() > ''' Hmm... I once used super where the class used as first arg was *not* the class defining the method, it was it's super class. So I was calling, not the super method, but it's grand-super method. Arguably, this is a clear sign of bad design on my part. But that's how it went, anyway. With my best regards, G. Rodrigues From hgeldenhuys at gims.com Wed Jan 21 09:32:24 2004 From: hgeldenhuys at gims.com (Herman Geldenhuys) Date: Wed, 21 Jan 2004 16:32:24 +0200 Subject: Dailing modem. Message-ID: <002601c3e02b$62f82130$b10d10ac@metasalio> HI. I need to dail a modem from python and disconnect it again. Is there a pythonic way of doing this? Life is just too short for fiddling with the complexity of TAPI via COM. But if you do have a TAPI-way of doing this, please share. Help will be welcomed greatly! Thanks Herman -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcfletch at rogers.com Fri Jan 9 09:06:33 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 09:06:33 -0500 Subject: Debugging Python In-Reply-To: References: Message-ID: <3FFEB569.9040007@rogers.com> Standard module pdb is popular (and what I use, though I also do lots of print-statement debugging too). There's also a win32db (or something like that) in PythonWin. Some of the IDE's have integrated debuggers which are normally very similar to pdb. I think HapDebugger is about the only truly "different" debugging system, in that it's an out-of-process (and IIRC, remote) debugging mechanism that relies on a patched version of Python. BTW, the Agile Programmer types have been known to suggest that debuggers are entirely unnecessary, as everything should be caught by more and more fine-grained unit-tests. Seems like a nice way to go, IMO. HTH, Mike Ashley Lloyd wrote: > What do people generally use to debug their Python programs? I haven't > seen anything out there that walks through the code, but perhaps I'm > looking in the wrong places? _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tweedgeezer at hotmail.com Wed Jan 28 10:26:25 2004 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 28 Jan 2004 07:26:25 -0800 Subject: I support PEP 326 References: <698f09f8.0401272000.79704ef0@posting.google.com> <698f09f8.0401271318.21c9ca72@posting.google.com> Message-ID: <698f09f8.0401280726.1c7f764e@posting.google.com> Anthony Baxter wrote in message news:... > >>> len(dir(__builtins__)) > 125 > > That's a _lot_ of stuff in one module. Even if you exclude the 40-odd > exceptions that are there, that's still a lot of guff in one big flat > namespace. There certainly is, but are the mistakes of the past going to doom us to put things in the wrong place until we get to clean it up? I think the one appropriate place for the proposed constants is __builtins__, for the obvious reasons that (a) all other singleton constants are there (None, True, False) and (b) ease of implementation of cmp (with Maximum and Minimum in __builtins__, it's a 5-line change, I read on Python-dev). Yes, __builtins__ is bloated, but as Mr. Holl mentioned, a significant amount of it can be removed once Guido's willing to break backwards-compatibility. But why make 3.0 even more backwards-incompatible than it is now by sticking rightful builtins somewhere else just to keep the builtin namespace artificially smaller? (Or consider this: as a native speaker of English, I have a working vocabulary of tens of thousands of English words, and a non-working vocabulary in the hundreds of thousands. Do people really believe that the difference between 125 and 127 (or 150, or 200) builtins is going to increase my cognitive load significantly?) Jeremy From raims at dot.com Tue Jan 13 11:26:07 2004 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 13 Jan 2004 17:26:07 +0100 Subject: Does anyone else not find the fun in programming...? References: Message-ID: <87smijolwg.fsf@mobile.foo> chris.lyon at spritenote.co.uk (Chris Lyon) writes: > Do I need help ? Mmmm maybe programming is not your way (or you work in a boring place :) -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From felix_mcallister at hotmail.com Thu Jan 8 07:45:21 2004 From: felix_mcallister at hotmail.com (Felix McAllister) Date: 8 Jan 2004 04:45:21 -0800 Subject: NNTP Server for this group References: Message-ID: If you don't mind not being able to post then try news://140.99.99.133 You'll find more servers that mirror comp.lang.python by going onto http://www.disenter.com/ Felix. jonas at jonasgalvez.com (Jonas Galvez) wrote in message news:... > Can anyone recommend a good NNTP server for accessing this group? > > Thanks in advance, > Jonas Galvez From mhammond at skippinet.com.au Sat Jan 31 17:15:54 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 01 Feb 2004 09:15:54 +1100 Subject: win32com support In-Reply-To: References: Message-ID: Crawley wrote: > File "E:\Python23\lib\site-packages\win32com\client\dynamic.py", line > 460, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > exceptions.AttributeError: .SetAddInInfo > > > Which I believe is because the object I'm calling does not support the > SetAddInInfo method. For some reason, the object you are using does not have makepy support, which is unusual. > After a bit of investigation, this makes sense as my class extends > _IDTExtensibility2 and for that the application parameter is of type > 'Object'. I cant see how to cast this into an IApplication instance, > which is what I need to call my function. Generally, you can do a QueryInterface for the object. However, if the object does not support IDispatch, you will haver trouble - we don't support arbitrary interfaces when calling them, only implementing them. ob = ob._obj_.QueryInterface( > Ive also tried making my object derive from IDSAddin (what VC uses), but > when I try the following (GUID found > here:http://msdn.microsoft.com/library/default.asp?url=/library/en- > us/vcug98/html/_asug_how_add.2d.ins_connect_and_disconnect.asp) > > universal.RegisterInterfaces('{C0002F81-AE2E-11cf-AD07-00A0C9034965}', 0, > 1, 0, ["_IDSAddin"]) > > I get the following error: The GUID must be for a type library. If you run "makepy.py -i", then you will get a list of all valid typelibs you can use, and the params for it. Mark. From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 02:14:17 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 13 Jan 2004 23:14:17 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: "Dan Olson" wrote in message news:pan.2004.01.14.04.32.52.403279 at fakeemail.com... > On Tue, 13 Jan 2004 19:00:43 -0800, Brandon J. Van Every wrote: > > > I'm curious what sky is going to fall if I don't follow your advice? > > It's just advice. I think it would have been smoother for everyone if > you'd followed it, but apparently you prefer to piss on my advice so > that's cool too. You have some deep-seated need for smootheness? I see no a priori value in smoothness. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From swalters_usenet at yahoo.com Mon Jan 5 17:05:43 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 05 Jan 2004 22:05:43 GMT Subject: Python/C and PYTHONPATH References: Message-ID: Fair warning: At this point, I couldn't even get the example you quoted to link properly. Of course, I didn't dig too deep, as I'm in a hurry. throw this c code into a .h file (my name for it is envdump.h) ---code--- #include extern char **environ; void fdump_env(FILE *fd) { char **ptr; int i = 0; ptr = environ; while(ptr[i] != NULL) { fprintf(fd, "%i : %s\n", ptr[i]); i++; } } void dump_env() { char **ptr; int i = 0; ptr = environ; while(ptr[i] != NULL) { printf("%i : %s\n", i, ptr[i]); i++; } } ---code--- Now, just inside the main function (or, perhaps, wherever you please, but I'd try the line right before the first if statement) call dump_env() and it will spit out all the environment variables that your C program received. You might find something there that's of interest. Or, call setenv ("man 3 setenv") to manually set a python-path. you can use that in combo with getenv ("man 3 getenv") to append to an existing PYTHONPATH, if you so choose. Give it a go, please let me know how it turns out. If this doesn't shed some light on the matter I might have another idea once I'm not rushing around. HTH Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From cwilcox at etcconnect.com Wed Jan 14 09:10:41 2004 From: cwilcox at etcconnect.com (Christian Wilcox) Date: Wed, 14 Jan 2004 08:10:41 -0600 Subject: Python and XForms: existing implementations? Message-ID: <69A0D4AB81C51447AD6BA387782B8D64093D6E@midl-mail4.etcconnect.com> Does anyone know of any existing Python implementations of an XForms viewer? Christian -------------- next part -------------- An HTML attachment was scrubbed... URL: From db3l at fitlinxx.com Mon Jan 12 12:00:32 2004 From: db3l at fitlinxx.com (David Bolen) Date: 12 Jan 2004 12:00:32 -0500 Subject: wxpython AttributeError! References: Message-ID: "frank" writes: > need help with wxpython. > wxpython code is made with boa-constructor > > when i run the code i get this error message: (...) > File "wxFrame1.py", line 157, in _init_ctrls > EVT_RIGHT_DOWN(self.treeCtrl1, self.OnTreectrl1RightDown) > AttributeError: wxFrame1 instance has no attribute 'OnTreectrl1RightDown' (...) > > this is the code have this code: > > self.treeCtrl1 = wxTreeCtrl(id=wxID_WXFRAME1TREECTRL1, name='treeCtrl1', > parent=self.splitterWindow1, pos=wxPoint(2, 2), > size=wxSize(200, > 610), style=wxTR_HAS_BUTTONS, validator=wxDefaultValidator) > self.treeCtrl1.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxNORMAL, > False, > 'Microsoft Sans Serif')) > EVT_RIGHT_DOWN(self.treeCtrl1, self.OnTreectrl1RightDown) > EVT_TREE_SEL_CHANGED(self.treeCtrl1, wxID_WXFRAME1TREECTRL1, > self.OnTreectrl1TreeSelChanged) > > and the event EVT_RIGHT_DOWN code is: > > def OnTreectrl1RightDown(self, event): > dosomething() > event.Skip() > > the "OnTreectrl1RightDown" is in the wxframe class > what to do? First is not to snip so much code for your post that context is lost :-) It's not clear from the above code whether or not your initialization code and the function definition are within the same class (especially with the different indentation levels). If in fact the initialization code is part of your __init__ definition in wxFrame1, which also holds the callback function definition, at first glance it looks like it should be ok. Or, if the callback definition is in a subclass of wxFrame1 then you should be ok as well. But the error you are getting would imply that 'self' in your initialization code is not the same object as that which contains the callback definition. If you could post a more complete snippet of the code (in particular, at a minimum an unchanged copy of the entire __init__ (or other function) containing the initialization code, including its enclosing class definition, as well as the same for the callback function), it might be easier to see what problem exists. -- David From sdeibel at wingide.com Thu Jan 22 15:02:40 2004 From: sdeibel at wingide.com (Stephan Deibel) Date: Thu, 22 Jan 2004 15:02:40 -0500 (EST) Subject: Nokia prefers Python In-Reply-To: <40102241.E4A38F73@engcorp.com> Message-ID: On Thu, 22 Jan 2004, Peter Hansen wrote: > Stephan Deibel wrote: > > > > Anyone happen to have a contact at Nokia that might be willing and able > > to write up a Python Success Story based on this? Or know of someone > > else that might? > > > > http://pythonology.org/success > > Maybe it's a bit soon to call it a "success"? It sounds like it's just > in evaluation at this stage... Yes, probably correct. I'm mainly trying to make contact... the actual process of writing a story and getting it approved by the company involved can take a long time. - Stephan From eddie at holyrood.ed.ac.uk Tue Jan 20 11:45:45 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 20 Jan 2004 16:45:45 +0000 (UTC) Subject: best book: aint no such thing, and encouragement for old coots References: <95aa1afa.0401192355.77568ed4@posting.google.com> Message-ID: cartermark46 at ukmail.com (Mark Carter) writes: >What I meant was: programs written in s-exprs makes it possible to >accomodate new paradigms because, ultimately, everything is a list, >which you can parse to accomodate your new paradigm. Programs not >written in s-exprs require extra syntax to be bolted onto the >language. The way I view it is that you can express _everything_ you want a computer to do as: COMMAND arg1 arg2 ... When you have code as data thrown in to the mix you can extend this concept to what you want done with code, so as well as saying: ADD x y z PUT this there etc. you have the ability to control the way code is executed DO this-body-of-code DO this-body-of-code for all these things And essentially new paradigms ARE about how we organise code, so we can indeed adapt to any paradigm AND we still have minimum syntax to deal with. One of the things I like about scheme in this instance is that the rules of your paradigm are explicit in the code/macros that you create to parse the basic constructs of your paradigm (objects, messages, whatever). >But I suppose, if you want, to argue that all Turing Complete >languages are equivalent, so they support all the paradigms that the >others support. Then you run into Greenspun's tenth rule amongst others. Also, of course, you have to consider expressiveness which is much harder to pin down. Eddie From swalters_usenet at yahoo.com Fri Jan 16 07:00:27 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Fri, 16 Jan 2004 12:00:27 GMT Subject: best book: aint no such thing, and encouragement for old coots References: Message-ID: | Eddie Corns said | > The next step is to read "Structure and Interpretation of Computer Programs" > aka SICP and start all over again, in terms of "clearer conceptual vantage > point" it just can't be beat. It's even availabe online somewhere. Here: http://mitpress.mit.edu/sicp/full-text/book/book.html It's the major reason I'm learning scheme. I just don't stop hearing good things about this book. Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From usenet at mail-2-me.com Fri Jan 30 20:09:15 2004 From: usenet at mail-2-me.com (Dirk) Date: Sat, 31 Jan 2004 02:09:15 +0100 Subject: How to start a DTS Package on MS-SQL-Server? In-Reply-To: References: Message-ID: Tim Golden wrote: >>-----Original Message----- >>From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com] >>Sent: 30 January 2004 12:48 >>To: python-list at python.org >>Subject: How to start a DTS Package on MS-SQL-Server? >> >> >>Hi! >> >>Does anybody know how to start a DTS-Package on a MS-SQL-Server out of >>a Python-Script? >> >>Thanks for your help! >> >>Dirk > > > Haven't tried it, but there is a dtsrun executable > (C:\Program Files\Microsoft SQL Server\80\Tools\BINN\dtsrun.EXE) > in my setup, which seems hopeful. > > There is also a DTS COM library which might do something. > > 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 > ________________________________________________________________________ > Hi! Sorry, I think I forgot to write that I want to start this from a remote computer. So I can't simply use popen. But I know about this dtsrun executable (that's how the sql-server does it itself...). Dirk From engsolnom at ipns.com Mon Jan 5 16:47:09 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Mon, 05 Jan 2004 13:47:09 -0800 Subject: NEWBIE: doctest question Message-ID: I'm trying to learn a bit about the doctest module, with the goal of incorporating unit test in my 'real' code. I created a test class, and it works fine, until I force an error. The results are: C:\Python23>python myfiles\tst_doctest.py ***************************************************************** Failure in example: print obj.s2hex('abcdef') from line #4 of __main__.Unittest Expected: *** Source string too long None Got: *** Source string too long None ***************************************************************** 1 items had failures: 1 of 3 in __main__.Unittest ***Test Failed*** 1 failures. If I remove the prints before and after print '*** Source string too long' in s2hex, it works fine, or if I just use: return '*** Source string too long' that works OK too. But if I try to compensate for the pre and post 'print' in the class doc string for the blank lines, it complains about that. The 'None' snows me... it would seem that on error, the return should be honored, and the 'return hex_string' should not be. Is the lesson here to handle exceptions better? All comments welcome. Norm TEST CODE: class Unittest: """ This class converts an ASCII string to the hex equiv blah blah >>> obj = Unittest() >>> print obj.s2hex('abcd') 61626364 >>> print obj.s2hex('abcdef') *** Source string too long None """ def __init__(self): pass def s2hex(self,source): hex_string = '' if len(source) > 5: print print '*** Source string too long' print return else: for char in source: hex_string += '%.2x' % ord(char) return hex_string if __name__ == '__main__': import doctest, sys doctest.testmod(sys.modules[__name__]) From python-url at phaseit.net Mon Jan 19 15:30:22 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 19 Jan 2004 20:30:22 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 19) Message-ID: <100ofiu8c1rmi1a@corp.supernews.com> QOTW: "I'm starting with Python and I find it really great! It's ... natural!" Lupe http://groups.google.com/groups?selm=mailman.539.1068218589.702.python-list%40python.org "I used to default to the widely-held position that 'language wars' are mostly content-free 'religious' arguments, but experience has taught me otherwise. There are big, important, differences in programmer efficiency, in computer-resource efficiency, and in community support. And, to some extent, in the ways they make you think about problems." John J. Lee The deadline for early bird registration for PyCon DC 2004 is 1 February. Expect the Sprint(s) to be a highlight. http://www.pycon.org/dc2004/register/ "An Introduction to the Twisted Networking Framework" is important, because Twisted is important, and it's accurate, because Itamar Shtull-Trauring knows everything about Twisted. http://www.onlamp.com/pub/a/python/2004/01/15/twisted_intro.html Denys Duchier makes "Continuations ... simple and illustrated". http://www.ps.uni-sb.de/~duchier/python/continuations.html "Sussen is a [Python-coded] security scanner which remotely tests computers ... on their vulnerabilities." http://sussen.sourceforge.net/ Stephan Diebel updates the status of the Python Success Stories. http://groups.google.com/selm=mailman.468.1074441904.12720.python-list%40python.org More Python recognition: among "the best Windows Freeware". http://www.pricelessware.org/2004/about2004PL.htm Raymond Hettinger codes a Floating Point Simulator class to provide executable illustrations of common FP surprises. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/265894 "The Tk Text Widget" introduces Tkinter's powerhouse Text() (although the article is expressed in Tcl rather than Python). http://www.linuxjournal.com/article.php?sid=7357 Roberto Alsina demonstrates how good PyQt programming with Eric3 can be. http://www.pycs.net/lateral/stories/16.html Premshree Pillai shares his automation of py2exe use. http://www.premshree.resource-locator.com/j/post.php?id=152 ======================================================================== 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 newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of 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 computer.problemen at skynet.be Fri Jan 9 03:57:18 2004 From: computer.problemen at skynet.be (broebel) Date: Fri, 9 Jan 2004 09:57:18 +0100 Subject: python newbie References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> <9drLb.2088$Wa.188@news-server.bigpond.net.au> Message-ID: <3ffe6b2d$0$1149$ba620e4c@news.skynet.be> thanks anthony, that's what I really wanted to know. "Anthony Borla" schreef in bericht news:9drLb.2088$Wa.188 at news-server.bigpond.net.au... > "broebel" wrote in message > news:3ffddcfd$0$16662$ba620e4c at news.skynet.be... > > hey, > > > > I'm a newbie in the programming world. > > I just started and already I'm in a whole lot of problems. > > > > And you'll probably experience a whole host more - welcome to the wonderful > world of programming ;) !!! > > > > > first problem is the fact that I started out with a little program > > who was part of a course but the problem is when I launch > > the program. I don't have the time to see the result because > > the screen closes immediately. > > > > Can anyone explain what's happening. > > > > > You are obviously not launching the interpreter from a console window. Thus, > launching the interpreter forces a new console window to be opened, your > program executes, and it then closes because it has finished. > > Possible remedies allowing you to view your program's output: > > * Launch interpreter as you have been doing, but add a line > such as: > > raw_input("Press a key to continue ") > > at the end of your code to prompt for a key press before > exiting, and closing the console window > > * Start using the intepreter from a console window i.e. start > using the command line. All generated output will appear > on the same console. > > Since you are in a course [?] I'd recommend asking your > instructor about suitable tutorials for doing this > > I hope this helps. > > Anthony Borla > > From http Wed Jan 14 02:10:29 2004 From: http (Paul Rubin) Date: 13 Jan 2004 23:10:29 -0800 Subject: Safe prime numbers in Python References: Message-ID: <7xd69nm2e2.fsf@ruckus.brouhaha.com> Tim Churches writes: > Does any know of or have Python code (or C or Fortran code wrapped > as a Python module) for efficiently finding safe prime numbers - > that is a number p such that p and (p-1)/2 are both prime? Yeah I have some, I'll see if I can dig it out and post it. It's pretty simple actually. From newsgroups at jhrothjr.com Mon Jan 5 10:06:59 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 5 Jan 2004 10:06:59 -0500 Subject: PRE-PEP: new Path class Message-ID: I'm adding a thread for comments on Gerrit Holl's pre-pep, which can be found here: http://tinyurl.com/2578q Frankly, I like the idea. It's about time that all of the file and directory stuff in the os module got objectified properly (or at least with some semblance of OO propriety!) In the issues section: 1) Should path be a subclass of str? No. Outside of the difficulty of deciding whether it's a subclass of single byte or unicode strings, it's a pure and simple case of Feature Envy. Granted, there will be times a developer wants to use string methods, but the most common operations should be supported directly. 2) virtual file system extensibility. No opinion at this time. I'd like to see a couple of attempts at an implementation first before settling on a single design. 3) Should the / operator map joinpath. I agree. No way. In the first place, that's a unixism (Windows uses \, the Mac uses :) In the second place it doesn't fit the common use of /, which is to divide (separate) things. If we want an operator for join (not a bad idea) I'd suggest using '+'. String already overloads it for concatenation, and as I said above, I'd just as soon *not* have this be a subclass of string. 4) Should path expose an iterator for listdir(?) I don't see why not, as long as the path is to a directory. 5) Should == operator be the same as os.path.samefile()? Why not... 6) Path.open()? Of course. 7) Should the various gettime methods return Datetime objects. Of course. 8) Touch method? Of course. 9) Current OS constants? What are they? Are we talking about the four constants in the access() function, or about something else? 10) Commonprefix, walk and sameopenfile? Commonprefix should be a string or list method, it doesn't fit here. walk is a nice function, but it should be redone to use the visitor pattern directly, with different method names for files, directories and whatever else a particular file system has in it's warped little mind. sameopenfile doesn't belong in the os.path module in the first place. It belongs in the os module under 6.1.3 - File Descriptor Operations. 11) rename join and split. I wouldn't bother. Since I'm against making it a subclass of str(), the issue doesn't arise. 12) Should == compare file sizes. No. Might have a method to do that. 13) chdir, chmod, etc? No. This has nothing to do with pathname. 14. Unicode filenames Have to have them on Windows and probably on the Mac. 15. Should files and directories be the same class. Probably not. While they share a lot of common functionality (which should be spelled out as an interface) they also have a lot of dissimilar functionality. Separating them also makes it easy to create objects for things like symbolic links. In addition to this, we should have the ability to update the other times (utime()) directly using another file or directory object as well as a Datetime object. John Roth From swalters_usenet at yahoo.com Sun Jan 11 01:09:39 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 11 Jan 2004 06:09:39 GMT Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: |Thus Spake Lothar Scholz On the now historical date of Fri, 09 Jan 2004 21:29:56 -0800| > Samuel Walters wrote in message > news:... > >> For numerical processing, C is the right tool, > > Definitely not, you don't want a pointer language when using numerical > processing: use Fortran. Hmm. I feel misunderstood. I'm going to try to clarify, but if I'm the one doing the misunderstanding, feel free to give me a good old-fashioned usenet style bitchslapping back to the stone age. First off: Truth in advertising. I know very little about numeric processing, and even less about Fortran. It's true that my background is in mathematics, but in *pure* mathematics where pointer-based languages tend to be helpful, not hurtful. I chose pure mathematics precisely because it eschews the grubby sort of shortcuts that applied mathematics uses. In other words, I didn't have the proper sort of mathematical intuition for it, so I chose pure, where my kind of intuition works well. (In the end, this was to my detriment. All the interesting problems are in applied math!) As I see it, when one considers which language is best for one's needs, one considers a couple of things: 1) Does the language have the semantics I want. 2) Does the language have the primitives I need. 3) Can I *easily* build any missing or suboptimal primitives. One would assume that Fortran has the proper semantics for numerical processing because it seems to have been wildly successful for a long period of time. It would appear that Python has the proper semantics for numerical processing because a significant number of people are using it for that, and they'd be using something else if Python caused them too many headaches. Fortran naturally comes with the primitives for numerical processing, because numerical processing is its stated goal. ("FORmula TRANslation") Python doesn't seem to have the native and optimal primitives for numerical processing, so that leads to point three. Whether one uses Fortran, Python, or any other language, all primitives are eventually implemented in either C or assembly. At some point or another, we end up scraping bare metal and silicon to get our answers. The question then becomes, "How easily can I extend this language to fit my needs." NumPy is evidence that at least a few people said "Easily enough." I don't know how extensible Fortran is, but I would guess "very" since I've heard of it being applied in many domains other than numerical processing. (OpenFirmware, for example.) So, I guess that my point is that C might not be the right language for doing numerical processing, but it seems the right language for implementing the primitives of numerical processing. Those primitives should, of course, be designed in such a manner that their behaviors are not muddied by pointer issues. Moving on: I think Python's strength flows from the three criterion for choosing a language. It's semantics seem to naturally fit the way a programmer thinks about problems. All the algorithmic primitives are there for naturally expressing one's self easily. Where the primitives don't exist, it's easy to bind outside primitives into the system seamlessly. One of the joy's of python is that c extension libraries almost never feel bolted on. They feel like an intimate part of the language itself. Part of that is the blood, sweat and tears of the library implementors, but much of it is also the elegance of Python. As far as the straw-poll goes, I think it's a good question to ask, and that the answer is important, but we also need to figure out where else we can ask this question. The problem with asking such a question solely on c.l.p is that everyone here has either decided that optimization in python isn't enough of an issue to bother them, or hasn't made up their mind yet. Those who have decided that optimization in python is a problem have already gone elsewhere. Perhaps a better question to ask is "Who has decided that Python is too slow for their needs, what prompted that decision and are the issues they had worth addressing?" Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From alan.gauld at btinternet.com Sat Jan 10 04:02:42 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Jan 2004 09:02:42 GMT Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> Message-ID: <3fffbe99.486050433@news.blueyonder.co.uk> On Fri, 9 Jan 2004 10:29:46 GMT, Harry George wrote: > > I'm not sure about others, but when I design and code using test-driven > > development (TDD), I tend not to need to debug almost ever. > told him almost exactly what you said: If you are doing test-based > (whether or not it is with someojne else and thus Agile), you don't > get into those grim debug sessions that are part of life in C/C++ > land. Interesting comments. How do people generally perform these tests then? My primary test tool, for low level testing, is usually the debugger. Batch mode debugging is something I've been doing since I worked on VAX/VMS systems and its seems as natural as breathing to me. Its easy to save a test session and run it later etc. How else do you test code at a low level? Or does using the debugger as a test harness not count as debugging? Alan g Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From latex-bugs at latex-project.org Fri Jan 30 10:24:49 2004 From: latex-bugs at latex-project.org (latex-bugs at latex-project.org) Date: Fri, 30 Jan 2004 16:24:49 +0100 (CET) Subject: hello In-Reply-To: <200401301524.i0UFOSZ4003976@rzdspc1.informatik.uni-hamburg.de> References: <200401301524.i0UFOSZ4003976@rzdspc1.informatik.uni-hamburg.de> Message-ID: <200401301524.i0UFOnKO024228@sun.dante.de> Thank you for your message to latex-bugs at latex-project.org. Sorry, but the latex-bugs email processor cannot handle MIME attachments. Please resend your problem report with the contents of latexbug.msg as the body of your message. -- From skip at pobox.com Wed Jan 14 11:37:42 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 14 Jan 2004 10:37:42 -0600 Subject: Time diff In-Reply-To: <40056c83$1@clarion.carno.net.au> References: <40056c83$1@clarion.carno.net.au> Message-ID: <16389.28758.703030.371512@montanaro.dyndns.org> Steve> I have two time strings: Steve> 2004-01-14 19:17:37, and 2004-01-15 01:45:33 Steve> How can I find out the number of minutes/seconds between the two Steve> times in python? >>> import datetime >>> help(datetime) Help on module datetime: NAME datetime - Fast implementation of the datetime type. FILE /usr/local/lib/python2.3/lib-dynload/datetime.so CLASSES __builtin__.object date datetime time timedelta tzinfo class date(__builtin__.object) | Basic date type. ... or http://www.python.org/dev/doc/devel/lib/module-datetime.html Skip From anton at vredegoor.doge.nl Wed Jan 7 00:44:29 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 07 Jan 2004 06:44:29 +0100 Subject: Iterating over a binary file References: <7xznd04ww1.fsf@ruckus.brouhaha.com> <7xd69wy5zq.fsf@ruckus.brouhaha.com> Message-ID: <3ffb9f21$0$1547$3a628fcd@reader2.nntp.hccnet.nl> Paul Rubin wrote: > Statement Reading difficulty > ========= ================== > > f = file(filename, 'rb') 1 > while len(data := f.read(1024)) > 0: 2 > someobj.update(data) 1 > f.close() 1 > > > Total reading difficulty: 5 In Python it can be done even simpler than in C, by making the "someobj.update" method return the length of the data: #derek.py class X: def update(self,data): #print a chunk and a space print data, return len(data) def test(): x = X() f = file('derek.py','rb') while x.update(f.read(1)): pass f.close() if __name__=='__main__': test() IMHO the generator solution proposed earlier is more natural to some (all?) Python programmers. Anton From ptmcg at users.sourceforge.net Thu Jan 15 12:02:26 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Thu, 15 Jan 2004 17:02:26 GMT Subject: parsing c-code References: Message-ID: "John Benson" wrote in message news:mailman.368.1074113221.12720.python-list at python.org... > I'm currently making my way through Thomas Christopher's Python Programming > Patterns which describes an LL(k) parser generator that might be of help. I > know there are other Python parsing tools out there as well, per Chapter 15 > of the Python Cookbook. > > Message: 4 > Date: Wed, 14 Jan 2004 09:27:55 +0100 > From: "tm" > Subject: Parsing c-code > To: python-list at python.org > Message-ID: > > Hello, > > are there recommended modules for parsing c-code. > I want to read in c-structs and display it in a tree graphic. > > -- > Torsten > If your c-structs aren't too complicated, try this (uses pyparsing, from http://pyparsing.sourceforge.net): from pyparsing import Optional, Word, Literal, Forward, alphas, nums, Group, ZeroOrMore, oneOf, delimitedList, cStyleComment, restOfLine import pprint cstructBNF = None def getCStructBNF(): global cstructBNF if cstructBNF is None: structDecl = Forward() ident = Word( alphas+"_", alphas+nums+"_$" ) integer = Word( nums ) semi = Literal(";").suppress() typeName = ident varName = ident arraySizeSpecifier = integer | ident # <- should really support an expression here, but keep simple for now typeSpec = Optional("unsigned") + oneOf("int long short double char void") bitfieldspec = ":" + arraySizeSpecifier varnamespec = Group( Optional("*", default="") + varName + Optional( bitfieldspec | ( "[" + arraySizeSpecifier + "]" ) ) ) memberDecl = Group( ( typeSpec | typeName ) + Group( delimitedList( varnamespec ) ) + semi ) | structDecl structDecl << Group( "struct" + Optional(ident) + "{" + ZeroOrMore( memberDecl ) + "}" + Optional(varnamespec) + semi ) cstructBNF = structDecl cplusplusLineComment = Literal("//") + restOfLine cstructBNF.ignore( cStyleComment ) # never know where these will crop up! cstructBNF.ignore( cplusplusLineComment ) # or these either return cstructBNF testData1 = """ struct { long a; short b; char c[32]; } a; """ testData2 = """ struct { long a; struct { int x; int y; } pt; // this is an embedded struct struct { int x,y; } pt2; struct { int x; int y; }* coordPtr; /* this is just a pointer to a struct */ short b; char c[32]; char d[MAX_LENGTH /* + 1 to make room for terminating null */ ]; char* name; char *name2; /* no one can agree where the '*' should go */ int bitfield:5; /* this is rare, but not hard to add to parse grammar */ int bitfield2:BIT2LEN; void* otherData; } a; """ for testdata in (testData1, testData2): pprint.pprint( getCStructBNF().parseString(testdata).asList() ) print From achrist at easystreet.com Fri Jan 30 22:01:27 2004 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 30 Jan 2004 19:01:27 -0800 Subject: PEP 327: Decimal Data Type References: <6ltk10h30riel0lghd18t5unjco2g26spi@4ax.com> Message-ID: <401B1A87.639CD971@easystreet.com> Stephen Horne wrote: > > I don't know what the solution should be, but I do think it needs to > be considered. > The C and C++ people have agreed. The next standards for those languages, whenever they come out, are supposed to include decimal floating point as a standard data type. The number of decimal places required is also profuse, something up around 25-30 places, more than current hardware, eg IBM mainframes, supports. If python adds decimal data, it probably ought to be consistent with C and C++. Otherwise, the C and C++ guys will have a dreadful time writing emulation code to run on computers built to support python. Al From glennrp at comcast.net Mon Jan 26 11:20:47 2004 From: glennrp at comcast.net (Glenn Randers-Pehrson) Date: Mon, 26 Jan 2004 11:20:47 -0500 Subject: [GM-apis] JPG - PNG conversion problem In-Reply-To: <971323274247EB44B9A01D0A3B424C85058496FD@FTWMLVEM02.e2k.ad .ge.com> Message-ID: <3.0.6.32.20040126112047.010b69a0@mail.comcast.net> At 08:01 AM 1/26/04 -0600, Raaijmakers, Vincent \(GE Infrastructure\) wrote: >Who can explain the huge increase in size when I convert a JPG into a PNG format using PythonMagick: JPEG offers more effective compression than PNG, when the source is a video or camera image. Glenn From tim at remove_if_not_spam.digitig.co.uk Tue Jan 13 06:46:07 2004 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Tue, 13 Jan 2004 11:46:07 +0000 Subject: Division oddity References: <7xeku5vrn8.fsf@ruckus.brouhaha.com> Message-ID: On 11 Jan 2004 18:15:39 -0800, Paul Rubin wrote: >Tim Rowe writes: >> If I do from __future__ import division then eval(1/2) gives me 0.5 as >> expected. But if I do print input("enter a sum: ") and enter 1/2 as >> the sum I get 0 as if I hadn't done the import. I thought input was >> supposed to give the same behaviour as an eval on raw input -- why the >> difference here? > >The input function is calling eval from the context of the module >where 'input' itself is defined. If you use "from __future__ import >division" in module A and have "print 3/2" in module B, the value of >3/2 in module B shouldn't be affected by the input, since module B >may depend on integer division having the old behavior. That makes sense, thanks. >The result is a little bit surprising at first glance though, so it >should probably be documented. Well, the documentation for "input()" says "Equivalent to eval(raw_input(/prompt/))". Perhaps it should say "/Usually/ equivalent...." From ashleylloyd at hotmail.com Wed Jan 7 05:13:00 2004 From: ashleylloyd at hotmail.com (Ashley Lloyd) Date: Wed, 07 Jan 2004 10:13:00 +0000 Subject: Newbie: Python equivalent to Delphi TTable Message-ID: Hi all, I don't know how many of you are very familiar with Delphi, but we're looking for anything that offers the user a similar kind of interface to an Interbase table as Delphi components TTable, TIBOTable, etc (findkey, etc). If anyone knows of anything allowing us to do this, I'd be grateful. Sorry that this no doubt sounds a little vague, I just can't really explain it any better! TIA Ashley _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From jzgoda at gazeta.usun.pl Wed Jan 14 15:52:10 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 14 Jan 2004 20:52:10 +0000 (UTC) Subject: wxPython worries References: Message-ID: James Goldwater pisze: > The target is Win32 for now (98 - XP). Now, if it were up to me, I'd use > Delphi - it's what I know best. But I'm working with a less experienced > developer with whom I have no languages in common. He's keen to get > started on C#, I've toyed with C# and though it looks easy, I don't see > any major gains over what I already know. I love Delphi but I would choose Python for simplicity, flexibility and library (will not mention that it works on AS/400, the best minicomputer(!) ever made). But I'm rather guerilla guy and mainstream makes me sick. (NP: The Pogues - Sally MacLennane) -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From cygnus at cprogrammer.org Fri Jan 23 13:44:00 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Fri, 23 Jan 2004 13:44:00 -0500 Subject: [OPINION] - does language really matter if they all do the same thing? In-Reply-To: <20040123183127.GA35281@mail.hitmedia.com> References: <20040123183127.GA35281@mail.hitmedia.com> Message-ID: <20040123184400.GA8164@mail.theserver.ath.cx> # Are programming languages like spoken languages, in the sense # that they all say the same things, just using different words? I don't think so. Programming languages affect the way people think about problem solving in different ways. The capacity to solve problems is one of the most important capacities a programmer can expect to have. In addition, it is the responsibility of the programmer to see that some languages are, by virtue of their design, made to solve certain problems in certain ways, under various definitions of program flow, data storage, etc. To suppose that all programming languages are, as you might put it, fundamentally equivalent is to suppose that english and arabic are, in the same sense, just two sides of the same coin, which is a gross oversimplification of the matter and a disrespect to the qualities of the languages that make them distinct. On a more conjectural note, spoken languages are more than just ways of expressing ideas; by virtue of being evolving systems of communication, they serve as an insight into the culture and people that developed them. Programming languages are the same in that respect. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From mark at mceahern.com Sun Jan 18 19:57:45 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 18 Jan 2004 18:57:45 -0600 Subject: How to call a system command with flexibility on Windows In-Reply-To: References: <4aEMb.1798$PK6.17978@nnrp1.uunet.ca> Message-ID: <1074473865.5354.9.camel@dev.internal> On Thu, 2004-01-15 at 20:09, Mark Hammond wrote: > Some, if not all of the popen functions on Windows will return the exit > code of the program when closing the last returned handle. I'm afraid I > have no time to check the docs or find sample code, but it does work :) I believe os.popen does on both cygwin and plain windows; e.g., cmd = 'some command' stdout = os.popen(cmd) print stdout.read() exitCode = stdout.close() if exitCode: print '%s failed, this probably says why:\n%s' % (cmd, stdout) Although I suppose spelling it "stdout" is misleading--doesn't popen return stdout/stderr combined? Cheers, // m From elainejackson7355 at home.com Thu Jan 29 20:05:16 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 30 Jan 2004 01:05:16 GMT Subject: number of arguments a function takes References: Message-ID: I think you're expectations of this are a little high. It's just something I did for amusement while I was drinking my coffee this morning. Anyway, here it is. And yes, I'd be very interested to see your code. Peace (code follows) NEG = lambda A: not A CONJ = lambda *args: False not in args DISJ = lambda *args: True in args IMPL = lambda A,B: (not A) or B EQUIV = lambda A,B: (A and B) or (not A and not B) def truthTable(boolFunct): assignmentList = lambda numArgs: (numArgs==0 and [[]]) or \ reduce(list.__add__,[[X+[False],X+[True]] for X in assignmentList(numArgs-1)]) import inspect numArgs=len(inspect.getargspec(boolFunct)[0]) for assignment in assignmentList(numArgs): print assignment," : ",boolFunct(*assignment) ## EXAMPLE: f = lambda x,y,z: DISJ(CONJ(x,y),NEG(z)) truthTable(f) "Corey Coughlin" wrote in message news:a8623416.0401291606.1fa4de31 at posting.google.com... | "Elaine Jackson" wrote in message news:... | > Exactly what I was looking for. Thank you very much. | > | > "Duncan Booth" wrote in message | > news:Xns947FAE6461014duncanrcpcouk at 127.0.0.1... | > | "Elaine Jackson" wrote in | > | news:CSaSb.329909$ts4.189798 at pd7tw3no: | > | | > | > Suppose one of the arguments of a function f_1 is another function | > | > f_2. Can f_1 access the number of arguments taken by f_2? (I'm | > | > writing a little script to automate the construction of logical | > | > truth-tables.) Thanks. | > | | > | Look at the inspect module, in particular you probably want | > | inspect.getargspec: | > | | > | >>> import inspect | > | >>> def f(a,b): pass | > | > | >>> inspect.getargspec(f) | > (['a', 'b'], None, None, None) | > | >>> help(inspect.getargspec) | > | Help on function getargspec in module inspect: | > | | > | getargspec(func) | > | Get the names and default values of a function's arguments. | > | | > | A tuple of four things is returned: (args, varargs, varkw, defaults). | > | 'args' is a list of the argument names (it may contain nested lists). | > | 'varargs' and 'varkw' are the names of the * and ** arguments or None. | > | 'defaults' is an n-tuple of the default values of the last n arguments. | > | | > | >>> | | So you're working on a truth table program? I have a truth table | object I did for my own application, more focused on finding | input/output transitions in arbitrary truth tables, but if you're | interested, let me know. Regardless, are you working on something | that will ultimately become public? If so, be sure to announce it | when you're done, I'd love to have a look. Especially if you're doing | anything with functional simplification, my object can return a simple | SOP function for a table (reducing out unused inputs is also an | option) but they can get kind of lengthy for complicated functions. | And if you need any other help, be sure to let me know! From theller at python.net Fri Jan 30 09:03:31 2004 From: theller at python.net (Thomas Heller) Date: Fri, 30 Jan 2004 15:03:31 +0100 Subject: Python ODBC Driver Module References: Message-ID: "Mark Buch" writes: > Hi, > > where can i find a freeware python odbc module for windows? win32all contains one. It's named odbc, iirc. Thomas From FBatista at uniFON.com.ar Thu Jan 22 11:46:23 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 22 Jan 2004 13:46:23 -0300 Subject: MySQL interface problem Message-ID: I'm trying to get the warnings from the last 'insert....' sql statement I send to the database and the conn.info() method returns always None. I'm using Python 2.2.3 with _mysql 0.9.2. There's a newer release that do this? Another interface? I'm doing something wrong? Thank you! Facundo Batista Gesti?n de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 mark at mceahern.com Sat Jan 3 16:01:24 2004 From: mark at mceahern.com (Mark McEahern) Date: Sat, 03 Jan 2004 15:01:24 -0600 Subject: importing In-Reply-To: <231bc96c.0401031249.12cff6d7@posting.google.com> References: <231bc96c.0401031249.12cff6d7@posting.google.com> Message-ID: <1073163684.12941.3.camel@dev.internal> On Sat, 2004-01-03 at 14:49, Boomer wrote: > here's the error > > Traceback (innermost last): > File "", line 5, in ? > AttributeError: 'string' object has no attribute 'split' Try this from that program: import sys print sys.version What does it say? // m From miki.tebeka at zoran.com Mon Jan 5 02:07:22 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 4 Jan 2004 23:07:22 -0800 Subject: Python for Embedded Devices? References: <221e7b06.0401041537.2896b22d@posting.google.com> Message-ID: <4f0a9fdb.0401042307.1f6bd4e8@posting.google.com> Hello Phil, > I've looked at Io, Lua, PyMite and Pippy, to name a few, and none are > quite appropriate. Io is perhaps the closest match, if it were > stripped down a lot. Have you looked at tinyscheme? It a full scheme interpreter in one C file. http://tinyscheme.sourceforge.net/home.html > I have been tinkering around with some ideas to make a new language to > fit the environment I deal with. This is slow work, as I haven't a lot > of time to spend on it, and I am not a language design expert, but I'm > having fun with it! Maybe you can work with Fredrik Lundh on Pytte (http://effbot.org/zone/pytte.htm) HTH. Miki From h.b.furuseth at usit.uio.no Mon Jan 5 12:33:35 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 05 Jan 2004 18:33:35 +0100 Subject: Get UID of username References: Message-ID: Florian Lindner wrote: > how can I find out the UID of a username on a linux system? from pwd import getpwnam try: print getpwnam('someuser')[2] except KeyError: pass See . -- Hallvard From donn at drizzle.com Sat Jan 3 23:39:08 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 04 Jan 2004 04:39:08 -0000 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module References: Message-ID: <1073191147.43307@yasure> Quoth "Martin v. Loewis" : ... | Errors should never pass silently. Which reminds me, this is a much stickier problem if you take into account errors that happen _after_ the fork. It can be highly useful to account for them, though. In my own process handling functions, I give myself the option, and the function I nearly always use is the one that raises an exception if the command exits with an error; the value of the error comes from unit 2 (a.k.a. stderr, though of course not actually stderr since it would be foolish to use a file object here instead of a file descriptor.) I haven't looked at the proposed module, would suggest that it be placed on a web page so people can do so conveniently. In my experience, attempts like this (including my own) tend to founder on the inherent complexity of the problem, failing to provide an interface that is simple and obvious enough to be generally useful. Donn Cave, donn at drizzle.com From arjen.dijkstra%no%-%spam% at hccnet.nl Mon Jan 19 13:35:58 2004 From: arjen.dijkstra%no%-%spam% at hccnet.nl (duikboot) Date: Mon, 19 Jan 2004 19:35:58 +0100 Subject: Oracle to Mysql, I'm (still) lost... References: Message-ID: It worked beautiful, thank you. On Mon, 19 Jan 2004 13:44:11 +0100, Marc Boeren wrote: > > Hi, > > instead of > >> cursMy.execute("insert into %s values %s", (tabel, a_oracle)) > > Try: > > sql = "insert into "+ tabel +" values (" > comma = "" > for value in a_oracle: > sql+= comma + "%s" > comma = ", " > sql+= ")" > > or better: > > sql = "insert into %s values (" % tabel > sql+= ", ".join(["%s"] * len(a_oracle)) > sql+= ")" > cursMy.execute(sql, a_oracle) > > which does the same thing. > > Your original sql-statement looked (for the execute call) like it needed two > (sql-style)parameters, when in fact it needs as much parameters as there are > fields in the table. And, the table-name is not an sql-parameter, it is just > something that needs filling in... > > Hope this helps, > > Cheerio, Marc. From mirandacascade at yahoo.com Fri Jan 23 16:29:38 2004 From: mirandacascade at yahoo.com (Miranda Evans) Date: 23 Jan 2004 13:29:38 -0800 Subject: progress bar Message-ID: <59e5b87.0401231329.6e084d6f@posting.google.com> OS: Win2K Python version: 2.2 Seeking references to documentation that discuss how a python script can handle displaying a progress bar. Also, if you are aware of any sample code that illustrates this, I'm interested in looking at that sample code. Are there ways to accomplish this that do not involve using a full-featured GUI toolkit like Tkinter or wxPython or PythonCard? From na Sun Jan 4 20:35:11 2004 From: na (Andrew) Date: Sun, 4 Jan 2004 17:35:11 -0800 Subject: mysql python Newbie Question References: Message-ID: Hi everyone and thank you for replying to my post My question was answered I need the python mysql modules for my program from what I understand I was just interested in building an app that could connect to my server and edit records in my database through a Graphical User Interface As for not knowing sql: I have a good grasp on MySQL although I am not the best I could be I know where to look for the information. Basically I could do the things I needed for my application what my question should have been: how do I connect to a DB server that is not on my computer through python to access my records. from What I understand I need to look at the Python Mysql documentation (If there is any) and build from there If there are any other modules or documentation I need to look at please let me know Thank You Andrew From jl at windsmith.net Fri Jan 16 08:50:08 2004 From: jl at windsmith.net (John Lull) Date: 16 Jan 2004 07:50:08 -0600 Subject: Multithreaded COM server problem... References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com> Message-ID: Mark Hammond wrote (with possible deletions): > John Lull wrote: > > Mark Hammond wrote (with possible > > deletions): > > > > > >>John Lull wrote: > > > > ... > > > >>>Unfortunately, this one has to be a local server since it's providing shared > >>>access to a pool of hardware devices from multiple distributed clients. I've > >>>carefully reviewed chapters 5 & 12, and appendix D, and wasn't able to find > >>>anything addressing threading models in the local server in detail. If I've > >>>missed something, I'd be grateful for any additional hints. > >> > >>The problem is that your client code is not running a message loop. If > >>you change the loop of your client test code to something like: > >> > >>for i in range(delay)*10: > >> time.sleep(0.1) > >> pythoncom.PumpWaitingMessages() > >> > >>It works as you expect. A better choice would probably be > >>win32event.MsgWaitForMultipleObjects, but that depends on what your app > >>really does. > >> > >>Mark. > > > > > > I presume you meant my server code. > > Nope - I meant the client. The server is already running such a loop > thank to localserver.py, which is hosting the object. > > The client code's main (and only) thread is blocked in a system call, > but it appears COM wants it to pump messages so the marshalling magic > happens. I can only speculate why COM needs this to happen in this > trivial case, but COM's rules do state this requirement. Now I'm *really* confused. Perhaps I need to clarify a bit. The sleep() method in my sample server is a perhaps-too-simplified substitute for what the real server is doing. It provides a variety of high-level operations on a piece of hardware. Some of the operations take as long as several dozen seconds, others take a millisecond or so. I need the client to block waiting for completion of each operation, regardless of how long the operation takes. I cannot break one of the long operations up into a series of calls from the client -- it must be implemented as a single call. My example would, perhaps, have been clearer if I'd named the method someLongRunningMethod() instead of sleep(). I've tried doing roughly what you suggested inside my test client, calling PumpWaitingMessages() both before and after each COM operation. That still leaves me with the same basic problem -- inside the server, all of my COM objects are created on the server's main thread, instead of on a separate thread for each client. That leaves all COM operations serialized through that single thread. My test client at the moment looks like this: import sys from pythoncom import PumpWaitingMessages from win32com.client import Dispatch PumpWaitingMessages() app=Dispatch('PyComThreads.Application') PumpWaitingMessages() app.someLongRunningMethod(20) PumpWaitingMessages() If this is not essentially what you meant, could you please let me know? The server is exactly like I had posted originally, except for renaming its sleep() method to someLongRunningMethod(). > That sucks, and is almost certainly a thread-state error. That was my thought. Thanks. Regards, John From tjreedy at udel.edu Tue Jan 27 17:26:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 Jan 2004 17:26:07 -0500 Subject: raw_input - why doesn't prompt go to stderr References: <4016A585.6050109@skynet.be> Message-ID: "Helmut Jarausch" wrote in message news:4016A585.6050109 at skynet.be... > Ofcourse I did the redirection of stdout. Since a program author can easily do so, as has been posted more than once over the years, the question was real. In fact, the addition of '>>ofile' to print statements was intended to make such redirection less common. > And this is very handy. > While testing I don't redirect stdout and so can see the output > immediately. Then I just redirect stdout for a 'production' run. > > Tell me any advantage in raw_input's prompt is going to stdout instead > of stderr? I don't know the ramification of the distinction, expecially across platforms, well enough to answer. I can only reiterate my suggestion, given Python as it is today and will remain for some time, that you print to 'ofile' with default ofile == sys.stdout but with command line or interactive redirection. Terry J. Reedy From guido at python.org Thu Jan 15 10:07:01 2004 From: guido at python.org (Guido van Rossum) Date: Thu, 15 Jan 2004 07:07:01 -0800 Subject: PyCon Reminders (proposal submission ends tonight!) Message-ID: <200401151507.i0FF72J14249@c-24-5-183-134.client.comcast.net> Proposal Submission Deadline: Tonight! -------------------------------------- Tonight at midnight (in *some* timezone :-) is the last time to submit PyCon proposals. http://pycon.org/dc2004/cfp/ Early Bird Registration ----------------------- Deadline for Early Bird Registration: January 31. *** Speakers, don't forget to register!!!!!! *** http://pycon.org/dc2004/register/ Sprint pre-announcement ----------------------- Come a few days early and participate in a coding sprint. Sprints are free (courtesy of the PSF!), and are held from Saturday March 20 through Tuesday March 23 (i.e. the four days leading up to the conference). http://pycon.org/dc2004 . Volunteers ---------- We're looking for volunteers to help run PyCon. http://mail.python.org/mailman/listinfo/pycon-organizers About PyCon ----------- PyCon DC 2004 will be held March 24-26, 2004 in Washington, D.C. Keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). Don't miss any PyCon announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCon with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCon DC 2004 is http://www.pycon.org/ Pictures from last year's PyCon: http://www.python.org/cgi-bin/moinmoin/PyConPhotos I'm looking forward to seeing you all in DC in March!!! --Guido van Rossum (home page: http://www.python.org/~guido/) Open Source Awards: http://builder.com.com/5100-6375_14-5136758.html From tdelaney at avaya.com Sun Jan 11 23:53:58 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 12 Jan 2004 15:53:58 +1100 Subject: exceptions Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01063A94@au3010avexu1.global.avaya.com> > From: Elaine Jackson > > Could someone give me a hint regarding exceptions? > Specifically, how you handle > different exceptions with different blocks of code? All I > know how to do now is > to follow "raise" with a string (and even that is now > deprecated, apparently). http://www.python.org/doc/current/tut/node10.html >From the Python web site: Home Beginners Guide (Documentation) Python for (Non-)Programmers Python Tutorial Tim Delaney From __peter__ at web.de Sat Jan 10 07:05:19 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Jan 2004 13:05:19 +0100 Subject: need help translating a PHP for statement to python References: <7xk740go52.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Python is more verbose than PHP when it comes to stuff like that. marques = """for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { $prd = $q * $y_ar[$y] + $car; $prd -= ($car = intval($prd / 1E7)) * 1E7; if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7; }""" rubin = """x = cx - cy - 1 for y in xrange(cy+1): prd = q * y_ar[y] + car car = int(prd / 1E7) prd -= car * 1E7 x_ar[x] -= prd + bar bar = x_ar[x] < 0 if bar: x_ar[x] += 1E7 x += 1""" if __name__ == "__main__": print "The ultimate verbosity check :-)" print "PHP", len(marques), "characters" print "Python", len(rubin), "characters" Output: The ultimate verbosity check :-) PHP 206 characters Python 205 characters Note that I didn't cheat and let if bar: x_ar[x] += 1E7 spread over two lines, thus deliberately wasting another 8 characters. Peter From EP at zomething.com Thu Jan 22 04:22:11 2004 From: EP at zomething.com (EP) Date: Thu, 22 Jan 2004 01:22:11 -0800 Subject: a curious IDLE Error In-Reply-To: <400f8315.60048965@news.blueyonder.co.uk> References: <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> <8g7u001k257pr6tjl3ng9t7pn3gvbq2328@4ax.com> Message-ID: <5.2.0.9.0.20040122011652.00b7ea80@mail.zomething.com> At 08:02 AM 1/22/2004 +0000, Alan Gauld wrote: >On Wed, 21 Jan 2004 21:50:01 -0800, EP wrote: > > > I opened a new Python shell from the instance of IDLE editor where my > > module was open and tried the raw_input(): > > > > >>> someFile=raw_input("enter: ") > > Traceback (most recent call last): > > File "", line 1, in ? > > someFile=raw_input("enter: ") > > TypeError: 'tuple' object is not callable > > > >This is a long shot but is it possible that you used raw_input as >the name of a variable somewhere. Thus you are trying to call >that variable (which apparently holds a tuple!). > >Try doing a text search for raw_input in your module code. > >Just a thought. I thought it might have been something like that as well, but I checked all my variable names (and I was only importing the string module). The strange behavior was that the module worked, just not in an IDLE shell opened up out of the same instance I created the module in. From aahz at pythoncraft.com Fri Jan 30 21:00:34 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2004 21:00:34 -0500 Subject: Accessing a shared generator from multiple threads. References: <7934d084.0401152058.164a240c@posting.google.com> <400EE6B5.27C6B694@hotmail.com> Message-ID: In article , Jim Jewett wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> >> My point is that I haven't (yet) seen many good use cases for sharing a >> generator between threads, and I'm guessing that many people will try >> using generators inappropriately for problems that really are better >> suited to Queue.Queue. > >A globally unique ID, such as: > > "What filename should I store this page under?" > >The standard library has (several versions of) similar functionality >for temporary filenames. They aren't all threadsafe, they often >enforce the "temporary" aspect, they run into hashing collision >problems eventually, there is no good way to include even approximate >ordering information, etc... > >The fact that these are in the standard library suggests that it is a >common use case. The fact that there are several different versions >each with their own problems suggests that the problem is hard enough >to justify putting a good solution in the library. You've got a good point. All right, I suggest you subscribe to python-dev (if you're not) and bring it up there so we can hash out which location would be best for this functionality. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From candiazoo at comcast.net Tue Jan 27 07:12:52 2004 From: candiazoo at comcast.net (Michael S. Jessop) Date: Tue, 27 Jan 2004 12:12:52 GMT Subject: Seem to be having trouble with Python/Bethon. References: <6a2dnXCsJ60-9Yzd4p2dnA@giganews.com> <1074926701.236022@yasure> <1075053883.217392@yasure> Message-ID: <8BsRb.166146$na.276860@attbi_s04> That IS interesting. :/ Granted my machine was customized to some extent, but it was basically 5.03 Pro, with BONE and OpenTracker and Mail Daemon replacement. I did also install the LibPak. Mike In message <1075053883.217392 at yasure>, "Donn Cave" wrote: > Quoth Michael S. Jessop : > | Rebuilt with Net_Server. Works fine now. > > Thanks, that's interesting. I would not have guessed that the > host network implementation could be a factor in the Python > type/class internals that seemed to be failing for you, so I'm > guessing that when you choose between the two, there are some > other things that come along that have nothing to do with the > network. I'm actually running a BONE system right now, as I > type this, and the Python inheritance works fine - Zeta RC1. > Python+Bethon comes on the CD, but looks like it's the standard > issue software built on 5.03 (and has a problem with the Zeta > internationalization software, crashes on exit after I suppose > it freed something it wasn't supposed to.) > > Donn Cave, donn at drizzle.com From zanesdad at bellsouth.net Mon Jan 19 17:51:47 2004 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 19 Jan 2004 17:51:47 -0500 Subject: Munkware 0.3 In-Reply-To: <400beeb1$1_1@nova.entelchile.net> References: <400beeb1$1_1@nova.entelchile.net> Message-ID: <20040119225147.GA3160@cerberus> * Rodrigo Benenson (rodrigob at elo.utfsm.cl) wrote: > as common, using twistedmatrix.com will ease a lot to you to provide remote > access methods > > rodrigob. > I seriously considered using Twisted (as well as Pyro) as a network interface as opposed to SOAP, REST, Corba or some home-grown protocol, but I really wanted to do 2 things: - create a queueing system that is language independent (so either Corba or some web services interface would be better suited for that), just in case folks who are using the wrong language take a liking to Munkware :-) - I've been hankering for an opportunity to begin work on a RESTish framework and this is as good of a chance as any. If I am pleased with how it turns out, I may distill the REST features out and create a second open source project for it alone. I'm not intimately familiar with Twisted, so it just may be that Twisted has provided wrappers for other languages, but that would still leave the fun of creating my own REST-like framework. Jeremy Jones From klapotec at chello.at Fri Jan 30 13:05:40 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 30 Jan 2004 18:05:40 GMT Subject: HowTo Search in nested lists References: Message-ID: On Fri, 30 Jan 2004 18:11:12 +0100, Florian Lindner wrote: >Hello, >I've two nested lists which are representing a table or matrix. > >A = [1, 2, 3] >B = [4, 5, 6] >C = [7, 8, 9] > >t = [A, B, C] > >print t[0][2] # Prints 3 > >Now I found to search for certain values in a certain column. >For example: column 1, search for 5, return 1, because 5 is found in the >first column of the second element of t > >I hope I could explain what I want. Is there any way to do that except: > >for i in len(t): > if t[i][1] == "phrase": > found = i > break Well, for a structurally similar approach to yours, first let's get rid of len. Python is not [C, Pascal, Basic, Java, whatever], lists can and should be iterated on directly. And let's make a function of it that returns the list(s) (in case you have more than one list fitting your search criteria) containing the searched for value. >>> t = [[1,2,3],[4,5,6],[7,8,9],[2,5,8]] >>> >>> def search_nested_list(nested_list, column, value_to_search_for): ... result = [] ... for lst in nested_list: ... if lst[column] == value_to_search_for: ... result.append(lst) ... return result ... >>> x = search_nested_list(t, 1, 5) >>> x [[4, 5, 6], [2, 5, 8]] If you only want to know whether any of the lists contains the value you look for, without caring which ones, you can instead do it like this: >>> def search_nested_list(nested_list, column, value_to_search_for): ... for lst in nested_list: ... if lst[column] == value_to_search_for: ... return True # or 1 for Python < 2.3 ... >>> x = search_in_nested_list(t, 1, 5) >>> x True Grok it, and then get rid of the unnecessary long names ;-) Or you could of course also do it with a list comprehension: Either: >>> [lst for lst in t if lst[1] == 5] [[4, 5, 6], [2, 5, 8]] Or: >>> [True for x in t if x[1] == 5] [True, True] where the length of the result also tells you how often the result was found. Getting the last example to only return True once for multiple hits and making functions of the list comprehensions is left as an exercise to the reader... -- Christopher From fumanchu at amor.org Wed Jan 21 02:53:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 20 Jan 2004 23:53:09 -0800 Subject: PyTime Object and Application Crashing Message-ID: I wrote: > Ryan Scott wrote: > > When I run a query against an access database and the default > > date for > > my date/time field is 12/30/1899 the application crashes. > > Changing this > > to a different date like 03/03/2003 works. > > AFAICT all dates on or before that date will crash. You have > several options: > > 3. Access the date value as a float, not a PyTime: > > # 12/30/1899, the zero-Date for ADO = 693594 > zeroHour = datetime.date(1899, 12, 30).toordinal() > > if value is None: > return None > else: > aDate, aTime = divmod(float(value), 1) > aDate = datetime.date.fromordinal(int(aDate) + zeroHour) > hour, min = divmod(86400 * aTime, 3600) > min, sec = divmod(min, 60) > aTime = datetime.time(int(hour), int(min), int(sec)) > return datetime.datetime.combine(aDate, aTime) Forgot to add, you can then set Date values using floats, as well: def datetime_out(self, inValue): return self.date_out(inValue) + self.time_out(inValue) def date_out(self, inValue): return inValue.toordinal() - zeroHour def time_out(self, inValue): return float(inValue.second + (inValue.minute * 60) + (inValue.hour * 3600)) / 86400 FuManChu From miki.tebeka at zoran.com Mon Jan 19 02:13:05 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 18 Jan 2004 23:13:05 -0800 Subject: parse binary file in python? References: Message-ID: <4f0a9fdb.0401182313.4c95718c@posting.google.com> Hello Andreas, > I want to parse a binary file in python. Does > python have some built in methods for doing this easily? Apart from struct and array module already suggested if you want specific structures I recommend reading them in C and exposing the interface using swig. This way you can access structure members by name and not by offset. HTH. Miki From usenet_spam at janc.invalid Wed Jan 14 21:03:35 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 15 Jan 2004 02:03:35 GMT Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <87brp7agl7.fsf@pobox.com> <7xvfnfmzy8.fsf@ruckus.brouhaha.com> <878yka2sze.fsf@pobox.com> <100bbekd61fbl53@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) schreef: >>Not sure what the goals were, but I'm not sure they were to compete >>with Netscape and IE. CNRI funding -- "R" for research -- seems to > Certainly not the *original* goal, because Grail antedated those > latecomers. My copy of Netscape 0.94beta for Windows has a file date of 1994-11-22. And from the Grail docs: "Grail was started in August 1995 as a quick and dirty demo. It quickly became a serious project, as witnessed by the release of version 0.2 in November 1995, and again by the planned release of version 0.3 (currently in beta) in June 1996." -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From ep at epoz.org Mon Jan 19 17:41:01 2004 From: ep at epoz.org (Etienne Posthumus) Date: Mon, 19 Jan 2004 23:41:01 +0100 Subject: Munkware 0.3 In-Reply-To: <20040119225147.GA3160@cerberus> References: <400beeb1$1_1@nova.entelchile.net> <20040119225147.GA3160@cerberus> Message-ID: <8EF44562-4AD0-11D8-95EE-0003935458F6@epoz.org> On Jan 19, 2004, at 11:51 PM, Jeremy Jones wrote: > - I've been hankering for an opportunity to begin work on a RESTish > framework > and this is as good of a chance as any. If I am pleased with how it > turns > out, I may distill the REST features out and create a second open > source project > for it alone. If you like toying with REST ideas, have a peek at the Quixote framework [1]. For me it has been the shortest route to going from REST ideas to implementation in Python. But of course you might want to do your own framework for fun/learning. Etienne Posthumus Amsterdam, Nederland [1] http://www.mems-exchange.org/software/quixote/ From LittleDanEhren at yahoo.com Thu Jan 29 17:07:25 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 29 Jan 2004 14:07:25 -0800 Subject: Printing/updating output to the screen References: <40192945$1@nntphost.cis.strath.ac.uk> Message-ID: <711c7390.0401291407.5195a5aa@posting.google.com> Daniel Pryde wrote in message news:<40192945$1 at nntphost.cis.strath.ac.uk>... > Hi there. I hope this isn't a stupid question to ask, but does anyone > know how to print out a string without moving to a new line each time > and simply updating the first line. An example would be, if I wanted to > have a percentage progress counter that was constantly updating. I'm > unsure how to do this without printing to a brand new line. Any help > would be greatly appreciated. Thanks. > > Daniel Put a comma after it. For example: print "hi", This, however, also prints a space. If that's not what you want, do the following: from sys import stdout stdout.write("hi") That won't append a space or a newline. Another Daniel From sera at fhwang.net Wed Jan 21 15:31:19 2004 From: sera at fhwang.net (Francis Hwang) Date: 21 Jan 2004 12:31:19 -0800 Subject: New to Python: my impression v. Perl/Ruby References: Message-ID: <7b561b93.0401211231.5ed33bda@posting.google.com> Ville Vainio wrote in message news:... > Phil> 10.times do something end > > Phil> is somehow so clear. It's almost zenlike. > > It's cute and fun to write, but less cute for people who have to read > lots of such code in short time. I have a soft spot for such style > also; I kinda like Python's "\n".join(["foo","bar"]), even if most > seem to consider it a wart for readability reasons. A lot of this has to do with how you conceptualize objects. In some languages objects are big and heavyweight. So the few things that get to be called Objects are blessed with special powers, and the lowly primitive values are supposed to look up to them with admiration and reverence. In other languages everything can be an object, which means that you have to think of the "object" idea differently. In Ruby integers are objects, but there's a lot of syntactic sugar to make that happen. After all, 10.times do something end is basically just fancy talk for for (i = 0; i < 10; i++ ) { something } or whatever you think should be more explicit. This method might break your conceptual model of what an object is, depending on which model you like. Personally, I love the Fixnum#times method, since it means I never make fence-post errors anymore. More time for interesting problems, less time spent on tediously stepping through code one iteration at a time. And if my conceptual model is getting in the way of my ability to write error-free code, then it's the conceptual model that has to change. Besides, once a language is Turing-complete, everything else is syntactic sugar. So you might as well get the best syntactic sugar you can get ... Francis From godoy at ieee.org Thu Jan 15 08:17:45 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 15 Jan 2004 11:17:45 -0200 Subject: wxwindows question References: Message-ID: On Tuesday 13 January 2004 21:55 Nuff Said wrote in : > wxpython is fine (actually: *very fine* :-) for Windows > applications, but I would not use it for cross-platform > development, because it is not stable enough on Linux. > > (Even some of the widgets in the wxpython demo crash on Linux; > and if you use wxpython with Unicode support, the situation gets > even worse. This might change in the near future, but right now, > wxpython is not stable enough on Linux IMHO.) Which ones? And in which version of wxPython + wxGTK + Python? I develop on Linux and run software on Linux and Windows. I don't have crashes on any of those systems. Those applications are used a lot to get reports from production of hundreds of employees in one company (input data, request reports and graphics, etc.) --- this one runs Windows --- and to track trucks with cutted trees in another company (also input of data, position of trucks, driver's name, vehicle license, government authorizations, etc.) --- this one runs Linux. Each case is a case. Works for me. Be seeing you, -- Godoy. From lbates at swamisoft.com Fri Jan 23 10:34:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 23 Jan 2004 09:34:51 -0600 Subject: file open problem References: Message-ID: <5bmdnRKHZpKHoozdRVn-sQ@comcast.com> It is just a guess but pytest.txt doesn't appear to exist in c:\temp directory on the laptop. Double check for the existence of this file. -Larry "Neil MacGaffey" wrote in message news:mailman.692.1074868692.12720.python-list at python.org... > Hi - I'm new to python and am stymied by something > that should be simple. The file open command below > works fine on my desktop machine, but I cant get it to > work on my laptop. Since using Python on my laptop is > realistically the only way I'm going to find the time > to learn Python, this is a big problem for me. Here's > what I'm up against: > > PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond > (mhammond at skippinet.com.au) - see > 'Help/About PythonWin' for further copyright > information. > >>> fobj = open(r'c:\temp\pytest.txt','r') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: > 'c:\\temp\\pytest.txt' > > The laptop is a Sony VIAO that's about 2 years old. > Its running Windows 2000, SP4. The desktop is an > older machine, but with the same Windows environment. > I've obtained a fresh download of Python 2.3.3 and the > Win32 extension and have re-installed both a couple of > times with no apparent problems. I also tried > dropping back to Python 2.3.2, but had same result. > Any ideas as to what I should be looking at on this > laptop that might be causing the problem? > > Thank you > Neil > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. Try it! > http://webhosting.yahoo.com/ps/sb/ > From kramb64 at hotmail.com Thu Jan 22 04:55:25 2004 From: kramb64 at hotmail.com (Kramb) Date: Thu, 22 Jan 2004 10:55:25 +0100 Subject: shelve slow in python 2.3.3 for windows References: <322u00ppo44l8g003dgtcu8lna432to411@4ax.com> Message-ID: <456v00hma5e5afsmujntins8basrfgotg3@4ax.com> On Wed, 21 Jan 2004 18:37:17 -0600, Skip Montanaro wrote: >'dbhash' and 'bsddb185' are really the same beast. > > Marco> Now the question is: is it possible to use bsddb185 with python > Marco> 2.3.3? > >You're barking up the wrong tree. That's not the problem. So you're telling me that dbhash (namely /python2.3/DLLs/_bsddp.pyd) on python 2.3.3 for Windows has a problem? From kbk at shore.net Sat Jan 31 19:09:52 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: 31 Jan 2004 16:09:52 -0800 Subject: quick question about IDLE References: Message-ID: <76f21d50.0401311609.5cc86b54@posting.google.com> "Elaine Jackson" wrote in message news:... > I've noticed that the menu in IDLE sometimes has an item called "Shell" with a > submenu that offers the opportunity to "Restart Shell". But at other times > "Shell" isn't there. Can anybody clue me in about this? TIA. The Shell window has this, and the Edit windows don't. -- KBK From tjreedy at udel.edu Wed Jan 28 15:10:39 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Jan 2004 15:10:39 -0500 Subject: Nested lists or conditional logic? References: Message-ID: "mike beck" wrote in message news:ead93a6.0401280956.41fd4193 at posting.google.com... > this is not all complex, but as a noob i'm having a hard time getting > my head around it. > > i have a list of items. i need to print the items in batches of x, > with a summary line after each complete or partial batch, and a total > line at the end of the job. > i've done the following, which works, but it seems like there must be > a better/simpler/faster way to do this with nested loops. ideas? The awkwardness is inherent in having non-0 remainders. An explicit counter strikes me as both simple and fast. Maybe because what you did is exactly the way I have done similar things. But I would probably make print_summary a function to avoid duplicating code in two places. Terry J. Reedy From timj at 914fan.net Sat Jan 31 17:22:39 2004 From: timj at 914fan.net (Tim Jones) Date: 31 Jan 2004 14:22:39 -0800 Subject: Pack parent control in child using control.pack(in_= syntax? Message-ID: I've a parent class the generates a menu as in: self.tm.menu = Menubutton(self.main, relief=RAISED, width=20, bd=0, bg='#ECECEC') ... I can then pack this menu (self.tm) into the current parent window/frame and it appears as expected. However, if I call another class - tool_panel(self) and then try to post the tm menu into a frame (tf) using pack(in_=tf, side=RIGHT, anchor=NE) - the menu takes up space, but doesn't appear. I can see this because when I pack the icon logo without the menu, the logo is centered in the new frame. With the menu included, the icon logo is shifted left. Thoughts or guidance will be greatly appreciated. Tim ------------ Here's my menu creation code in the parent class: self.tm = Menubutton(relief='raised', width=20, bd=0, bg='#ECECEC') self.tm.menu = Menu(self.tm, tearoff=0, title='Tool Option') self.tm['menu'] = self.tm.menu I set up the call to the tool_panel with a call: self.tool_panel = tool_panel(self) Here's the actual tool_panel that I wish to pack into (imported from another source file called panels.py with 'from panels import *'): class tool_panel(panel): def __init__(self, parent): panel.__init__(self, parent) tf = Frame(self.main) self.parent.tm.pack(in_=tf, side=RIGHT) self.logo = PhotoImage(data=images.icon) Label(tf, image=self.logo).pack(side=TOP) tf.pack(side=BOTTOM, fill=BOTH, expand=1) return def display(self): self.display0() return pass From james at logicalprogression.net Wed Jan 28 09:39:33 2004 From: james at logicalprogression.net (James Henderson) Date: Wed, 28 Jan 2004 14:39:33 +0000 Subject: r prefix bug ... or my lack of understanding? In-Reply-To: References: Message-ID: <200401281439.33421.james@logicalprogression.net> On Wednesday 28 January 2004 2:27 pm, Bill Sneddon wrote: > Below is from python 2.3.3 on windows. > I have tryed on Pythonwin and Idle and on > a Solaris unix build 2.2.2. > > I know there are work arounds but the behavior > seems a bit strange to me. > > >>> path = r'c:\data' #this is fine > >>> print path > > c:\data > > >>> path = r'c:\data\' > > Traceback ( File "", line 1 > path = r'c:\data\' > ^ > SyntaxError: EOL while scanning single-quoted string Your second backslash is escaping the closing quotation mark. > >>> path = r'c:\data\\' > >>> print path > > c:\data\\ Try this (with no "r": >>> print 'c:\\data\\' c:\data\ James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ http://sourceforge.net/projects/mailmanager/ From grahamd at dscpl.com.au Sat Jan 10 17:34:27 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 10 Jan 2004 14:34:27 -0800 Subject: xml-rpc References: Message-ID: Skip Montanaro wrote in message news:... > Walt> Curious about why the same very simple xml-rpc demo code should > Walt> execute quickly under python2.1 but very slowly under python2.3 > > Walt> python2.1 ~4 seconds > Walt> python2.3 ~24 seconds on the same machine > > Walt> Is there a well known reason for the difference? > > Nope. I tweaked your script to contact my XML-RPC server over the net > (about 20-30ms ping times between client and server) and just make > server.echo() calls. It took between 1.6 and 2.5 seconds real time running > python 2.4a0 (aka CVS) on the client and 2.2.3 on the server. Note that the > server is in production, so the different times were probably due to > transient server load. Any difference in speed between different versions of Python can sometimes be accounted for by there not being sgmlop or expat modules installed with the slower version of Python. But then, if the data set going back and forth is small, this shouldn't really be the case. Still worthwhile to keep in mind later on if the amount of data does increase. From phleum_nospam at chello.se Sat Jan 3 10:35:33 2004 From: phleum_nospam at chello.se (Carl) Date: Sat, 03 Jan 2004 16:35:33 +0100 Subject: Python as a numerical prototyping language. References: <67n0966wsz.fsf@aster.homelinux.net> Message-ID: Johannes.Nix at web.de wrote: > In my eyes, what Python, and Open Source in general, is still lacking > is an very easy, fast and very high-quality library for scientific and > financial plotting, although there are lots of good and thougthful > beginnings like Gnuplot, OpenDX, and many more. This would be an > essential building block to foster the use of Python in science. I agree! I use Gnuplot, it works OK, but is not perfect. I am also not that enthusiastic about the algebra syntax of the Numerics module. I wish it was closer to the Matlab syntax, which is much easier to grasp. Python + Numeric + pygsl + FFTW + ... is, according to my view, a very good alternative to using Matlab, Scilab, or R. What is missing is a large, rich scientific library, and a better syntax for manipulating matrices and vectors. On the other hand, what Python has got is an enormous amount of modules for doing almost anything. For instance, there are Python libraries for reading and writing to databases and building interfaces (very important for building industry strength applications). So, if only Python had a very large, rich, and fast library for numerical calculations and scientific plotting I would be as happy as one can be. I have used Matlab, Scilab, and R for quite some time. The last year, however, I have started to use Python more and more. I wonder why? My guess is that Python already is a viable environment for doing explorative data analyses and testing numerical algorithms. When it comes to speed, I feel that Python + Numeric is up to the task. For example, I have been playing around with Monte Carlo simulation using list, dictionaries, an numerical vectors and matrices as much as possible, and have experienced performance very close to comparable code in C. Carl From aahz at pythoncraft.com Sun Jan 25 10:14:10 2004 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2004 10:14:10 -0500 Subject: [OPINION] - does language really matter if they all do the samething? References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <58587302-4E30-11D8-8FAB-0003934ACDEC@zdome.net> <4012FEB1.5000106@prescod.net> Message-ID: In article , Dietrich Epp wrote: >On Jan 24, 2004, at 3:24 PM, Paul Prescod wrote: >> >> function random_sword_magic_power(quality): >> return choose_random_assoc( >> selector = (quality, (poor, medium, good)), >> properties = { (5, 0, 0): glows_in_the_dark(), >> (3, 3, 0): magically_silent(), >> (1, 5, 1): elemental_power( >> choice([earth, water, air, fire]) >> (0, 2, 4): magical_keen_edge(), >> (0, 0, 2): ????} >> >> I don't follow what you are doing with the last line so I didn't >> duplicate it. > >The last line recursively calls random_sword_magic_power() twice and >concatenates the results. It's something that I used a lot in this >program, which I originally wrote in Python, but I was completely >baffled trying to implement this part. The reason you can't do it with >a dict or list in Python is that the list is always evaluated, and >recurses infinitely. A dict isn't appropriate because there would be >duplicate keys. Think of it as three tables collapsed into one, the >'poor', 'medium', and 'good' tables, where the relative probabilities >for each table fall on a different column. Well, choose_random_assoc() needs to dispatch on functions rather than values. That will recurse only one level, and only in choose_random_assoc(). You'll also need to identify tuples in order to pass in values. Here's a rewrite of Paul's function that shows roughly what you need to do: function random_sword_magic_power(quality): return choose_random_assoc( selector = (quality, (poor, medium, good)), properties = { (5, 0, 0): glows_in_the_dark, (3, 3, 0): magically_silent, (1, 5, 1): (elemental_power, choice([earth, water, air, fire]), (0, 2, 4): magical_keen_edge, (0, 0, 2): ((random_sword_magic_power, medium), (random_sword_magic_power, medium)), } Quite frankly, though, for this kind of application, I probably would choose to write a domain-specific language (more precisely, a "smart" config file format). That would make it easier for someone who wasn't a programmer to add functionality. As I said earlier, I don't think the fact that Lisp makes it easy to directly express this idiom makes up for its other faults. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From garabik-news-2002-02 at kassiopeia.juls.savba.sk Fri Jan 16 05:52:06 2004 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 16 Jan 2004 10:52:06 GMT Subject: ANNOUNE: pyeve-0.1 Message-ID: pyeve is a simple quickhack-ish utility in python reacting to special keys (found mostly on notebooks). Primary goal was to enable soundcard volume control via those special Fn-keys, working not only in X11, but also on text console. It works with linux kernel 2.6.* with evdev input interface, equally well on console as in X11. URL: http://kassiopeia.juls.savba.sk/~garabik/software/pyeve/ Licence: GPL -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From __peter__ at web.de Fri Jan 16 04:59:54 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Jan 2004 10:59:54 +0100 Subject: Redefining __call__ in an instance References: <73b00f0c.0401151529.676347b6@posting.google.com> Message-ID: Robert Ferrell wrote: > I have a question about assigning __call__ to an instance to make that > instance callable. I know there has been quite a bit of discussion > about this, and I've read all I can find, but I'm still confused. > > I'd like to have a factory class that takes a string argument and returns > the appropriate factory method based on that string. I'd like the > instances to be callable. Like this: > > fact = Factory('SomeThing') > aSomeThing = fact(some args) > > anotherFact = Factory('SomeThingElse') > anotherThing = anotherFact(some other args) I think fact and anotherFact could be methods instead of classes, e. g. fact = Factory("SomeThing").someMethod # see complete example below # Here's something that should meet your specs: class Factory: def __init__(self, times=1, *args): self.times=times def something(self, a1="alpha",*args): print "something" return a1*self.times def somethingElse(self, a1="beta", *args): print "something else" return a1*self.times def factory(what, *initargs): """ factory with one instance per call """ return getattr(Factory(*initargs), what) f1 = factory("something") f2 = factory("somethingElse", 2) for f in (f1, f2): print "%s() --> %s" % (f.__name__, f()) > The way I thought to do this was to assign the __call__ attribute of > the fact instance to the appropriate factory method in __init__. That > does not > work, as many others have pointed out. I know there are workarounds. > The appended code shows the variants I know of. I can use one of > them, but they are not quite what I am looking for. > > Have I missed the key message that explains how to make new-style > classes callable, with the called method unique to each instance? Why not be generous and make a dedicated (sub)class for each kind of call? Every instance of a subclass of Callable is just a stateful function. # Here's what I would prefer: class Callable: def __init__(self, times=1, *args): self.times=times class MoreCallable(Callable): def __call__(self, a1="gamma",*args): print "more" return a1*self.times class OrLessCallable(Callable): def __call__(self, a1="delta",*args): print "or less" return a1*self.times # a bare bones registry _callables = { "more": MoreCallable, "less": OrLessCallable } def factory(what, *initargs): # a variant that uses Callable instances # instead of classes could easily be devised return _callables[what](*initargs) for f in (factory("more"), factory("less", 3)): print "%s() --> %s" % (f.__class__.__name__, f()) Both variants respect default arguments. Peter From jjl at pobox.com Fri Jan 9 09:28:35 2004 From: jjl at pobox.com (John J Lee) Date: Fri, 9 Jan 2004 14:28:35 +0000 (GMT) Subject: win32: internet explorer automation problem In-Reply-To: References: Message-ID: On Fri, 9 Jan 2004, [iso-8859-2] Micha? ?yli?ski wrote: > > > It just 'watches' the MSIE behaviour and > > > simulates the user work. > > > > And...? [...] > document.window[window_index or whatever]... It seems like javascript > extends the IHTMLDocument object model. Well, it's got to be in there somewhere (not necessarily IHTMLDocument -- there are a bunch of interfaces whose names I don't remember). John From eric.brunel at N0SP4M.com Mon Jan 19 04:10:18 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 19 Jan 2004 10:10:18 +0100 Subject: What's the best Python freeze tool? References: Message-ID: Nick wrote: > I've tried a couple of Python freeze tool. But encountered some bugs. > Anyone know what's the most mature Python Freeze tool? Thanks. I'm working with McMillan Installer and didn't see any major bug. Note however I'm still using Python 2.1 and Installer 5b5_5. There is apparently a new Installer version (6 something - not yet "official"), but I don't know if it correctly supports Python 2.3 now; I'm quite interested in hearing other users' experiences, BTW... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From arjen.dijkstraNoSpam at hccnet.nl Wed Jan 14 11:24:53 2004 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Wed, 14 Jan 2004 17:24:53 +0100 Subject: Oracle to Mysql (dates) Help please References: <4003b6e7$0$142$e4fe514c@dreader4.news.xs4all.nl> <40051543$0$137$e4fe514c@dreader11.news.xs4all.nl> Message-ID: <40056d5f$0$15165$e4fe514c@dreader14.news.xs4all.nl> Thank you all very much for your help. I'll think it will work now (don't know yet, I'll work on it later this week) Cheers Arjen (If you're interested, I will post the solution that worked for me) From ville.spamstermeister.vainio at thisisspamprotectiontut.finland Thu Jan 22 05:40:30 2004 From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio) Date: 22 Jan 2004 12:40:30 +0200 Subject: Nokia prefers Python References: <%pLPb.214668$X%5.181901@pd7tw2no> Message-ID: >>>>> "Parzival" == Parzival writes: Parzival> With 1.3 million developers, Nokia should REALLY raise Parzival> the Python profile. Guido may have to move again. I dream of the time when Appendix C of a Cell phone manual contains an abridged Python tutorial :-). In the meantime, Python will be a great tool for us who work on Symbian OS - especially if wrapping of Symbian OS apis via swig/equivalent works out alright. We could prototype the cell phone apps in Python and later on port them to C++... Not to mention how much that would improve unit testing. *drool* -- Ville Vainio http://tinyurl.com/2prnb From mwh at python.net Fri Jan 23 06:19:20 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 23 Jan 2004 11:19:20 GMT Subject: Simple way of turning -DNDEBUG off in distutils References: <5eb8fb88.0401221141.35549e53@posting.google.com> Message-ID: rick_muller at yahoo.com (Rick Muller) writes: > Is there a simple way of toggling the -DNDEBUG flag in the distutils > builds? I just realized that all of my assert statements were being > skipped because by default the distutils put in -DNDEBUG. Well, one way is to build against a debug build of Python. There might be some other way, but I don't know it... Cheers, mwh -- The PROPER way to handle HTML postings is to cancel the article, then hire a hitman to kill the poster, his wife and kids, and fuck his dog and smash his computer into little bits. Anything more is just extremism. -- Paul Tomblin, asr From philh at invalid.email.address Sat Jan 3 04:52:59 2004 From: philh at invalid.email.address (phil hunt) Date: Sat, 3 Jan 2004 09:52:59 +0000 Subject: Text-to-HTML processing program References: <7xwu89pnan.fsf@ruckus.brouhaha.com> Message-ID: On 02 Jan 2004 22:18:56 -0800, Paul Rubin wrote: >philh at invalid.email.address (phil hunt) writes: >> Does anyone know of a text-to-HTML processing program, ideally >> written in Python because I'll probably be wanting to make small >> modifications to it, which is simple and straightforward to use >> and which uses a simple markup language (something like Wikipedia >> markup would be ideal)? > >I really wish Wikipedia, BBCodes, and all that would just use regular >HTML instead of continually inventing new "simplified" markup codes >for users to remember. The one thing they do that's useful is convert >blank lines to

. Wikipedia markup is significantly easier to use than HTML. Compare: This is a ''list'': * A list * [http://www.cabalamat.org/ my website] * [http://slashdot.org/ Slashdot] With:

This is a list:

-- "It's easier to find people online who openly support the KKK than people who openly support the RIAA" -- comment on Wikipedia (Email: , but first subtract 275 and reverse the last two letters). From swalters_usenet at yahoo.com Mon Jan 12 15:19:59 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Mon, 12 Jan 2004 20:19:59 GMT Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: |Thus Spake Bicho Verde On the now historical date of Mon, 12 Jan 2004 13:05:19 +0000| > I have now free time and money to do what I want :-) Go to the Bahamas. You'll enjoy it more. [chop] > Anyone would help me and give me some hints? Here's my two cents on which languages to learn, why and in what order. Python: Python is probably the best language from which to branch out to other languages. If you learn it well, you will have all the major concepts of programming as part of your mental toolkit. Luckily, Python's learning curve is not at all steep, there's a great and wonderful community that gladly answers questions and helps you through the confusing parts. As a bonus, you'll find that it's terribly, dastardly useful. C: In my opinion, this is where a student should move next. At some point or another, every serious programmer has to dig into some C code. It's important to learn C before C++ because many of the conveniences of C++ make one lazy about learning C. Because of it's vast popularity, you can often find resources that give algorithms and outlines of processes in C, and those ideas can then be applied to your language of choice. Be sure to investigate linked lists, trees, hashing and memory allocation methods and other such "not quite basic" constructs in C. From those, you will understand a lot more of what goes on behind the scenes in other languages. C++: If you've learned C, It's good to move onto C++ if only for the sake of completeness. When I first learned C++, I was completely enamored of it, but that crush has since died. It's important in GUI based applications and gives you a fair grounding in Object Oriented programming. I strongly recommend Bruce Eckel's "Thinking in C++" as a guide to the language *after* you've gotten the basics down. It is available for free online, but I'm glad I bought the dead tree version of it. There is some debate as to how useful C++ is, but I think it's at least useful enough to take some time learning well. Lisp/Scheme: Lisp and Scheme are two languages that people claim will give you Jedi-like powers as a programmer. I'm learning them right now, so I can't give you advice on why one would learn them. I'm learning Scheme first, because there seem to be many more introductory tutorials and a lot of advice that one should learn Scheme, then move to Common Lisp. YMMV. If you like AI, at some point you will run across Lisp code, so it should be of particular interest to you. In short, the consensus is that Lisp, like milk, does a body good. It is my philosophy that one should at least learn enough of a lot of languages that you can at least browse some code without feeling lost. Each new language gives you some new ideas that make you better at other languages. What follows is the minimum I would suggest you familiarize yourself with. Sed/Awk/Bash shell Scripting: Sed, Awk and bash shell scripting get tossed around enough that you should be able to read them. Sed and Awk are confusing at first, and take some measure of work to develop even a minimum competency in. Don't give up easily here. It pays off in the long run. Perl: I don't like perl, but you shouldn't judge a language on my opinion of it. Perl is very popular and is worthy understanding the basics of. Even if you don't like it, learn enough of it to read programs written in it. It is a very important language. Perl is easier to learn once you have mastered Sed and Awk. (and vice versa) In many ways Perl is a souped up combination of the two languages that's been imbued with mutant super-powers. Java: Once you have learned C++, it's almost trivial to learn Java. The hardest part is keeping separate in your head what applies to C++ and what applies to Java. Besides, it's not a bad thing to be able to put on your resume. C# and .Net: I fear that C# is just another Microsoft misadventure, but for now it's worth gaining a cursory knowledge of. If nothing else, it's a buzzword compliant way to build your resume. Though, Microsoft can be a tricky devil, so think carefully before you bank a career on something they control. PHP: PHP has it's fair share of warts, but reading a couple of books on it gives you a strong grounding in the issues a dynamic web-based application faces. Assembly: Research carefully, and find a good book on assembly language programming. Spend some time wrestling with it. It's hard and confusing. You may never again touch a lick of assembly in your life, but you will always be glad for the knowledge it gave you. Assembly is more of a long term project than any of the other languages I've mentioned, so go slow here. And always remember: Programming is not a spectator sport. Close the book often and try to write code from memory. HTH Good Luck! Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From ed_zeng at yahoo.com Fri Jan 23 16:46:24 2004 From: ed_zeng at yahoo.com (ex laguna) Date: 23 Jan 2004 13:46:24 -0800 Subject: py2exe with shelve error Message-ID: <53ab57.0401231346.1696247f@posting.google.com> I have run into this problem below with py2exe version 0.5.0 and python 2.3.3. Does anyone know a solution or workaround for this? Thanks much! ## Begin of test.py import shelve f = shelve.open('test.txt') f['hello'] = 'world' f.close() f = shelve.open('test.txt') print f.keys() print f.values() f.close() ## End of test.py ## Begin of setup.py from distutils.core import setup import py2exe setup(console=["test.py"]) ## End of setup.py c:\Python>python -V Python 2.3.3 c:\Python>python test.py ['hello'] ['world'] c:\Python>python setup.py py2exe running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension '_sre' creating python loader for extension 'datetime' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** skipping byte-compilation of C:\Program Files\Python23\lib\__future__.py to __future__.pyc skipping byte-compilation of C:\Program Files\Python23\lib\copy_reg.py to copy_reg.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_compile.py to sre_compile.pyc skipping byte-compilation of C:\Program Files\Python23\lib\locale.py to locale.pyc byte-compiling c:\Python\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc skipping byte-compilation of C:\Program Files\Python23\lib\unittest.py to unittest.pyc skipping byte-compilation of C:\Program Files\Python23\lib\macpath.py to macpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\popen2.py to popen2.pyc skipping byte-compilation of C:\Program Files\Python23\lib\stat.py to stat.pyc byte-compiling c:\Python\build\bdist.win32\winexe\temp\datetime.py to datetime.pyc skipping byte-compilation of C:\Program Files\Python23\lib\atexit.py to atexit.pyc skipping byte-compilation of C:\Program Files\Python23\lib\whichdb.py to whichdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\cmd.py to cmd.pyc skipping byte-compilation of C:\Program Files\Python23\lib\os2emxpath.py to os2emxpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\tempfile.py to tempfile.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pprint.py to pprint.pyc skipping byte-compilation of C:\Program Files\Python23\lib\_strptime.py to _strptime.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_constants.py to sre_constants.pyc skipping byte-compilation of C:\Program Files\Python23\lib\re.py to re.pyc skipping byte-compilation of C:\Program Files\Python23\lib\ntpath.py to ntpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\tokenize.py to tokenize.pyc skipping byte-compilation of C:\Program Files\Python23\lib\getopt.py to getopt.pyc skipping byte-compilation of C:\Program Files\Python23\lib\doctest.py to doctest.pyc skipping byte-compilation of C:\Program Files\Python23\lib\random.py to random.pyc skipping byte-compilation of C:\Program Files\Python23\lib\string.py to string.pyc skipping byte-compilation of C:\Program Files\Python23\lib\warnings.py to warnings.pyc skipping byte-compilation of C:\Program Files\Python23\lib\UserDict.py to UserDict.pyc skipping byte-compilation of C:\Program Files\Python23\lib\inspect.py to inspect.pyc skipping byte-compilation of C:\Program Files\Python23\lib\repr.py to repr.pyc skipping byte-compilation of C:\Program Files\Python23\lib\traceback.py to traceback.pyc skipping byte-compilation of C:\Program Files\Python23\lib\copy.py to copy.pyc skipping byte-compilation of C:\Program Files\Python23\lib\bdb.py to bdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\types.py to types.pyc skipping byte-compilation of C:\Program Files\Python23\lib\anydbm.py to anydbm.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre.py to sre.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pickle.py to pickle.pyc skipping byte-compilation of C:\Program Files\Python23\lib\StringIO.py to StringIO.pyc skipping byte-compilation of C:\Program Files\Python23\lib\pdb.py to pdb.pyc skipping byte-compilation of C:\Program Files\Python23\lib\linecache.py to linecache.pyc skipping byte-compilation of C:\Program Files\Python23\lib\token.py to token.pyc skipping byte-compilation of C:\Program Files\Python23\lib\dummy_thread.py to dummy_thread.pyc skipping byte-compilation of C:\Program Files\Python23\lib\opcode.py to opcode.pyc skipping byte-compilation of C:\Program Files\Python23\lib\posixpath.py to posixpath.pyc skipping byte-compilation of C:\Program Files\Python23\lib\calendar.py to calendar.pyc skipping byte-compilation of C:\Program Files\Python23\lib\shelve.py to shelve.pyc skipping byte-compilation of C:\Program Files\Python23\lib\sre_parse.py to sre_parse.pyc skipping byte-compilation of C:\Program Files\Python23\lib\os.py to os.pyc skipping byte-compilation of C:\Program Files\Python23\lib\dis.py to dis.pyc *** copy extensions *** *** copy dlls *** copying C:\Program Files\Python23\Lib\site-packages\py2exe\run.exe -> c:\Python\dist\test.exe c:\Python>cd dist c:\Python\dist>test.exe Traceback (most recent call last): File "test.py", line 3, in ? File "shelve.pyc", line 231, in open File "shelve.pyc", line 211, in __init__ File "anydbm.pyc", line 62, in ? ImportError: no dbm clone found; tried ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute'writeback'" in ignored c:\Python\dist> From skip at pobox.com Tue Jan 6 11:21:45 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 6 Jan 2004 10:21:45 -0600 Subject: Speed? In-Reply-To: <3FFABBA8.3A24716F@engcorp.com> References: <3FFABBA8.3A24716F@engcorp.com> Message-ID: <16378.57497.208914.583823@montanaro.dyndns.org> [ on creating benchmarks ] Peter> And with Python, of course, it's almost trivial to do this kind Peter> of thing, compared to some other languages. Sigh. Which was just another data point in your decision, right? After all, if Python is so much easier to write your benchmarks in than some/most/all of the alternatives, that has to factor into the choice of implementation language. Skip From vmontressor at yahoo.com Sun Jan 11 11:52:57 2004 From: vmontressor at yahoo.com (Vincent Montressor) Date: 11 Jan 2004 08:52:57 -0800 Subject: Restoring my own PyGNOME panel applets under GNOME 1.4 Message-ID: <88fe7467.0401110852.5480a822@posting.google.com> I'm playing around with writing my own panel applets, and I'm trying to figure out how to get my panel applets to be restored when I log in. As an experiment, I'm using the simple clock applet that comes with PyGNOME (clock-applet.py). It works fine when I run it from the shell, but when I log out and log in again, there's just a tiny GNOME-foot icon where the applet should be. After poking around in ~/.gnome/panel.d, I think I've figured out that the panel knows there should be an applet in that spot, but there's nothing telling it what executable to run to put the applet there. Do I somehow need to create that mapping, or is the problem something else altogether? Applets I add to the panel through the normal process (right-click -> Applets -> ...) are restored when I log in, as expected. I'm using GNOME 1.4 on Red Hat 7.3 (sorry, but this is a work system, and I can't upgrade; I also can't put my code where the system applets are). Thanks for any help you can offer. From claird at lairds.com Mon Jan 12 20:06:49 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 13 Jan 2004 01:06:49 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> Message-ID: <1006h59mr5qu11e@corp.supernews.com> In article , Donn Cave wrote: . . . >If so, that might be a good direction for yet another book about >Python. > > Donn Cave, donn at u.washington.edu I sure think so; if only I were a man of leisure, writing *Programming in the Large with Python* would be verrrrrry tempting. -- Cameron Laird Business: http://www.Phaseit.net From richardshea at fastmail.fm Mon Jan 12 22:07:02 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 12 Jan 2004 19:07:02 -0800 Subject: Accessing "GIS (ESRI shape file)" files from Python ? Message-ID: <282f826a.0401121907.498543e6@posting.google.com> Hi - As usual having Python is making me consider doing things I wouldn't normally ! I've come across some files described as "GIS version (ESRI shape file)" which consitute an electronic map of the Wellington, New Zealand. There are six files in the package : suburbs.shx suburbs.prj suburbs.sbn suburbs.sbx suburbs.shp suburbs.shp.xml suburbs.dbf Can anyone tell me - is there, freely available, existing software accessible from Python which would allow me to read these files ? One thing I'm particularly interested to discover is if they contain contour (altitude) information so ideally that's that the sort of thing I would extract - but I'm just generally curious and wanting to educate myself a little in this area. In case it needs saying my knowledge of GIS is ... light ;-) but I'm interested to discover a little more. thanks richard shea. From opengeometry at yahoo.ca Wed Jan 21 17:51:41 2004 From: opengeometry at yahoo.ca (William Park) Date: 21 Jan 2004 22:51:41 GMT Subject: Checking for duplicate instances of a script... References: <400e4638$0$19274$626a54ce@news.free.fr> Message-ID: Guillaume Dargaud wrote: > Hello, python beginner here, > How can I make sure that a given script is never run more than once at the > same time in a system ? > Besides checking 'ps' for its own name. Most modern langages have a direct > way to do that. 1. Check 'ps'. But, if 2 processes checks at the same, then they see nothing is running and decides to run themselves. 2. Use lockfile. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From gerrit at nl.linux.org Tue Jan 6 14:31:22 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 6 Jan 2004 20:31:22 +0100 Subject: PRE-PEP: new Path class In-Reply-To: References: Message-ID: <20040106193122.GC4581@nl.linux.org> Just wrote: > In article , > "John Roth" wrote: > > 4) Should path expose an iterator for listdir(?) > > > > I don't see why not, as long as the path is to a > > directory. > > _An_ iterator, sure, but not __iter__. How about path.listdir()? :) > __iter__ could also iterate over the path elements, so it's ambiguous at > least. I think it should be called .list(): this way, it is better extendable to archive files like zip and tar. Indeed: I know at least 3 different possibilities for path.__iter__. Because of "In the face of ambiguity, refuse the temptation to guess.", I think there should be no __iter__ (which is even another reason not to subclass __str__, by the way) [0]. > > 15. Should files and directories be the same > > class. > > > > Probably not. While they share a lot of common > > functionality (which should be spelled out as an > > interface) they also have a lot of dissimilar > > functionality. Separating them also makes it easy > > to create objects for things like symbolic links. > > But what about paths for not-yet-existing files of folders? I don't > think you should actually _hit_ the file system, if all your doing is > path.join(). Another problem is dat I may not know whether I have a file or a directory. If a directory is a different type than a file, it would probably have a different constructor as well, and I may end up doing: p = path(foo) if p.isdir(): p = dirpath(foo) If this is done implicitly, you can't create a path without fs-interaction, which is bad for virtual-fs extensibility and confusing if it doesn't mean a path always exists [1]. [0] http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html#for-foo-in-mypath [1] http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html#absent-paths yours, Gerrit. -- 257. If any one hire a field laborer, he shall pay him eight gur of corn per year. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From danb_83 at yahoo.com Tue Jan 6 00:28:28 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jan 2004 21:28:28 -0800 Subject: PRE-PEP: new Path class References: Message-ID: "John Roth" wrote in message news:... > I'm adding a thread for comments on Gerrit Holl's pre-pep, which > can be found here: > > http://tinyurl.com/2578q > ... > 1) Should path be a subclass of str? > > No. So will the file constructor be "overloaded" to accept path objects? What about all those functions in the os module? From cookedm+news at physics.mcmaster.ca Tue Jan 13 09:49:36 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 13 Jan 2004 09:49:36 -0500 Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> <4002F93D.298A2394@alcyone.com> <40037BDE.CAFB05A9@alcyone.com> Message-ID: At some point, Erik Max Francis wrote: > "David M. Cooke" wrote: > >> Do you mean something like >> os.environ['startTime'] = '`rm -rf /`' >> ? > > No, I mean something like > > os.environ['startTime'] = '"; rm -rf /; : "' > > The lesson to be learned here is: Do not build shell commands from > untrusted inputs. Ever. Doesn't work: >>> os.environ['string'] = '"; uname; : "' >>> os.system('echo "$string"') "; uname; : " Although the advice of not building shell commands is still prudent; just because none of mine or your methods to defeat haven't worked, doesn't mean there isn't a technique that will. It's also dependent on having a good shell -- I'm using bash 2.05b.0. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From pythonguy at Hotpop.com Thu Jan 8 06:12:30 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 8 Jan 2004 03:12:30 -0800 Subject: KeyboardInterrupt and threading References: Message-ID: <84fc4588.0401080312.4f96b409@posting.google.com> There is an easier way than using signals. Add a keyboard interrupt handler for your main function. And in the handler code, write a clean up function which will be able to then manage threads. This is the method I have used in my HarvestMan program. I am copying this code here. ------------(copied code)---------------------------------------- try: self.start_project() except (KeyboardInterrupt, EOFError): # Localise links if not self._cfg.ignorekbinterrupt: # dont allow to write cache, since it # screws up existing cache. GetObject('datamanager').conditional_cache_set() self.clean_up() --------------------------------------------------------------------- The clean_up method takes care of cleaning the thread. There you can add code to pass on the interrupt to the main thread or perform your own clean up actions. One way to do this is to use the currentThread() method of threading module which can tell you whether the thread is the main or a worker. One drawback with this method is that you might need to set your threads as 'daemon' threads to make sure that the threads dont hang your python program. This is because the entire python program exits when the only threads left are daemon threads. -Anand q2n8byu02 at sneakemail.com (Ivan Nestlerode) wrote in message news:... > Michael Hudson wrote in message news:... > > This is hard for me to answer -- it works fine for me. What platform > > are you on? ISTR Debian, but not versions of anything. > > > > I'm somewhat inclined to start blaming libc at this point... > > > > As you may well be aware, the combination of threads and signals is a > > bit of a minefield. Python runs all threads other than the main > > thread with all signals masked. My understanding is that when a signal > > is delivered to a process it's delivered to an arbitrary thread that > > has that signal unmasked -- in Python's case, this should be the main > > thread. It kind of sounds like in your case the signal is being > > queued up on a non-main thread, but as the signal is never unblocked, > > it never gets handled. > > > > [...] > > > I think this is a bug though (I shouldn't have to put hacks into the > > > main thread to get this to work). > > > > Agreed, but I'm not sure they're in Python. > > > > > Any thoughts? > > > > Upgrade glibc? > > > > Cheers, > > mwh > > I've filed the bug with Debian since I think it is something wrong > with their Python or their glibc. The bug is #226547. > > FYI, here are the exact details of the kernel/packages that don't seem > to work: > > $ uname -a > Linux debian 2.4.23 #1 Sun Nov 30 21:11:49 EST 2003 i686 GNU/Linux > > packages and versions: > ii libbz2-1.0 1.0.2-1 > ii libc6 2.3.2.ds1-10 > ii libdb4.1 4.1.25-10 > ii libncurses5 5.3.20030719-4 > ii libreadline4 4.3-8 > ii libssl0.9.7 0.9.7c-5 > ii python 2.3.3-4 > ii python2.3 2.3.3-4 > ii zlib1g 1:1.2.1-3 > > > -Ivan From jjl at pobox.com Mon Jan 12 18:29:35 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Jan 2004 23:29:35 +0000 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> Message-ID: <87hdz0g2zk.fsf@pobox.com> Jacek Generowicz writes: [...] > If you want to perform miracles, then learn Lisp. If you > merely want to write programs that rock, then learn Python. [...] ...and then somebody argues that macros aren't a programming language feature, but a harmful means of inventing new languages, and then we get into that endless macro thread again... John From somebody at nowhere.com Tue Jan 13 01:57:46 2004 From: somebody at nowhere.com (Sean Richards) Date: Tue, 13 Jan 2004 19:57:46 +1300 Subject: Accessing "GIS (ESRI shape file)" files from Python ? References: <282f826a.0401121907.498543e6@posting.google.com> Message-ID: <87r7y4gwt1.fsf@hugin.valhalla.net> http://thuban.intevation.org/ I have not used this but it purports to be able to read ESRI shapefiles and is written in Python + wxPython. If you are not totally dogmatic about using Python then you could just download ESRI's arcexplorer which seemed pretty useful when I used it several years ago Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From cpl.19.ghum at spamgourmet.com Wed Jan 28 07:03:06 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 28 Jan 2004 13:03:06 +0100 Subject: package similar to XML::Simple References: Message-ID: Paulo Pinto > does anyone know of a Python package that > is able to load XML like the XML::Simple > Perl package does? Good to ask! I know of at least 3 packages that do sth. similiar. - Fredrik Lundhs elementtree - D. Merzs gnosis xml utilities - handyxml just google for them. From __peter__ at web.de Fri Jan 16 05:13:41 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Jan 2004 11:13:41 +0100 Subject: Make a function call itself after set amount of time References: Message-ID: Bart Nessux wrote: > Peter Otten wrote: >> Bart Nessux wrote: >> >> >>>Bart Nessux wrote: >>> >>>>How do I make a function call itself every 24 hours. Also, is there a >>>>way to start the program automatically w/o depending on the OS functions >>>>like 'Task Scheduler' or 'Start Up Items'... this is on Windows 2k and >>>>xp. Below is an example of what I'm trying to do. >> >> >> [...] >> >> >>>I figured it out. I added this to the function definition: >>>ipconfig_email() >> >> >> Note that Python has a limit for nesting functions: >> >> >>>>>depth = 0 >>>>>def callself(): >> >> ... global depth >> ... depth += 1 >> ... callself() >> ... >> >>>>>try: >> >> ... callself() >> ... except RuntimeError, e: >> ... print "depth", depth >> ... print e >> ... >> depth 999 >> maximum recursion depth exceeded >> >> >>>>>999/365.25 >> >> 2.7351129363449691 >> >> This means that your app will probably crash in less than three years. >> Would that be a problem on W2K ? >> >> If so, a loop could go much longer: >> >> while True: >> ipconfig_email() >> >> Seriously, you should reconsider the OS features. >> >> Peter >> > > The computers are turned off and on... the script starts at boot. I > don't think I'll hit a limit, do you? No, I just wanted to warn you that your recipe may fail when applied on tasks that are invoked with higher frequency - and of course test your confidence in W2K :-) Peter From bdash at gmx.net Tue Jan 13 07:18:16 2004 From: bdash at gmx.net (Mark Rowe) Date: Wed, 14 Jan 2004 01:18:16 +1300 Subject: pycap installation problem In-Reply-To: References: Message-ID: <4003E208.80600@gmx.net> fahad wrote: > Hi, > I'm trying to install pycap-0.1.6 using following commnad: > python setup.py build --compiler=mingw32 > but it throws a lot of errors about missing files some of them is: [snip] Hi, Currently pycap has not been tested under Windows. I have made brief attempts to get it to compile but as of yet I have not succeeded (http://pycap.sourceforge.net/todo.html). The biggest problems that I experienced when trying to compile on Windows were my inability to convince the compiler to find libnet's header files. This seems to be similar to the problem that you are experiencing. The solution may be as simple as patching setup.py to point your compiler in the right direction for the header files on your system, but other code changes may also be necessary to make pycap function correctly under Windows. When I next have some free time and access to a Windows machine I will make another attempt at making pycap compile smoothly out of the box on Windows. Patches and other advice in this avenue would be most welcome. In the mean time, if your need for a packet capturing and injection library from Python under Windows is pressing, take a look at the Pcapy/Impacket combo provided by Core Security Technologies (http://oss.coresecurity.com/). Thanks for the interest, Mark Rowe http://bdash.bluewire.net.nz From bignose-hates-spam at and-benfinney-does-too.id.au Mon Jan 26 20:23:56 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 Jan 2004 12:13:56 +1050 Subject: Single and double asterisks preceding variables in function arguments References: Message-ID: On Mon, 26 Jan 2004 20:15:22 -0500, Eric Amick wrote: > Try section 4.7.2 of the tutorial. Matter of fact, try the whole tutorial, beginning to end. It will answer many questions you haven't thought of yet. -- \ "Those are my principles. If you don't like them I have | `\ others." -- Groucho Marx | _o__) | Ben Finney From oliphant at ee.byu.edu Mon Jan 19 15:32:51 2004 From: oliphant at ee.byu.edu (Travis Oliphant) Date: Mon, 19 Jan 2004 14:32:51 -0600 Subject: Status of Numeric Message-ID: <400C3EF3.8090005@ee.byu.edu> Numarray is making great progress and is quite usable for many purposes. An idea that was championed by some is that the Numeric code base would stay static and be replaced entirely by Numarray. However, Numeric is currently used in a large installed base. In particular SciPy uses Numeric as its core array. While no doubt numarray arrays will be supported in the future, the speed of the less bulky Numeric arrays and the typical case that we encounter in SciPy of many, small arrays will make it difficult for people to abandon Numeric entirely with it's comparatively light-weight arrays. In the development of SciPy we have encountered issues in Numeric that we feel need to be fixed. As this has become an important path to success of several projects (both commercial and open) it is absolutely necessary that this issues be addressed. The purpose of this email is to assess the attitude of the community regarding how these changes to Numeric should be accomplished. These are the two options we can see: * freeze old Numeric 23.x and make all changes to Numeric 24.x still keeping Numeric separate from SciPy * freeze old Numeric 23.x and subsume Numeric into SciPy essentially creating a new SciPy arrayobject that is fast and lightweight. Anybody wanting this new array object would get it by installing scipy_base. Numeric would never change in the future but the array in scipy_base would. It is not an option to wait for numarray to get fast enough as these issues need to be addressed now. Ultimately I think it will be a wise thing to have two implementations of arrays: one that is fast and lightweight optimized for many relatively small arrays, and another that is optimized for large-scale arrays. Eventually, the use of these two underlying implementations should be automatic and invisible to the user. A few of the particular changes we need to make to the Numeric arrayobject are: 1) change the coercion model to reflect Numarray's choice and eliminate the savespace crutch. 2) Add indexing capability to Numeric arrays (similar to Numarray's) 3) Improve the interaction between Numeric arrays and scalars. 4) Optimization: Again, these changes are going to be made to some form of the Numeric arrays. What I am really interested in knowing is the attitude of the community towards keeping Numeric around. If most of the community wants to see Numeric go away then we will be forced to bring the Numeric array under the SciPy code-base and own it there. Your feedback is welcome and appreciated. Sincerely, Travis Oliphant and other SciPy developers From amonroejj at yahoo.com Thu Jan 15 08:10:03 2004 From: amonroejj at yahoo.com (R. Alan Monroe) Date: Thu, 15 Jan 2004 13:10:03 GMT Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: In article , usenet at janc.cjb.net wrote: >"Brandon J. Van Every" schreef: > >> I am not sure how I feel about it. I think it only bothers me when >> they claim to be cross-platform in theory, and the Windows build >> simply does not work in practice. A working Windows build should be >> easy to obtain all the dependencies for, and it should just build. >> When it doesn't do that, when you have to chase all over Hell's green >> acre to find the libraries, and then the build simply coughs and gags >> and dies, I'm not even slightly amused at how "cross-platform" some >> Linuxer is claiming things to be. > >You think "cross-platform" means "it runs out-of-the-box on all possible >platforms that ever existed, now exist, and will ever exist"? > >Please go searching and come back when you find 1 (one) program which fits >that definition... :-p "Hello World"? :^) Alan From kenfar42 at yahoo.com Sat Jan 24 00:03:01 2004 From: kenfar42 at yahoo.com (Ken) Date: 23 Jan 2004 21:03:01 -0800 Subject: closing database connections References: <71fd0ae5.0401230838.309e9b02@posting.google.com> Message-ID: dlee at rightnow.com (dustin lee) wrote in message news:<71fd0ae5.0401230838.309e9b02 at posting.google.com>... > I'd be interested to hear if any one has been bitten by not > explicitly closing database connections and under what cirumstances. > My main fear is that I will "run out of" database connections or in > some other way adversely affect server performance. I'm using recent > versions of both mysql and oracle. Yep, you should definitely and explicitely close database connections. Failure to do so can easily leave connections open and resources locked - not much unlike closing your ssh sessions by killing the client rather that logging out. Kind of a coincidence my seeing this email actually - just two minutes ago I read an email from a team member instructing others on the team to close their database connections (php/db2) because some connections occasionally hang and interfere with our loads. ken From peter at engcorp.com Tue Jan 6 08:39:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 08:39:52 -0500 Subject: Python for Embedded Devices? References: <221e7b06.0401041537.2896b22d@posting.google.com> Message-ID: <3FFABAA8.2D35FD03@engcorp.com> Phil Schmidt wrote: > > I am one such developer who works with very small systems: 8-bit > micros with under 128K flash and 4K RAM. I am keenly interested in > Python or some other similar langauge that would run on such hardware. > 'C' is the usual language for such environments, but I believe that, > in many cases, using a dynamic and 'object-able' language would reduce > development time and improve product quality significantly. > > I've looked at Io, Lua, PyMite and Pippy, to name a few, and none are > quite appropriate. Io is perhaps the closest match, if it were > stripped down a lot. Would you be willing to spend a sentence or two describing what basic problems you feel each of those has for your application? -Peter From hatespam at fakeemail.com Tue Jan 13 20:17:05 2004 From: hatespam at fakeemail.com (Dan Olson) Date: Tue, 13 Jan 2004 19:17:05 -0600 Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: As a person heavily involved in the pseudo-commercial Linux game industry and a Linux user in general, I must say that I agree with your general assessment that Linux users do far too little to make sure that their applications run and run well on Windows. That said, I disagree that Open Source projects have little to no value in commercial projects. There are countless examples that could be pointed out, but I'll just point out one of them: OpenAL. Here is my future advice: get a month and a half into a project before announcing it. Not only will you have people not saying "I told you so" if you scrap it, but people will in general be more interested in your project when you have something to show for it. Are you planning to make your vs.net version of FreeCiv available? Others might be interested in continuing the work. Cygwin is a horrible horrible way to run things on Windows, and I'd like to take this time to insult the mothers of everyone who has ever made their Linux application run on Windows using only Cygwin. From param at cs.wisc.edu Mon Jan 19 15:26:04 2004 From: param at cs.wisc.edu (Paramjit Oberoi) Date: Mon, 19 Jan 2004 14:26:04 -0600 Subject: ConfigParser - setting the order of options in a section In-Reply-To: References: Message-ID: > I am trying unsuccessfully to set the order of options using the > set(section,option,value) method ( Python 2.2.2) and writing to a > file. But the options always appear in a random order. Before each > option I am writing a comment line using set(section,"#",value) - a > one line explanation for the option that follows - but the comments > get re-ordered randomly. There is a module which was originally written for the SpamBayes project which probably does what you want. Search Google Groups for 'UpdatableConfigParser' for details. From gerrit at nl.linux.org Tue Jan 20 13:32:04 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 20 Jan 2004 19:32:04 +0100 Subject: Python T-shirt In-Reply-To: <400D6C40.2070802@coretrek.com> References: <400D6C40.2070802@coretrek.com> Message-ID: <20040120183204.GA4266@nl.linux.org> Vidar Braut Haarr wrote: > I was looking for a Python Tshirt the other day, and I couldn't find any > good ones.. Therefore I made this one: > > > The source images can be found here: > > > The code on the back of it was written by a very cool guy.. I don't > remember who. Thanks, anyways! :) > > Anyways, feel free to shop! I'm not getting any profit from this. I'm > not a python guy (I made the shirt as a birthday presant to a buddy), so > don't ask me about the code. I also don't subscribe to this list, so if > you reply, please include me as To/Cc. I think there once was a shirt with just the text "import this" on it, and that was the only reason to include this.py to Python... I'm not sure, though. yours, Gerrit. -- 257. If any one hire a field laborer, he shall pay him eight gur of corn per year. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From timr at probo.com Wed Jan 28 03:27:26 2004 From: timr at probo.com (Tim Roberts) Date: Wed, 28 Jan 2004 00:27:26 -0800 Subject: wxPython: images from URLs References: Message-ID: Jonathan Daugherty wrote: > >Does anyone here know if the wxImage class in wxPython supports dislaying >images from URLs? wxImage will read from a file or from a wxWindows stream. It won't download from a web site, but that's trivially easy using something like urllib. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From no at spam.pls Mon Jan 12 04:34:07 2004 From: no at spam.pls (Matthias) Date: 12 Jan 2004 10:34:07 +0100 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> Message-ID: <36wptdp7bow.fsf@chagall.ti.uni-mannheim.de> Peter Hansen writes: > This is my "straw poll" question: > > Do you spend a "significant" amount of time actually optimizing your > Python applications? (Significant is here defined as "more than five > percent of your time", which is for example two hours a week in a > 40-hour work week.) I was working on an image processing application and was looking for a quick prototyping language. I was ready to accept a 10-fold decrease in execution speed w.r.t. C/C++. With python+psycho, I experienced a 1000-fold decrease. So I started re-writing parts of my program in C. Execution speed now increased, but productivity was as low as before (actually writing the programs directly in C++ felt somewhat more natural). Often it happened that I prototyped an algorithm in python, started the program, implemented the algorithm in C as an extension module and before the python algorithm had finished I got the result from the C-algorithm. :-( I've tried numerics, but my code was mostly not suitable for vectorization and I did not like the pointer semantics of numerics. So my answer to the question above is NO, I don't spend significant times optimizing python code as I do not use python for computationally intensive calculations any more. My alternatives are Matlab and (sometimes) Common Lisp or Scheme or Haskell. From jcarlson at uci.edu Wed Jan 21 01:09:53 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Jan 2004 22:09:53 -0800 Subject: Introspection and member ordering References: <6f03c4a5.0401202118.d17d7a8@posting.google.com> Message-ID: <20040120214835.3E3E.JCARLSON@uci.edu> > Is there a way to get any sort of introspection which would return the > content of an instance *in the order they were declared or executed* > as opposed to alphabetical order? > > Example: > > >>> class a: > ... def __init__(self): > ... self.value = 12 > ... self.avalue = 78 > >>> class b(a): > ... def __init__(self): > ... a.__init__(self) > ... self.bvalue = 5 > ... def f(self): > ... self.z = 3 > ... > >>> c=b() > >>> c.__dict__ > {'bvalue': 5, 'avalue': 78, 'value': 12} > > Wrong answer, I am looking for something that would give me > {'value':12, 'avalue':78, 'bvalue':5'} > > I tried the inspect.getmembers(c) without success. > > Anyone has some advice how I can get the members listed in declaration > or execution order? Rim, You'd have to either overload the class's __getattribute__, __setattr__ and __delattr__ methods, or replace the builtin instance.__dict__ attribute with a new dictionary-like object that will produce the ordering you want. As an option, I've written an LRU that does such kinds of updates quickly, though it also updates on read. Reading the comment at the bottom will allow you to translate the update on read, to only updating on write. The recipe is available here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 Doing a quick check, it doesn't look like you can say: self.__dict__ = NON_DICT_OBJECT Making LRU a subclass of dict seems to work on the surface, but it looks to break a few things. Perhaps I should rewrite LRU to be more Pythonic. Until then, you'll have to update __getattribute__, __setattr__ and __delattr__. - Josiah From jayoconnor at earthlink.net Sat Jan 31 18:49:34 2004 From: jayoconnor at earthlink.net (Jay O'Connor) Date: Sat, 31 Jan 2004 23:49:34 GMT Subject: OT: why do web BBS's and blogs get so slow? In-Reply-To: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Lots of times, when a blog (that supports user comments) or a web BBS > gets heavily loaded, it slows down horribly, even when it's hosted at > an ISP on a fast computer with plenty of net bandwidth. I'm wondering > what those programs are doing, that makes them bog down so badly. > Anyone know what the main bottlenecks are? I'm just imagining them > doing a bunch of really dumb things. > > I'm asking this on clpy because thinking about the problem naturally > made me wonder how I'd write a program like that myself, which of > course would mean using Python. > > FWIW, here's how I'd do it: > > 1) It would be single threaded web server (asyncore, twistedmatrix) > with a select loop talking to a socket, either on port 80 directly, or > to a proxy web server running mod_gzip, SSL, and so forth. > 2) It might use MySQL for infrequent operations like user info lookup > at login time or preference updates, but not for frequent operations > like reading and posting messages. User session info and preferences > would be in ram during a session, in a python dict indexed by a > browser session cookie. This is similar to what I wrote in Smalltalk several years and is now running http://www.ezboard.com From ketulp_baroda at yahoo.com Sat Jan 10 06:58:09 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 10 Jan 2004 03:58:09 -0800 Subject: what is best for web development?? Message-ID: i am developing a web application and i am really confused on what should i use. should i use just python and use the cgi module availabe. Or should i use application like WebWare.Also there is PSP available. I am really confused and need help From guido.schimmels at freenet.de Fri Jan 23 15:47:39 2004 From: guido.schimmels at freenet.de (Guido Schimmels) Date: Fri, 23 Jan 2004 22:47:39 +0200 Subject: How to build Tkinter as extension module? Message-ID: When I build python with tkinter support (Linux), the python interpreter is linked to the tcl/tk shared libraries, thus making them a hard dependency. That is unfortunate. A friend told me, Debian supports tkinter via an autonomous extension module. I have looked at the Debian rules file but wasn't able to discover the trick. From EP at zomething.com Tue Jan 13 21:38:45 2004 From: EP at zomething.com (EP) Date: Tue, 13 Jan 2004 18:38:45 -0800 Subject: Myth or Urban Legend? Python => Google [ was: Why learn Python ??] In-Reply-To: <873cajafr8.fsf@pobox.com> References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> <87d69og2jl.fsf@pobox.com> Message-ID: <5.2.0.9.0.20040113181737.00b7e730@mail.zomething.com> Is it true that the original Google spider was written in Python? I came across a paper on the web some time back that I saved and read just last night: The Anatomy of a Large-Scale Hypertextual Web Search Engine Sergey Brin and Lawrence Page {sergey, page}@cs.stanford.edu Computer Science Department, Stanford University, Stanford, CA 94305 A neat read, but I'm not sure of the authenticity of the paper: I could be gullible. It would appear to be a paper written some years back on the genesis of the Google search engine. [excerpt] Running a web crawler is a challenging task. There are tricky performance and reliability issues and even more importantly, there are social issues. Crawling is the most fragile application since it involves interacting with hundreds of thousands of web servers and various name servers which are all beyond the control of the system. In order to scale to hundreds of millions of web pages, Google has a fast distributed crawling system. A single URLserver serves lists of URLs to a number of crawlers (we typically ran about 3). Both the URLserver and the crawlers are implemented in Python. Each crawler keeps roughly 300 connections open at once. This is necessary to retrieve web pages at a fast enough pace. At peak speeds, the system can crawl over 100 web pages per second using four crawlers. This amounts to roughly 600K per second of data. A major performance stress is DNS lookup. Each crawler maintains a its own DNS cache so it does not need to do a DNS lookup before crawling each document. Each of the hundreds of connections can be in a number of different states: looking up DNS, connecting to host, sending request, and receiving response. These factors make the crawler a complex component of the system. It uses asynchronous IO to manage events, and a number of queues to move page fetches from state to state. [/excerpt] It would seem like the poster boy example for using Python in some respects, if true. Eric, Intrigued "but at least I didn't top post" -------------- next part -------------- An HTML attachment was scrubbed... URL: From scottdog at nospam.com Tue Jan 20 16:21:13 2004 From: scottdog at nospam.com (Dog@will.hunt) Date: Tue, 20 Jan 2004 13:21:13 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> Message-ID: <400c451a_1@newsfeed.slurp.net> The instructions that came with SpamBayes says it. THey say to either run the setup.py file in the Python GUI (IDLE) or froma command prompt. I have tried both to no avail... "Rene Pijlman" wrote in message news:up5r00hr648soiun3j6q326ga9n808hf17 at 4ax.com... > Dog at will.hunt: > >It says to run the setup.py file using the following command in IDLE > > Where does it say that? The wordt "idle" doesn't appear on > http://cvs.sourceforge.net/viewcvs.py/*checkout*/spambayes/spambayes/README. txt?rev=HEAD&content-type=text/plain > > >in the directory that I extracted the spambayes files into: python setup.py > >install. > > > >When I do this, it tells me that python is not a recognized command. > ^^ > What exactly is "it"? Is it a Unix/Linux shell, or the Windows command > interpreter? > > -- > Ren? Pijlman From glenfant at NOSPAM.bigfoot.com Wed Jan 28 14:16:53 2004 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Wed, 28 Jan 2004 20:16:53 +0100 Subject: How to detect that a key is being pressed, not HAS been pressed earlier!?? References: <6ed33425.0401281103.61987e72@posting.google.com> Message-ID: "Rune" a ?crit dans le message de news:6ed33425.0401281103.61987e72 at posting.google.com... > Hey > > I'm trying to build a gui application and need to know if the user is > actually holding down the shift or ctrl key. That is, if the user > currently is holding down the shift key. In pseudo code this will boil > down to something like this: > > def test: > if user presses shift: > return SHIFT_IS_PRESSED > elif user presses ctrl: > return CTRL_IS_PRESSED > else > return false > > It's important to notice here that I'm not interested if the user has > already pressed shift or ctrl. I'm only interested in knowing if he is > currently holding down one of these keys. (I have looked into msvcrt > and the like but have found no answer..) The function should also work > in both windows and Linux. > > Any help is appriciated :) You should have a look at the wxPython demo (wxKeyEvents section) that shows how this is handled in a cross platform fashion. Search for wxPython from www.sf.net -- Gilles From jhg at galdon.com Sun Jan 25 06:27:11 2004 From: jhg at galdon.com (Juan Huertas) Date: Sun, 25 Jan 2004 12:27:11 +0100 Subject: Embeedding OCX controls in pythonwin or wxpython Message-ID: It's possible to embeed OCX controls using win32com and this work fine. But: How it is possible to assign properties at dessing time (not accesibles at run time) to the OCX objects? In Visual Basic, for example, this is ease using dialogs asociated at desing time, in IE using parameters clause (PARAM NAME an VALUE) to define the embeeded object, etc. In win32com or wxpython? Please aids. Thank You. From bkelley at wi.mit.edu Fri Jan 23 16:09:58 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 23 Jan 2004 16:09:58 -0500 Subject: closing database connections In-Reply-To: References: <71fd0ae5.0401230838.309e9b02@posting.google.com> Message-ID: <40118d3b$0$567$b45e6eb0@senator-bedfellow.mit.edu> andy wrote: > I seem to remember reading somewhere that as client connections are a finite > (and often scarce) resource, it's not the client but the server that will > suffer when you do this. I think there might be two issues here. One is using the reference counting scheme to close files and databases, the other is to keep connections open, which andy seems to be referring too. This discussion has occured a lot in the python community. I'll give a case in point. The python interface to metakit has no close method. It can only be closed through reference counting and by going out of scope. The problem with this, is that if some piece of code has a reference to the metakit database, it will *never* be closed and this causes hard to find bugs with metakit. In C-python reference counting closes files and database connections "soon" after they go out of scope. This may or may not be true in java python. I haven't tested this. The upside is that if you explicitly close the database, it will be closed when you expect and you don't have to worry about other objects having a reference to your cursor or connection or what not. That being said, just relying on the reference count and letting python clean up has worked very well for me with metakit. > hth, > -andyj > > From jepler at unpythonic.net Thu Jan 8 10:00:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 8 Jan 2004 09:00:13 -0600 Subject: unicode keys in dicts In-Reply-To: <20040108150835.7242ef01.jiba@tuxfamily.org> References: <20040108150835.7242ef01.jiba@tuxfamily.org> Message-ID: <20040108150013.GB14102@unpythonic.net> >>> chr(0xe9) == unichr(0xe9) Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) unequal objects can hash to the same value. Your two keys are not equal (in fact, you can't even compare them on my system). They would be comparable but not equal on many systems, for instance one where the system's encoding is Microsoft's CP850. You can misconfigure your system to assume that byte strings are in (eg) iso-8859-1 encoding by changing site.py. Jeff From aisung at bubblemotions.com Tue Jan 27 21:08:02 2004 From: aisung at bubblemotions.com (Michael G. A. Sung) Date: Tue, 27 Jan 2004 18:08:02 -0800 Subject: PAP connection Message-ID: <00e201c3e543$915fcc90$3c01a8c0@mike> Hi all, I am new to python. I am trying to write a script to connect to a PPG server. so is through PAP(Push Access Protocol). How do I do so? The exact address is http://edevgate.openwave.com:9002/pap . So anyone have any idea? Thanks in advance, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From piedmontbiz at aol.com Wed Jan 14 19:03:50 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 15 Jan 2004 00:03:50 GMT Subject: Printing to console, no scroll References: Message-ID: <20040114190350.06766.00000031@mb-m21.aol.com> Sorry for my post with all the ansi.py code. I forgot the website I got it from. Allen From codeapocalypse at msn.com Sat Jan 31 21:38:34 2004 From: codeapocalypse at msn.com (Brian) Date: 31 Jan 2004 18:38:34 -0800 Subject: QT usage confusion References: <40069912$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: Marco Bubke wrote in message news:... > There is a new Book(look at www.trolltech.com) with the Qt 3.2.1 Windows > non-commerial Version. > Note that on the pyqt-dev mailing list, Phil Thompson has stated that he has not decided whether or not to support the new non-comm Windows edition/version. Personally, I'm waiting to hear if he'll decide to support (wrap) ActiveQt, the Qt module for support of Microsoft's ActiveX components. It might then be possible to convince my work mgmt. to buy a slew of BlackAdder copies. ;) For more about ActiveQt, see http://www.trolltech.com/products/qt/whitepaper/qt-whitepaper-15-1.html From martin at v.loewis.de Sat Jan 3 16:50:24 2004 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 03 Jan 2004 22:50:24 +0100 Subject: [Python-Dev] PEP 324: popen5 - New POSIX process module In-Reply-To: References: Message-ID: <3FF73920.8090402@v.loewis.de> Peter ?strand wrote: > This PEP describes a new module for starting and communicating > with processes on POSIX systems. I see many aspects in this PEP that improve the existing implementation without changing the interface. I would suggest that you try to enhance the existing API (making changes to its semantics where reasonable), instead of coming up with a completely new module. With that approach, existing applications could use these features with no or little change. > - One "unified" module provides all functionality from previous > functions. I doubt this is a good thing. Different applications have different needs - having different API for them is reasonable. > > - Cross-process exceptions: Exceptions happening in the child > before the new process has started to execute are re-raised in > the parent. This means that it's easy to handle exec() > failures, for example. With popen2, for example, it's > impossible to detect if the execution failed. This is a bug in popen2, IMO. Fixing it is a good thing, but does not require a new module. > - A hook for executing custom code between fork and exec. This > can be used for, for example, changing uid. Such a hook could be merged as a keyword argument into the existing API. > - No implicit call of /bin/sh. This means that there is no need > for escaping dangerous shell meta characters. This could be an option to the existing API. Make sure it works on all systems, though. > - All combinations of file descriptor redirection is possible. > For example, the "python-dialog" [2] needs to spawn a process > and redirect stderr, but not stdout. This is not possible with > current functions, without using temporary files. Sounds like a new function on the popen2 module. > - With popen5, it's possible to control if all open file > descriptors should be closed before the new program is > executed. This should be an option on the existing API. > - Support for connecting several subprocesses (shell "pipe"). Isn't this available already, as the shell supports pipe creation, anyway? > - Universal newline support. This should be merged into the existing code. > - A communicate() method, which makes it easy to send stdin data > and read stdout and stderr data, without risking deadlocks. > Most people are aware of the flow control issues involved with > child process communication, but not all have the patience or > skills to write a fully correct and deadlock-free select loop. Isn't asyncore supposed to simplify that? So in short, I'm -1 on creating a new module, but +1 on merging most of these features into the existing code base - they are good features. Regards, Martin From peter at engcorp.com Mon Jan 19 10:48:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Jan 2004 10:48:36 -0500 Subject: Escaping slashes (double backslash plague) References: Message-ID: <400BFC54.FC6EADF4@engcorp.com> Aloysio Figueiredo wrote: > > I need to replace every ocurrence of '/' in s by '\/' > in order to create a file named s. My first attempt > was: > > s = '\/'.join(s.split('/')) > > but it doesn't work: > > >>> s = 'a/b' > >>> s = '\/'.join(s.split('/')) > >>> s > 'a\\/b' > >>> repr(s) > "'a\\\\/b'" > >>> > > '\/'.join() escapes the backslashes and I don't know why. It does not, although *you* are not escaping the backslash yourself, and that is dangerous. Get in the habit of always escaping your own backslashes, so that if you ever happen to use a backslash followed by one of the characters which _is_ a valid escape sequence, you won't get confused. '\/' == '\\/' but '\t' != '\\t' The first example shows two ways of writing a string with the blackslash character followed by a forward slash. The second example shows a TAB character on the left, but a backslash plus the letter 't', on the right. As for your apparent automatic escaping of backslashes: when you show results in an interactive session by just typing the expression, such as when you do ">>> s" you will see the repr() of the value, not the actual content. Use print instead and you'll see the difference: >>> print s This is all covered pretty well, I think, by the Python tutorials and such. Have you gone through those? -Peter From seanl at chaosring.org Sat Jan 3 15:24:10 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 12:24:10 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: I hate replying to myself, but I've written some more code. I hope to have something posted soon so people can rip it apart without needing to resort to conjecture :) I had been considering using a name-mangled setattr for doing attribute assignment to only allow assignment to attributes on descendants of the class one was writing methods on, but it occurred to me that I could probably treat "self" as a special name using only compiler modifications, so I could eliminate RestrictedPython's need to turn all Getattrs and AssAttrs (shouldn't it be GetAttr) into method calls. Now, of course, I'm limited to static checks on names to control access, but Python already disallows, for example, access to f.func_globals, and RestrictedPython disallows names that begin with underscore. Now I need to write a bunch of code that uses this system and attempts to break it :) From martin at v.loewis.de Sat Jan 3 16:17:20 2004 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Jan 2004 22:17:20 +0100 Subject: Creating a capabilities-based restricted execution system References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: "Sean R. Lynch" writes: > RestrictedPython avoids this by removing the type() builtin from the > restricted __builtins__, and it doesn't allow untrusted code to create > names that start with _. Ah, ok. That might restrict the usefulness of the package (perhaps that is what "restricted" really means here :-). People would not normally consider the type builtin insecure, and might expect it to work. If you restrict Python to, say, just integers (and functions thereof), it may be easy to see it is safe - but it is also easy to see that it is useless. The challenge perhaps is to provide the same functionality as rexec, without the same problems. Regards, Martin From http Sat Jan 24 18:12:26 2004 From: http (Paul Rubin) Date: 24 Jan 2004 15:12:26 -0800 Subject: crypt, md5, sha modules References: Message-ID: <7xy8rxc55x.fsf@ruckus.brouhaha.com> Marco Herrn writes: > So my main question is: can I use the md5 module for creating hashes > compatible with exims md5-function? And if so, how? Examine the exim source code and see what it's doing, then code something interoperable with the md5 module. From altis at semi-retired.com Mon Jan 26 17:03:25 2004 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 26 Jan 2004 14:03:25 -0800 Subject: wxPython: images from URLs References: Message-ID: "Jonathan Daugherty" wrote in message news:mailman.810.1075149139.12720.python-list at python.org... > Does anyone here know if the wxImage class in wxPython supports dislaying > images from URLs? Yes, the trick is to use StringIO to convert the data rather than saving to a file and loading it from disk. Here's a concrete example... ka --- import urllib from wxPython import wx from cStringIO import StringIO # I'll assume you already have an app, frame... # to draw into if that's what you want to do wx.wxInitAllImageHandlers() # here's a real URL for testing purposes url = 'http://pythoncard.sourceforge.net/images/addresses_01.png' try: fp = urllib.urlopen(url) data = fp.read() fp.close() img = wx.wxImageFromStream(StringIO(data)) except: # decide what you want to do in case of errors # there could be a problem getting the data # or the data might not be a valid jpeg, png... pass # now you can do whatever you want with the image From cygnus at cprogrammer.org Sat Jan 31 14:57:51 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sat, 31 Jan 2004 14:57:51 -0500 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia In-Reply-To: References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: <20040131195751.GA16029@mail.theserver.ath.cx> # Software patents are evil. # Hell to them. Agreed. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From jcarlson at nospam.uci.edu Mon Jan 26 15:54:29 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 12:54:29 -0800 Subject: Guardian: open source is a throwback says Jack Schofield In-Reply-To: <40156FB6.F71C19B0@engcorp.com> References: <64cff82f.0401251143.328388bd@posting.google.com> <40156FB6.F71C19B0@engcorp.com> Message-ID: >>Never underestimate the power of stupidity (or ignorance, or denial, or...). >> >>Speaking of which... >>http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html >> >> - Josiah > > > I'm sorry, really, to bring this up, but as a Canadian I might be a little > thick on this point, so help me out: was that site hacked? Or is this for > real? > > -Peter Peter, I understand your confusion. You are thinking, "Surely the president of the United States can't be that foolish." That is what the entire world thought...until they started listening to what he had to say. The history of the Iraq war, told entirely in lies: http://www.harpers.org/RevisionThing.html?pg=1 Dishonest Dubya Action Figure (all unaltered quotes from GWB): (could be short on bandwidth, resulting in a 509 error) http://www.praesentia.us/archives/dishonestdubya.html Let us hope the general population votes consistantly for a single, non-GWB candidate. Dean would be fine, Clark would be better. - Josiah From mhammond at skippinet.com.au Fri Jan 30 18:53:41 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 31 Jan 2004 10:53:41 +1100 Subject: win32com support In-Reply-To: References: Message-ID: Crawley wrote: > Im trying to produce a small Visual Studio Addin. Taking the > OutlookAddin example and changing the registry place it installs too, > everything works ok. > > Examples in C++ show that in the OnConnection method I have to registry > my commands and also pass an instance of my sub class of ICommands. > > The C code looks like this: > > IApplication* pApplication = NULL; > pApp->QueryInterface(IID_IApplication, (void**) &pApplication) > > CCommandsObj::CreateInstance(&m_pCommands); > m_pCommands->AddRef(); > m_pCommands->SetApplicationObject(pApplication); > > pApplication->SetAddInInfo((long) AfxGetInstanceHandle(), > (LPDISPATCH) m_pCommands, -1, -1, m_dwAddin)); > > > So far Im trying something like this: > > self._command = VCCmd(application) > application.SetAddInInfo(AfxGetInstanceHandle(), self._command, - > 1, -1, addin ) > > > with VCCmd defined like: > > class VCCmd: > _com_interfaces_ = ['_ICommands'] > _public_methods_ = [] > > _application = None > > def __init__( self, app ): > self._application = app > print "VCCmd __init__" > > > Needless to say, its not working, so questions. > > 1) AfxGetInstanceHandle dosent appear to exist in the win32api... so how > do I call it. AfxGetInstanceHandle returns the handle to your MFC built DLL. The assumption is that your object is built into a nice, single little DLL. This doesn't make sense for Python. Your code is not implemented in a DLL at all, but in a .py file. There are a few DLLs involved (pythonxx.dll, pythoncomxx.dll), and the handles to these can be found pretty easily - but it is unclear if that helps you. You really need to determine *why* SetAddInInfo() wants a DLL handle and what the implications are. My guess is that it expects to be able to pull Win32 resources (such as bitmaps, menus, etc) from that DLL, which may be a problem. > 2) am I defining VCCmd correctly to be a subclass of ICommands That looks OK, assuming that the type library where ICommands is defined has been registered for universal support. You will note the Outlook addin sample specifies the generic IDTExtensibility interface - if ICommands is VS specific (and therefore in a different typelib), then it is likely you also need to specify that additional typelib. > > 3) am I correct in thinking i dont have to explicitly 'cast' application > into an IApplication instance Correct - the framework will automatically perform a QI in most cases. Of course, if your object is not implemented correctly, this QI will fail. > > Many thanks for any light you may be able to shed on the subject Register your addin with "--debug" on the command-line. Then use the Pythonwin "Remote Trace Collector" tool, and you should see lots of output as your object is instantiated and used. You should also be able to see most exceptions raised by your object, which are generally invisible without this debugging technique. When you get it working, consider contributing it back as a sample I can put next to the Outlook one ;) Mark. From M at a.k Fri Jan 2 11:03:07 2004 From: M at a.k (Midas) Date: Fri, 02 Jan 2004 16:03:07 GMT Subject: Passing to a function -- object and method names (or references) Message-ID: <3ff595e2.67831682@news.iprimus.ca> Greetings everyone, I'm including code, for cut/paste, to better explain my question. I create a Car object then I call some of its methods. No problem. Then I try to pass, to a function, the name of the Car object and the name of one of its methods. I found one way to get this to work but can someone show me a more orthodox way? Is there a way using references to the object and somehow the method? Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 IDLE 0.8 class Car: def __init__(self): self.milespergallon=25.0 self.gas=20 self.travelled=0 def drive(self, miles): self.travelled=self.travelled+miles self.gas=self.gas-(miles/self.milespergallon) # a test >>> carObjA=Car() ; carObjA.drive(100) ; print carObjA.gas 16.0 # Next, trying to pass object and method "references", to someFuncA def someFuncA(objArg1,strArg2): print carObjB.strMethB >>> carObjB=carObjA ; strMethB="gas" ; someFuncA(carObjB,strMethB) Traceback (most recent call last): File "", line 1, in ? someFuncA(carObjB,strMethB) File "", line 2, in someFuncA print carObjB.strMethB AttributeError: Car instance has no attribute 'strMethB' # Next, trying to pass object and method "references", to someFuncB def someFuncB(strArg1,strArg2): e = "print " + strArg1 + "." + strArg2 exec e >>> strObjB="carObjA" ; strMethB="gas" ; someFuncB(strObjB,strMethB) 16.0 # That worked but is there a more orthodox way to pass these "references"? From me at privacy.net Fri Jan 30 04:14:14 2004 From: me at privacy.net (Duncan Booth) Date: 30 Jan 2004 09:14:14 GMT Subject: what is the use of weakref? References: <1jipe1-fqq.ln1@news.slu.edu.ph> Message-ID: "ali" wrote in news:1jipe1-fqq.ln1 at news.slu.edu.ph: > i've seen a lot of times in programs but until now i still dont know > the use of the weakref module... any help will be appreciated... > thanks... > Normally in Python an object is never destroyed until you can no longer reference it. Occasionally it can be convenient to hold onto an object, but not to mind too much if it gets destroyed. For example, say you had a word processing application with a complex data structure for each paragraph style that was used in a document. When someone changes the style of an existing paragraph, if it now matches the style of another paragraph you want to share the same data structure rather than creating a new one. What you could do here would be to make each paragraph hold a strong reference to the required data structure, but also store a weak value dictionary which maps the description of the paragraph style onto the data structures. With this kind of setup, the entries in the weak value dictionary always exactly match the paragraph styles which are in use; as soon as a style is no longer used it can be released, but you never need to duplicate the complex data structure as a simple dictionary lookup will give you a suitable one if it exists. In short weak references help you to share or reuse data structures while still allowing them to be freed automatically when no longer used. From goodger at python.org Mon Jan 5 11:10:37 2004 From: goodger at python.org (David Goodger) Date: Mon, 05 Jan 2004 11:10:37 -0500 Subject: Pyserial question In-Reply-To: <000d01c3d3a4$db8464d0$17abfa84@Nuvodido> References: <000d01c3d3a4$db8464d0$17abfa84@Nuvodido> Message-ID: <3FF98C7D.1000708@python.org> Kelia Nichols wrote: > I am using Pyserial to work with a RS232 device. My question is, > how do I write hex to the device or cannot write hex to it pyserial? What do you mean exactly? Do you want to write a value in hex to the RS232 port (e.g. write 26 [decimal] as "1A")? If so, just use string formatting: >>> "%02X" % 26 '1A' Or do you want to send a byte for which you know the hex representation (e.g. send "1A" as ASCII 26)? If so, use integer conversion & character value conversion: >>> chr(int('1a', 16)) '\x1a' If it's more complex than that (values larger than 255, etc.), the "struct" module may help. Post more details for better help. -- David Goodger From miki.tebeka at zoran.com Mon Jan 19 17:26:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 19 Jan 2004 14:26:53 -0800 Subject: Where to post an article? References: <4f0a9fdb.0401181356.79a1ec87@posting.google.com> <400BEB11.E5572142@engcorp.com> Message-ID: <4f0a9fdb.0401191426.1a76d195@posting.google.com> Hello Peter, > > Can you recommend a site/paper to publish it? > > Is the focus on Python, or on the "rapid" part? If any agile processes > were used, maybe test-driven development, you would of course be best off > posting on the extremeprogramming Yahoo mailing list. > > Else here, as Michael has suggested. OK. Thanks you both. Miki From chris at chrisburkert.de Sun Jan 18 04:03:16 2004 From: chris at chrisburkert.de (Chris Burkert) Date: Sun, 18 Jan 2004 10:03:16 +0100 Subject: [Q] Pyython and curses/ncurses/snack/tinter/... Message-ID: Hi I want to write a little application for the shell with a userinterface that is not line based. Think of the UI of mc for example. And I want to use Python on different Operating Systems. So it should be portable. Now what would you prefer as UI-library? I'm searching for a highlevel library with buttons, text boxes, dialog boxes, progress bars, ... I have heard of: - curses, ncurses ... low-level - snack ... wrapper for newt and slang - tinter Do you know of any other good library that is widely available? I have seen a lot of examples for curses and ncurses but not for the others. Snack seems to be only available for Linux and not well documented?!? thanks for any help! Chris Burkert From jcarlson at nospam.uci.edu Sun Jan 25 13:42:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 10:42:19 -0800 Subject: xrange not hashable - why not? In-Reply-To: References: Message-ID: > why is an xrange object not hashable? > I was trying to do something like: Could be a hold-over from xrange trying to have all of the features of a list returned by range; lists are unhashable because they are mutable. > comments = { > xrange(0, 4): "Few", > xrange(4, 10): "Several", > xrange(10, 100): "A lot", > xrange(100, sys.maxint): "Can't count them"} > for (k, v) in comments.items(): > if n in k: > commentaar = v > break > It would not be difficult to let xrange have a hash: > > hash((self.start, self.step, self.stop)) I don't believe anyone ever said it was. *wink* > Hmm, start, step and stop appear to have disappeared in Python 2.3... I don't know about that: 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. >>> help(xrange) Help on class xrange in module __builtin__: class xrange(object) | xrange([start,] stop[, step]) -> xrange object > So, should I use one of the alternatives after all? Or does someone have > something better to offer? Honestly it is one of those things that are easily remedied by a custom-built class. Like the below: class HashableXRange: def __init__(self, s1, s2=None, s3=None): if s2 is None: s1, s2, s3 = 0, s1, 1 elif s3 is None: s3 = 1 self.start = s1 self.stop = s2 self.step = s3 def __hash__(self): return hash((self.start, self.stop, self.step)) def __cmp__(self, other): if isinstance(other, self.__class__): return cmp(self.start, other.start) or\ cmp(self.stop, other.stop) or\ -cmp(self.step, other.step) return cmp(self.start, other) def __iter__(self): return iter(xrange(self.start, self.stop, self.step)) def __contains__(self, object): if self.start <= object < self.stop: if (object-self.start) % self.step == 0: return 1 return 0 I included the __cmp__ function in order to give it a richer set of behavior. One thing to note about hashes is that they are not required to be unique. As such, the hashing algorithm is not the absolute best algorithm ever. It is pretty good, but it is not guaranteed that hash((a,b,c)) != hash((d,e,f)) for different sets of three objects. Better to be safe than sorry. I would have subclassed xrange, but Python 2.3 doesn't like that. Apparently there is no subclassing for xranges. - Josiah From ashleylloyd at hotmail.com Wed Jan 7 15:03:22 2004 From: ashleylloyd at hotmail.com (Ashley) Date: Wed, 7 Jan 2004 20:03:22 -0000 Subject: Newbie question References: Message-ID: You will no doubt get many better replies than mine, since I'm very much a newbie here, but here goes: With many programming languages, you are correct - you write the code, and compile it, which gives you an executable which you can then run independently. With Python, the language is interpreted, not compiled. Slightly different, and I don't pretend to know everything about the difference. However, you will need python installed to run any of the code you write. Then it depends how the code is written. If you write a module with a mind to it being used like an executable (this will make more sense when you start coding), then it pretty much can be used as one. If python is installed properly, and you double click (assuming you're using Windows) on yourModuleName.py, then python will try to run it. Python can be downloaded from http://www.python.org/download/ I know this isn't much, and like I say more people will probably give more comprehensive answers - and no doubt correct my mistakes, but as a basic start I hope it helps. Cheers Ashley ----- Original Message ----- From: "Paul Mcshane" Newsgroups: comp.lang.python To: Sent: Wednesday, January 07, 2004 4:42 PM Subject: Newbie question > I havn't got a clue what I'm doing so don't treat me like I'm stupid even > though I am compared to all of you. What is the basics to programming, you > write the code and compile it? I know a few useless web languages so they > should come in handy on my way. So you need a compiler to compile your code > unless you can do it yourself? Once the program is compiled you can run it > as a normal executable? > Any answers are appreciated, I just wanna get to know what I'm doing before > I start to learn anything. > Thanks again, > Paul Mc. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From sulfugor at rocketmail.com Sun Jan 11 11:12:47 2004 From: sulfugor at rocketmail.com (H.V) Date: 11 Jan 2004 08:12:47 -0800 Subject: solving a small programm References: <40004254$0$16669$ba620e4c@news.skynet.be> Message-ID: <279b566d.0401110812.ea53a45@posting.google.com> "broebel" wrote in message news:<40004254$0$16669$ba620e4c at news.skynet.be>... > hey, > > for the real programmers amongst you, this may be really annoying but I've > been learning the language for only two days. > > this is my problem, > in this programm,which already works I now have to make a total count of how > many coins are used. > this program gives the total per coin. It should be a small peace of code > (as explained in a tutorial i read, without the answer.)that counts the > total of all the coins. > I ve been searching for two days and for this kind of programm it really > seems kind of long. > > thanks in advance > > # Een bedrag gepast betalen met zo min mogelijk euromunten > > bedrag = input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) > > for munt in 200, 100, 50, 20, 10, 5, 2, 1 : > aantal = 0 > > while bedrag >= munt : > aantal = aantal + 1 > bedrag = bedrag - munt > > if aantal > 0 : > print aantal, 'x', munt > > what i need is: > for example > the programm gives > 68= 50*1 > 10*1 > 5*1 > 2*1 > 1*1 > I need an additional code to get the "5" total of all the coins together. -- An alternative to keeping track of coins as you go would be to store your results in some kind of data structure : use a dict whose keys are the coin type and whose values ate the number of each type of coin needed. Then you can just add all the "values" . I like the data centric approach . Your code doesn't seem to exploit any of the convenient data structures at all . sulf From gandalf at geochemsource.com Wed Jan 7 05:11:15 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 07 Jan 2004 11:11:15 +0100 Subject: Windows service in Python Message-ID: <3FFBDB43.9040703@geochemsource.com> Can anybody tell me how to write a windows service in Python? I would only use file operations (maybe the logger module) and TCP/IP. I already have my server and it runs fine both on Windows, Linux and FreeBSD maybe others too, who knows? :-) The only problem is that it should be a service. It is easy to make it a service on a UNIX machine but I need to run as a Windows service on NT/2000/XP. Is this possible? Can you show me a link to an example? Any help appreciated. Thanks in advance, Laci 1.0 From godoy at ieee.org Fri Jan 16 06:35:53 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 16 Jan 2004 09:35:53 -0200 Subject: wxPython worries References: <92c59a2c.0401152257.5b93167b@posting.google.com> Message-ID: On Friday 16 January 2004 04:57 MetalOne wrote in <92c59a2c.0401152257.5b93167b at posting.google.com>: > I also suppose I shouldn't rant to much about something that is > free. However my first two GUIs hit critical problems, and > these were really simple GUIs. Granted, the first problem has been > fixed now, and I have not yet written a bug report on the second. I think that ranting is good *IF* it has a bug report to the developers to back it up. Developers can't imagine all the uses people will do from their work and they need to know what happened when you tried doing something so that they can help you: fixing the problem, pointing another way of doing it or even saying that it can't be done and making you stop loosing your time trying to figure out what you can do :-) With regards to the notebooks page, have you seen that there are two methods: AddPage and InsertPage? With InsertPage you can specify the position where the page is to be inserted, putting them on the desired order. But I don't know if you already tried that and it didn't do what you expected... Be seeing you, -- Godoy. From __peter__ at web.de Tue Jan 27 12:56:13 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Jan 2004 18:56:13 +0100 Subject: Problem with RE matching backslash References: <7b5e60b8754ab5afcea58d4ecc8b8849@news.meganetnews.com> <9114f8b2d460bc916150d0ae96a69ea7@news.meganetnews.com> Message-ID: Jeff Epler wrote: >> What is still not clear to me is why the search examples work and yield >> 'm'. > > Because the first pattern, which you wrote as "\\m", will match a lone > 'm'. So 'match' fails, because m is not in the first position. But > 'search' succeeds at index 1. > > Jeff This was my first guess, but it took me a while do find it documented. I will reproduce the tiny relevant paragraph from http://www.python.org/doc/current/lib/re-syntax.html "The special sequences consist of "\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character "$". " [description of characters with special meaning omitted] I don't know if this list of characters is likely to grow, but I would definitely prefer a "bogus escape" exception: >>> re.compile("\\m") <_sre.SRE_Pattern object at 0x40289660> versus >>> re.compile("\\1") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/sre.py", line 179, in compile return _compile(pattern, flags) File "/usr/local/lib/python2.3/sre.py", line 229, in _compile raise error, v # invalid expression sre_constants.error: bogus escape: '\\1' Peter From Pieter.Claerhout at Creo.com Wed Jan 28 04:22:00 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 28 Jan 2004 10:22:00 +0100 Subject: Cross Platform Browser Launcher Message-ID: <490316A24CC5D411ACD700B0D078F7F003915E28@cseexch01.cse.creoscitex.com> Take a look at the webbrowser module... http://www.python.org/doc/current/lib/module-webbrowser.html Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: michael at foord.net [mailto:michael at foord.net] Sent: 28 January 2004 10:18 To: python-list at python.org Subject: Cross Platform Browser Launcher I've written a simple application in python with an HTML help file. I'm looking for a cross platform way of launching the help file. On windows I'd use : os.system('start help.html') Which automatically opens the file with the users browser. Is there a cross-platform way of doing the same thing ? I can do a platform test and use different techniques for different systems - but I don't know how to achieve the same effect on a Linux (Unix ? Mac ?) machine..... Any help appreciated. Fuzzy -- 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.voidspace.org.uk/atlantibots/pythonutils.html Python functions - home of dateutils, ConfigObj, StandOut, CGI-News and more.... -- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera -- http://mail.python.org/mailman/listinfo/python-list From jjl at pobox.com Sat Jan 10 19:50:49 2004 From: jjl at pobox.com (John J. Lee) Date: 11 Jan 2004 00:50:49 +0000 Subject: Databases: Which one's right for me? References: <4378fa6f.0401091717.1ae63541@posting.google.com> Message-ID: <878ykf71g6.fsf@pobox.com> Rene Pijlman writes: > Marc: > >Basically I need a db that will travel with my executable script and > >faithfully store and edit the data needed in that script. > > Have a look at ZODB. > > Introduction: > http://www.python.org/workshops/2000-01/proceedings/papers/fulton/zodb3.html Which doesn't have a built-in query system, so isn't a database in the same way as a relational DB like Postgres or Oracle. It's more like BSDDB + pickle. John From michael at foord.net Wed Jan 7 03:44:16 2004 From: michael at foord.net (Fuzzyman) Date: 7 Jan 2004 00:44:16 -0800 Subject: Python Utils - A simple config file parser and output object Message-ID: <8089854e.0401070044.1e8116ad@posting.google.com> A couple of little scripts I've written for my python project (AAAcontroller - see www.atlantibots.org.uk) might be useful to others - so I've stuck them up on the web : http://www.voidspace.org.uk/atlantibots/pythonutils.html They're my new config object - ConfigObj - and my output object StandOut....... ConfigObj parses and updates simple config files (including multiple values for keywords, preserving comments, and updating sections of the file). StandOut is an output object that can print messages to the screen *and* to a logfile..... Fuzzy -- 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.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. --- 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 kenfar42 at yahoo.com Sat Jan 3 19:14:43 2004 From: kenfar42 at yahoo.com (Ken) Date: 3 Jan 2004 16:14:43 -0800 Subject: Python Job Market References: Message-ID: Samuel Walters wrote in message news:... > You know. I never thought about this before. Maybe I could find a niche > reformatting old cobol records and systems. Is there any demand for that > sort of thing? Sure - though conversion of batch mainframe applications involves considerable more complexity than just being able to read COBOL copybooks. Perhaps there's more work in data conversion. I've been using python successfully on data warehouse ETL (extract, transform, load) projects for a couple of years now. Best practices are to use a commercial product for this - but you can easily get hung up in procurement, training, feasibility studies, approvals, etc - that many projects end up being implemented in perl instead. These applications tend to be maintenance-intensive, are often developed iteratively, have a heavy focus on data quality, and should be accessible to a wide range of IT personnel - python is a natural fit. Anyhow, my current etl project is about 5% korn shell and 95% python and is processing about 10 million rows/day - and is expected to have to scale to 300 million rows/day by the end of 2004. This load will require some optimizations but can be achieved with the hardware at hand based on current performance figures. Note that python wasn't on the list of approved solutions in this organization, but I was allowed to use it - since I was doing much of the work in my own time - and presented the option of an eventual path to Java (via jython). Now most of the team is firmly behind it - they've seen how low the learning curve has been, and how fast it has been to develop with. ken From jeffplus at comcast.net Sat Jan 3 11:05:54 2004 From: jeffplus at comcast.net (Jeff Schwab) Date: Sat, 03 Jan 2004 11:05:54 -0500 Subject: Text-to-HTML processing program In-Reply-To: References: Message-ID: phil hunt wrote: > Does anyone know of a text-to-HTML processing program, ideally > written in Python because I'll probably be wanting to make small > modifications to it, which is simple and straightforward to use > and which uses a simple markup language (something like Wikipedia > markup would be ideal)? How about troff? Or if you really want to keep it simple, why not use the
 tag in HTML?




From alessandro at sephiroth.it  Mon Jan 12 17:58:12 2004
From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*)
Date: Mon, 12 Jan 2004 22:58:12 GMT
Subject: dde
Message-ID: <8EFMb.102403$_P.3808599@news4.tin.it>

Hi all
I would like to send dde messages to an application, but i don't know which messages it supports.
Is possible to do in some way or I absolutely need the api specifications?

ps. i can't find any documentation about dde module. is there a link?

tnks in advance
Alessandro




From teengo at yahoo.com  Mon Jan 12 12:50:38 2004
From: teengo at yahoo.com (Ticachua)
Date: 12 Jan 2004 09:50:38 -0800
Subject: How to intercept a keypress using python?
Message-ID: 

Hello all,

Does anyone know how to intercept user's keypress or mouseclick in Python?
I'd like to write a small tool (Python-based preferrably) running on
Windows to capture the user's keypresses and mouseclicks and write 
them to a file.

Thanks for your help.


From marco at bubke.de  Thu Jan 15 12:56:25 2004
From: marco at bubke.de (Marco Bubke)
Date: Thu, 15 Jan 2004 18:56:25 +0100
Subject: QT usage confusion
References: <40069912$0$251$4d4ebb8e@news.nl.uu.net>
Message-ID: 

Guyon Mor?e wrote:

> hmmm, all this time that I am fooling around with python I never took a
> good look at (py)QT.
> I want to have a go at it, after being a bit disapointed about the
> alternatives.
> 
> I have read multiple docs about it and searched this newsgroup I came to
> the conclusion that, as I am a windows user, I have only 2 options:
> 
> - buy a commercial qt license
> - try it out for 30 days (!)
> 
> that sucks ;)
> 
> am I wrong?
> please tell me I'm wrong.

There is a new Book(look at www.trolltech.com) with the Qt 3.2.1 Windows
non-commerial Version.

Marco


From michael at foord.net  Thu Jan 29 03:12:41 2004
From: michael at foord.net (Fuzzyman)
Date: 29 Jan 2004 00:12:41 -0800
Subject: Webhosting with Python
References: <8089854e.0401280834.6fd4f972@posting.google.com>
	
Message-ID: <8089854e.0401290012.465ba364@posting.google.com>

> On 2004-01-28 11:34:43 -0500, michael at foord.net (Fuzzyman) said:
> 
> > I've recently starting using a very cheap web hoster who has python
> > 2.2 installed.... almost free hosting (but not quite).....
> > 
> > Thought some of you guys might be interested..........
> > 
> > http://www.xennos.com
> > 
> > Fuzzyman
> 
> How do you plan to make money off of this?

I don't intend to make any money off it...... it's not my hosting firm
- but I know how long it took me to find cheap hosting with Python -
so I thought others might be interested.

Fuzzy


From cygnus at cprogrammer.org  Mon Jan 26 15:32:15 2004
From: cygnus at cprogrammer.org (Jonathan Daugherty)
Date: Mon, 26 Jan 2004 15:32:15 -0500
Subject: wxPython: images from URLs
Message-ID: <20040126203215.GA4742@mail.theserver.ath.cx>

Does anyone here know if the wxImage class in wxPython supports dislaying
images from URLs?

-- 

  Jonathan Daugherty
  http://www.cprogrammer.org

  "It's a book about a Spanish guy called Manual, you should read it."
                                                            -- Dilbert



From jjl at pobox.com  Fri Jan  2 18:19:22 2004
From: jjl at pobox.com (John J. Lee)
Date: 02 Jan 2004 23:19:22 +0000
Subject: Can this be reversed (Tkinter)?
References: 
Message-ID: <87znd6j5vp.fsf@pobox.com>

"mark"  writes:

> I am looking at the format used by root.geometry().  The string returned
> from root.geometry() is "%dx%d+%d+%d".  Is there a quick and painless
> way to extract the values from that string (i.e., "100x150+25+25" =>
> (100,150,25,25))?

def geometry_tuple_from_string(text):
    a, rest = text.split("x")
    b, c, d = rest.split("+")
    return tuple([int(x) for x in (a, b, c, d)])

print geometry_tuple_from_string("100x150+25+25")


John


From mtadin66 at yahoo.com  Sun Jan 18 23:46:36 2004
From: mtadin66 at yahoo.com (Marijan Tadin)
Date: Mon, 19 Jan 2004 05:46:36 +0100
Subject: Searching for UTF8 capable font for REPORTLAB
References: 
Message-ID: 

Try following code, replace value of my_location_of_TTF with your
location of TTF (of course you should have TT fonts somewhere on your
machine, on windows they are allways there, AFAIK you can download them
for linux):

There is also mailing list on ReportLabs website, it is where I found
the hint how to use ReportLab and Unicode.


from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

canv = canvas.Canvas('test_03.pdf')
fontname = 'CS'

my_location_of_TTF = 'C:\WINNT\FONTS\comic.TTF'

pdfmetrics.registerFont(TTFont(fontname,my_location_of_TTF))
a=u'\u010d\u0107\u017e\u0161\u0111\u010c\u0106\u017d\u0160\u0110'
canv.setFont(fontname,10)
canv.drawString(50,100,'Some text:'+a.encode('UTF8'))
canv.save()


"Andreas Jung"  wrote in message
news:mailman.429.1074256100.12720.python-list at python.org...
> Reportlab has some problems with creating PDFs from UTF8 encoded text.
For
> this reason
> they are using a truetype font rina.ttf which looks *very ugly*. Does
> anyone know of a
> suitable free available truetype font that works with UTF8?
>
> -aj
>
>



From jepler at unpythonic.net  Mon Jan 12 11:24:23 2004
From: jepler at unpythonic.net (Jeff Epler)
Date: Mon, 12 Jan 2004 10:24:23 -0600
Subject: Python is far from a top performer according to benchmark
	test...
In-Reply-To: <6ee58e07.0401120542.5d79090d@posting.google.com>
References:  
	
	<6ee58e07.0401092129.302cb9d4@posting.google.com>
	
	<6ee58e07.0401120542.5d79090d@posting.google.com>
Message-ID: <20040112162422.GF2810@unpythonic.net>

On Mon, Jan 12, 2004 at 05:42:22AM -0800, Lothar Scholz wrote:
> Python for hardcore numerics, even with PyNumerics, is simply a very
> bad solution.

I think that many of us are not in a situation where we have to make our
program run fast enough to save a million on a supercomputer, but where
we have to make our program run soon enough to save a few thousands or
maybe tens of thousands on programmer time.

ObLink: http://cens.ioc.ee/projects/f2py2e/

Jeff



From virus.manager at st.com  Wed Jan 28 05:16:34 2004
From: virus.manager at st.com (virus.manager at st.com)
Date: Wed, 28 Jan 2004 10:16:34 -0000
Subject: Virus Alert
Message-ID: <20040128101634.B42AFF380@zeta.dmz-eu.st.com>

The mail message (file: body.pif) you sent to  contains a virus. (on zeta)



From fuf at mageo.cz  Wed Jan 28 12:16:02 2004
From: fuf at mageo.cz (Michal Vitecek)
Date: Wed, 28 Jan 2004 18:16:02 +0100
Subject: isinstance() bug
In-Reply-To: 
References: <20040128132225.GA10842@foof.i3.cz>
	<16407.54576.283608.505067@montanaro.dyndns.org>
	
	
Message-ID: <20040128171602.GC11485@foof.i3.cz>

Peter Otten wrote:
>Which reminds me - why do you want to put a package directory into your
>python path in the first place?. Before spending to much effort on fixing
>the problems that this practice entails, what are the benefits?

 i never said i wanted to do it - and i don't do it. it's just i've come
 across this buggy behaviour and thought to ask/report it for other
 thoughts on the issue.

-- 
		fuf		(fuf at mageo.cz)



From cpl.19.ghum at spamgourmet.com  Thu Jan  1 15:58:55 2004
From: cpl.19.ghum at spamgourmet.com (Harald Massa)
Date: Thu, 1 Jan 2004 21:58:55 +0100
Subject: Quote of an Imam
Message-ID: 


"""Many packages are also coded in obscure languages such as Mod Perl, 
Python and Tcl. 'A lot of them have been around for a long time and have 
been put together by the kind of webmasters at which they were aimed, so 
they tend to use languages which theorists think are good languages, but 
you don't get many skills in the market - it's not .NET or Java,' says 
Hoque."""

http://www.itconsultantmagazine.com/magazine/index.cfm?
fuseaction=article&ArticleID=411


I don't know what I dislike more: calling Python "obscure", that he talkes 
about "theorists ...." or that he lines up Python with Perl and Tcl.

But I got most upset when I was reading "theorists" as "terrorists" :)))))

Harald


From jl at windsmith.net  Sun Jan 11 02:48:09 2004
From: jl at windsmith.net (John Lull)
Date: 11 Jan 2004 01:48:09 -0600
Subject: Multithreaded COM server problem...
References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com>
	
Message-ID: 

Mark Hammond  wrote (with possible deletions):

> John Lull wrote:
> 
> > I'm writing a multithreaded COM server to manage a pool of hardware resources.
> > All objects are designed to be thread-safe, and I've set sys.coinit_flags to
> > COINIT_MULTITHREADED before importing pythoncom.
> 
> Note that this flag is effeectively ignored for the server.  Objects are 
> created in the same "apartment" as their creator.  This, the code 
> implementing your object need not specify this, but the code *creating* 
> the object must.  This is what determines the appartment.
> 
> COM threading rules are complex, but "Python Programming on Win32" (1/2 
> by me :) covers these rules in words I would have trouble finding again :)

It covers threading rules for in-process servers pretty thoroughly.

Unfortunately, this one has to be a local server since it's providing shared
access to a pool of hardware devices from multiple distributed clients. I've
carefully reviewed chapters 5 & 12, and appendix D, and wasn't able to find
anything addressing threading models in the local server in detail. If I've
missed something, I'd be grateful for any additional hints. 

Thanks.


Regards,
John



From sross at connectmail.carleton.ca  Thu Jan  1 21:45:01 2004
From: sross at connectmail.carleton.ca (Sean Ross)
Date: Thu, 1 Jan 2004 21:45:01 -0500
Subject: finding file size
Message-ID: <4V4Jb.12709$Vl6.2811218@news20.bellglobal.com>

Hi.

Recently I made a small script to do some file transferring (among other
things). I wanted to monitor the progress of the file transfer, so I needed
to know the size of the files I was transferring.  Finding out how to get
this information took some time (reading the manuals - googling did not
prove worthwhile). Anyway, I did eventually figure out how to do it (there
are a few ways, including os.path.getsize(filename)).

My question is this: Is there a reason why file objects could not have a
size method or property? So that you could then just ask the file how big it
is using fd.size or fd.size(). I'm just curious, because, well, it seems to
have obvious utility, and the way to find it is less than obvious (at least,
it was to me).

Thanks,
Sean




From daniel.dittmar at sap.com  Mon Jan 19 05:49:19 2004
From: daniel.dittmar at sap.com (Daniel Dittmar)
Date: Mon, 19 Jan 2004 11:49:19 +0100
Subject: Analysing Word documents (slow) What's wrong with this code
	please!
References: <3d06fae9.0401161351.75e7f5a@posting.google.com>
Message-ID: 

jmdeschamps wrote:
> Anyone has a hint how else to get faster results?
> (This is to find out what was bold in the document, in order to grab
> documents ptoduced in word and generate html (web pages) and xml
> (straight data) versions)
[...]
> for i in range(len(MSWord.Documents[0].Content.Text)):
>     if MSWord.Documents[0].Range(i,i+1).Bold  : # testing for bold

Perhaps you can search for bold text. The Word search dialog allows this.
And when you use the keybord macro recording feature of Word, you can
probably figure out how to use that search feature from Python.

Daniel





From xpythonist at yahoo.com.br  Mon Jan 19 07:43:01 2004
From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=)
Date: Mon, 19 Jan 2004 09:43:01 -0300 (ART)
Subject: Escaping slashes (double backslash plague)
Message-ID: <20040119124301.6247.qmail@web21501.mail.yahoo.com>

I need to replace every ocurrence of '/' in s by '\/'
in order to create a file named s. My first attempt
was:

s = '\/'.join(s.split('/'))

but it doesn't work:

>>> s = 'a/b'
>>> s = '\/'.join(s.split('/'))
>>> s
'a\\/b'
>>> repr(s)
"'a\\\\/b'"
>>>

'\/'.join() escapes the backslashes and I don't know
why. 

Any help?

Aloysio Figueiredo

______________________________________________________________________

Yahoo! GeoCities: a maneira mais f?cil de criar seu web site gr?tis!
http://br.geocities.yahoo.com/



From mhammond at skippinet.com.au  Sat Jan 10 17:17:28 2004
From: mhammond at skippinet.com.au (Mark Hammond)
Date: Sun, 11 Jan 2004 09:17:28 +1100
Subject: Communicating with MSVC++ via COM: how?
In-Reply-To: 
References: 
Message-ID: 

Eric Brunel wrote:
> This script doesn't work: the call to docs.CloseAll fails with the error:
> 
> Traceback (most recent call last):
>   File "test.py", line 13, in ?
>     docs.CloseAll()
> TypeError: object of type 'int' is not callable

This is because docs.CloseAll is making the call, and returning an int. 
  This, docs.CloseAll() is attempting to call that int.

It looks very much like you have no makepy support for MSVC built.

Just after the line:
app = win32com.client.Dispatch('MSDev.Application')
Try adding:
app = win32com.client.gencache.EnsureDispatch(app)

That should force makepy, and everything should start working.

Mark



From sombDELETE at pobox.ru  Sat Jan  3 18:13:07 2004
From: sombDELETE at pobox.ru (Serge Orlov)
Date: Sun, 4 Jan 2004 02:13:07 +0300
Subject: Creating a capabilities-based restricted execution system
References:  
	
Message-ID: 


"Sean R. Lynch"  wrote in message news:d7ycncKp5rket2qiXTWc-g at speakeasy.net...
> Serge Orlov wrote:
> > "Sean R. Lynch"  wrote in message news:LmmdnUn4seDeGWuiXTWc-w at speakeasy.net...
> >>To create private attributes, I'm using "name mangling," where names
> >>beginning with X_ within a class definition get changed to
> >>__, where the UUID is the same for that class. The UUIDs
> >>don't need to be secure because it's not actually possible to create
> >>your own name starting with an underscore in RestrictedPython; they just
> >>need to be unique across all compiler invocations.
> >
> >
> > This is a problem: you declare private attributes whereas you should be
> > declaring public attributes and consider all other attributes private. Otherwise
> > you don't help prevent leakage. What about doing it this way:
> >
> > obj.attr means xgetattr(obj,acc_tuple) where acc_tuple = ('attr',UUID)
> > and xgetattr is
> > def xgetattr(obj,acc_tuple):
> >   if not has_key(obj.__accdict__,acc_tuple):
> >     raise AccessException
> >   return getattr(obj,acc_tuple[0])
> >
> > __accdict__ is populated at the time class or its subclasses are created.
> > If an object without __accdict__ is passed to untrusted code it will
> > just fail. If new attributes are introduced but not declared in __accdict__
> > they are also unreachable by default.
>
> This is very interesting, and you may convince me to use something
> similar, but I don't think you're quite correct in saying that the
> name-mangling scheme declares private attributes; what is the difference
> between saying "not having X_ in front of the attribute makes it public"
> and "having X_ in front of the attribute makes it private?"

You're right, the wording is not quite correct. My point was that it should
take effort to make attributes _public_, for example, going to another
source line and typing attribute name or doing whatever "declaration" means.
This way adding new attribute or leaking "unsecured" object will
raise an exception when untrusted code will try to access it. Otherwise
one day something similar to rexec failure will happen: somebody
added __class__ and __subclasses__ attributes and rexec blindly
allowed to access them. The leading underscore doesn't matter, it
could be name like encode/decode that is troublesome.

By the way, my code above is buggy, it's a good idea that you're
not going to use it :) Let me try it the second time in English words:
If the attribute 'attr' is declared public give it. If the function with
UUID has access to attribute 'attr' on object 'obj' give it. Otherwise fail.


>
> I am not (particularly) concerned about DoS because I don't plan to be
> running anonymous code and having to restart the server isn't that big
> of a deal. I do plan to make it hard to accidentally DoS the server, but
> I'm not going to sacrifice a bunch of performance for that purpose. As
> for covert channels, can you give me an example of what to look for?

Nevermind, it's just a scary word :) It can concern you if you worry
about information leaking from one security domain to another. Like
prisoners knocking the wall to pass information between them. In
computers it may look like two plugins, one is processing credit
cards and the other one has capability to make network connections.
If they are written by one evil programmer the first one can "knock
the wall" to pass the information to the second. "knocking the wall"
can be encoded like quick memory allocation up to failure = 1, no
quick memory allocation = 0. Add error correction and check summing
and you've got a reliable leak channel.

>
> I am certainly worried about non-obvious things, but my intent wasn't to
> put up a straw man, because if I ask if I'm missing non-obvious things,
> the only possible answer is "of course."
>
> > By the way, did you think about str.encode? Or you are not worried about
> > bugs in zlib too?
>
> Well, it'll only take *one* problem of that nature to force me to go
> back to converting all attribute accesses to function calls. On the
> other hand, as long as any problem that allows a user to access
> protected data is actually a in (zlib, etc), I think I'm not going to
> worry about it too much yet. If there is some method somewhere that will
> allow a user access to protected data that is not considered a bug in
> that particular subsystem, then I have to fix it in my scheme, which
> would probably require going back to converting attribute access to
> method calls.

I'm not sure how to deal with str.encode too. You don't know what
kind of codecs are registered for that method for sure, one day there
could be registered an unknown codec that does something unknown.
Shouldn't you have two (or several) codecs.py modules(instances?)
for trusted and untrusted code? And str.encode should be transparently
redirected to the proper one?

-- Serge.




From DSAVDATALEX_NT001 at datalex.ie  Fri Jan 30 13:57:57 2004
From: DSAVDATALEX_NT001 at datalex.ie (DSAVDATALEX_NT001(Network Associates Anti-Virus - Mailbox Agent))
Date: Fri, 30 Jan 2004 18:57:57 -0000
Subject: ALERT - Virus W32/Mydoom.a@MM found; an attachment/message has be
	en quarantined
Message-ID: <111302C972D7D01185A00060977D7D4105F29094@DATALEX_NT>

Action Taken:
An attempt to disinfect the attachment was unsuccessful,
so the attachment was quarantined from the message and replaced with
a text file informing the recipient of the action taken. The infected
attachment
has been placed in the designated quarantine folder.
Please exercise extreme caution when handling the quarantined attachment

To:
dave at datalex.ie

From:
python-list at python.org

Sent:
-115776512,29615970

Subject:
Hi

Attachment Details:-

Attachment Name: doc.zip
File: doc.zip
Infected? Yes
Repaired? No
Virus Name: W32/Mydoom.a at MM



	
*********************************************************************
This electronic transmission is strictly confidential and intended solely
for the addressee. It may contain information which is covered by legal,
professional or other privilege. If you are not the intended addressee,
you must not disclose, copy or take any action in reliance of this
transmission. If you have received this transmission in error, 
please notify the sender as soon as possible.

This footnote also confirms that this message has been swept
for computer viruses.
**********************************************************************

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/ms-tnef
Size: 2526 bytes
Desc: not available
URL: 

From tmartinez at ammsoft.com  Mon Jan 26 15:51:46 2004
From: tmartinez at ammsoft.com (Ya)
Date: Mon, 26 Jan 2004 21:51:46 +0100
Subject: wxpython and wxlocale
Message-ID: 

Problem:
In a computer it is wanted to install an application that must show
information in different languages.
Thanks to the module we, gettext, have been able to implement that the texts
that are shown are translated.
The user selects the language and act from a file .mo every language.
The problem are the messages and dialogues since it shows the buttons in the
language of the operating system by default.
Is there any way of telling python that the text of the dialogues is in a
specific language?
And in affirmative case. How is it made? since all the attempts have been
useless.
I think that wxLocale has to be used, but I do not become clear.

We are using Python 2.3.3 and wxpython 2.4.2.4 in W2K.

Greetings.





From davidb at mcs.st-and.ac.uk  Thu Jan  8 16:18:09 2004
From: davidb at mcs.st-and.ac.uk (David Boddie)
Date: 8 Jan 2004 13:18:09 -0800
Subject: metadocumentation (keyword help)
References: 
	
	<3ffb0edf$1@nntp0.pdx.net> 
	 
Message-ID: <4de76ee2.0401081318.bab6f62@posting.google.com>

Jacek Generowicz  wrote in message news:...

> I always wonder whether I should post concise articles, or wordy ones,
> covering all possbile assumpitons and misconceptions.
> 
> It appears that, usually, I get the balance hopelessly wrong :-( Or,
> maybe, that's just what life is like in a large public forum; whatever
> you say, there will always be hundreds of people who misunderstand you.

Let's hope I'm answering your original question.

> Does someone who writes 
> 
> > > GNU/Linux, Mac OS X, and even Windoze
>                              ^^^^    ^^^^
> really look like someone who is looking for instructions on fixing his
> Python installation on a M$ operating system ?

I don't know why you wrote that originally. I can only presume that you
were asking for a general solution because, otherwise, it would appear
that you were asking for assistance which you didn't want. Anyway, it
doesn't really matter.

The quoting gets confusing in your message, so I presume that all of
the following attributable to you:

> The point is
> that I hope that the studens will go away with the ability to find
> most things out for themselves. In this context, I would like them to
> be able to find out for themselves how to fix the keyword
> documentation, which is why I phrased my original question thus:
> 
> > Where can I find concise, clear documentation[*] describing what one
> > has to do in order to enable Python's internal help to be able to
> > provide descriptions of Python keywords ?
> 
> Note, I did NOT say "How do I ...", I said "Where do I find
> [...] documentation ...".

Five minutes with Google failed to reveal any "official" document, if
you don't count mailing list archives. However, five seconds with the
search engine at

    http://www.python.org/search/

revealed that the basic information about the PYTHONDOCS environment
variable can be found at the foot of the following page:

    http://www.python.org/dev/doc/devel/lib/module-pydoc.html

I'm sorry if this isn't good enough for your purposes.

> I am NOT interested in a recipe posted here. I want to know where to
> find the official instructions on how it is done, so that I can show
> newbies how to find the information themselves.
> 
> "Give a man a fish, and he can eat for a day. Teach a man to fish ...",
> and all that.

Well, I learned something from the recipes posted in this thread, even
if it isn't suitable for your purposes.

> If these instructions are, as it seems, absent, then I would
> appreciate advice on what I can do to make them appear in the
> appropriate place, and what the appropriate place might be.

They could always be written up in the PythonInfo Wiki, then at
least you have a python.org URL to give your students.

> I recognize my impatience with poor documentation as a pathological
> flaw in my characer, which is why I am asking for help in
> finding/creating this documentation here.

You're going to have to be quite patient, though. If the documents
you want aren't obvious then it's probably up to you to write them. :-/

David

P.S. You'll note that I haven't come up with my own recipe so far.
For what it's worth, a document describing how to obtain help on
keywords might start in the following way:

Configuring Python to supply help on keywords
=============================================

Introduction
------------
Recent versions of Python include the ability to display help on
existing objects, or to search for information on installed modules,
from within the interactive environment. However, it is also possible
to use the help system to display information on the keywords used
in the language itself, such as "if" and "for. This feature appears
to be less well-known, possibly because users seek basic language
information elsewhere, but maybe also because it is not always
enabled by default.

Requirements
------------
In order to seek help on keywords from within the interactive
environment, two things need to be done before Python is invoked:

 * The HTML documentation needs to be downloaded and installed in an
   accessible location; this will depend on the operating system in
   use.
 
 * The PYTHONDOCS environment variable will need to be set to the
   path of the installed HTML files.

Setting it up
-------------
First of all, check whether the HTML documentation has already been
installed for the version of Python you are using. This could save
you the effort of downloading and installing it manually.

If the documentation is required then go to::

  http://www.python.org/download/

and find the appropriate documentation. Download it and install it
in a place where it can be read by those who will be using it.

Checking it works
-----------------
Using the appropriate method provided by your operating system, set
the PYTHONDOCS environment variable to the directory which contains
the main index file for the documentation.

For example, you may have installed the documentation in
/usr/share/doc/python so that the directory layout look like::

  /usr/share/doc/python
  |- Misc
  |- README
  \- html
     |- about.html
     |- acks.html
     |- api/
     |- dist/
     |- doc/
     ...

and so on. Therefore, PYTHONDOCS should be set to /usr/share/doc/python/html
since this contains the information required. On Linux systems, using the
bash shell, you might type::

  export PYTHONDOCS=/usr/local/share/python/html python

to start the interpreter. Within the Python environment, typing::

  help("if")

should now cause something like the following to be displayed::

  7.1 The if statement
  
    The if statement is used for conditional execution:
    
          if_stmt   ::=    "if" expression[1] ":" suite[2]
                           ( "elif" expression[3] ":" suite[4] )*
                           ["else" ":" suite[5]]
  
    Download entire grammar as text.[6]
  
    It selects exactly one of the suites by evaluating the expressions one
    by one until one is found to be true (see section 5.10[7] for the
    definition of true and false); then that suite is executed (and no other
    part of the if statement is executed or evaluated). If all expressions
    are false, the suite of the else clause, if present, is executed.

Enabling this by default
------------------------
Any ideas?


From amy-g-art at cox.net  Fri Jan 23 17:55:52 2004
From: amy-g-art at cox.net (Amy G)
Date: Fri, 23 Jan 2004 14:55:52 -0800
Subject: Various strings to dates.
References: <4GfQb.16187$AA6.14368@fed1read03>
	
	
	
Message-ID: 

That is exactly what I am looking for.  However I don't have the module
installed.  Where can I get it?

"Michael Spencer"  wrote in message
news:K4ydna_ey7rvOIzdRVn-jw at comcast.com...
> "Amy G"  wrote in message
> news:PRgQb.16209$AA6.9881 at fed1read03...
> > No it won't.  Unfortunatly I don't necessarily have a comma delimited
date
> > string.  Thanks for the input though.
> >
> > The following three date strings is another example of the various date
> > formats I will encounter here.
> >
> > Thursday, 22 January 2004 03:15:06
> > Thursday, January 22, 2004, 03:15:06
> > 2004, Thursday, 22 January 03:15:06
> >
> > All of these are essentially the same date... just in various formats.
I
> > would like to parse through them and get a comparable format so that I
can
> > display them in chronological order.
> >
> >
> > "wes weston"  wrote in message
> > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net...
> > > Amy,
> > >     I hope there is a better way but, if you go here:
> > >
> > > http://www.python.org/doc/current/lib/datetime-date.html
> > >
> > > The new datetime module may help. This and the time mod
> > > should get you where you want to go.
> > >
> > > list     = strdate.split(", ")
> > > daystr   = list[0]
> > > daynum   = int(list[1])
> > > monthstr = list[2]
> > > year     = int(list[3])
> > > #funct to get a month int is needed
> > >
> > > d = datetime.Date(y,m,d)
> > >
> > > wes
> > >
> > > ---------------------------------------
> > >
> > > Amy G wrote:
> > > > I have seen something about this beofore on this forum, but my
google
> > search
> > > > didn't come up with the answer I am looking for.
> > > >
> > > > I have a list of tuples.  Each tuple is in the following format:
> > > >
> > > > ("data", "moredata", "evenmoredata", "date string")
> > > >
> > > > The date string is my concern.  This is the date stamp from an
email.
> > > > The problem is that I have a whole bunch of variations when it comes
> to
> > the
> > > > format that the date string is in.  For example I could have the
> > following
> > > > two tuples:
> > > >
> > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15")
> > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004
> > 03:15:06")
> > > >
> > > > I know there is some way to use the date string from each of these
to
> > get a
> > > > date usable by python, but I cannot figure it out.
> > > > I was trying to use time.strptime but have been unsuccesful thus
far.
> > > >
> > > > Any help is appreciated.
> > > >
> > > >
> > >
> >
> >
>
> This was asked and answered earlier today
>
> See: https://moin.conectiva.com.br/DateUtil
>
> >>> from dateutil.parser import parse
> >>> parse("Thursday, 22 January 2004 03:15:06")
> datetime.datetime(2004, 1, 22, 3, 15, 6)
> >>> parse("Thursday, January 22, 2004, 03:15:06")
> datetime.datetime(2004, 1, 22, 3, 15, 6)
> >>> parse("2004, Thursday, 22 January 03:15:06")
> datetime.datetime(2004, 1, 22, 3, 15, 6)
> >>>
>
>
>




From dw-google.com at botanicus.net  Fri Jan 23 18:46:46 2004
From: dw-google.com at botanicus.net (David M. Wilson)
Date: 23 Jan 2004 15:46:46 -0800
Subject: Ordered dictionary?
References: 
	
Message-ID: <99dce321.0401231546.5f73d721@posting.google.com>

"Paul McGuire"  wrote...

> If you really need to access the dictionary in sorted key order, is this so
> difficult?

That was not the original poster's question. Order is semantic
information which a dictionary does not record or represent in any
way.


David.


From fumanchu at amor.org  Thu Jan 15 19:16:20 2004
From: fumanchu at amor.org (Robert Brewer)
Date: Thu, 15 Jan 2004 16:16:20 -0800
Subject: Redefining __call__ in an instance
Message-ID: 

Robert Ferrell wrote:
> I'd like to have a factory class that takes a string argument 
> and returns
> the appropriate factory method based on that string.  I'd like the
> instances to be callable.  Like this:
> 
> fact = Factory('SomeThing')
> aSomeThing = fact(some args)
> 
> anotherFact = Factory('SomeThingElse')
> anotherThing = anotherFact(some other args)

Perhaps this will give you some ideas:

>>> class SomeThing(object):
... 	pass
... 
>>> def Factory(classname, *args, **kwargs):
... 	return globals()[classname](*args, **kwargs)
... 
>>> st = Factory('SomeThing')
>>> st
<__main__.SomeThing object at 0x010C0F10>


If you still want to package that into a class instead of a function
(and then override __call__), feel free. Obviously, more exception
checking could be done.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



From irmen at -NOSPAM-REMOVETHIS-xs4all.nl  Sun Jan 25 08:41:26 2004
From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong)
Date: Sun, 25 Jan 2004 14:41:26 +0100
Subject: compress string of data
In-Reply-To: 
References: 
Message-ID: <4013c786$0$325$e4fe514c@news.xs4all.nl>

Jos? Carlos wrote:

> How i could compress string of data?.

Type "python compress string of data" in google and press "I'm feeling lucky".
That might help you out.

--Irmen


From jcribbs at twmi.rr.com  Thu Jan 29 23:21:00 2004
From: jcribbs at twmi.rr.com (Jamey Cribbs)
Date: Fri, 30 Jan 2004 04:21:00 GMT
Subject: Simple Database Package
In-Reply-To: <8089854e.0401280622.4e145267@posting.google.com>
References: <8089854e.0401280622.4e145267@posting.google.com>
Message-ID: 

Fuzzyman wrote:
> Anyone able to reccomend a simple module / package I can use...  ?
> I've never done any database work before and am ken to learn - but
> most of the ones I've seen seem to rely on a database engine buit into
> a server.. I need a simple stand alone engine. Of course I could just
> build the functions I need - but that would be a bit of a waste and
> not so extendable........

Have a look at KirbyBase (http://www.netpromi.com/kirbybase.html).  It's 
written in Python, can be either embedded in your application or used in 
a multi-user/client server mode, and stores its data as plain-text files 
that can be opened by any text editor.  I'm probably a little biased 
because I wrote it, but, if your needs are simple, it might prove useful.

Jamey


From hotrearia at jetable.net  Tue Jan 27 12:51:19 2004
From: hotrearia at jetable.net (Nicolas Lehuen)
Date: Tue, 27 Jan 2004 18:51:19 +0100
Subject: Python 2.3.3 : Win32 build vs Cygwin build performance ?
Message-ID: <4016a71d$0$15004$afc38c87@news.easynet.fr>

Hi,

Is it me, or does anyone else get significantly better pystone results under
Cygwin versus the standard Win32 build ?

CYGWIN 1.5.6 + python 2.3.3-1 :
$ time python /usr/lib/python2.3/hotshot/stones.py
Pystone(1.1) time for 50000 passes = 2.344
This machine benchmarks at 21331.1 pystones/second
         850004 function calls in 4.371 CPU seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    50000    1.351    0.000    2.917    0.000 pystone.py:133(Proc1)
    50000    1.132    0.000    1.202    0.000 pystone.py:53(copy)
        1    0.609    0.609    4.371    4.371 pystone.py:79(Proc0)
    50000    0.239    0.000    0.239    0.000 pystone.py:208(Proc8)
   150000    0.184    0.000    0.184    0.000 pystone.py:203(Proc7)
   150000    0.157    0.000    0.157    0.000 pystone.py:221(Func1)
    50000    0.147    0.000    0.200    0.000 pystone.py:229(Func2)
    50000    0.104    0.000    0.153    0.000 pystone.py:160(Proc3)
    50000    0.098    0.000    0.153    0.000 pystone.py:184(Proc6)
    50000    0.090    0.000    0.090    0.000 pystone.py:149(Proc2)
    50002    0.070    0.000    0.070    0.000 pystone.py:45(__init__)
    50000    0.068    0.000    0.068    0.000 pystone.py:177(Proc5)
    50000    0.067    0.000    0.067    0.000 pystone.py:170(Proc4)
    50000    0.055    0.000    0.055    0.000 pystone.py:246(Func3)
        1    0.000    0.000    4.371    4.371 pystone.py:67(pystones)
        0    0.000             0.000          profile:0(profiler)


real    0m26.603s
user    0m25.765s
sys     0m0.280s

Win32 :
C:\Documents and Settings\nlehuen>python c:\Python23\Lib\hotshot\stones.py
Pystone(1.1) time for 50000 passes = 4.1542
This machine benchmarks at 12036 pystones/second
         850004 function calls in 14.917 CPU seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    3.772    3.772   14.917   14.917 pystone.py:79(Proc0)
    50000    2.226    0.000    6.314    0.000 pystone.py:133(Proc1)
   150000    1.166    0.000    1.166    0.000 pystone.py:221(Func1)
   150000    1.123    0.000    1.123    0.000 pystone.py:203(Proc7)
    50000    1.075    0.000    1.075    0.000 pystone.py:208(Proc8)
    50000    0.939    0.000    1.410    0.000 pystone.py:53(copy)
    50000    0.903    0.000    1.279    0.000 pystone.py:229(Func2)
    50000    0.795    0.000    1.157    0.000 pystone.py:160(Proc3)
    50000    0.776    0.000    1.137    0.000 pystone.py:184(Proc6)
    50000    0.500    0.000    0.500    0.000 pystone.py:149(Proc2)
    50002    0.472    0.000    0.472    0.000 pystone.py:45(__init__)
    50000    0.416    0.000    0.416    0.000 pystone.py:170(Proc4)
    50000    0.394    0.000    0.394    0.000 pystone.py:177(Proc5)
    50000    0.361    0.000    0.361    0.000 pystone.py:246(Func3)
        1    0.000    0.000   14.917   14.917 pystone.py:67(pystones)
        0    0.000             0.000          profile:0(profiler)

(total real time elapsed > 30 seconds)




From __peter__ at web.de  Fri Jan  9 05:08:08 2004
From: __peter__ at web.de (Peter Otten)
Date: Fri, 09 Jan 2004 11:08:08 +0100
Subject: __init__, __slot__ and **keywordargs
References: 
Message-ID: 

Zunbeltz Izaola wrote:

> I'm playing with __slot__ (new class) and the __init__ method of my
> class. I want the arguments of __init__ to be keywords and that the
> method initialize all the attributes in __slot__ to None except those
> in the argument of __init__ (Is this a good practice?). I've the
> following class

You misspelt: in fact it's __slots__, and it will work as expected. As far
as I know slots are an optimization technique that is useful to save some
space, when you have many (that would be millions) of small objects. It's
not meant as a safety belt for the programmer.
In your case, I wouldn't use it, but rather not initialize the attributes
not given as constructor - __init__() - arguments. Also, I would consider
the ability to provide additional arguments, say "Nickname", not a bug but
a feature. Of course you have to change your client code to test for

hasattr(person, "Birthday") 

instead of 

person.Birthday is None

Peter




From mwh at python.net  Tue Jan 13 06:39:52 2004
From: mwh at python.net (Michael Hudson)
Date: Tue, 13 Jan 2004 11:39:52 GMT
Subject: Why learn Python ??
References: <40029dad$0$28706$a729d347@news.telepac.pt>
	
	 <87hdz0g2zk.fsf@pobox.com>
	
	
Message-ID: 

Jacek Generowicz's alter ego  writes:

> Jacek Generowicz  writes:
> 
> > jjl at pobox.com (John J. Lee) writes:
> > 
> > > Jacek Generowicz  writes:
> > > [...]
> > > > If you want to perform miracles, then learn Lisp. If you
> > > > merely want to write programs that rock, then learn Python.
> > > [...]
> > > 
> > > ...and then somebody argues that macros aren't a programming language
> > > feature, but a harmful means of inventing new languages, and then we
> > > get into that endless macro thread again...
> > 
> > Well they're all Nazis.
> 
> Godwin's Law !

I believe Godwin's Law was meant to be descriptive, not prescriptive.
HAND.

Cheers,
mwh

-- 
  LINTILLA:  You could take some evening classes.
    ARTHUR:  What, here?
  LINTILLA:  Yes, I've got a bottle of them.  Little pink ones.
                   -- The Hitch-Hikers Guide to the Galaxy, Episode 12


From michael at foord.net  Fri Jan 16 03:53:38 2004
From: michael at foord.net (Fuzzyman)
Date: 16 Jan 2004 00:53:38 -0800
Subject: best book
References: 
Message-ID: <8089854e.0401160053.36e0f1aa@posting.google.com>

km  wrote in message news:...
> Hi all,
> 
> What is the best book to start with python ? i am have been working since 1 yr with Perl. 
> 
>  kindly enlighten,
> 
> thanks,
>  KM

There is a wealth of good, free python resources on the web.
For a comprehensive list of tutorials, online books and python
resources - Try :

http://www.voidspace.org.uk/coollinks/python_links.shtml

270 links in various sections.... 
Learning to program is a good online book, Dive into Python suits more
experienced programmers - whilst some of the tutorials will get you
the basics very quickly.
The Python documentation is good for built-in functions, types and the
standard libraries - which you will need to refer to a lot.

As a reference book I use the O'Reilly pocket reference book - very
useful and very handy (and not very expensive).

For learning to actually *use* Python (once I had grasped the basics)
I use (present tense) 'Programming Python' - from the same series as
'Learning Python' - (by Mark Lutz ?) I can't recommend it enough...
very good.

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.atlantibots.org.uk
http://groups.yahoo.com/group/atlantis_talk/
Atlantibots - stomping across the worlds of Atlantis.
---
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 webmaster at beyond-thoughts.com  Tue Jan  6 05:45:24 2004
From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng)
Date: Tue, 06 Jan 2004 11:45:24 +0100
Subject: PRE-PEP: new Path class
In-Reply-To: 
References: 
	
Message-ID: <3FFA91C4.8090006@beyond-thoughts.com>

Dan Bishop wrote:
> "John Roth"  wrote in message news:...
> 
>>I'm adding a thread for comments on Gerrit Holl's pre-pep, which
>>can be found here:
>>
>>http://tinyurl.com/2578q
>>
> 
> ... 
> 
>>1) Should path be a subclass of str?
>>
>>No.
> 
> 
> So will the file constructor be "overloaded" to accept path objects? 
> What about all those functions in the os module?

IMO this is the bettter way.
However it might be useful for transition subclass str. (see my other 
posting)






From http  Mon Jan 12 08:38:41 2004
From: http (Paul Rubin)
Date: 12 Jan 2004 05:38:41 -0800
Subject: Why learn Python ??
References: <40029dad$0$28706$a729d347@news.telepac.pt>
Message-ID: <7xisjh1e3i.fsf@ruckus.brouhaha.com>

"Bicho Verde"  writes:
>     And also I don't know exactly why would I learn Python rather than C#,
> C++ or Perl. Basicaly I don't know where to start, if there is much to do or
> if it is has it seems and there is software to everything nowadays and so
> doesn't make sense to spend time in learning a programming language.

I'd say don't bother with C++ unless you're working on a big
multi-person project.  Its design will make no sense to you unless
you've faced the problems that come up in those projects.  Otherwise
it's a big mess.

Perl has its fans and I can't promise you won't be one.  It's built
like a natural (spoken) language, that is, it wasn't designed, it just
sort of evolved, and has all kinds of specialized rules and exceptions
and multiple ways of doing the same thing.  Some people think that's
great.  Others (most Python fans) think Perl is a big mess.  The book
"Learning Perl" by Schwartz and Christiensen is definitely very good,
so you might look at it to decide if you like Perl.  But note that the
book only scratches the surface, and Perl gets messier the deeper you go.

C# is mostly Microsoft-specific and not much serious is done with it, IMO.

>     I just have this idea that I would like to contribute to the curve of
> accelarated exponential progress (technological singularity), artificial
> intelligence and so on. From that point of view there is much to do... But
> can I stand for it and where to start?
>       Anyone would help me and give me some hints?

Traditionally that kind of research has been done in Lisp.  You could
look at Winston and Horn's book on Lisp, which is also a reasonably
good introduction to AI methods.  


From aahz at pythoncraft.com  Wed Jan 21 19:38:26 2004
From: aahz at pythoncraft.com (Aahz)
Date: 21 Jan 2004 19:38:26 -0500
Subject: an example of a singleton design pattern in python?
References: 
Message-ID: 

In article ,
Daniel Ortmann   wrote:
>
>Does anyone have an example of a singleton design pattern in python?

It appears that none of the other responses mentioned the two simplest
techniques:

* Within a single module, use a global class as your singleton object.

* Across modules, use a module as your singleton object.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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


From mcfletch at rogers.com  Mon Jan  5 16:37:34 2004
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Mon, 05 Jan 2004 16:37:34 -0500
Subject: PRE-PEP: new Path class
In-Reply-To: 
References: 
Message-ID: <3FF9D91E.2090302@rogers.com>

John Roth wrote:
...

>1) Should path be a subclass of str?
>
>No. Outside of the difficulty of deciding whether it's a
>subclass of single byte or unicode strings, it's a pure
>and simple case of Feature Envy. Granted, there will
>be times a developer wants to use string methods, but
>the most common operations should be supported directly.
>  
>
It's not the methods that make me want to use str/unicode as the base, 
it's the ability to pass the resulting instances to built-in methods 
that explicitly expect/require str/unicode types.  Not sure how many of 
the core functions/libraries still have such requirements, but I'd guess 
it's a few.

That said, I don't mind making path it's own base-class, I just *really* 
want to be able to pass them to path-unaware code without extra coercian 
(otherwise switching a module to *producing* paths instead of raw 
strings will cause the *clients* of that module to break, which is a 
serious problem for rapid adoption).

>3) Should the / operator map joinpath.
>  
>
Agreed, no.  As for using + for join, that will break a lot of code that 
does things like this:

    p = mymodule.getSomeFilename()
    backup = p + '.bak'
    copyfile( p, backup )
    open( p, 'w').write( whatever )

i.e. we're thinking of returning these things in a lot of situations 
where strings were previously returned, string-like operations should 
IMO, be the norm.  But then we disagree on that anyway ;) .

>4) Should path expose an iterator for listdir(?)
>
>I don't see why not, as long as the path is to a
>directory.
>  
>
Seems ambiguous to me.  Also seems silly to use a generator when we're 
producing a list anyway from the underlying call, might as well return 
the list to allow length checks and random access.  Iterators for 
"ancestors" might be useful, but again, doesn't really seem like it 
needs to be __iter__ instead of "ancestors".

>5) Should == operator be the same as os.path.samefile()?
>
>Why not...
>  
>
__eq__ sounds about right.  I gather this call goes out to the 
filesystem first, though.  Might be good to first check for absolute 
equality (i.e. the same actual path) before doing that.

>6) Path.open()?
>
>Of course.
>  
>
Ditto.

>7) Should the various gettime methods return Datetime
>objects.
>
>Of course.
>  
>
What are we doing for Python 2.2 then?  I agree with the principle, but 
we should likely have a fallback when datetime isn't available.

>8) Touch method?
>
>Of course.
>  
>
Neutral, seems fine.

>9) Current OS constants?
>
>What are they? Are we talking about the four
>constants in the access() function, or about something
>else?
>  
>
Don't know myself.

>10) Commonprefix, walk and sameopenfile?
>
>Commonprefix should be a string or list method,
>it doesn't fit here.
>  
>
Path commonprefix are different operations from str commonprefix.  Paths 
should only accept entire path-segments (names) as being equal, while 
strings should accept any set of characters:

    '/this/that/those/them'
    '/this/thatly/those/them'

should see '/this/' as the commonprefix for the paths, not '/this/that'.

>walk is a nice function, but it should be redone to
>use the visitor pattern directly, with different method
>names for files, directories and whatever else a
>particular file system has in it's warped little mind.
>  
>
Reworking walk is probably a good idea.  I'll let others worry about it, 
as I've re-implemented the functionality so many times for my own code 
that I'm just sick of it :) .

>11) rename join and split.
>
>I wouldn't bother. Since I'm against making it a
>subclass of str(), the issue doesn't arise.
>  
>
No real preference one way or another here.  join -> "append" for paths 
seems fine.  split -> "elements" or "steps" for paths also seems fine.

>12) Should == compare file sizes.
>
>No. Might have a method to do that.
>  
>
Agreed, though even then, if we have a method that returns file-sizes:

    path( ... ).size() == path( ... ).size()

seems almost as reasonable as having a method for it?

>13) chdir, chmod, etc?
>
>No. This has nothing to do with pathname.
>  
>
chmod has to do with altering the access mode of a file/directory by 
specifying it's path, no?  Seems like it could readily be a method of 
the path.  chdir should accept a path, otherwise doesn't seem like it 
should be a method.

>14. Unicode filenames
>
>Have to have them on Windows and probably
>on the Mac.
>  
>
Yes.

>15. Should files and directories be the same
>class.
>  
>
Replied to this in the sub-thread...

Enjoy all,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






From vmontressor at yahoo.com  Mon Jan 12 05:35:11 2004
From: vmontressor at yahoo.com (Vincent Montressor)
Date: 12 Jan 2004 02:35:11 -0800
Subject: Restoring my own PyGNOME panel applets under GNOME 1.4 [SOLVED]
References: <88fe7467.0401110852.5480a822@posting.google.com>
Message-ID: <88fe7467.0401120235.153e6fe1@posting.google.com>

vmontressor at yahoo.com (Vincent Montressor) wrote in message news:<88fe7467.0401110852.5480a822 at posting.google.com>...

> I'm playing around with writing my own panel applets, and I'm trying
> to figure out how to get my panel applets to be restored when I log
> in.  As an experiment, I'm using the simple clock applet that comes
> with PyGNOME (clock-applet.py).  It works fine when I run it from the
> shell, but when I log out and log in again, there's just a tiny
> GNOME-foot icon where the applet should be.

Ah, never mind: adding the applet to my GNOME startup programs list solved it.  Duh.


From mhammond at skippinet.com.au  Thu Jan 15 21:07:30 2004
From: mhammond at skippinet.com.au (Mark Hammond)
Date: Fri, 16 Jan 2004 13:07:30 +1100
Subject: Multithreaded COM server problem...
In-Reply-To: <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com>
References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com>
	
	
	
	<0pr700ddfdf3op14oulk7u82cthaped040@4ax.com>
Message-ID: 

John Lull wrote:
> Mark Hammond  wrote (with possible
> deletions):
> 
> 
>>John Lull wrote:
> 
> ...
> 
>>>Unfortunately, this one has to be a local server since it's providing shared
>>>access to a pool of hardware devices from multiple distributed clients. I've
>>>carefully reviewed chapters 5 & 12, and appendix D, and wasn't able to find
>>>anything addressing threading models in the local server in detail. If I've
>>>missed something, I'd be grateful for any additional hints. 
>>
>>The problem is that your client code is not running a message loop.  If 
>>you change the loop of your client test code to something like:
>>
>>for i in range(delay)*10:
>>     time.sleep(0.1)
>>     pythoncom.PumpWaitingMessages()
>>
>>It works as you expect.  A better choice would probably be 
>>win32event.MsgWaitForMultipleObjects, but that depends on what your app 
>>really does.
>>
>>Mark.
> 
> 
> I presume you meant my server code. 

Nope - I meant the client.  The server is already running such a loop 
thank to localserver.py, which is hosting the object.

The client code's main (and only) thread is blocked in a system call, 
but it appears COM wants it to pump messages so the marshalling magic 
happens.  I can only speculate why COM needs this to happen in this 
trivial case, but COM's rules do state this requirement.

> This still leaves all calls to the
> server running in a single thread, however. If I insert a call to
> PumpWaitingMessages() in a short operation, and it happens to start a
> long operation, the result of that short operation will be delayed
> until the long operation completes. This will make my server unusable.

Make the change I suggested, and it works as you hope.

> At first glance this seems to do what I want -- requests to the server
> seem to run from a thread pool. However, I also get intermittent (but
> frequest) startup errors, with a Microsoft Visual C++ Runtime Library
> error dialog (during pythoncom.PumpMessages but before my server
> module gets imported) reporting:
>   Runtime Error!
>   Program: c:\Apps\Python2.2\pythonw.exe
>   abnormal program termination

That sucks, and is almost certainly a thread-state error.  If you have a 
debug build of Python, it will offer to break into the debugger at this 
point.

Mark.



From christian.eslbauer at liwest.at  Sun Jan  4 09:15:27 2004
From: christian.eslbauer at liwest.at (EsC)
Date: Sun, 4 Jan 2004 15:15:27 +0100
Subject: SMTP - Topic & add files
References: <1073137983.983243@news.liwest.at>
	<3d06fae9.0401031339.7a2dcdb5@posting.google.com>
Message-ID: <1073224147.517695@news.liwest.at>

hy!

thanks for this simple and excellent solution!

greetings
EsC


"jmdeschamps"  schrieb im Newsbeitrag
news:3d06fae9.0401031339.7a2dcdb5 at posting.google.com...
> "EsC"  wrote in message
news:<1073137983.983243 at news.liwest.at>...
> > Hy!
> >
> > probably a dummy question, but i don't
> > know how to set a Topic-Text and add
> > Files to an email ...
> >
> > i use the SMTPLIB module and the
> > function/method: .sendmail(from,to,msg)
> >
> > but how can i set a topic Text?
> > is there an other function/method, or
> > must it be encoded within the message-text?
> >
> > thanks for your help
> > EsC
>
> its in the msg parameter of sendmail such as :
>
> yourSmtp = smtplib.SMTP('yourMailServer.org')
>
> #envoi un message
> #ARGUMENTS from sendMail
> #from: your own client adress
> #to: the intended recipient's adress
> #msg: what will really show...in different fields
> monSmtp.sendmail("From: ownMail at yourMailServer.org",
>                        "To: recipientAdresse at hisServer.org",
>                        "From:joe\r\nTo: Owner \nSubject: 3 weeks left"
>                        + "\n\nTopic text of the  message! ")
>
> on Windows, may differ slightly on Linux :)
>
> Good messaging,
>
> JM




From alanmk at hotmail.com  Wed Jan 21 15:53:09 2004
From: alanmk at hotmail.com (Alan Kennedy)
Date: Wed, 21 Jan 2004 20:53:09 +0000
Subject: Accessing a shared generator from multiple threads.
References: <7934d084.0401152058.164a240c@posting.google.com>
	<40083eac$0$321$e4fe514c@news.xs4all.nl>
	
	<40086C6E.8536542C@hotmail.com>
	<40098f12$0$320$e4fe514c@news.xs4all.nl>
	<400AB936.BA1D9D73@hotmail.com>
	<7934d084.0401181805.71029c2f@posting.google.com>
Message-ID: <400EE6B5.27C6B694@hotmail.com>

[Andrae Muys]
> Moved to email for higher bandwidth.  Feel free to quote to usenet if
> you desire. 

[Alan Kennedy]
>> I think I'm with Aahz on this one: when faced with this kind of 
>> problem, I think it is best to use a tried and tested inter-thread 
>> communication paradigm, such as Queue.Queue. In this case, Queue.Queue
>> fits the problem (which is just a variation of the producer/consumer
>> problem) naturally. Also, I doubt very much if there is much excessive
>> resource overhead when using Queue.Queues. 

[Andrae Muys]
>Well I'm puzzled, because I couldn't see an easy way to use Queue.Queue
>to achieve this because this isn't a strict producer/consumer problem.
>I am trying to synchronise multiple consumers, but I don't have a
>producer.  So the only way I can see to use Queue.Queue to achieve 
>this is to spawn a thread specifically to convert the iterator in to 
>a producer. 

Andrae,

I thought it best to continue this discussion on UseNet, to perhaps
get more opinions.

Yes, you're right. Using a Queue in this situation does require the
use of a dedicated thread for the producer. There is no way to "pull"
values from a generator to multiple consumers through a Queue.Queue.
The values have to be "pushed" onto the Queue.Queue by some producing
thread of execution.

The way I see it, the options are

Option 1. Spawn a separate thread to execute the producing generator.
However, this has problems:-

A: How do the threads recognise the end of the generated sequence?
This is not a simple problem: the Queue simply being empty does not
necessarily signify the end of the sequence (e.g., the producer thread
might not be getting its fair share of CPU time).

B: The Queue acts as a (potentially infinite) buffer for the generated
values, thus eliminating one of the primary benefits of generators:
their efficient "generate when required" nature. This can be helped
somewhat by limiting the number of entries in the Queue, but it is
still slightly unsatisfactory.

C: A thread of execution has to be dedicated to the producer, thus
consuming resources.

Option 2. Fill the Queue with values from a main thread which executes
the generator to exhaustion. The consuming threads simply peel values
from the Queue. Although this saves on thread overhead, it is the
least desirable in terms of memory overhead: the number of values
generated by the generator and buffered in the Queue could be very
large.

Option 3. Use the same paradigm as your original paradigm, i.e. there
is no producer thread and the consuming threads are themselves
responsible for calling the generator.next() method: access to this
method is synchronised on a threading.Lock. I really like this
solution, because values are only generated on demand, with no
temporary storage of values required.

I think that an ideal solution would be to create a dedicated class
for synchronising a generator, as my example did, BUT to implement the
same interface as Queue.Queue, so that client code would remain
ignorant that it was dealing with a generator.

Here is my version of such a beast

# -=-=-=-=-= file GenQueue.py =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import threading

class Empty(Exception): pass
class Exhausted(StopIteration): pass
class IllegalOperation(Exception): pass

class GenQueue:
  "Simulate a Queue.Queue, with values produced from a generator"

  def __init__(self, gen):
    self.lock = threading.Lock()
    self.gen = gen

  def __iter__(self):
    return self

  def _get(self, block=1):
    if self.lock.acquire(block):
      try:
        try:
          return self.gen.next()
        except StopIteration:
          raise Exhausted
      finally:
        self.lock.release()
    else:
      raise Empty

  def next(self):
    return self._get(1)

  def get(self, block=1):
    return self._get(block)

  def get_nowait(self):
    return self._get(0)

  def put(self, item, block=1):
    raise IllegalOperation

  def put_nowait(self, item):
    self.put(item, 0)

  def full(self):
    return False

  def empty(self):
    return False

  def qsize(self):
    return 1j

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

And here is some code that tests it

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

import sys
import time
import thread
import GenQueue

def squares(n):
  i = 1
  while i <= n:
    yield i*i
    i = i+1

def test_blockget(results, queue):
  while 1:
    try:
      results.append(queue.get())
    except GenQueue.Empty:
      raise TestFailure
    except GenQueue.Exhausted:
      break

def test_iter(results, queue):
  for v in queue:
    results.append(v)

def test_noblockget(results, queue):
  while 1:
    try:
      results.append(queue.get_nowait())
    except GenQueue.Empty:
      pass
    except GenQueue.Exhausted:
      break

def threadwrap(func, queue, markers):
  markers[thread.get_ident()] = 1
  results = []
  func(results, queue)
  print "Test %s: Thread %5s: %d results." % (func.__name__, \
    thread.get_ident(), len(results))
  del markers[thread.get_ident()]

def test():
  numthreads = 10
  for tfunc in (test_blockget, test_iter, test_noblockget):
    print "Test: %s ------------------------------->" % tfunc.__name__
    threadmarkers = {}
    q = GenQueue.GenQueue(squares(100))
    threads = [thread.start_new_thread(threadwrap,\
                (tfunc, q, threadmarkers)) for t in
xrange(numthreads)]
    while len(threadmarkers.keys()) > 0:
      time.sleep(0.1)

if __name__ == "__main__":
  test()

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I find the combination of the iteration protocol and a Queue
intriguing: in this case, Queue.get() and iter.next() mean the same
thing. Or maybe I'm just being sucked in by the syntactic niceties of
something like

def worker(inq, outq):
  for thing in inq: outq.put(thing.work()) 

I'm interested to hear other opinions about the commonalities and
differences between Queues and iterators. 

One problem that is always in the back of my mind these days is how
one could write a dispatch-based coroutine scheduler that would work
efficiently when in communication (through Queue.Queues?) with
independently executing coroutine schedulers running on other
processors in the box. (And before you jump in shouting "Global
Interpreter Lock!", remember jython + generators will be able to do
this).

Not that I need such a thing: it's just a fun thing to think about,
like crosswords :-)

cheers,

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


From harry.g.george at boeing.com  Wed Jan 14 06:50:30 2004
From: harry.g.george at boeing.com (Harry George)
Date: Wed, 14 Jan 2004 11:50:30 GMT
Subject: Printing to console, no scroll
References: 
Message-ID: 

"Totte Karlsson"  writes:

> Hi,
> How can I print to the console without having it scrolling to a new line for
> each print statement?
> I want to print a count down in the console, but for each count it scrolls
> the screen (of course).
> 
>  Is there another way?
> 
> Here is the simple script for now
> 
> print "Closing window in :"
> for second in range(10):
>     time.sleep(1)
>     print `10-second` +" seconds"
> 
> thanks
> /totte
> 
> 
> 
> 

You need to flush after the print statements.  If you have several
prints (not just 1 as in this example), it is easier to hide in a
separate function.

def msg(txt):
    sys.stdout.write(txt)
    sys.stdout.flush()

> for second in range(10):
>     time.sleep(1)
>     msg(`10-second` +" seconds ")  #add a space at the end to delimit
> print    #to finish off the line


-- 
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 342-5601


From seanl at chaosring.org  Mon Jan  5 00:44:15 2004
From: seanl at chaosring.org (Sean R. Lynch)
Date: Sun, 04 Jan 2004 21:44:15 -0800
Subject: Creating a capabilities-based restricted execution system
In-Reply-To: 
References:  
	 
	 
	 
Message-ID: 

I put up a page on my Wiki with what I can remember off the top of my 
head of what we've discussed so far and some of what I've implemented so 
far (though my implementation is in flux). It's at 
. Feel free to add comments.


From michael at foord.net  Fri Jan 16 04:34:16 2004
From: michael at foord.net (Fuzzyman)
Date: 16 Jan 2004 01:34:16 -0800
Subject: Setting Window Size using Pack Under Tkinter
Message-ID: <8089854e.0401160134.5674a86c@posting.google.com>

I'm having trouble implementing my GUI using Tkinter......
I've been working through the Tkinter tutorials from 'Programming
Python' and am generally happy enough with the functionality and feel
of the results *but* - I can't see how to set the size of the root
window (or any top level window) and to stop it being resized........

Thanks for any help.

Fuzzyman


-- 

YAPLP
Yet Another Python Links Page
http://www.voidspace.org.uk/coollinks/python_links.shtml

Python Utils
http://www.voidspace.org.uk/atlantibots/pythonutils.html

--

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.atlantibots.org.uk
http://groups.yahoo.com/group/atlantis_talk/
Atlantibots - stomping across the worlds of Atlantis.
---
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 HQ-611 at interliant.com  Fri Jan 30 09:12:28 2004
From: HQ-611 at interliant.com (HQ-611 at interliant.com)
Date: Fri, 30 Jan 2004 08:12:28 -0600
Subject: NAV detected a virus in a document you authored.
Message-ID: 

Please contact your system administrator.


The scanned document was QUARANTINED.


Virus Information:
The attachment seqlt.pif contained the virus W32.Novarg.A at mm and could NOT
be repaired.





From stefano.covino at libero.it  Thu Jan 15 17:14:01 2004
From: stefano.covino at libero.it (Stefano Covino)
Date: Thu, 15 Jan 2004 23:14:01 +0100
Subject: function minimization
References: 
	
Message-ID: 


> 
> See
> 
> http://pylab.sourceforge.net/
> 
> then
> 
> optimize.py
> 
> /Carl

Yes, this is exactly what I was looking for. 

Thank you a lot,
		Stefano



From wfolta at netmail.to  Mon Jan 19 17:22:29 2004
From: wfolta at netmail.to (Wayne Folta)
Date: Mon, 19 Jan 2004 17:22:29 -0500
Subject: New to Python: my impression v. Perl/Ruby
In-Reply-To: <87ad4kxees.fsf@pobox.com>
References: 
	<87ad4kxees.fsf@pobox.com>
Message-ID: 

John,

I think one problem here is that somehow I left a paragraph out of my 
original posting. After years and years of Perl use, I evaluated Ruby 
and Python and have adopted Python. Ruby intrigues me, but it's not 
what I will use to get things done. I thought that as a newcomer to 
both, I though I might have a different perspective from people who 
were native users, hence my posting.

I can see that without that info, it may have appeared that I was 
possibly advocating Ruby over Python, which would be inappropriate in a 
Pyton forum. I apologize for the confusion!

> Well, that's not exactly a huge leap given any knowledge of how the
> internet works.  I'm not sure that Python's docs should be in the
> business of educating people about that...

There's no necessary connection between the protocol stack and software 
packages. It's good and sensible that POP3 is built on socket, but it 
could be based on my_sockets or _socket or who knows what. I'm not 
asking that the entire protocol stack be documented, and it's not as if 
"obvious" things aren't documented in detail elsewhere in Python. (For 
example, there's an entire paragraph on socket's gethostname(). I could 
rhetorically say this is so obvious it should be replace with "returns 
host name" or "see GETHOSTNAME(3)"?)

For me, it's just totally natural that I'd say, "The POP3 package is 
built using the socket package and socket exceptions are not caught by 
POP3." That single sentence immediately tells me everything I needed to 
know. That's the way I'd document any higher-level package, regardless 
of whether there was an obvious candidate for underlying packages (or 
classes) or not. For me, it's as basic as mentioning what types a 
function returns, or what types its arguments are, or what class is a 
subclass of another.

> ...but the fact that there is no timeout support in client modules of
> the socket module is a known bug:

This is a bug? I guess it can cause problems in the underlying package, 
but I sure hope that the exception is handled and then re-raised as 
timeout_proto or something distinct from error_proto. I personally 
prefer fine-grained exception, which I believe best takes advantage of 
multiple-except try clauses. I hate catching something then having to 
sort through variables to figure out what really happened.

 From an external viewpoint I don't see that much difference between 
"fixing" this bug and simply documenting the other exceptions you might 
see from underlying packages.

> In the absence of some explanation of what you mean by "Real OO", that
> sounds trollish.

No trolling intended. I simply have read what Python advocates say 
about Python and what Ruby advocates say about Ruby (in comparison to 
languages like Python) and said that. I'm making no statement about 
reality, but simply about what advocates mantras are. (Or actually, as 
I carefully said, "might be".)

(Actually, now that I reread it, I should've said "pure OO", which I 
believe is more reflective of their statements. And this has some basis 
in fact, I believe, if you look at the v1 of Ruby and Python and what 
is first-class and what is not.)

> I don't see how a missing feature in Python reveals any difference in
> culture between Python and Ruby, other than perhaps that the Ruby
> people like implementation inheritance more than the people who
> designed the Python standard library.

You have taken my observation and transformed it into ignorance on my 
part and a supposed bug on Python's part. Once you've done that, yes, 
it is no longer illuminative.

Again, as you yourself say, they chose to subclass protocol services 
off of a class 'protocol' and Python did not. In fact, Python chose to 
not subclass POP3 from anything. Why? Because of the culture, in my 
opinion. Ruby emphasizes OO and that it's "pure OO" (their opinion) and 
so an implementation that involves a Smalltalk-ish subclassing of 
everything recommends itself.

Python has a different culture where such strict tree-like class 
structure does not recommend itself. Python's "batteries included" 
philosophy resulted in a more straightforward and (mostly) better 
documented way to do it.

Intellectually, I prefer Ruby. Ruby and Smalltalk intrigue me. But the 
"pure OO" approach (my words this time) is annoying, and even at some 
point inconsistent, as I mentioned in my paragraph about 0.step(). I 
feel like Python has got the right balance where it's OO and pretty 
much fully so, but not fanatically so. And it's what I've adopted.

You can see that the three languages have been driven by central 
personalities and the user groups reflect these personalities. Before 
Perl were various languages and shell/awk/sed. Larry triangulated 
things and stuck a flag in the semi-script, expedient measure area. 
("Do what I mean", "Swiss Army Chainsaw".) His brilliance was in tying 
very disparate tools together in one syntax that hung together and did 
the "right thing" based on how these other tools worked.

(And he got away from some of the weaknesses of shell scripts, such as 
substititional evaluation, which were there because they were 
interactive first, then became scripting languages. Somehow TCL didn't 
learn this kind of lesson and I've never liked it.)

Unfortunately, expedient measures don't scale well and Perl has, as 
someone famous said, pushed well beyond its performance envelope. 
(Probably in v5.)

Guido was able to learn from Perl and moved more towards a language 
that was farther removed from "scripting" with a cleaner syntax, solid 
OO, etc. But he kept what I'd consider the best of Perl's expediency 
philosophy. ("Batteries Included".)

Matz saw both of these and went for a "pure", Smalltalk-ish OO. He also 
kept some of Perl's expediency, but in more of a syntactic way. So I 
find Ruby to be a strange combination of almost fanatical OO philosophy 
but at the same time an expediency of syntax.

Just my opinion. But in summary, I prefer Python. It feels right to me. 
OO but not what I'd call the fanatical OO of Ruby. Clean syntax. Good 
packages bundled. Somehow, I would say it has a less-flexible syntax, 
but more-flexible philosophy. (Which is good.)

(OK, one thing to add is I'm on MacOS X and Python's EasyDialogs is 
VERY convenient and attractive and the other programs don't seem to 
have an equivalent. It just doesn't make sense for me to program with 
something that doesn't allow for easy GUI interaction with a user on a 
machine with such a great GUI.)




From ggg at zzz.it  Wed Jan 28 08:13:50 2004
From: ggg at zzz.it (deelan)
Date: Wed, 28 Jan 2004 14:13:50 +0100
Subject: newsgroup lib
In-Reply-To: <6b17fa95.0401280501.4be454cb@posting.google.com>
References: <6b17fa95.0401280501.4be454cb@posting.google.com>
Message-ID: 

Jesper Olsen wrote:

> Is there a python module for accessing newsgroup articles?
> 
> Something similar to urllib for downloading web pages...
nttplib?
see: 



-- 
email: goldicus1970 AT yahoo.it
blog: http://www.deelan.com/






From elainejackson7355 at home.com  Fri Jan 30 01:07:52 2004
From: elainejackson7355 at home.com (Elaine Jackson)
Date: Fri, 30 Jan 2004 06:07:52 GMT
Subject: conditional expression sought
References: 
	
	
	<6PjSb.138487$6y6.2697536@bgtnsc05-news.ops.worldnet.att.net>
Message-ID: 

Thanks for your help. I just looked at some values of random.randint(0,1) in my
interpreter, and one of them was 0. Getting nonboolean values from conjunction
and disjunction allows conditional evaluation of expressions; for example:
reciprocal = lambda x: (x!=0 and 1.0/x) or (x==0 and "undefined").

"wes weston"  wrote in message
news:6PjSb.138487$6y6.2697536 at bgtnsc05-news.ops.worldnet.att.net...
| Elaine,
|     The last code line:
|
| print "I would have liked this to be B[2] = ",B[2]
|
| prints the value of B[2]; the value you don't want.
| I think what you meant was that you want B[2] to be
| 0.0 not false. bool(0.0) does equal false.
| ---------------------------------------------------
| The code:
|
| A.append(bool(randint(0,1)))
|
| will always yield an A of [true,true,true]
| ---------------------------------------------------
| I didn't know this about python, and I'm not sure I
| like it:
|
| wes at linux:~/amy> python
|
|  >>> print 1.1 and 2.2
| 2.2
|  >>> print 2.2 and 1.1
| 1.1
|  >>> print (1.1 and 2.2)
| 2.2
|
| The order is important. To me, it should be printing true
| and not either number or the last number.
|




From sdeibel at wingide.com  Mon Jan 19 12:38:49 2004
From: sdeibel at wingide.com (Stephan Deibel)
Date: Mon, 19 Jan 2004 12:38:49 -0500 (EST)
Subject: Using python for _large_ projects like IDE
In-Reply-To: 
Message-ID: 

On Mon, 19 Jan 2004, Eric Brunel wrote:
> > I am a little experienced python programmer (2 months).  I am somewhat
> > experienced in C/C++.  I am planning (now in design stage) to write an
> > IDE in python.  The IDE will not be a simple one.  I had an idea of
> > writing the IDE in C/C++, as it is a big project, bcoz of the
> > following
> > 
> > 1. if python is used, then the memory required for running the IDE
> > will be high.
> 
> It's quite hard to tell, since I've never seen anybody writing a significant 
> application *both* in C/C++ and Python to compare their memory usage... I'd say 
> memory usage depends a lot more on the design than on the language used. Python 
> does introduce an extra cost in memory consumption, but the larger the 
> application, the less you'll notice it.

Actually, I've done a little of this in areas where Python was too slow or
memory intensive, by first writing in Python and then rewriting in C or
C++ (so I briefly had two implementations of the same thing).

You can do things in Python to reduce memory consumption and increase
speed, and you can recode select portions in C/C++ also, and which you
choose depends on the code, situation, requirements, etc.  Similarly,
whether memory usage is significantly greater in Python depends on what
you're doing.

The best approach is to write in pure Python and recode on select *small
as possible* parts in C/C++.  I started by doing whole modules and quickly
found out that minimizing the size of the C/C++ code base is better than
having whole modules in one or the other.  The ability to integrate back
and forth is good enough that this is quite doable.

> > Are there any ways to forsee the performance critical parts? > 
> I really think you shouldn't care; remember, "premature optimization is the root 
> of all evil" ;-)

Absolutely:  Use a profiler, not your brain, to find the parts that are
problems and need to be converted!

Stephan Deibel

--
Wing IDE for Python
Archaeopteryx Software, Inc
Take Flight!

www.wingide.com



From wish2banonymous  Thu Jan  1 05:40:28 2004
From: wish2banonymous (PPeterson)
Date: Thu, 1 Jan 2004 18:40:28 +0800
Subject: pynettestuser
Message-ID: 

Hi,

I am a newbie to python. python installer created a directory named
pynettestuser in the c:\documents and settings. What is that? Thanks.

PP




From hjwidmaier at web.de  Thu Jan  8 16:39:39 2004
From: hjwidmaier at web.de (Hans-Joachim Widmaier)
Date: Thu, 08 Jan 2004 22:39:39 +0100
Subject: Tkinter button command curiousity
References: 
Message-ID: 

Am Thu, 08 Jan 2004 15:08:56 -0500 schrieb mksql:

> New to Tkinter. Initially, I had some code that was executing button commands at
> creation, rather than waiting for user action. Some research here gave me a
> solution, but I am not sure why the extra step is necessary.

There is no "extra step," as you will see.

> This causes the "graph" function to execute when the button is created:
> 	Button(root, text='OK', command=graph(canvas)))

Here you are calling graph() immediatly and bind the result to the
parameter 'command' - most likely not the intended effect (as you
observed).

> However, this waits until the button is pressed (the desired behavior):
> 	def doit():
> 	     graph(canvas)
> 	Button(root, text='OK', command=doit))

Here you bind the function object 'doit' to the command parameter, which
will then be called when the button is clicked on. You could also bind
the 'graph' function object to command, but then you cannot give it your
argument 'canvas'. Lambdas are often used to overcome this problem, but
your 'doit' local function essentially amounts to the same.

> Functionally, what is the difference? Why do I need to create a
> function, to call a function, simply to make a button command wait until
> pressed? Is there a better method?

The difference is, again:

def function(blah)
    pass

Here, 'function(x)' calls the function, whereas 'function' (without the
parenthethis) is just the function object (which can be bound to a name
which then later can be used to call it).

A better method? Would you call this better?

    Button(root, text='OK', command=lambda event, cvs=canvas: graph(cvs))

Usually, Tkinter programs employ a class that implements the GUI. Here you
can keep your canvas in a class attribute and use it in the callback
method:

class myGUI(Frame):
     # ....
         self.canvas = Canvas(root, ...)
         Button(root, text='OK', command=self.graph)

     def graph(self, event=None):
         # Use self.canvas

Hope this helps,
Hans-Joachim




From cartermark46 at ukmail.com  Tue Jan 20 11:59:37 2004
From: cartermark46 at ukmail.com (Mark Carter)
Date: 20 Jan 2004 08:59:37 -0800
Subject: Python-based file synchronizer (like Unison)?
References: 
Message-ID: 

Kyler Laird  wrote in message news:...
> I've been using Unison
> 	http://www.cis.upenn.edu/~bcpierce/unison/
> for awhile and it causes me a lot of grief.  I'd love to have a
> Python version which would be vastly easier to modify.
> 
> Anyone know of anything like this?  

I'm involved with DirSync - which is written in Python, and requires wxPython:
http://sourceforge.net/projects/dirssync/


From csgcsg39 at hotmail.com  Tue Jan 20 12:34:49 2004
From: csgcsg39 at hotmail.com (C GIllespie)
Date: Tue, 20 Jan 2004 17:34:49 -0000
Subject: simple class question
Message-ID: 

Dear all,

I'm new to both python and OOP, so could I ask a simple question.

I have class:

class species:
    __init__(self,pop=0):
        self.pop=pop

Now I want to do something like this:

X=species(pop=10)
Y=species(pop=X.pop)
OK, but now I want to update X.pop and have that mirrored in Y.pop, i.e. if
X.pop=5, Y.pop now equals 5.

What is the best/nicest/simplest way of doing this?

Many thanks

Colin




From ajborla at bigpond.com  Fri Jan  9 00:44:37 2004
From: ajborla at bigpond.com (Anthony Borla)
Date: Fri, 09 Jan 2004 05:44:37 GMT
Subject: python newbie
References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be>
Message-ID: <9drLb.2088$Wa.188@news-server.bigpond.net.au>

"broebel"  wrote in message
news:3ffddcfd$0$16662$ba620e4c at news.skynet.be...
> hey,
>
> I'm a newbie in the programming world.
> I just started and already I'm in a whole lot of problems.
>

And you'll probably experience a whole host more - welcome to the wonderful
world of programming ;) !!!

>
> first problem is the fact that I started out with a little program
> who was part of a course but the problem is when I launch
> the program. I don't have the time to see the result because
> the screen closes immediately.
>
> Can anyone explain what's happening.
>


You are obviously not launching the interpreter from a console window. Thus,
launching the interpreter forces a new console window to be opened, your
program executes, and it then closes because it has finished.

Possible remedies allowing you to view your program's output:

* Launch interpreter as you have been doing, but add a line
   such as:

       raw_input("Press a key to continue ")

   at the end of your code to prompt for a key press before
   exiting, and closing the console window

* Start using the intepreter from a console window i.e. start
   using the command line. All generated output will appear
   on the same console.

   Since you are in a course [?] I'd recommend asking your
   instructor about suitable tutorials for doing this

I hope this helps.

Anthony Borla




From __peter__ at web.de  Sun Jan  4 13:42:00 2004
From: __peter__ at web.de (Peter Otten)
Date: Sun, 04 Jan 2004 19:42:00 +0100
Subject: Launching pdb from within a script
References: 
Message-ID: 

Graham Nicholls wrote:

> A year or so ago, I was given a really useful answer to a question posed
> here, which showed me how to start the debugger from withing a script.

Are you looking for pdb.set_trace()?

Peter


From tdelaney at avaya.com  Wed Jan 28 18:05:57 2004
From: tdelaney at avaya.com (Delaney, Timothy C (Timothy))
Date: Thu, 29 Jan 2004 10:05:57 +1100
Subject: PEP 326 is D-E-A-D (was Re: How does compare work?)
Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE011DB0A3@au3010avexu1.global.avaya.com>

> From: Batista, Facundo
> 
> Aahz wrote: 
> #- >Even then, what about PEP 326, which presumes to define highest and 
> #- >lowest objects that can be compared with anything? 
> #- 
> #- What about it?  ;-) 
> #- 
> #- (Guido just posted a Pronouncement rejecting it.) 
> 
> Can't find it at http://www.python.org/doc/essays/pepparade.html 
> I'm looking in the wrong place? 

Yes - the PEP parade is *very* out of date, and is not maintained.

The pronouncement only occurred overnight (from my viewpoint) so you can't expect documents to be updated yet.

Basically, Aahz revealed the rejected status to c.l.python with his email.

Tim Delaney



From ciwwy at aol.com  Tue Jan 27 03:44:04 2004
From: ciwwy at aol.com (ciwwy at aol.com)
Date: Tue, 27 Jan 2004 01:44:04 -0700
Subject: Error
Message-ID: <0HS5007DV49QYB@csomail.cso.atmel.com>

test

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: MailMonitor_report.txt
URL: 

From faizan at jaredweb.com  Tue Jan 27 20:39:42 2004
From: faizan at jaredweb.com (Fazer)
Date: 27 Jan 2004 17:39:42 -0800
Subject: Best way to compare a list?
Message-ID: <7b454334.0401271739.59267018@posting.google.com>

Hello,

I was wondering which would be the best way to compare a list?

I was thinking of just using a for loop and testing the condition.

What do you guys think?  The best/fastest way of comparing lists.

Thanks,

Faizan


From jussij at zeusedit.com  Sat Jan 24 00:10:20 2004
From: jussij at zeusedit.com (Jussi Jumppanen)
Date: Sat, 24 Jan 2004 16:10:20 +1100
Subject: C compilers
References: 
	
Message-ID: <4011FE3C.7BF2@zeusedit.com>

Patrick Useldinger wrote:
> 
> Borland C++ 5 - and it's free.

The Borland BCC Verison 5.5 c/c++ compiler is now almost
free (you need to supply some user details) and here is 
the link:

  http://www.borland.com/bcppbuilder/freecompiler

Jussi Jumppanen
Author of: Zeus for Windows, Win32 (Brief, Emacs, etc) FTP Text Editor
"The C/C++, Java, HTML, Python, Pascal, PHP, Perl programmer's editor"
Home Page: http://www.zeusedit.com


From peter at cendio.se  Wed Jan 28 05:42:38 2004
From: peter at cendio.se (Peter Astrand)
Date: Wed, 28 Jan 2004 11:42:38 +0100 (CET)
Subject: Cross-version extension modules?
In-Reply-To: <490316A24CC5D411ACD700B0D078F7F003915E29@cseexch01.cse.creoscitex.com>
Message-ID: 

On Wed, 28 Jan 2004, Pieter Claerhout wrote:

> extension modules in Python are always linked to a specific version of
> Python. You might perform some tricks with writing a pure Python module
> about your extension that, based on the version of the python interpreter,
> loads a different version of your extension. This is e.g. the way the Python
> drivers for SapDB work.

Thanks. Is PYTHON_API_VERSION guaranteed to increase only when the Python 
major or minor version increases, or can it change between micro versions 
as well?


/Peter
> -----Original Message-----
> From: Peter Astrand [mailto:peter at cendio.se] 
> Sent: 28 January 2004 10:40
> To: python-list at python.org
> Subject: Cross-version extension modules?
> 
> 
> 
> If I build a extension module with Python 2.2 and then loads it with 2.3, 
> I get:
> 
> RuntimeWarning: Python C API version mismatch for module _foo: This
> Python has API version 1012, module _foo has version 1011.
> 
> How fatal is this? Is it safe to use the module anyway? If not, is it
> possible to build the module differently, so that it actually is safe to
> use it with different versions of Python?
> 
> 

-- 
Peter ?strand		www.thinlinc.com
Cendio			www.cendio.se
Teknikringen 3		Phone: +46-13-21 46 00
583 30 Link?ping




From inyeol.lee at siimage.com  Mon Jan 26 18:57:04 2004
From: inyeol.lee at siimage.com (Inyeol Lee)
Date: Mon, 26 Jan 2004 15:57:04 -0800
Subject: How does compare work?
In-Reply-To: <40158680$0$7044$ba620e4c@news.skynet.be>
References: <40158680$0$7044$ba620e4c@news.skynet.be>
Message-ID: <20040126235704.GD13453@siliconimage.com>

On Mon, Jan 26, 2004 at 10:28:31PM +0100, Helmut Jarausch wrote:
> Hi,
> 
> what does Python do if two objects aren't comparable (to my opinion)
> If I've understood "Python in a Nutschell" correctly it should raise an
> exception but it doesn't do for me.
> 

>From section 5.9 in Python 2.3.3 Reference manual;
"""
The operators <, >, ==, >=, <=, and != compare the values of two
objects. The objects need not have the same type. If both are numbers,
they are converted to a common type. Otherwise,
objects of different types always compare unequal, and are ordered
consistently but arbitrarily. 

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of
different types are likely to change.) 
"""

-Inyeol Lee



From alet at librelogiciel.com  Sun Jan 18 17:45:23 2004
From: alet at librelogiciel.com (Jerome Alet)
Date: Sun, 18 Jan 2004 23:45:23 +0100
Subject: ANN: PyKota v1.16 is out
Message-ID: 

Hi there

I'm pleased to announce that PyKota v1.16 Final is out.

PyKota is an entirely Python written, GNU GPLed, centralized, full
featured, internationalized, and easily extensible, print quota and
accounting solution for CUPS and LPRng under Unix like systems like
GNU/Linux.

PyKota can store its datas either in PostgreSQL or in OpenLDAP, and
integrating PyKota with an existing LDAP directory is really easy thanks
to PyKota's unprecedented flexibility.

After several months of developpment, this release includes many many
improvements :

  - New CUPS backend wrapper, which allows point & click
    installation into CUPS and supports device enumeration. The old pykota
    filter is now deprecated for use with CUPS, unless for dumb printers.
    This CUPS backend also allows immediate hardware accounting, instead
    of delayed by one job hardware accounting.
    WARNING : installation is still partially manual for CUPS 1.14
              (for example under Debian Woody)
    
  - Printers Groups are implemented and can be nested.
    See FAQ for explanations.
  
  - Printers and users can now be automatically added to the database
    on first print in a completely configurable way.
    
  - Six languages are now supported : English, French, Spanish,
    Portuguese, Brasilian Portuguese and Swedish.
    
  - Web interface is now partially internationalized.
  
  - Web interface can now display print jobs history per printer,
    per user, and per user+printer.
  
  - Preliminary documentation on how to use OpenOffice.org
    to create personnalized reports for PyKota + PostgreSQL.
          
  - Spanish installation guide for SuSe + CUPS + PyKota + PostgreSQL
    added to the documentation. Doesn't yet document v1.16 though. This 15
    pages guide was generously contributed to the project by Dennis Romero
    L.
    
  - User's email address can now be set at user creation time.
  
  - Improved database caching mechanism.
  
  - Several environment variables are now exported to accounters,
    requesters and mailers.
    
  - Includes a script to send email+winpopup message to users
    over quota.
    
  - Includes a script to wait for Appletalk printers being ready.
    
  - New option to automatically convert all usernames to lowercase.
    
  - Jobs history contains more fields than before.
  
  - Documentation is now licensed under the GNU GPL too (was GNU FDL).
  
  - Major code refactoring and cleaning.
  
  - Usual bug fixes.
  
The complete list of changes is available from :

  http://www.librelogiciel.com/software/PyKota/action_News
  
IMPORTANT : Before upgrading from an older version, please :

        - Double check the toplevel README and the FAQ.
        
        - Upgrade your PostgreSQL database or LDAP schema as
          explained in the initscripts/ directories, if needed.
          
        - Double check the sample configuration files for new
          options and features.
          
Learn more about PyKota, see live reports or screenshots, download the CVS
version or buy yearly Official Packages subscription from :

  http://www.librelogiciel.com/software/PyKota/action_Presentation

Chat with us, ask for help, report problems or successes, on the mailing
list at :

  http://cgi.librelogiciel.com/mailman/listinfo/pykota

Or through IRC :

        /server irc.freenode.net
        /join #pykota
        
Plans for next releases, unsorted :

    - Make LPRng support on-par with CUPS support again,
      allowing immediate hardware accounting for LPRng too.
    
    - Improve documentation.
    
    - Explore PyKota database + OpenOffice.org interactions.
    
    - Allow more ways to limit printing, like by combining
      page + balance quota for example (thanks Henrik !)
      
    - Web based administrative interface.
    
    - Allow to see the printers groups history too
      (actually only individual printers history is
       shown)
       
Thank you for reading.

Jerome Alet

-- 
"A non-free program is a predatory social system that keeps people 
in a state of domination and division, and uses the spoils to 
dominate more." - RMS


From tjreedy at udel.edu  Fri Jan  2 00:46:18 2004
From: tjreedy at udel.edu (Terry Reedy)
Date: Fri, 2 Jan 2004 00:46:18 -0500
Subject: NEWBIE: map | zip | list comp
References: 
Message-ID: 


 wrote in message
news:odv9vvgb4aobq4c617k0ju4plat2d81j0o at 4ax.com...
> Hello again...hope everyone had a great New Year...:)
>
> In the quest to learn more about Python, I decided to create an arbitrary
sequence,
> then march each member through a 'field' of each of the members in turn,
and just to complicate it a
> bit, make the length of the field user defined.
> Hard to explain...an example might serve:
>
> 10000
> 01000
> 00100
>   .
>   .
> 00009
> 01111
> 10111
> 11011
>   .
>   .
> 21111
> 12111
> 11211
> and so forth.
>
> The only coding I could come up with is:
>
> base_seq = 'ABCD'
> length = 6
>
> for char_1 in base_seq:                          # Loop thru the set
char_1 at a time
>     for char_2 in base_seq:                     # Loop thru the seq again
for each char_1
>         if char_2 == char_1: continue         # Don't march 'A' thru a
field of 'A's
>         for ix in range(length):                     # Now march char_2
thru a field of char_1's
>             print (char_1 * length)[:ix] + char_2 + (char_1 *
length)[ix:-1]

Move the constant char_1*length outside of the two inner loops, or else
multiple by the actual needed length instead of making too much and
slicing.

>
> which, as you can see, has three nested FOR loops. I played with map, zip
and list comps a bit, but
> couldn't figure out how to compress the above code.

You mean something like (untested):

[char_1*ix + char_2 + char_1*(length - ix -1) for char_1 in base_seq
  for char_2 in base_seq if char_1 != char_2 for ix in range(length)]

> Am I barking up the wrong Python tree?

I think so.  Consider how long it took you to write clear conprehensible
code using Python's significant indentation *feature* and how long it took
you to not successfully get rid of it and how long it took you to convince
yourself that my no-indent perversion produces the same items (though in a
list), if indeed it does.  In my view, expressions should be only as long
as can be grokked in one mental gulp, and I think above overdoes it a bit.
Of course, the humancode quality can be restrored by writing it more
clearly as

[char_1*ix + char_2 + char_1*(length - ix -1)
    for char_1 in base_seq
        for char_2 in base_seq
            if char_1 != char_2
               for ix in range(length)]

in which case one has just moved the last line to the top and avoided
result=[] and result.append().

Terry J. Reedy




From jzgoda at gazeta.usun.pl  Tue Jan 13 16:11:11 2004
From: jzgoda at gazeta.usun.pl (Jarek Zgoda)
Date: Tue, 13 Jan 2004 21:11:11 +0000 (UTC)
Subject: id3v2 module
References: 
	
Message-ID: 

Guido Schimmels  pisze:

>> I'd like to know if there is a third-party module for reading/writing
>> id3v2 informations.
>> Thanks
> 
> http://id3-py.sourceforge.net/

This one is able to read and write only ID3v1.1 tags.

-- 
Jarek Zgoda
Unregistered Linux User #-1
http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/


From usenet at -OBFUSCATED-joefrancia.com  Fri Jan  9 01:21:00 2004
From: usenet at -OBFUSCATED-joefrancia.com (Joe Francia)
Date: Fri, 09 Jan 2004 06:21:00 GMT
Subject: python newbie
In-Reply-To: 
References: <3ffddcfd$0$16662$ba620e4c@news.skynet.be>
	<5unrvv8u1vpske1j464epj4aff0f54k2nf@4ax.com>
	
Message-ID: 

d wrote:
> Worked fine for me on Linux... made two suggested changes: 1) use
> raw_input(), not input(), 2) check user input for errors. Sorry, I don't
> know how to say "Enter a number between 0 and 500" in whatever language
> this is in (German?)
> 

You're a Python user and you don't recognize Dutch?!?!  For shame... ;>)


From Kyler at news.Lairds.org  Tue Jan 20 13:12:06 2004
From: Kyler at news.Lairds.org (Kyler Laird)
Date: Tue, 20 Jan 2004 18:12:06 GMT
Subject: Do (USA) Python conferences require a coast?
Message-ID: <6b50e1-goo.ln1@jowls.lairds.org>

In 2001 I attended the Python conference in Long Beach, CA.  I
had just decided that Python was something I should use and the
conference provided me a (well-fitted) brainful of good insight.
	http://lairds.org/Kyler/photos/disk0019/img_0421.jpg/image_viewer

Now I use Python constantly.  I'd like to get face-to-face with
Python experts so that I can better understand complex pieces
and discover new tools.  I want to attend another conference.

It looks like PyCon
	http://pycon.org/
is always in Washington, DC.  I try to avoid DC.

Python10
	http://www.python10.org/
is also essentially in DC (Alexandria, VA).

Even the Plone conference (New Orleans) was on a coast.  Do
Python users always have to be "on edge"?

Does anyone consider hosting a Python conferences in cheaper/
safer/freer/more central locations?  (Say...Indianapolis?)  I
see that there are some Python intros in Longmont, Colorado.
	http://www.python.org/community/events.html
That'd be a dandy location for a conference too.  (It's been
awhile since I visited Estes Park.)

Thank you.

--kyler


From aahz at pythoncraft.com  Mon Jan  5 12:35:45 2004
From: aahz at pythoncraft.com (Aahz)
Date: Mon, 5 Jan 2004 12:35:45 -0500
Subject: REMINDER: BayPIGgies Jan 8: Python Threads
Message-ID: <20040105173544.GA1029@panix.com>

The next BayPIGgies meeting is this Thursday, January 8, 2004, 7:30pm

Aahz will be presenting a talk on Python threads.

BayPIGgies meetings are held at Stanford, California.  For more
information, see http://www.baypiggies.net/
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

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



From andy at reportlab.com  Sat Jan 31 18:28:18 2004
From: andy at reportlab.com (Andy Robinson)
Date: Sat, 31 Jan 2004 23:28:18 -0000
Subject: Python vacancies at ReportLab, London
Message-ID: 

ReportLab develop enterprise reporting solutions using
cutting-edge Python technology, and have a growing
business with an excellent blue chip customer base. You
may also know us from our open source PDF and graphics
library....

We are looking for two positions with immediate effect:

(1) Trainee I.T. consultants working in our solutions team
Full time junior positions based in our London office.


(2) Technical Writer / Marketeer / Evangelist
A dual role maintaining documentation and writing articles,
press releases and web content to promote the company.
Either a junior full time position in our London office,
or a remote part-time role for an experienced writer.

Full details are at http://www.reportlab.com/careers.html
Please use the vacancies address there; don't contact me
directly.

Best Regards,

Andy Robinson
CEO/Chief Architect
ReportLab Europe Ltd.
mobile +44-7976-355742
office +44-20-8544-8049
 



From try_vanevery_at_mycompanyname at yahoo.com  Thu Jan 15 00:20:11 2004
From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every)
Date: Wed, 14 Jan 2004 21:20:11 -0800
Subject: The GPL / BSD cultural divide (was ProtoCiv: porting Freeciv to
	Python CANNED)
References: 
	
	
	<4004EC9E.1E2E2893@alcyone.com> 
	
	
Message-ID: 


"James Keasley"  wrote in message
news:slrnc0bg61.3p2.me at localhost.localdomain...
> In article , Brandon J. Van
Every wrote:
>
> > Agreed, and more specifically, there is a huge *cultural divide* between
> > most OSS developers and proprietary commercial developers who simply
want to
> > add some OSS "to get the boring bits over with."
>
> Yeah, it indicates that you are a lazy cunt who wants to get something for
> nothing,

Wow, isn't *that* a sophisticated business model.  Call me so impressed.

> if you want to use someone elses work that you haven't commissioned
> from them, find what you want from someone who isn't fussed, and has used
the
> BSD license, people who have used the GPL have done so cos they *don't*
> want some software company ripping off their hard work and not
contributing
> anything back.

Here's my attitude towards free software:

- if you are going to give something away, give it away completely.
- if it's too valuable to give away, don't.
- software, in general, is not supposed to be free.
- we save labor when "the boring bits" are free.
- ergo, give your boring bits to the common good.  Keep the interesting /
valuable stuff for yourself.

-- 
Cheers,                     www.indiegamedesign.com
Brandon Van Every           Seattle, WA

20% of the world is real.
80% is gobbledygook we make up inside our own heads.



From mxlaym009 at nospam_hotmail.com  Sun Jan 11 17:49:34 2004
From: mxlaym009 at nospam_hotmail.com (M. Laymon)
Date: Sun, 11 Jan 2004 22:49:34 GMT
Subject: Python installation breaks Outlook Express
Message-ID: 

I just installed Python 2.3.3 under Windows XP professional.   After I
did, my wife tried to access her email using Outlook Express and got
the error messages:

Your server has unexpectedly terminated the connection. Possible
causes for 
this include server problems, network problems, or a long period of
inactivity. 
Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net', 
Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F

Your server has unexpectedly terminated the connection. Possible
causes for this 
include server problems, network problems, or a long period of
inactivity. 
Account: 'incoming.verizon.net', Server: 'incoming.verizon.net',
Protocol: POP3, 
Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F

 (No comments about Outlook, please.I have tried to get her to use a
different email program, but she likes Outlook.)   I checked the
settings, then recreated her account in Outlook, but nothing worked.
My Mozilla Thunderbird email client worked fine.

Since the only thing I had done recently was to install Python.  I
used system restore to go back to the point before installing Python.
After I did, Outlook started working again.  Has anyone else seen this
behavior ?

Thanks.

M. Laymon


From Pieter.Claerhout at Creo.com  Wed Jan 28 09:26:49 2004
From: Pieter.Claerhout at Creo.com (Pieter Claerhout)
Date: Wed, 28 Jan 2004 15:26:49 +0100
Subject: Simple Database Package
Message-ID: <490316A24CC5D411ACD700B0D078F7F003915E2F@cseexch01.cse.creoscitex.com>

Take a look at:
MetaKit: http://www.equi4.com/metakit/
SQLite: http://www.sqlite.org/

Cheers,


pieter

Creo
pieter claerhout | product support prinergy | tel: +32 2 352 2511 |
pieter.claerhout at creo.com | www.creo.com

IMAGINE CREATE BELIEVE(tm)


-----Original Message-----
From: michael at foord.net [mailto:michael at foord.net] 
Sent: 28 January 2004 15:23
To: python-list at python.org
Subject: Simple Database Package


I'm looking to build a simple database application for use on the
desktop (customer contact and feedback database).

Anyone able to reccomend a simple module / package I can use...  ?
I've never done any database work before and am ken to learn - but
most of the ones I've seen seem to rely on a database engine buit into
a server.. I need a simple stand alone engine. Of course I could just
build the functions I need - but that would be a bit of a waste and
not so extendable........

Thanks in advance for your help.

Fuzzy

fuzzy man AT atlantibots DOT org DOT uk

-- 

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.voidspace.org.uk/atlantibots/pythonutils.html
The home of Python dateutils - dateutils, ConfigObj, StandOut,
CGI-News etc
-- 
http://mail.python.org/mailman/listinfo/python-list



From mwilson at the-wire.com  Tue Jan 27 11:56:14 2004
From: mwilson at the-wire.com (Mel Wilson)
Date: Tue, 27 Jan 2004 11:56:14 -0500
Subject: Ordered dictionary?
References: 
	
	<99dce321.0401231546.5f73d721@posting.google.com>
Message-ID: 

In article <99dce321.0401231546.5f73d721 at posting.google.com>,
dw-google.com at botanicus.net (David M. Wilson) wrote:
>"Paul McGuire"  wrote...
>
>> If you really need to access the dictionary in sorted key order, is this so
>> difficult?
>
>That was not the original poster's question. Order is semantic
>information which a dictionary does not record or represent in any
>way.

Wants order of insertion.  Best I can think of is



class OrderedDict (dict):
    "Retains order-of-insertion in the dictionary"
    def __setitem__ (self, key, value):
        dict.__setitem__ (self, key, (len (self), value,) )

    def __getitem__ (self, key):
        return dict.__getitem__ (self, key)[1]

    def ordered_items (self):
        i = [(v, k) for (k, v) in self.items()]
        i.sort()
        return [(k, v[1]) for (v, k) in i]

# end class OrderedDict

if __name__ == '__main__':
    D = OrderedDict()
    D['oranges'] = 41
    D['lemons'] = 22
    D['limes'] = 63

    print D
    print D.ordered_items()



   Possibly other refinenemts:  __init__ that inserts from a
sequence of 2-tuples, keeping a sequence number as a class
attribute instead of using len, etc.

        Regards.        Mel.


From webmaster at beyond-thoughts.com  Mon Jan 12 17:05:49 2004
From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng)
Date: Mon, 12 Jan 2004 23:05:49 +0100
Subject: Immutable Proxy-Class, "Pseudo freeze(obj)"
Message-ID: <40031A3D.2070408@beyond-thoughts.com>

Hello,

There are many cases where you have a mutable object and would like to 
use its __hash__-method (e.g. use it as key for a dict). Of course a 
mutable class should not define __hash__ because it doesn't make much 
sense if the object can change.

However you could define the class Immutable (if you mind about 
isinstance you can define a special __new__ ...) that is effectivly a 
proxy for the object given the constructor so it passes all accesses to 
the real object. But it defines a __hash__ method. This return a 
hash-value calculated when the Immutable-instance has been created. Each 
time there is an access to the underlying real object the proxy checks 
if the newly-calculated hash-value and the old one (calculated on 
instantiation) are different before and after access. If they are 
different it will raise an Exception.
Since there is no way to prevent someone to keep a reference to the 
original/real object obj it is not possible to avoid changing this 
object. But then if the Immutable(obj)-instance is accessed the 
hash-value will have changed. Thus causing an Exception.

One problem I see is that you can't find out where such an "illegal 
operation" happened. You just see when the Immutable-instance is access 
and it fails.
On the other hand if the Immutable-instance isn't accessed anymore 
changing the original object is no problem.


What do you think?
Badstyle?
Handy?
...


Thanks,
    Christoph Becker-Freyseng


PS:
Some links on similar subjects:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159143    ASPN : 
Python Cookbook : A ThreadedProxy wrapper

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078
ASPN : Python Cookbook : Wrapping method calls (meta-class example)

http://www.python.org/doc/current/ref/customization.html
3.3.1 Basic customization

http://www.python.org/search/hypermail/python-recent/0556.html
Python Archive (recent): freezing structures.

http://gpk.wftp.org:8082/sets.html
Python: module sets







From heavens7s at hotmail.com  Wed Jan 28 13:49:15 2004
From: heavens7s at hotmail.com (Joe)
Date: 28 Jan 2004 10:49:15 -0800
Subject: getting files over ftp
Message-ID: <560d84ab.0401281049.18d377f3@posting.google.com>

How can you grab files over an ftp connection using ftplib?  I can
make the connection, browse to the directory, view directory, but
can't copy over the files.

Thanks


From t-meyer at ihug.co.nz  Wed Jan 21 03:41:46 2004
From: t-meyer at ihug.co.nz (Tony Meyer)
Date: Wed, 21 Jan 2004 21:41:46 +1300
Subject: Installing SpamBayes
In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1304BA3CD2@its-xchg4.massey.ac.nz>
Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677860@its-xchg4.massey.ac.nz>

[example of using "cd" snipped]
> I hope that is enough of an example for you to figure out 
> what is going on. As to which path you need to change to, it 
> is wherever you decided to uncompress Spambayes.
[...]
> If this isn't enough, then Jeebus help you.

Or if Jeebus isn't available, then the OP could try the experimental binary
installer for SpamBayes, which includes all that's necessary to use
SpamBayes with Outlook Express.  If the OP can't manage the install process,
then they're probably better off with the binary, anyway.



=Tony Meyer




From jepler at unpythonic.net  Thu Jan 29 10:19:47 2004
From: jepler at unpythonic.net (Jeff Epler)
Date: Thu, 29 Jan 2004 09:19:47 -0600
Subject: regexp upward compatibility bug ?
In-Reply-To: 
References: 
Message-ID: <20040129151947.GC18498@unpythonic.net>

The problem is the use of '-' in the character groups, like
    r'[\w-]'

Here's what the library reference manual has to say:
[]
    Used to indicate a set of characters. Characters can be listed
    individually, or a range of characters can be indicated by giving
    two characters and separating them by a "-". Special characters are
    not active inside sets. For example, [akm$] will match any of the
    characters "a", "k", "m", or "$"; [a-z] will match any lowercase
    letter, and [a-zA-Z0-9] matches any letter or digit. Character
    classes such as \w or \S (defined below) are also acceptable inside
    a range. If you want to include a "]" or a "-" inside a set, precede
    it with a backslash, or place it as the first character. The pattern
    []] will match ']', for example.
           http://www.python.org/doc/current/lib/re-syntax.html

So you may want to write r'[-\w]' or r'[\w\-]' instead, based on my
reading.

The same goes for the later part of the pattern [\w-\.?=].

Jeff



From paul at prescod.net  Fri Jan 23 20:04:23 2004
From: paul at prescod.net (Paul Prescod)
Date: Fri, 23 Jan 2004 17:04:23 -0800
Subject: [OPINION] - does language really matter if they all do
	the	samething?
In-Reply-To: <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net>
References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com>
	<028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net>
Message-ID: <4011C497.1040302@prescod.net>

Dietrich Epp wrote:
> 
>...
> 
> 
> 
> Python seems to take the middle ground.  It's build from a procedural 
> standpoint, in an environment where most things are objects and some are 
> functions.  It's not what I'd choose as an example of an object oriented 
> language.  There are no messages, only function calls, so you can't 
> capture them. 

That's certainly not true. Take a look at how the XML-RPC libraries 
work. They capture "messages" sent from the program to the proxy object, 
reify them as XML "messages" sent across the network and then turned 
back into function calls applied to objects.

  The plus side is that methods behave exactly the same as
> functions, this makes the language simple and the two ideas 
> interchangeable.  You can set an object's method to a function.  The 
> minus side is that the paradigm of sending a message "to" an object 
> doesn't exist, and anyone coming from Smalltalk or even Objective-C 
> might miss that and feel constrained (I did).  But if Python were really 
> object-oriented like that, then it wouldn't have Python's simplicity any 
> more.
> 

I would appreciate an example of something you would do by capturing a 
message that cannot be done in Python.

I rather wonder if you've illustrated the downside of flitting from 
language to langauge. You may think you're using a language to capacity 
without actually doing so. I could be wrong but perhaps even the tasks 
you turn to Lisp or Perl for may have easy equivalents in Python.

  Paul Prescod




From peter at engcorp.com  Mon Jan  5 17:28:30 2004
From: peter at engcorp.com (Peter Hansen)
Date: Mon, 05 Jan 2004 17:28:30 -0500
Subject: intellectual property agreements and open source . was - Re:
 Why does this fail? [2]
References: 
	
	<84fc4588.0401042209.60cdb724@posting.google.com>
	
Message-ID: <3FF9E50E.C6AE7E21@engcorp.com>

Dave Murray wrote:
> 
> After re-reading this part, I can see that it is an idea that I like. How
> does participating in open source work for someone (me) who has signed the
> customary intellectual property agreement with the corporation that they
> work for? Since programming is part of my job, developing test solutions
> implemented on automatic test equipment (the hardware too) I don't know if I
> would/could be poison to an open source project. How does that work? I've
> never participated. If all the work is done on someone's own time, not using
> company resources, yadda-yadda-hadda-hadda, do corporate lawwwyaahhhs have a
> history of trying to dispute that and stake a claim? No doubt, many of you
> are in the same position.

My own agreement, which is not quite as archaic in restricting me as some I've
seen, boils down to saying that if I work on something that is either (done 
on company time or with company resources) OR (relates to the current or 
likely future business of the company) then I'm agreeing that the company 
in effect gets an exclusive right to whatever it is.

If, on the other hand, it's on my own time AND does not involve what the
company's business is (in contrast to, say, simply relating to tools that 
they might use within the business), then they don't get any right to it.
We use various test tools at work, but just because I work on a similar 
open source test tool doesn't mean the company has any exclusive right to it.
We sell RF stuff, not test tools, so test tools are not the company's 
business, nor are they likely ever to be...

I believe many or most agreements these days boil down to the same thing,
but of course your own might not so reading it would be a good idea.  

Generally there is lots of boilerplate legalese but it surrounds one or
two key paragraphs of fairly simple English with the essence described above, 
and it's not as hard to dig the key ideas out as it might seem at first glance.

-Peter


From ken at perfect-image.com  Sat Jan 31 22:25:07 2004
From: ken at perfect-image.com (Ken Godee)
Date: Sat, 31 Jan 2004 20:25:07 -0700
Subject: wxPython documentation
In-Reply-To: <30260531.0401311835.2246510f@posting.google.com>
References: <401c25a3$0$11357$636a55ce@news.free.fr>	
	<30260531.0401311835.2246510f@posting.google.com>
Message-ID: <401C7193.2060009@perfect-image.com>

simo wrote:
> Jonathan Daugherty  wrote:
> 
> 
>>>Where could I find a good documentation about wxPython (a documentation
>>>which is not for C++ !!!)
> 
> 
>>There are some wxpython tutorials and documents but the official wxPython
>>documentation is the wxWindows documenation itself -- wxPython notes are
>>sprinkled throughout.
> 
> 
> This is what I found off-putting about PyQt - the documentation
> basically points you to the Qt C++ docs:
> 

I find Qt's c++ Doc's to be a great/complete set of documents.
In a very short period of time one can just look at the c++ docs
and know how to convert it to PyQt.

But....If one finds it to confusing, "www.thekompany.com" sells
a set of "Qt c++" docs converted to "PyQt", I think they get about 
$15.00 bucks for it or/and it's included with Blackadder.





From zunbeltz at wm.lc.ehu.es.XXX  Mon Jan 26 10:17:21 2004
From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola)
Date: 26 Jan 2004 16:17:21 +0100
Subject: unittest
References: 
	
Message-ID: 

Tnaks, why is this so?

zunbeltz

Skip Montanaro  writes:

>     Zunbeltz> class KnowValues(unittest.TestCase):
> 
>     Zunbeltz>     KnownRotationMatrices = [
>     Zunbeltz>         ((Rotational3Part([[-1,0,0],[0,1,0],[0,0,-1]])),
>     Zunbeltz>         (1, -1, 2, matrix.vector([0,1,0])))
>     Zunbeltz>         ]
> 
>     Zunbeltz>     def TestRotationalPartdeterminant(self):
>     Zunbeltz>         """ RotationalPart. determinant with known values."""
>     Zunbeltz>         for i in  self.KnownRotationMatrices:
>     Zunbeltz>             det = i[0].determinant()
>     Zunbeltz>             self.assertEqual(det,i[1][0])
> 
> 
>     Zunbeltz> if __name__ == "__main__":
>     Zunbeltz>    unittest.main()
> 
>     Zunbeltz> but when i run this scrip i get the following output
> 
>     ...
> 
> Try renaming your test case method "test_rotational_partdeterminant".
> 
> Skip


From fnord at u.washington.edu  Sat Jan  3 23:44:26 2004
From: fnord at u.washington.edu (Lonnie Princehouse)
Date: 3 Jan 2004 20:44:26 -0800
Subject: Project dream
References: 
Message-ID: 

I keep thinking that a good graph module would be really handy (as in
nodes and edges, not plotting), with the ability to traverse and
manipulate graphs in nice Pythonic ways, as well as implement some
basic graph theory (finding cycles, paths, cliques, etc).  I've
started writing one, but it's nowhere near completion.


From max at alcyone.com  Mon Jan 12 05:15:20 2004
From: max at alcyone.com (Erik Max Francis)
Date: Mon, 12 Jan 2004 02:15:20 -0800
Subject: building strings with variable input
References: 
Message-ID: <400273B8.E991F41D@alcyone.com>

Olaf Meyer wrote:

> Especially if you have a lot of variable input it makes it hard to
> match
> the variables to the proper fields. From other scripting languanges
> I'm
> used to something like:
> 
>   $cmd = "$executable -start $startTime -end $endTime -dir $directory"
> 
> This makes it very easy to see how the string is actually built. You
> dont't have to worry where which variables go.
> 
> Is there a similar way to do this in python?

Sure:

cmd = "%(executable)s -start %(startTime)s -end %(endTime)s -dir
%(directory)s" % locals()

There are also more expansive solutions such as YAPTU or EmPy.

Note, however, that what you are trying to do (presuming you're passing
this to os.system or something similar) is potentially a serious
security risk.  If the values of the strings you are constructing the
command line are not fully trustworthy, they can be easily manipulated
to make your program execute arbitrary shell commands.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ In the fight between you and the world, back the world.
    -- Frank Zappa


From a at a.invalid  Thu Jan  8 18:25:15 2004
From: a at a.invalid (Timo Virkkala)
Date: Fri, 09 Jan 2004 01:25:15 +0200
Subject: Cheetah - Test suite failures
In-Reply-To: 
References: 
	
	
Message-ID: 

Just to put info here, in case someone else has the same problem:

Before seeking help on the Cheetah mailing list, I browsed through the 
last couple of months of posts there, and apparently the test suite just 
doesn't work properly on Windows. It seems that the major functions of 
Cheetah work fine, but there's problems with the test suite.

--
Timo Virkkala


From nopa90 at msn.com  Sat Jan 17 01:31:49 2004
From: nopa90 at msn.com (maxwell hammer)
Date: Sat, 17 Jan 2004 06:31:49 +0000
Subject: Wrapper to speex and ffmpeg library
Message-ID: 

Anyway make a wrapper to speex library (different from the otherone someone 
else make)

Make wrapper for ffmpeg or the libavcodec part atleast

You can find them here

http://www.jjanecek.ca.tf

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963




From claird at lairds.com  Wed Jan 14 15:56:02 2004
From: claird at lairds.com (Cameron Laird)
Date: Wed, 14 Jan 2004 20:56:02 -0000
Subject: Terminal Emulation with IBM ES9672 mainframe via multiplexer.
References: 
Message-ID: <100bb7231sighd6@corp.supernews.com>

In article ,
  wrote:
>Hi All, 
>
>Sorry for repeating, in the earlier msg i forgot to add a Subject line !! 
>
>I am a student-newbie to Python-List (for that matter Python language)
>working on a project for Terminal Emulation. The dumb terminal interacts
>with an
>IBM ES9672 mainframe through a 'multiplexer-MUX'. 
>The s/w is currently running in 'C' on a Windows NT environment and the
>requirement is to introduce Object Oriented concepts and C++ was the obvious
>choice, but i came across  'Python' (and also Perl, Ruby, ..etc) after i
>installed RH8 on my PC last month. We are actively canvassing the advantages
>of GNU
>s/w and philosophy and would like to simultaneously port it to GNU/Linux
>platform.
>
>I have read some of the documentation in Python.
>Before using Python as our project language it would be useful to know
>whether Python has functions, libraries/headers (like C does) capable of
>handling
>the foll. :
>
>1] open and close serial ports,
>2] set baud rates,
>3] check parity bit/byte,
>4] stop bits,
>5] Hardware handshaking,
>6] selection of port,......
>
>Our existing 'C' code is to be ported to the GNU/Linux platform so we are
>actively looking at an OOP concept. The part for serial port communication
>in
>C++ has classes so its easier to write customized programs to do most of the
>above. 
>
>Most importantly compatibility issues with the existing Multiplexer and
>Cisco Routers have to be kept in mind as the company will *not* make any H/W
>changes. 
>
>We saw that python has some routines for using existing C code, so we dont
>have to rewrite everything and can make modules containing functions and use
>it to operate on files. 
>Does it provide any other serial port communication features ?
>It would be nice if anyone could throw some light on some of the above
>issues.
			.
			.
			.
Yes, Python can do all this.

Although perhaps not as well as other approaches.  I don't understand
your description.  You have something that "works", now, and you want
... well, I'm not sure what you want.  Is the software you're looking
to change the terminal emulator, or the MUX?  I think it's the former.
What's the relation of the new software and the software it's
replacing?  Are they supposed to have the same design?  Would it be
easier for you to do object-oriented analysis and design, then imple-
ment in C (while C isn't a particularly inviting language for OO, it
*is* possible to use it)?  Is the terminal emulator connecting to a
mainframe, or routers, or both?  Is it enough for you just to exhibit
one of the many free-software terminal emulators available?  When *I*
work in this area, I certainly start with as much re-use as possible.

Perhaps I'm not following the academic spirit of this assignment.  It
sounds as though you have settled on construction of certain low-level
serial-line capabilities in C++, and one of your requirements is to
interface with that (as yet uncoded?) specific library.  Do I have 
that right?

Boost is a nice way to use Python and C++ together.

Expect  is *very* widely used by 
those working with terminal emulation, serial-line connections,
networking hardware, and so on.  Perhaps Expect is exactly what you
lack; I really can't tell.  There's a Python-based Expect, although
it's not as well documented as the original one.

Is the point of this to construct working software, or learn OO, or
port to Linux, or ...?  Or all of the above?
-- 

Cameron Laird 
Business:  http://www.Phaseit.net


From skip at pobox.com  Thu Jan 29 10:24:54 2004
From: skip at pobox.com (Skip Montanaro)
Date: Thu, 29 Jan 2004 09:24:54 -0600
Subject: mod_speling for python
In-Reply-To: <9d1c4d6d.0401282106.d69b2c5@posting.google.com>
References: <9d1c4d6d.0401282106.d69b2c5@posting.google.com>
Message-ID: <16409.9670.680122.128304@montanaro.dyndns.org>


    prtk3> ... if there is a NameError exception, python walks the globals()
    prtk3> and locals() to see if it might be just a minor
    prtk3> spelling/capitalization error.

    prtk3> I can see how this might be done for ImportErrors, using ihooks
    prtk3> or iu, but I don't see how to do it for NameErrors. The python
    prtk3> compiler module doesn't seem to be the answer.

    prtk3> I know there are drawbacks, disadvantages, this is "evil", etc.
    prtk3> I only wanted to know what ways there are to add such a hook if
    prtk3> it is possible without altering the C source for python itself.

Take a look at sys.excepthook.  Actual implementation is left as an exercise
for the reader. 

Skip



From merkosh at hadiko.de  Tue Jan 20 20:06:33 2004
From: merkosh at hadiko.de (Uwe Mayer)
Date: Wed, 21 Jan 2004 02:06:33 +0100
Subject: always the same object (2)
References: 
Message-ID: 

Uwe Mayer wrote:

Thanks for all the responses. As John Roth  wrote
in <100rgj1etbcqr9d at news.supernews.com>:

> class DataWrapper():
>         data = { } 
>         def __init__(self, arg): #arg will contain a tuple
>                 data['var1'], data['var2'] = arg

the "data" variable is a class variable and shared by all DataWrapper,
therfore:

> result = [ ]
> while not :
>         data = struc.unpack("4s4s", f.read(8))
>         record = DataWrapper( data ) # pass tuple from unpack
>         result.append( record )

all "record"s in "result" share the same instance and thus all the data gets
overwritten. :)

Moving "data" into __init__() in DataWrapper does the trick.

Thanks again
Ciao
Uwe     


From mwh at python.net  Mon Jan 12 07:09:23 2004
From: mwh at python.net (Michael Hudson)
Date: Mon, 12 Jan 2004 12:09:23 GMT
Subject: Division oddity
References: 
	<7xeku5vrn8.fsf@ruckus.brouhaha.com>
	<5d83790c.0401120125.7d186102@posting.google.com>
Message-ID: 

python at rcn.com (Raymond Hettinger) writes:

> [Tim Rowe]
> > > If I do from __future__ import division then eval(1/2) gives me 0.5 as
> > > expected. But if I do print input("enter a sum: ") and enter 1/2 as
> > > the sum I get 0 as if I hadn't done the import.  I thought input was
> > > supposed to give the same behaviour as an eval on raw input -- why the
> > > difference here?
> 
> [Paul Rubin[
> > The input function is calling eval from the context of the module
> > where 'input' itself is defined.  If you use "from __future__ import
> > division" in module A and have "print 3/2" in module B, the value of
> > 3/2 in module B shouldn't be affected by the input, since module B
> > may depend on integer division having the old behavior.
> 
> Right!
> 
> So, the way to get eval() to respond to the import is to pass along
> the current environment:
> 
> >>> from __future__ import division
> >>> eval('9/2', globals())
> 4.5

Um, that's not how it works.  Off the top of my head I'm not entirely
sure why eval() respects future statements and input() does not, but
it's probably easy enough to fix, if anyone cares (I don't think I
do).

Cheers,
mwh

-- 
  Windows 2000: Smaller cow. Just as much crap.  -- Jim's pedigree of
  operating systems, asr


From john.abel at pa.press.net  Fri Jan 23 09:02:53 2004
From: john.abel at pa.press.net (John Abel)
Date: Fri, 23 Jan 2004 14:02:53 +0000
Subject: Sending Through ^] Through telnetlib
Message-ID: <4011298D.6040401@pa.press.net>

I have written a script that makes a telnet connection, runs various 
commands, and returns the output.  That was the easy bit :)  However, to 
close the session, I need to send ^] followed by quit.  I've tried 
sending chr(29), which is the ascii equivalent, but that doesn't seem to 
work.  Is there something I'm missing?

Any pointers would be much appreciated.

Thanks

J



From kdahlhaus at yahoo.com  Wed Jan 28 09:33:58 2004
From: kdahlhaus at yahoo.com (Kevin Dahlhausen)
Date: 28 Jan 2004 06:33:58 -0800
Subject: raw audio input on Windows
References: 
Message-ID: <283adf56.0401280633.765771aa@posting.google.com>

> Any hints are appreciated.


I've not messed with this myself yet, but I know of an app that does
serious audio processing that had to go through some part of the
direct-X library.  That app is sampling at a lot higher rate -
probably closer to the limits of pc sound cards.

If there's not a direct python api for directx, no pun intended,
there's a library that wraps any dll that should do the trick.


From sidharthk at hotmail.com  Wed Jan 28 12:51:21 2004
From: sidharthk at hotmail.com (Sidharth Kuruvila)
Date: Wed, 28 Jan 2004 23:21:21 +0530
Subject: isinstance() bug
References: 
	
	
Message-ID: 

Stupid post must be ignored at all costs

"Sidharth Kuruvila"  wrote in message
news:bv8qhc$ph1mk$1 at ID-223265.news.uni-berlin.de...
> i dont know unix.
> how does abs path work with sym-links.
>
>
>




From mesteve_b at hotmail.com  Wed Jan 14 22:03:53 2004
From: mesteve_b at hotmail.com (python newbie)
Date: Thu, 15 Jan 2004 03:03:53 GMT
Subject: I come not to bury C++, but to praise it...
References: 
Message-ID: 

Are you against using C++ wrapped in a library such as wxWindows?  This
library makes it pretty easy painless to write cross-platform stuff, but
even on Windows alone, it beats MFC or the going price of Delphi.

"John Benson"  wrote in message
news:mailman.337.1074032524.12720.python-list at python.org...
> I got into Python because I took one look at C++ and saw all the
handwaving
> in the introductory O'Reilly book to the effect that "everything looks
sweet
> now, but wait until these snazzy little features interact..." and then
> started casting around for another road to OOP. I happened upon Python,
and
> continue to use Python.
>
> I think that the already-posted comments seeking to appreciate the
> historical origin and motivations of C++ are essential to understanding
it's
> applicability in the present.
>
> C++ started as a quintessentially Unix-like exercise in software
> engineering: add functionality by leveraging existing software components
to
> the max. Another level of preprocessor (Cfront) was added to the compiler
> tool chain and Bingo! you had a new language. The advantage was quick
> time-to-implement. A big disadvantage was that you had to grok C to debug
> C++. Later compilers took C++ direct to object, but the C, non-OOP
heritage
> persisted in the new language: you had to master pointers and references
to
> really do C++. Later languages simplified the situation by dumping
pointers.
>
> I think that C++ was a great exercise, but software engineering has
> advanced. Why not take advantage of the latest packaging of OOP and enjoy
> the smoother ride? Pick Java, or Python or whatever pleases you. I'm happy
> using C for projects that fit it, and Python for more ambitions OOP stuff.
> C++ was a great way to move OOP forward, but now it looks more like a
> transitional form than a best-of-breed. Sic transit gloria mundi, which is
> Latin for "when you're hot, your hot; when you're not, you're not" or
> something like that.
>
> If you have a big investment in C++ and can crank out beautiful code in
your
> sleep, that's fine too. I just don't expect it to be as easy to find
people
> to maintain it as if it were written in C, or Python, or Java, or
whatever.
>
>
>




From elainejackson7355 at home.com  Thu Jan 29 13:03:36 2004
From: elainejackson7355 at home.com (Elaine Jackson)
Date: Thu, 29 Jan 2004 18:03:36 GMT
Subject: number of arguments a function takes
References: 
	
Message-ID: 

Exactly what I was looking for. Thank you very much.

"Duncan Booth"  wrote in message
news:Xns947FAE6461014duncanrcpcouk at 127.0.0.1...
| "Elaine Jackson"  wrote in
| news:CSaSb.329909$ts4.189798 at pd7tw3no:
|
| > Suppose one of the arguments of a function f_1 is another function
| > f_2. Can f_1 access the number of arguments taken by f_2?  (I'm
| > writing a little script to automate the construction of logical
| > truth-tables.)  Thanks.
|
| Look at the inspect module, in particular you probably want
| inspect.getargspec:
|
| >>> import inspect
| >>> def f(a,b): pass
|
| >>> inspect.getargspec(f)
| (['a', 'b'], None, None, None)
| >>> help(inspect.getargspec)
| Help on function getargspec in module inspect:
|
| getargspec(func)
|     Get the names and default values of a function's arguments.
|
|     A tuple of four things is returned: (args, varargs, varkw, defaults).
|     'args' is a list of the argument names (it may contain nested lists).
|     'varargs' and 'varkw' are the names of the * and ** arguments or None.
|     'defaults' is an n-tuple of the default values of the last n arguments.
|
| >>>




From antivirus at lg.ehu.es  Tue Jan 27 08:31:32 2004
From: antivirus at lg.ehu.es (antivirus at lg.ehu.es)
Date: Tue, 27 Jan 2004 14:31:32 +0100
Subject: Virus Alert
Message-ID: <200401271331.i0RDVW4l022013@lgsx13.lg.ehu.es>

The mail message (file: doc.scr) you sent to jose at we.lc.ehu.es contains a virus (WORM_MIMAIL.R).



From tzot at sil-tec.gr  Thu Jan  8 12:08:55 2004
From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou)
Date: Thu, 08 Jan 2004 19:08:55 +0200
Subject: Why " ".some_string is often used ?
References: 
	 <3FFD43EC.BC8240F9@alcyone.com>
Message-ID: <5f3rvvgohelv3ab6hk3fc4hbb41ii9mbio@4ax.com>

On Thu, 08 Jan 2004 03:50:04 -0800, rumours say that Erik Max Francis
 might have written:

[' '.join discussion]

>And above all, of course, if you think it personally looks ugly, you can 
>
>	from string import join
>
>or write your own join function that operates over sequences and does
>whatever else you might wish.  That's what the flexibility is there for.

I believe str.join(string, sequence) works best for the functional types
(no need to rely on the string module).
-- 
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix


From ykingma at accessforall.nl  Sun Jan  4 18:33:20 2004
From: ykingma at accessforall.nl (Ype Kingma)
Date: Mon, 05 Jan 2004 00:33:20 +0100
Subject: Scoped Lock
References: 
Message-ID: <3ff8a259$0$121$e4fe514c@dreader10.news.xs4all.nl>

Marco Bubke wrote:

> Hi
> 
> There is the Lock object in the threading module.
> But there is no medode there I could aquire a scoped
> lock like:
> 
> mutex = threading.Lock()
> my_lock = mutex.scoped_acquire() # maybe scoped_lock()
> #now this stuff is locked
> 
> del mylock
> 
> #the lock is released.
> 
> def do_domething:
>   my_lock = mutex.scoped_acquire()
>   #now this stuff is locked
>   #the lock is released after its out of scope
> 
> 
> I have written this my own but I'm not sure there is a drawback
> because its looks so convinent. So I wonder why its not in
> the module?

Some reasons:
- What should happen when an exception happens during the locked stuff?
- It is possible pass a reference to the lock during the locked stuff,
  so although the lock goes out of local scope, there still might be
  a reference to it.
- The moment that __del__() is called is not guaranteed.

You can also do it like this:

mutex = threading.Lock()
mutex.acquire()
try:
    # now this stuff is locked
finally:
    mutex.release() # explicit is better than implicit

Regards,
Ype

email at xs4all.nl


From prtk3 at yahoo.com  Wed Jan 14 15:21:59 2004
From: prtk3 at yahoo.com (PT)
Date: 14 Jan 2004 12:21:59 -0800
Subject: wxPython worries
References: 
Message-ID: <9d1c4d6d.0401141221.22c587f5@posting.google.com>

> What worries me is wxPython: 
> I'm also 
> unclear as to how easy custom controls are to build.

None of the Python GUI toolkits support making good custom controls as
well as Java and .NET do.  TKinter is probably the best Python option
for that.  If you are comfortable with Windows programming though,
wxPython will not be too difficult.

> Am I just being confused by my newbie-ness, or are my initial concerns 
> justified?  What's anybody else's experiences with gui programming in 
> wxPython like vs a RAD like Delphi or .NET?

If you want something similar to Delphi or .NET, then you would
probably like QT Designer much better than the wx options.  See
BlackAdder (Win, $$) or eric3 (Linux, free):
http://www.thekompany.com/products/blackadder/
http://www.die-offenbachs.de/detlev/eric3.html

If money isn't an issue though, just stick with Visual Studio and C#
and let the other guy do most of the work.


From peter at engcorp.com  Wed Jan 28 09:17:03 2004
From: peter at engcorp.com (Peter Hansen)
Date: Wed, 28 Jan 2004 09:17:03 -0500
Subject: Easy way to make EXEs...
References: 
Message-ID: <4017C45F.D7501215@engcorp.com>

Xero Limit 126 wrote:
> 
> Okay, I am completely new to Python, and I really dont understand much, but
> I was wondering how to make a python script/program into a standalone .EXE?
> I dont understand py2exe at all, so if someone could tell me or find me an
> easy (For a newbie) to convert Python scripts to EXEs, please let me know!

What don't you understand about py2exe?  How it works, or how to actually
execute it?  Or something else?  If you have trouble with it, perhaps there
could be some improvements in the documentation...  but nobody will know 
unless you help us figure out what the problem is.

-Peter


From pythonhda at yahoo.com.replacepythonwithlinux  Fri Jan 30 10:10:27 2004
From: pythonhda at yahoo.com.replacepythonwithlinux (pythonhda at yahoo.com.replacepythonwithlinux)
Date: Fri, 30 Jan 2004 10:10:27 -0500
Subject: pyc file problem
References: 
Message-ID: <20040130101027.0f484734.pythonhda@yahoo.com.replacepythonwithlinux>

You can also compile the .py to a python optimized file .pyo. That'll get rid of the comments.

Check out the "py_compile" module in the documentation.

The easiest way to do it would be to invoke python with the -O flag and import your module to generate the .pyo file.

On Fri, 30 Jan 2004 18:45:22 +0800
"Leo Yee"  wrote:

> Hi,
> 
> I am programming a online game program. I use python as my game's script
> language. To avoid hacking and cheating I don't want anyone to read the
> python script file and find useful information for hacking the game.
> 
> I know I can compile the '.py' file to '.pyc' file but I found that a normal
> text editor can read a lot of information from the '.pyc' file even those
> comments I wrote.
> 
> My question is if there is a methond to compile the '.py' file into a state
> that there are no human readable strings.
> 
> Thanks in advance.
> 
> Leo Yee
> 
> 
> 
> 


From tim.golden at viacom-outdoor.co.uk  Tue Jan 27 05:13:28 2004
From: tim.golden at viacom-outdoor.co.uk (Tim Golden)
Date: Tue, 27 Jan 2004 10:13:28 -0000
Subject: NetGetAnyDCName() - get PDC of a foreign WinNT-domain
Message-ID: 

[... snip my suggestion of pdc = win32net.NetGetAnyDCName (None,
"name_of_other_domain") ...]

>From: usenet at mail-2-me.com [mailto:usenet at mail-2-me.com]
>
>Thanks for your help, but that does not work. I get an error message
>which sais it can't reach the domain.
>But I'm sure did not make an syntax-error, because if I enter my own
>domain it works.
>
>Any other idea?
>
>Dirk
>
>

To ask the obvious question: do you definitely have all
the necessary security / connectivity in place to reach
the domain controller on that domain?

Can you log onto it normally with whatever name you're
running under now?

(I don't have more than one domain here, so it's difficult
for me to test)
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 fred.duwez at freesurf.fr  Tue Jan 13 08:23:36 2004
From: fred.duwez at freesurf.fr (Sinclair)
Date: Tue, 13 Jan 2004 14:23:36 +0100
Subject: Generate PDF or LaTeX ?
Message-ID: 

Hi all,

I am looking for a way to generateLaTeX or PDF code from python/zope
objects. The goal is to produce print documents.
Does any python module exist to do that ?

Thanks for your help.




From virus at sbs.at  Mon Jan 26 20:43:12 2004
From: virus at sbs.at (virus at sbs.at)
Date: Tue, 27 Jan 2004 02:43:12 +0100
Subject: Virus Alert
Message-ID: <200401270143.i0R1hCgL002351@nets109x.sie.siemens.at>

The mail attachment file data.cmd was blocked, according to Siemens Austria InterScan VirusWall's configuration. The action rejected was taken. Please send your attachment in a zip-file protected with a password.



From bkelley at wi.mit.edu  Thu Jan  8 10:58:32 2004
From: bkelley at wi.mit.edu (Brian Kelley)
Date: Thu, 08 Jan 2004 10:58:32 -0500
Subject: MySQLDB multiple cursor question
In-Reply-To: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu>
References: <3ffc6160$0$572$b45e6eb0@senator-bedfellow.mit.edu>
Message-ID: <3ffd7dbe$0$560$b45e6eb0@senator-bedfellow.mit.edu>

Brian Kelley wrote:
> I am trying to use threads and mysqldb to retrieve data from multiple 
> asynchronous queries.
> 
> My basic strategy is as follows, create two cursors, attach them to the 
> appropriate databases and then spawn worker functions to execute sql 
> queries and process the results.

The problem goes away if I have only one cursor per connection and just 
use multiple connections.  This seems like a bug but I don't know for sure.

Brian



From tchur at optushome.com.au  Wed Jan 14 16:53:13 2004
From: tchur at optushome.com.au (Tim Churches)
Date: 15 Jan 2004 08:53:13 +1100
Subject: Safe prime numbers in Python
In-Reply-To: <16389.28642.425686.771599@montanaro.dyndns.org>
References: <200401140639.i0E6dxt09128@mail001.syd.optusnet.com.au>
	
	<4005725d$1@nntp0.pdx.net>
	<16389.28642.425686.771599@montanaro.dyndns.org>
Message-ID: <1074117193.1189.69.camel@emilio>

On Thu, 2004-01-15 at 03:35, Skip Montanaro wrote:
>     >> Here's what I came up with using gmpy:
>     ...
> 
>     Scott> I suspect it might be faster if you looked for the lower prime:

Many thanks to Skip Montanaro and Scott Daniels for these suggestions. I
did not suspect that the gmpy library would have functions for prime
finding or testing. With a few days of processing I'll have more safe
primes than I'll ever need. Next step is to find all quadratic residuals
modulo p (where p is a safe prime). It notice that GMP has a function to
calculate the Legendre symbol (which hopefully gmpy wraps), so it should
be simple. Fab!

-- 

Tim C

PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere
or at http://members.optushome.com.au/tchur/pubkey.asc
Key fingerprint = 8C22 BF76 33BA B3B5 1D5B  EB37 7891 46A9 EAF9 93D0


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: This is a digitally signed message part
URL: 

From sdfATexpertuneDOTcom  Fri Jan 23 13:20:41 2004
From: sdfATexpertuneDOTcom (Scott F)
Date: Fri, 23 Jan 2004 18:20:41 -0000
Subject: Program Python in VIM
References: <871xpsc5zf.fsf@tulip.whu.ca> 
	<40103ee7.108130723@news.blueyonder.co.uk>
	<3ae9c53d.0401230913.64c7150d@posting.google.com>
Message-ID: 

mike at mhuffman.com (Mike Huffman) wrote in
news:3ae9c53d.0401230913.64c7150d at posting.google.com: 

> 
>:w
>:!python %
> 
> then thereafter in the current vi session:
>:!!
> 
> It would be nice to be able to combine the write and shell command
> in one single command...
> 

This should do it.

    map  :w:!python %

Scott


From markus_wankus at hotmail.com  Wed Jan 21 11:42:56 2004
From: markus_wankus at hotmail.com (Markus Wankus)
Date: Wed, 21 Jan 2004 11:42:56 -0500
Subject: Help, *.CHM, etc
References: <90f2d9db.0401201803.6f2adbf8@posting.google.com>
Message-ID: 

If you are interested, here is a snippet of how I did it a long time ago 
in a galaxy far, far away.  It avoids spawning multiple instances of the 
same .chm.

# 
----------------------------------------------------------------------------
# The Help..Contents menu command
     def OnMnuHelpContents(self, event):
         """This method opens the Help file (if it isn't open already)."""
         # Display the help file - nothing fancy - just run it
         # ToDo - if already running bring to top (I can't see a way to do
         # this, currently)
         global helpfile_active

         helpfilename = os.path.join(r'path_to_your_helpfile', 
r'yourhelpfile.chm')
         if not helpfile_active:
             helpprocid = wxNewId()
             self.helpfile_process = wxProcess(self, helpprocid)
             EVT_END_PROCESS(self, helpprocid, self.OnHelpWindowTerminate)
             helpfile_active = wxExecute('hh.exe %s' % helpfilename, False,
                                     self.helpfile_process)
# 
----------------------------------------------------------------------------
     def OnHelpWindowTerminate(self, event):
         """This event function is fired when the help window is closed."""
         global helpfile_active

         if helpfile_active:
             self.helpfile_process.Detach()
             self.helpfile_process.Destroy()
         helpfile_active = 0
# 
----------------------------------------------------------------------------

Couldn't tell you if os.startfile is better or not...but I imagine 
wxExecute is calling the Windows ShellExecute under the covers anyway.  Of 
course, this also fails if they do not have hh.exe installed but this is 
only on stock Win95 or older NT machines with IE < 5.0.  I imagine you 
could spruce it up with more error checking.

You may also want to get rid of the global and use a real attribute...this 
is from my beginner days. ;o)

Markus.

On 20 Jan 2004 18:03:36 -0800, Tom  wrote:

> A question for gui application programmers. . .
> I 've got some GUI programs, written in Python/wxPython, and I've got
> a help button and a help menu item.  Also, I've got a compiled file
> made with the microsoft HTML workshop utility, lets call it
> c:\path\help.chm.  My question is how do you launch it from the GUI?
> What logic do I put behind the "help" button, in other words.
>
> I thought it would be
>
> os.spawnv(os.P_DETACH, "c:\\path\\help.chm", [])
>
> but I get an error:
>
> OSError: [Errno 8]  Exec format error
>
> so I guess help.chm isn't executable itself, but is associated with
> some unknown executable.  I tried explorer.exe- at the dos cmd line it
> basically works to type
>
> explorer.exe c:\path\help.chm
>
> although there is a nag screen that would be nice to do without.
>
> so you'd think
>
> os.spawnv(os.P_DETACH, 'explorer.exe', ["c:\\path\\help.chm"])
>
> would be equivalent but it fails.  I have to believe someone out there
> in python community likes to include help.chm with their applications,
> nad there is a right way to do this.
>
> On another note, are there pure python based help viewers that people
> use instead?  The reason I ask is that would be more portable then the
> *.chm files are.  If there is such a beast I can't find it.


From bignose-hates-spam at and-benfinney-does-too.id.au  Thu Jan 22 23:19:22 2004
From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney)
Date: 23 Jan 2004 15:09:22 +1050
Subject: get "yesterday's" date in iso format
References: 
Message-ID: 

On Thu, 22 Jan 2004, necromancer_stupidspambot at quanta1.world-vr_stupidspambot.com wrote:
> I am trying to find a simple way to get "yesterday's" date.

    >>> import datetime
    >>> today = datetime.date.today()
    >>> today
    datetime.date(2004, 1, 23)
    >>> yesterday = today - datetime.timedelta( 1 )
    >>> yesterday
    datetime.date(2004, 1, 22)

-- 
 \      "We must become the change we want to see."  -- Mahatma Gandhi |
  `\                                                                   |
_o__)                                                                  |
Ben Finney 


From miki.tebeka at zoran.com  Mon Jan 19 17:35:16 2004
From: miki.tebeka at zoran.com (Miki Tebeka)
Date: 19 Jan 2004 14:35:16 -0800
Subject: What's the best Python freeze tool?
References:  
Message-ID: <4f0a9fdb.0401191435.5b134ad@posting.google.com>

Hello Eric,

> I'm working with McMillan Installer and didn't see any major bug. Note however 
> I'm still using Python 2.1 and Installer 5b5_5. There is apparently a new 
> Installer version (6 something - not yet "official"), but I don't know if it 
> correctly supports Python 2.3 now; I'm quite interested in hearing other users' 
> experiences, BTW...

I've used py2exe a lot and it's OK. The latest version (0.5) made me
switch to cx_freeze (new syntax for setup.py, less comptability with
scripts running from the interpreter ...). I'm pretty happy with it.

Miki


From deets_noospaam at web.de  Sun Jan  4 10:44:17 2004
From: deets_noospaam at web.de (Diez B. Roggisch)
Date: Sun, 04 Jan 2004 16:44:17 +0100
Subject: how to make a code object a function
References: 
	
Message-ID: 

Hi,

> Too lazy to type self?

yes. I used an underscore in java as indication for member-variables, so
typing _. appeared natural to me. 
 
>>>> import types
>>>> class T(object):
> ...     def add_dependency(self, name):
> ...             print "adding dependency", name
> ...
>>>> t = T()
>>>> def p_op1(_, args):
> ...     _.add_dependency("p_op1")
> ...
>>>> t.p_op1 = types.MethodType(p_op1, t)
>>>> t.p_op1(1)
> adding dependency p_op1
>>>>
> 
> By the way, types.MethodType and new.instancemethod seem to be equivalent.

Interesting - from the docs, I can't see that types.MethodType has a
constructor like this. 

Your example above gave me the idea to simply exec() my code-object, so in
the end I have a new function called p_op1 in my scope - that function I
can get using locals()['p_op1']. I know the name, so that works. 

Just out of curiosity - is there a way to know the name of a code object you
know nothing about except that it will become a function definition? I
guess I could go for some AST-stuff looking for a "def foo" statement, so I
know I will end up having defined foo when exec'ing the code object.

Regards,

Diez B. Roggisch


From bsneddonNOspam at yahoo.com  Wed Jan 28 10:24:51 2004
From: bsneddonNOspam at yahoo.com (Bill Sneddon)
Date: Wed, 28 Jan 2004 10:24:51 -0500
Subject: r prefix bug ... or my lack of understanding?
In-Reply-To: 
References: 
	
Message-ID: 

David Goodger wrote:

> It's a FAQ:
> http://www.python.org/doc/faq/general.html#why-can-t-raw-strings-r-strings-end-with-a-backslash 
> 
> (or question 4.24 of http://www.python.org/doc/faq/general.html).
> 
> -- David Goodger
> 
> 
Thanks I looked at faqs.org did not see it.
It does not seem to be kept up to date.  I will check python.org in
the future.

Bill



From gongli at cutey.com  Sat Jan  3 17:46:26 2004
From: gongli at cutey.com (gong)
Date: 3 Jan 2004 14:46:26 -0800
Subject: pickling lambdas?
Message-ID: <9abf3a27.0401031446.4d73cfb2@posting.google.com>

hi

i would like to pickle a lambda; according to the library docs in 2.3,
i believe this shouldnt be possible, since a lambda is not a function
defined at the top level of  a module (?)

however, upon google searching for "python lambda pickle" i find 2
posts, one including gvr, which apparently demonstrate that this was
being attempted and even suggest that it is feasible.  has this become
available yet, or will it be soon?

thanks
gong


From rmkrauter at yahoo.com  Sun Jan 25 00:58:30 2004
From: rmkrauter at yahoo.com (Rich Krauter)
Date: Sun, 25 Jan 2004 00:58:30 -0500
Subject: perl bug File::Basename and Perl's nature
In-Reply-To: <7fe97cc4.0401242131.22acf485@posting.google.com>
References: <7fe97cc4.0401242131.22acf485@posting.google.com>
Message-ID: <1075010310.4567.72.camel@vaio>

You're supposed to pass in regexes, perhaps? So your '.m'  argument
actually means "anything followed by an m" and not literally "a dot
followed by an m". Just a guess, but that would explain your problem.  
Rich

On Sun, 2004-01-25 at 00:31, Xah Lee wrote:

> Just bumped into another irresponsibility in perl.
> 
> the crime in question this time is the module File::Basename.
> 
> Reproduction:
> 
> 1. create a directory containing a file of this name: "cdrom.html".
> 2. "use File::Basename;", with the line:
>    ($name,$path,$suffix) = fileparse($File::Find::name, ('.html',
> '.m'));
> 3. Notice that your cdrom.html will be parsed into "cdr" with suffix
> "om.html".
> 
> expletive Perl and Perl slinging morons.
> 
> Now, if you peruse the "documentation" of "perldoc File::Basename",
> you'll see that it shouldn't be so. AND, the writting as usuall is
> fantastic incompetent. To illustrate, i quote:
> 
> --begin quote
> 
>  fileparse
> 
>  The fileparse() routine divides a file
>  specification into three parts: a leading path, a
>  file name, and a suffix. The path contains
>  everything up to and including the last directory
>  separator in the input file specification. The
>  remainder of the input file specification is then
>  divided into name and suffix based on the
>  optional patterns you specify in
>  @suffixlist. Each element of this list can be a
>  qr-quoted pattern (or a string which is
>  interpreted as a regular expression), and is
>  matched against the end of name. If this
>  succeeds, the matching portion of name is removed
>  and prepended to suffix. By proper use of
>  @suffixlist, you can remove file types or
>  versions for examination.
> 
> --end quote
> 
> Note the last sentence: "By proper use of @suffixlist, you can remove
> file types or versions for examination." Now, this is in sync with the
> usual verbiages of unix man pages, of mentioning irrevalent things.
> Why the fuck do i need to know what is version, or examination what??
> Not every morons in this world is using unix with its morinic
> convention of appending things to file names as a versioning system,
> and not every moron in this world need to "exam" things. The unix
> irrevalency, inprecision, driveling are paragoned above.
> 
> Here is a better documentation for the fileparse subroutine.
> 
>  fileparse
> 
>  fileparse divides a file name into 3 parts:
>  directory string, file name, file name
>  suffix. fileparse($filename, @suffixes) returns a
>  array of 3 elements ($name, $dir_path,
>  $suffix). The concocted result of
>  "dir_path$name$suffix" is guaranteed to equal to
>  $filename. The @suffixes is a array of strings,
>  for example ('\.html', '\.txt', '\.png'). These
>  strings are interpreted to be regular
>  expressions, and is matched against the end of
>  $filename.
> 
> 
> But NOOO, perl morons are too enamored with driveling to write such
> functional spec, after all, the code is sloppy and they don't REALLY
> know what the code really does. This is not just one incompetence.
> Perl is filled with them.
> 
> This report is on Perl version:
>   This is perl, v5.8.1-RC3 built for darwin-thread-multi-2level
>   (with 1 registered patch, see perl -V for more detail)
> 
> --
> 
> To the rookie programers out there, i advice against learning Perl.
> (i suggest Python instead) Please see
>  http://xahlee.org/UnixResource_dir/perlr.html
> 
>  Xah
>  xah at xahlee.org
>  http://xahlee.org/PageTwo_dir/more.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From webmaster at beyond-thoughts.com  Thu Jan  8 17:44:56 2004
From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng)
Date: Thu, 08 Jan 2004 23:44:56 +0100
Subject: PRE-PEP: new Path class; isValid, exists
In-Reply-To: 
References: 	<3FFA7E82.4020609@beyond-thoughts.com>		<3FFC9209.7060703@beyond-thoughts.com>
	
Message-ID: <3FFDDD68.9070202@beyond-thoughts.com>

Gerrit Holl wrote:

> Christoph Becker-Freyseng wrote:
> 
>>Additionaly path-validity is filesystem-dependend. And worse on system 
>>like Linux there can be more than one file system within the same root / 
>>and they all could have different restrictions!
>>(if I were a viscious guy I could even umount and mount a different fs 
>>making a valid path possibly invalid)
> 
> 
> I think this makes validating a path essentially impossible to get
> right. Let's say we can declare path to be invalid, but we can't declare
> a path to be valid. Is it a good thing to add a method for it then? (I
> think yes)
> 
> 
>>So I think the better solution would be to define a
>>path.isValid()
> 
> 
> I agree that it's better. We should allow invalid paths after all.
Yes. path.isValid would it make possible to check better for situations 
were calling things like mkdir and mkdirs (they directly depend on the 
path being valid) makes trouble.
We could also add an InvalidPathException. Which will at least help 
debugging. isValid could have a default argument "raiseExc=False" to 
make checking in these functions convienent e.g.
def mkdir(self):
	self.isValid(raiseExc=True)
	moreStuff ...
If the path is invalid it will stop with an InvalidPathException.

Also path.exists should depend on path.isValid (not the other way).
If the full-path doesn't exist one can go up all the parent-dirs until 
one exist. Here we can check if the specified sub-path is valid by 
getting some information about the filesystem where the parent-dir is 
stored. *this implicit makes isValid a reading method* --- however AFAIK 
isValid is only needed for reading and writing methods.
> 
> 
>>We also need a
>>path.exists()
>>method.
> 
> 
> Sure.
> 
> 
>>I'm not sure how both should interact ??
> 
> 
> Well, if path.exists(), path.isValid(). The question is - should
> path.isValid() read the filesystem?
Yes as stated above.

path.exists should at first check if the path isValid at all. If it 
isn't a statement about it's existance is senseless. In this case it 
should return None, which evaluates also False but is different  (it's a 
"dreiwertige Logik" --- when you have 3 states (true, false, unknown) 
how is this called in English)

FIXME: We have to finetune the "recursive" behavior of isValid and 
exists otherwise we have a lot of unnecessary calls as exists and 
isValid call each other going one dir up ...


Christoph Becker-Freyseng






From Florian.Lindner at xgm.de  Thu Jan 29 11:12:21 2004
From: Florian.Lindner at xgm.de (Florian Lindner)
Date: Thu, 29 Jan 2004 17:12:21 +0100
Subject: Get number of iteration
Message-ID: 

Hi!
If I iterate through a list, is there a way I can get the number of the
iteration: first, second, third, ...

l = ["three", "four", "five", "six"]
for x in l
  print x
  print x.iteration()  # <- That's what I'm looking for!
  print "next"

prints that:

three
1
next
four
2
next
fixe
3
next
six
4
next

Thx,
Florian


From bart_nessux at hotmail.com  Thu Jan 15 15:08:23 2004
From: bart_nessux at hotmail.com (Bart Nessux)
Date: Thu, 15 Jan 2004 15:08:23 -0500
Subject: python & mathematical methods of picking numbers at random
In-Reply-To: 
References: 
	
Message-ID: 

Jeff Epler wrote:
> It sounds like your co-worker has re-written sample.  random.sample(l, 1)
> is the same as random.choice(l), so that's another source of inefficiency.
> 
> But why are *you* using 
>     random.sample(range(len(x)), 25)
> instead of
>     random.sample(x, 25)
> ?
> 
> Jeff
> 

Because it works and it's fast and len(count) changes every drawing.



From gsmith at oxfam.org.uk  Wed Jan 28 09:53:33 2004
From: gsmith at oxfam.org.uk (Graham)
Date: Wed, 28 Jan 2004 14:53:33 -0000
Subject: Distributing Python programs
References: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net>
	<4017C6EE.E7F1B27@engcorp.com>
Message-ID: <4017cd62$0$9388$ed9e5944@reading.news.pipex.net>

"Peter Hansen"  wrote in message

> Yes, we run dozens of machines from a single network installation.
> Depending on what extensions you need to install (e.g. win32all) you may
> need to make some small manual adjustments to get it to work, but
> in essence you can just do a "non-admin" local install, then copy the
> entire directory tree to the network.
>
Peter
Thanks for this info.  Will this work with Python for Windows?  I tried what
you suggested a few days ago but found when I ran a python script it asked
me for a python.dll which I have found not in the directory tree but in my
local system32 directory (I have a local Python installation).

What is significant about the "non-admin" install and how do you do this?

regards

Graham Smith

PeopleSoft Technical Team Leader
OXFAM GB
+44 (1865) 313255
gsmith at oxfam.org.uk




From steve at ninereeds.fsnet.co.uk  Sat Jan 31 14:33:40 2004
From: steve at ninereeds.fsnet.co.uk (Stephen Horne)
Date: Sat, 31 Jan 2004 19:33:40 +0000
Subject: PEP 327: Decimal Data Type
References: 
	
	
	
	
Message-ID: 

On Sat, 31 Jan 2004 09:35:09 -0800, Josiah Carlson
 wrote:

>> If I needed more than that, I'd use a rational type - I speak from
>> experience as I set out to write a base N float library for C++ once
>> upon a time and ended up writing a rational instead. A rational, BTW,
>> isn't too bad to get working but that's as far as I got - doing it
>> well would probably take a lot of work. And if getting Base N floats
>> working was harder than for rationals, getting them to work well would
>> probably be an order of magnitude harder - for no real benefit to 99%
>> or more of users.
>
>I also wrote a rational type (last summer).  It took around 45 minutes. 
>  Floating point takes a bit longer to get right.

Was your implementation the 'not too bad to get working' or the 'doing
it well'?

For instance, there is the greatest common divisor that you need for
normalising the rationals. 

I used the Euclidean algorithm for the GCD. Not too bad, certainly
better than using prime factorisation, but as I understand it doing
the job well means using a better algorithm for this - though I never
did bother looking up the details.

Actually, as far as I remember, just doing the arbitrary length
integer division functions took me more than your 45 minutes. The long
division algorithm is simple in principle, but I seem to remember
messing up the decision of how many bits to shift the divisor after a
subtraction. Of course in Python, that's already done.

Maybe I was just having a bad day. Maybe I remember it worse than it
really was. Still, 45 minutes doesn't seem too realistic in my memory,
even for the 'not too bad to get working' case.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk


From ville.spamstermeister.vainio at thisisspamprotectiontut.finland  Tue Jan 20 16:26:06 2004
From: ville.spamstermeister.vainio at thisisspamprotectiontut.finland (Ville Vainio)
Date: 20 Jan 2004 23:26:06 +0200
Subject: an example of a singleton design pattern in python?
References: 
Message-ID: 

>>>>> "Daniel" == Daniel Ortmann  writes:

    Daniel> Hello, Does anyone have an example of a singleton design
    Daniel> pattern in python?


This trivial snippet might be enough for your needs:

class Foo():
    pass

_inst = None

def fooinstance():
    if not _inst:
        _inst = Foo()
    return _inst

-- 
Ville Vainio   http://tinyurl.com/2prnb


From rganesan at myrealbox.com  Tue Jan 20 06:33:04 2004
From: rganesan at myrealbox.com (Ganesan R)
Date: Tue, 20 Jan 2004 17:03:04 +0530
Subject: ctypes 0.6.3 released
References: 
Message-ID: 

>>>>> "Thomas" == Thomas Heller  writes:

>     It works on Windows, Linux and MacOS X (the latter require that
>     your machine is supported by libffi).

Hi,

I maintain the ctypes Debian package. The following patch allows ctypes to
be built on 64-bit archs.

--- ctypes-0.6.3.orig/source/callproc.c
+++ ctypes-0.6.3/source/callproc.c
@@ -549,11 +549,11 @@
 #if (SIZEOF_LONG_LONG == 8 && SIZEOF_LONG == 4)
 #undef ffi_type_ulong
 #define ffi_type_ulong ffi_type_uint32
-#define ffi_type_ulonglong ffi_type_uint64
 #undef ffi_type_slong
 #define ffi_type_slong ffi_type_sint32
-#define ffi_type_slonglong ffi_type_sint64
 #endif
+#define ffi_type_ulonglong ffi_type_uint64
+#define ffi_type_slonglong ffi_type_sint64

Ganesan

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



From Antigen_EXCHANGE_MTL at smtp.cidc.net  Fri Jan 30 21:49:22 2004
From: Antigen_EXCHANGE_MTL at smtp.cidc.net (Antigen_EXCHANGE_MTL at smtp.cidc.net)
Date: 30 Jan 2004 21:49:22 -0500
Subject: Our Anti-Vrus system found VIRUS= MyDoom.A@m (Norman, CA(Vet),
	Kaspersky) worm
Message-ID: 

Our Anti-Vrus system found doc.zip->doc.exe infected with VIRUS= MyDoom.A at m (Norman,CA(Vet),Kaspersky) worm.
The message is currently Purged.  The message, "Test", was
sent from python-list at python.org 




From max at alcyone.com  Sat Jan  3 18:19:27 2004
From: max at alcyone.com (Erik Max Francis)
Date: Sat, 03 Jan 2004 15:19:27 -0800
Subject: Cheetah best for templating?
References: 
Message-ID: <3FF74DFF.6BE7AC7D@alcyone.com>

Roger Jack wrote:

> I have just finished reading Code Generation In Action which uses Ruby
> for
> code generation. I would like to use Python instead. Is Cheetah the
> best
> tool to use for templating source code files and then generating code?
> Is
> there something more mature or better?

I tend to think highly of EmPy, but that's not exactly a surprise :-):

	http://www.alcyone.com/software/empy/

I do know that there are several people on the EmPy mailing list using
EmPy for exactly the purpose you're considering.

What's going to be best for you is really going to depend on your
aesthetic sensibilities; pretty much all of templating systems' base
features are universal, just expressed in different ways.  The only
thing that might objectively make one system better than another for you
would be ancillary features which are included on top.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Granted that I must die, how shall I live?
    -- Michael Novak


From jdhunter at ace.bsd.uchicago.edu  Thu Jan 22 07:39:19 2004
From: jdhunter at ace.bsd.uchicago.edu (John Hunter)
Date: Thu, 22 Jan 2004 06:39:19 -0600
Subject: prog/lib to draw graphs
In-Reply-To:  (Florian Lindner's message
	of "Thu, 22 Jan 2004 13:34:56 +0100")
References: 
Message-ID: 

>>>>> "Florian" == Florian Lindner  writes:

    Florian> Hello, I'm looking for a program or python library to
    Florian> draw graphs.  They should look like the that:


    Florian> /--------\ /--------\ | Node A | ------ belongs to ---->
    Florian> | Node B | \--------/ \--------/

    Florian> Which is a result of the function call like that:

    Florian> connectNodes(firstNode, secondNode, description,
    Florian> lineStyle) connectNodes("Node A", "Node B", "belongs to",
    Florian> dashed)

    Florian> It should have a open scalable vector format as output
    Florian> (DVI, SVG, PDF, ...)  and should be able to make
    Florian> automatic optimal placement of the items.  Do you know
    Florian> something like that?  Thx, Florian --
    Florian> http://mail.python.org/mailman/listinfo/python-list

graphviz is a sophisticated graph drawing program

  http://www.research.att.com/sw/tools/graphviz/

There is a python interface

    http://www.cs.virginia.edu/~jg9h/graphiz/

JDH




From reply.in.the.newsgroup at my.address.is.invalid  Fri Jan 23 04:40:26 2004
From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman)
Date: Fri, 23 Jan 2004 10:40:26 +0100
Subject: Accessing Microsoft Word from Python
References: 
Message-ID: 

Mickel Gr?nroos:
>Does anybody have any good pointers on where I can find information 
>about accessing Word-documents (or other Microsoft Office applications) 
>from Python?

This book: http://safari.oreilly.com/1565926218 explains how to access
Excel from Python. It also explains COM-interfacing in general.

>To be more specific, I want to be able to:

I think you should look that up in the Word object model (probably on
http://msdn.microsoft.com), since it's not Python-specific.

-- 
Ren? Pijlman


From alanmk at hotmail.com  Fri Jan 16 17:57:50 2004
From: alanmk at hotmail.com (Alan Kennedy)
Date: Fri, 16 Jan 2004 22:57:50 +0000
Subject: Suggested generator to add to threading module.
References: <7934d084.0401152058.164a240c@posting.google.com>
	<40083eac$0$321$e4fe514c@news.xs4all.nl>
	
Message-ID: <40086C6E.8536542C@hotmail.com>

[Andrae Muys]
>>> Found myself needing serialised access to a shared generator from
>>> multiple threads.  Came up with the following
>>>
>>> def serialise(gen):
>>>   lock = threading.Lock()
>>>   while 1:
>>>     lock.acquire()
>>>     try:
>>>       next = gen.next()
>>>     finally:
>>>       lock.release()
>>>     yield next

[Ype Kingma]
>> Is there any reason why the lock is not shared among threads?
>> From the looks of this, it doesn't synchronize anything
>> between different threads. Am I missing something?

[Jeff Epler]
> Yes, I think so.  You'd use the same "serialise" generator object in
> multiple threads, like this:
> 
> p = seralise(producer_generator())
> threads = [thread.start_new(worker_thread, (p,))
>                 for t in range(num_workers)]

Hmm. I think Ype is right: the above code does not correctly serialise
access to a generator.

The above serialise function is a generator which wraps a generator.
This presumably is in order to prevent the wrapped generators .next()
method being called simultaneously from multiple threads (which is
barred: PEP 255: "Restriction:  A generator cannot be resumed while it
is actively running")

http://www.python.org/peps/pep-0255.html

However, the above implementation re-creates the problem by using an
outer generator to wrap the inner one. The outer's .next() method will
then potentially be called simultaneously by multiple threads. The
following code illustrates the problem

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import time
import thread
import threading

def serialise(gen):
  lock = threading.Lock()
  while 1:
    lock.acquire()
    try:
      next = gen.next()
    finally:
      lock.release()
    yield next

def squares(n):
  i = 1
  while i < n:
    yield i*i
    i = i+1

def worker_thread(iter, markers):
  markers[thread.get_ident()] = 1
  results = [] ; clashes = 0
  while 1:
    try:
      results.append(iter.next())
    except StopIteration:
      break
    except ValueError, ve:
      if str(ve) == "generator already executing":
        clashes = clashes + 1
  del markers[thread.get_ident()]
  print "Thread %5s: %d results: %d clashes." % (thread.get_ident(),\
   len(results), clashes)

numthreads = 10 ; threadmarkers = {}
serp = serialise(squares(100))
threads = [thread.start_new_thread(worker_thread,\
            (serp, threadmarkers)) for t in xrange(numthreads)]
while len(threadmarkers.keys()) > 0:
  time.sleep(0.1)
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I believe that the following definition of serialise will correct the
problem (IFF I've understood the problem correctly :-)

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import time
import thread
import threading

class serialise:
  "Wrap a generator in an iterator for thread-safe access"

  def __init__(self, gen):
    self.lock = threading.Lock()
    self.gen = gen

  def __iter__(self):
    return self

  def next(self):
    self.lock.acquire()
    try:
      return self.gen.next()
    finally:
      self.lock.release()

def squares(n):
  i = 1
  while i < n:
    yield i*i
    i = i+1

def worker_thread(iter, markers):
  markers[thread.get_ident()] = 1
  results = [] ; clashes = 0
  while 1:
    try:
      results.append(iter.next())
    except StopIteration:
      break
    except ValueError, ve:
      if str(ve) == "generator already executing":
        clashes = clashes + 1
  del markers[thread.get_ident()]
  print "Thread %5s: %d results: %d clashes." % (thread.get_ident(),\
   len(results), clashes)

numthreads = 10 ; threadmarkers = {}
serp = serialise(squares(100))
threads = [thread.start_new_thread(worker_thread,\
            (serp, threadmarkers)) for t in xrange(numthreads)]
while len(threadmarkers.keys()) > 0:
  time.sleep(0.1)
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Also, I don't know if I'm happy with relying on the fact that the
generator raises StopIteration for *every* .next() call after the
actual generated sequence has ended. The above code depends on the
exhausted generator raising StopIteration in every thread. This seems
to me the kind of thing that might be python-implementation specific.
For example, the original "Simple Generators" specification, PEP 255,
makes no mention of expected behaviour of generators when multiple
calls are made to the its .next() method after the iteration is
exhausted. That I can see anyway? Am I wrong?

http://www.python.org/peps/pep-0255.html

regards,

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


From poelzi at poelzi.org  Tue Jan  6 09:17:57 2004
From: poelzi at poelzi.org (daniel.poelzleithner)
Date: Tue, 06 Jan 2004 15:17:57 +0100
Subject: Problems with threads and embedding
Message-ID: <3FFAC395.9080900@poelzi.org>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

i wrote a module for ctrlproxy which embedds python and provides an api
that ctrlproxy is scriptable.

Every script is started in an own interpreter instance and registers
some callback functions for different events.
The module is threadsafe and everything works just fine, with one
exceptions, dead threads are not removed from the process list.



import time
import thread
import sys
import os

def runme():
	time.sleep(2)
	print "PID: %s" %(os.getpid())
	print "PID: %s" %(os.getppid())
	print " ------------ END -------------"

print thread.start_new(runme,())


Results in:


poelzi   20633  0.1  2.2 17296 11508 pts/17  S    02:24   0:12  |   \_
gdb ./ctrlproxy
poelzi   15187  0.7  1.0 13136 5464 pts/17   T    05:55   0:00  |
\_ /home/poelzi/Projects/ctrlproxy/ctrlproxy
poelzi   15189  0.0  1.0 13136 5464 pts/17   T    05:55   0:00  |
~    \_ /home/poelzi/Projects/ctrlproxy/ctrlproxy
poelzi   15190  0.0  0.0     0    0 pts/17   Z    05:55   0:00  |
~        \_ [ctrlproxy] 



I tried to spend time in every created thread through the advanced
debugging api, but this changed nothing. I experimented with the
sys.exitfunc without success.


I added some debugging function to see what happens.

[...]
** INFO: Loading Python scripts
CREATED THREAD 16384
[...]

16384 is the thread of the script

[...]
ID:0:/home/poelzi/Projects/ctrlproxy/example/test.py
Joining channel #test
IS: 0x80cba58 134560928
TS: 0x810e2d0 16386
TS: 0x80fe860 16384
TS: 0x80bb028 16384
IS: 0x8083638 16384
TS: 0x8083660 16384
IS: 0x80cba58 134560928
TS: 0x810e2d0 16386
TS: 0x80fe860 16384
TS: 0x80bb028 16384
IS: 0x8083638 16384
TS: 0x8083660 16384
** INFO:  ------------ END -------------
IS: 0x80cba58 134560928
TS: 0x80fe860 16384
TS: 0x80bb028 16384
IS: 0x8083638 16384
TS: 0x8083660 16384
IS: 0x80cba58 134560928
TS: 0x80fe860 16384
TS: 0x80bb028 16384
IS: 0x8083638 16384
TS: 0x8083660 16384

IS is a interpreter state and TS a thread state.
16386 seems to be the thread created by the script. After it exists,
Python knows nothing about the thread anymore, but the return code
didn't seems to be catched.


The sourcecode is to large and CVSweb currently broken...
I uploaded the code @
http://files.poelzi.org/tmp/ctrlproxy_python/

http://files.poelzi.org/tmp/ctrlproxy_python/python.c is the main file.


Any hints for me so solve this anoying problem ? :(


regards
~ Daniel

- --
nihil me cirumdat

.. . .. ... . . .. . ... . .. . ... . . .
pgp key @ http://files.poelzi.org/pgp.txt
ED80 E53D 5269 4BB1 1E73 3A53 CBF9 A421 0A7B 003D
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Debian - http://enigmail.mozdev.org

iD8DBQE/+sOVy/mkIQp7AD0RAg5mAJwKD+DTxhmsQu8bzKnzSj5f/p0bjQCgp/Tf
M07tS7uaBFLKi5Z0/IjvSi4=
=doSL
-----END PGP SIGNATURE-----




From try_vanevery_at_mycompanyname at yahoo.com  Thu Jan 15 17:24:02 2004
From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every)
Date: Thu, 15 Jan 2004 14:24:02 -0800
Subject: The bigger white book penis (was Re: ProtoCiv: porting Freeciv to
	Python CANNED)
References: 
	
	
	
	
	
	<4004EC9E.1E2E2893@alcyone.com>
	<23891c90.0401140223.344b22af@posting.google.com>
	<100bbb6kj9m03a4@corp.supernews.com>
	
	<1AjNb.8936$1e.894@newsread2.news.pas.earthlink.net>
	
	
Message-ID: 

Andrew Dalke wrote:
> Brandon Van Every wrote:
> > Andrew Dalke wrote:
>>
>>> It's made even worse when you make claims related to your
>>> profession (like "Even 12 years ago, "Computer Graphics: Principles
>>> and Practice" didn't teach texture mapping.
>
>> It didn't.  I have my copy still, and there is no discussion of
>> texture mapping algorithms in it.  It was considered "an advanced
>> subject."
>
> Then you don't own the second edition, which came out a year
> before that "12 years ago" comment you made.  Had you said
> 14 years ago then things would be different.

Oh please FUCK OFF!!!  12 years, 13 years, 14 years, awhile ago!  Why are
you wasting our time on this nonsense???  "Computer Graphics, Principles &
Practice," 2nd. ed, 1990.  ISBN 0-201-12110-7.   Acquired my copy at Cornell
U., spring semester 1991.  NO GODDAMN TEXTURE MAPPING TREATISES.  In those
days, you pulled your "advanced" papers on texture mapping, and unless you
owned very expensive 3D HW you implemented them by hand.  PITA.  Never
bothered.  Still can't stand texture mapping to this day.  What a bunch of
inelegant ugly flat looking crap!

> A slight timing
> error perhaps, but properly you should have used the publication
> date of your book.

Look at what the *original* title of the thread was.  Consider where you've
*taken* it.  *What* is your fucking point???  Your point was, and is, and
will continue to be... ***ME!!!***

I give up!!!  You have won!!!  I am driven screaming from the FUCKING
C.G.D.* NEWSGROUPS, NOT TO RETURN FOR QUITE SOME TIME!!!
AAAAAAAAAAAAAARRRRRRGGHGHGHH!!!!

Wouldn't be the first time, either.  Probably not the last.  Hard for their
founder to stay away forever.  In the meantime, we will be MUTUALLY THANKFUL
for the absence!

-- 
Cheers,                     www.indiegamedesign.com
Brandon Van Every           Seattle, WA

I need a .sig about not suffering fools.



From max at cNvOiSsiPoAnMtech.com  Fri Jan  2 15:03:55 2004
From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin)
Date: Fri, 02 Jan 2004 20:03:55 GMT
Subject: re 
Message-ID: 

I am studying the re module and still do not understand how to do some 
really simple tasks:
1) say I need to capitalize any word that is between the words 'United' 
and  'of America'. So I do
re.findall|match|search('United .* of America', s)
this may return 'United States of America', but not 'States', which is 
the word of interest.
2) There is a further problem:
even if I had a way to specify 'States' in the example above as the 
matched regex, the sub function proves insufficient: re.sub allows me to 
specify only the replacement string, but not a operator:
re.sub(pat, lambda pat: Capitalize(pat), str)
would have been much more powerful.

are there ways to use re that I missed? is there another module that can 
do these?

thanks,
max.



From latex-bugs at latex-project.org  Thu Jan 29 21:41:13 2004
From: latex-bugs at latex-project.org (latex-bugs at latex-project.org)
Date: Fri, 30 Jan 2004 03:41:13 +0100 (CET)
Subject: hi
In-Reply-To: <200401300241.i0U2f6IA014897@rzdspc1.informatik.uni-hamburg.de>
References: <200401300241.i0U2f6IA014897@rzdspc1.informatik.uni-hamburg.de>
Message-ID: <200401300241.i0U2fDbE016353@sun.dante.de>

Thank you for your message to latex-bugs at latex-project.org.

Sorry, but the latex-bugs email processor cannot handle
MIME attachments. Please resend your problem report with
the contents of latexbug.msg as the body of your message.

-- 



From fBechmann at web.de  Fri Jan  2 05:43:43 2004
From: fBechmann at web.de (Frank Bechmann)
Date: 2 Jan 2004 02:43:43 -0800
Subject: question: Python or Lua for rejuvenation of old PCs?
References: 
Message-ID: 

maybe these links help, even if you have to look at the numbers and
charts w/ some care:

http://dada.perl.it/shootout/craps_mem.html
  quite old win2K machine (partly running cygwin tools)
  Python 2.3.2 vs. Lua 5.0 (and Lua 4.0)
  Lua (both versions, Lua 5.0 is even better) lead on memory usage


http://www.bagley.org/~doug/shootout/craps.shtml?xcpu=0&xmem=1&xloc=0&ackermann=1&ary3=3&wc=3&echo=5&except=1&fibo=2&hash=1&hash2=4&heapsort=4&hello=1&lists=3&matrix=3&methcall=5&nestedloop=4&objinst=5&prodcons=1&random=3®exmatch=4&reversefile=4&sieve=4&spellcheck=4&moments=2&strcat=2&sumcol=3&wordfreq=5
  even older linux machine
  Python 2.1 vs. Lua 4.0
  Python leads on memory usage

having read your application specs FORTH came to my mind, having the
advantage that it is even more crude, so you have even less chances to
intermix both languages. and no one will doubt that it is usefull for
embedded controller tasks.


From cygnus at cprogrammer.org  Sat Jan 31 17:11:44 2004
From: cygnus at cprogrammer.org (Jonathan Daugherty)
Date: Sat, 31 Jan 2004 17:11:44 -0500
Subject: wxPython documentation
In-Reply-To: <401c25a3$0$11357$636a55ce@news.free.fr>
References: <401c25a3$0$11357$636a55ce@news.free.fr>
Message-ID: <20040131221144.GA16935@mail.theserver.ath.cx>

# Where could I find a good documentation about wxPython (a documentation
# which is not for C++ !!!)

There are some wxpython tutorials and documents but the official wxPython
documentation is the wxWindows documenation itself -- wxPython notes are
sprinkled throughout.

-- 

  Jonathan Daugherty
  http://www.cprogrammer.org

  "It's a book about a Spanish guy called Manual, you should read it."
                                                            -- Dilbert



From reply.in.the.newsgroup at my.address.is.invalid  Sat Jan  3 05:41:55 2004
From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman)
Date: Sat, 03 Jan 2004 11:41:55 +0100
Subject: Text-to-HTML processing program
References: 
Message-ID: 

phil hunt:
>Does anyone know of a text-to-HTML processing program, ideally
>written in Python [...] which uses a simple markup language 
>(something like Wikipedia markup would be ideal)?

"reStructuredText is an easy-to-read, what-you-see-is-what-you-get
plaintext markup syntax and parser system. The reStructuredText parser is
a component of Docutils. reStructuredText is a revision and
reinterpretation of the StructuredText and Setext lightweight markup
systems."
http://docutils.sourceforge.net/FAQ.html#what-is-restructuredtext

"Structured Text is a simple plain text markup format used by Zope and
many Zope products, invented by.. JimFulton? ? The idea is to have text
that is easy to read both in source and rendered form."
http://dev.zope.org/Members/jim/StructuredTextWiki/FrontPage/

-- 
Ren? Pijlman


From __peter__ at web.de  Mon Jan 19 15:03:51 2004
From: __peter__ at web.de (Peter Otten)
Date: Mon, 19 Jan 2004 21:03:51 +0100
Subject: Delayed evaluation and setdefault()
References: 
Message-ID: 

Leo Breebaart wrote:

> Hi all,
> 
> I have a question about Python and delayed evaluation.
> 
> Short-circuiting of Boolean expressions implies that in:
> 
>    >>> if a() and b():
> 
> any possible side-effects the call to b() might have will not
> happen of a() returns true, because then b() will never be
> executed.
> 
> However, if I go looking for dictionary keys like this:
> 
>    >>> d = {}
>    >>> d.setdefault('foo', b())
> 
> then b() *does* get executed regardless of whether or not the
> value it returns is actually used ('foo' was not found) or not
> ('foo' was found).
> 
> If b() has side-effects, this may not be what you want at all. It
> would seem to me not too exotic to expect Python to have some
> sort of construct or syntax for dealing with this, just as it
> supports Boolean short-circuiting.
> 
> So I guess my question is twofold: one, do people think
> differently, and if so why?; and two: is there any elegant (or
> other) way in which I can achieve the delayed evaluation I desire
> for setdefault, given a side-effect-having b()?
> 

Lazy evaluation is dangerous as the state of mutable objects may have
changed in the mean time. In your case

if "foo" not in d:
    d["foo"] = b()

should do.

However, if you absolutely want it, here's a slightly more general approach:


class Defer:
    def __init__(self, fun, *args):
        self.fun = fun
        self.args = args
    def __call__(self):
        """ Calculate a deferred function the first time it is
            invoked, return the stored result for subsequent calls
        """
        try:
            return self.value
        except AttributeError:
            self.value = self.fun(*self.args)
            return self.value

def defer(fun, *args):
    """ Use, e. g., defer(average, 1, 2) to delay the calculation
        of the average until the first time undefer() is called
        with the Defer instance.
    """
    return Defer(fun, *args)

def undefer(value):
    """ Check if value is deferred, if so calculate it, otherwise
        return it unchanged
    """
    if isinstance(value, Defer):
        return value()
    return value

#example usage:

class Dict(dict):
    def setdefault(self, key, value):
        try:
            return self[key]
        except KeyError:
            # it might make sense to further delay the
            # calculation until __getitem__()
            self[key] = value = undefer(value)
            return value

def b(value):
    print "side effect for", value
    return value
dv = defer(b, "used three times")

d = Dict()
d.setdefault("x", defer(b, "a1"))
d.setdefault("x", defer(b, "a2"))
d.setdefault("y", "b")
d.setdefault("a", dv)
d.setdefault("b", dv)
d.setdefault("c", dv)
print ",\n".join(repr(d).split(","))
assert d["a"] is d["b"]



You will still have to bother with undeferring in *many* places in your
program, so the above would go into the "or other" category. For lazy
evaluation to take off, I think it has to be build into the language. I
doubt, though, that much effort will be saved, as a human is normally lazy
enough to not calculate things until absolutely needed.

Peter



From johngrayson at cox.net  Thu Jan  8 18:55:35 2004
From: johngrayson at cox.net (John Grayson)
Date: Thu, 08 Jan 2004 18:55:35 -0500
Subject: Scrolling graphs in a Tk GUI?
In-Reply-To: 
References: 
	
	
Message-ID: 

Try going to manning.com

mksql at yahoo.com wrote:
> On Wed, 07 Jan 2004 18:36:49 -0500, John Grayson  wrote:
> 
> 
>>You'll find an example in Python and Tkinter Programming...
> 
> 
> I can't find any copies to purchase. Every vendor I know is out.
> 



From llothar at web.de  Fri Jan 30 08:55:18 2004
From: llothar at web.de (Lothar Scholz)
Date: 30 Jan 2004 05:55:18 -0800
Subject: easiest transition for a PHP website to move to Python?
References: 
Message-ID: <6ee58e07.0401300555.12c07aa3@posting.google.com>

Python Baby  wrote in message news:...
> I've got a database-driven website that's written entirely in PHP.
> 
> It's all pretty MVC : NOT embedded little calls inside HTML, but
> rather little controller apps in the webroot that merge data with
> HTML templates on the fly.
> 
> But for various reasons (mostly fun) I want to rewrite it in Python.
> 
> There are so many different approaches, though!  Zope, Twisted,
> mod_python, clearsilver, and all the goodies in standard library.
> 
> What would be the SMOOTHEST TRANSITION for a newbie like me to
> rewrite my PHP+MySQL website to Python?
> 
> 

Most important, what can you use ? 
If you are independ, this means have your own dedicated or virtual
server, then i would suggest webware which is the most sophisticated
real python (Zope is not python) solution. Twisted is more a server
framework then a web solution.

If you don't want a app server then use mod_python with one of the ten
web frameworks. Look at www.python-hosting.com for a list. I recommend
Quixote or Sypce.


From http  Wed Jan 21 20:35:01 2004
From: http (Paul Rubin)
Date: 21 Jan 2004 17:35:01 -0800
Subject: Secure Voting software
References: <20040121174434.28446.00000428@mb-m15.aol.com>
Message-ID: <7xvfn4lq9m.fsf@ruckus.brouhaha.com>

piedmontbiz at aol.com (PiedmontBiz) writes:
> What things must I keep in mind when I design a python application to be
> secure?
> 
> Since python is developed using C, can python be free from the
> buffer overrun problems which plague other C programs?

Buffer overruns are just one narrow type of security failure.
Security is really a hard subject and even systems built by experts
often have security holes.  There are various books written on how to
write secure software, and also some HOWTO's.  For systems like voting
machines, there are a lot of non-software issues you have to deal with too.  

The book "Security Engineering" by Ross Anderson is a good place to start
reading if you're interested in the subject.


From engsolnorm at ipns.com  Sun Jan 25 16:38:43 2004
From: engsolnorm at ipns.com (engsol)
Date: Sun, 25 Jan 2004 13:38:43 -0800
Subject: Python and writing a CSV file
References: 
	
	<20040121232549.GA28328@mail.theserver.ath.cx>
	<009501c3e07e$80b62e30$97443d42@homebass1>
	<16399.7079.192926.761791@montanaro.dyndns.org>
	<000c01c3e2b7$a6eabcc0$97443d42@homebass1>
	
	
	
Message-ID: <1qd810dl9rr7i3n9kb6j3jr2f8kos1ck6n@4ax.com>

On Sun, 25 Jan 2004 14:29:41 -0600, Skip Montanaro 
wrote:

>
>    Norm> writer = csv.writer(file('csv_test.CSV', 'w'))
>    ...
>    Norm> So the question is, where does the extra crlf in the csv file come
>    Norm> from? And how do I get rid of it?
>
>Try opening the CSV file in binary mode:
>
>    writer = csv.writer(file('csv_test.CSV', 'wb'))
>
>Skip

Thanks Skip....works like a charm!
Norm



From max at alcyone.com  Thu Jan 22 06:07:31 2004
From: max at alcyone.com (Erik Max Francis)
Date: Thu, 22 Jan 2004 03:07:31 -0800
Subject: utf8 encoding problem
References: 
Message-ID: <400FAEF3.5C305961@alcyone.com>

Wichert Akkerman wrote:

> I'm struggling with what should be a trivial problem but I can't seem
> to
> come up with a proper solution: I am working on a CGI that takes utf-8
> input from a browser. The input is nicely encoded so you get something
> like this:
> 
>   firstname=t%C3%A9s
> 
> where %C3CA9 is a single character in utf-8 encoding. Passing this
> through urllib.unquote does not help:
> 
>   >>> urllib.unquote(u't%C3%A9st')
>   u't%C3%A9st'

Unquote it as a normal string, then convert it to Unicode.

>>> import urllib
>>> x = 't%C3%A9s'
>>> y = urllib.unquote(x)
>>> y
't\xc3\xa9s'
>>> z = unicode(y, 'utf-8')
>>> z
u't\xe9s'

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ I do not promise to consider race or religion in my appointments.
    I promise only that I will not consider them. -- John F. Kennedy


From __peter__ at web.de  Sat Jan 17 06:35:32 2004
From: __peter__ at web.de (Peter Otten)
Date: Sat, 17 Jan 2004 12:35:32 +0100
Subject: help with cr in reg exp...
References: <4009126a$0$22321$626a54ce@news.free.fr>
Message-ID: 

GrelEns wrote:

> hello,
> 
> i had a trouble with re that i didn't understand (this is a silly example
> to show, to parse html i use sgmllib) :
> having this string :
> 
>>>> s = """
> 
> 
> help > """ > > why do i get : > >>>> p = re.compile("(?=|)"); p.findall(s) > [] > > while i was expected this kind of behaviour : > ['form name="test" method="post" action="test.php">\n name="title" size="1." value="test...">\n
\n href="help.php">help'] > > which what i nearly get with : >>>> p = re.compile("(?=|)"); > p.findall(s.replace('\n', '')) > ['
name="title" size="1." value="test...">
help '] > > it looks like \n isn't matched by . (dot)* in my re while i though (and > need) it should, i must be missing something. > > thanks! Try re.compile(yourpattern, re.DOTALL) Peter From afriere at yahoo.co.uk Tue Jan 6 01:35:49 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 5 Jan 2004 22:35:49 -0800 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> <38ec68a6.0312181529.729b654@posting.google.com> <1071900300.434091@yasure> Message-ID: <38ec68a6.0401052235.2c223dca@posting.google.com> "Donn Cave" wrote in message news:<1071900300.434091 at yasure>... > Quoth Jp Calderone : > |The maybe-mutate-maybe-rebind semantics of += lead me to avoid its use > | in most circumstances. > > This tacky feature certainly ought to be considered for the > chopping block in version 3, for exactly that reason. > And go back to 'someVariableName = someVariableName + 1' to do the simple increment? The various 'assignment' operators are popular with good reason imho. Perhaps what should be considered is making sure that operators which appear to be assignment operators actually (and consistently) behave as such. From tdelaney at avaya.com Thu Jan 8 17:51:07 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 9 Jan 2004 09:51:07 +1100 Subject: What psyco is goot at [Was: Rookie Speaks] Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0106375B@au3010avexu1.global.avaya.com> > From: Jacek Generowicz > > Samuel Walters writes: > > > If you'd like to see an example of both the psyco and > profile modules in > > action, let me know and I'll give you some more > understandable code that I > > once wrote to see what types of things psyco is good at optimizing. As an example, check these pystone results (Python 2.3.3, psyco 1.1.1, Windows 2K SP4). Note I've upped the number of passes ... The benchmarks with `from psyco.classes import __metaclass__` are interesting - they're counter to what one would expect from the docs - increased memory usage and decreased performance. Is this a known thing Armin, or is something going screwy on my box? It's happening consistently. Note that psyco.profile() depends heavily on how your code works. I've got one piece of code that performs approx 5 times better with psyco.full(), but actually performs worse with psyco.profile() than without psyco at all! Unfortunately, I can't make it available, but it's a single pass over a file (line by line), matching and extracting data using various regexes, writing lots of other files, then iterating over the other files to produce even more files. The datasets tend to be very large - 500MB+. The main functions only get called one time each (which is probably the killer) and the bulk of the work is done inside while loops in those functions. I suspect that if I moved the contents of the main while loops to their own functions psyco.profile() would do a lot better. No psyco ======== Pystone(1.1) time for 500000 passes = 11.9274 This machine benchmarks at 41920.2 pystones/second psyco.full() ============ Pystone(1.1) time for 500000 passes = 2.36103 This machine benchmarks at 211772 pystones/second 09:37:27.73 memory usage: 97+ kb psyco.profile() =============== Pystone(1.1) time for 500000 passes = 2.41374 This machine benchmarks at 207147 pystones/second 09:39:02.90 memory usage: 50+ kb psyco.full() with `from psyco.classes import __metaclass__` =========================================================== Pystone(1.1) time for 500000 passes = 3.2981 This machine benchmarks at 151602 pystones/second 09:40:40.79 memory usage: 107+ kb psyco.profile() with `from psyco.classes import __metaclass__` ============================================================== Pystone(1.1) time for 500000 passes = 3.5345 This machine benchmarks at 141463 pystones/second 09:42:13.09 memory usage: 80+ kb Tim Delaney From dallasm at aiinet.com Thu Jan 22 12:28:24 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Thu, 22 Jan 2004 12:28:24 -0500 Subject: Identifing current function Message-ID: > -----Original Message----- > From: Brian Donovan [mailto:john at doe.com] > Sent: Wednesday, January 21, 2004 6:22 PM > To: python-list at python.org > Subject: Identifing current function > > > Hi all, > > Is there a way to identify the current function. For example: > > class A: > def B(self): > print current_function_name > > > -- > http://mail.python.org/mailman/listinfo/python-list > import traceback def getFuncName(): # get the stack frame of the caller of this func stack = traceback.extract_stack()[-2] # get the function/method name return stack[2] - Dallas S. Mahrt From skip at pobox.com Sat Jan 10 16:49:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 10 Jan 2004 15:49:22 -0600 Subject: Emacs python mode question In-Reply-To: References: Message-ID: <16384.29538.411489.830261@montanaro.dyndns.org> jb> If I should like to go to line 345: how can I do that? Typing M-x jb> goto-line and then 345 is a bit cumbersome. I defines the key Alt-g jb> to be goto-line, but it does not work. Is M-g not bound to goto-line? You can check for keybindings by typing "C-h w" then entering the name of a command. Skip From CGStartup at earthlink.net Sat Jan 31 19:49:12 2004 From: CGStartup at earthlink.net (Stan Schwartz) Date: 31 Jan 2004 16:49:12 -0800 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: <2da21d6c.0401311649.51a73403@posting.google.com> Josiah Carlson wrote in message news:... > > produced demo output that clearly demonstrates the viability of > > my approaches, which I've been showing to potential licensees and > > investors. This demo output is currently being generated through > > Hey Stan, > > I don't suppose you'd post a link to a bit of demo output? > > - Josiah Hi Josiah, I don't leave the demo output on the web. For me to temporarily post it for you to look at, we'd first have to go through a dance that would involve your signing a non-disclosure. Over the next couple of days, I'll send you some more information privately about what I'm working on, and you can decide whether you want to take it further. BTW, some examples of my Python work with images, although not directly related to the startup are at and . Stan From PeterAbel at gmx.net Wed Jan 7 08:20:50 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 7 Jan 2004 05:20:50 -0800 Subject: Iterating over a binary file References: Message-ID: <21064255.0401070520.7996bac6@posting.google.com> "Derek" wrote in message news:... > Pardon the newbie question, but how can I iterate over blocks of data > from a binary file (i.e., I can't just iterate over lines, because > there may be no end-of-line delimiters at all). Essentially I want to > to this: > > f = file(filename, 'rb') > data = f.read(1024) > while len(data) > 0: > someobj.update(data) > data = f.read(1024) > f.close() > > The above code works, but I don't like making two read() calls. Any > way to avoid it, or a more elegant syntax? Thanks. There's an aproach to mimic the following C-statements in Python: while (result = f.read(1024)) { do_some_thing(result); } >>> def assign(val): ... global result ... result=val ... return val ... >>> f=file('README.txt','rb') >>> while assign(f.read(1024)): ... print len(result) ... 121 >>> f.close() Regards Peter From merkosh at hadiko.de Mon Jan 26 06:01:58 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Mon, 26 Jan 2004 12:01:58 +0100 Subject: use of buffer() function Message-ID: Hi, I was browsing the reference manual to pick up some functions I haven't been using up until now. I tumbled over the buffer() function. I know what it does now, but I'm lacking a possible usage szenario. Can anyone explain the benefits of this function and f.e a usefull example? Thanks in advance Uwe From pythonguy at Hotpop.com Mon Jan 5 04:39:06 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 5 Jan 2004 01:39:06 -0800 Subject: Py2exe?? Error: Nothing to do? References: <86df8ed4.0401031028.6edf2381@posting.google.com> <86df8ed4.0401032126.4031bcc8@posting.google.com> Message-ID: <84fc4588.0401050139.79b48d4e@posting.google.com> Post via a usenet news program. Examples are Mozilla , Netscape. Dedicated news readers also exist. If you prefer online posting, try http://www.dbforums.com which updates its newsgroup databases faster than google. But you may not find all news items in this forum that you find here. -Anand nick889 at mail.com (Nick) wrote in message news:<86df8ed4.0401032126.4031bcc8 at posting.google.com>... > Yes, i did manage to get it to work, thank you. > > Also, i am kinda new to the whole newgroups thing. I am currently > posting from google.com and they say it takes several hours before the > groups are updated. Is there anyway to make it so that the newgroups > are like update instantly. From rha207 at worldnet.att.net Tue Jan 20 10:18:20 2004 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Tue, 20 Jan 2004 10:18:20 -0500 Subject: shelve error Message-ID: <000501c3df68$a7ae0ba0$0b394b0c@computer> I have Python 2.2 and when I try this program I get a popup with this message. Can you see what I'm doing wrong? I just want to take some info I have in a file and (shelve it?). PYTHONW caused an invalid page fault in module MSVCRT.DLL at 0167:78012473. Registers: EAX=00000002 CS=0167 EIP=78012473 EFLGS=00010246 EBX=00750880 SS=016f ESP=0062cdc4 EBP=0062cdcc ECX=ffff01f0 DS=016f ESI=00aef68e FS=0f77 EDX=00000000 ES=016f EDI=00aef70e GS=0000 Bytes at CS:EIP: 8a 06 88 07 8a 46 01 c1 e9 02 88 47 01 83 c6 02 Stack dump: 0000ff8e 1e03b1d0 0062ce00 00f1812c 00aef70e 00aef68e ffff01f2 00ada1c0 00aef68e 00add470 00aef70e 00adf700 00000008 00000080 1e030200 0062ce48 This program ass performed an illegal operation and will be shut do. ### Here's the program ######### import cPickle, shelve hold = [] data = open('inout.txt', 'r') while 1: temp = data.readline() if temp == '': break temp = temp[:-1] temp = temp.split('\t') hold.append(temp) data.close() data = shelve.open('inventory') for num in hold: a = num[0] b = num[1] c = num[2] d = num[3] e = num[4] f = num[5] g = num[6] h = num[7] i = num[8] j = num[9] k = num[10] l = num[11] m = num[12] n = num[13] data[b] = [a, c, d, e, f, g, h, i, j, k, l, m, n] data.sync() data.close Ron A From eric.brunel at N0SP4M.com Thu Jan 15 03:50:56 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Thu, 15 Jan 2004 09:50:56 +0100 Subject: CheckButton -- modify "check state" References: <104c369a.0401141314.5c64a727@posting.google.com> Message-ID: Askari wrote: > Hi, > How do for do a "select()" on a CheckButton in a menu (make with > add_checkbutton(....) )? > I can modify title, state, etc but not the "check state". :-( Assuming you're using Tkinter, the way to do it is to use the variable option when you create the menu, and them modify the variable. Here is an example code: --menu.py------------------------ from Tkinter import * root = Tk() ## Create the menu bar menuBar = Menu(root) root.configure(menu=menuBar) ## Create the menu menu = Menu(menuBar) menuBar.add_cascade(label='Menu', menu=menu) ## Create the variable for the check button myCheckVar = BooleanVar() ## Functions to check/uncheck/print the check state def check(*whatever): myCheckVar.set(1) def uncheck(*whatever): myCheckVar.set(0) def print_option(*whatever): print myCheckVar.get() ## Entries in menu menu.add_checkbutton(label='Option', variable=myCheckVar) menu.add_command(label='Check', command=check) menu.add_command(label='Uncheck', command=uncheck) menu.add_command(label='Print', command=print_option) root.mainloop() --------------------------------- If you do not specify a command for the add_checkbutton, the default action is to toggle the check state. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From harry.g.george at boeing.com Thu Jan 8 03:11:27 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 8 Jan 2004 08:11:27 GMT Subject: creating a daemon? References: <3ffd355c.0@news1.mweb.co.za> Message-ID: bmgx writes: > This is what I am trying to find out, instruction on how to create a > simple daemon on unix systems(Linux), can't find any info on usual > sources.. > 1. The idea is to fork, clean up all the inheritable stuff like files and environment vars, and then fork again. The resulting process can then be left running to do the daemon work. I recall there is a daemon.py module somewhere which does this all for you. Here are the basics: def main(args): #---first fork--- try: pid = os.fork() if pid > 0: #---first parent--- sys.exit(0) except OSError,e: print >>sys.stderr, "fork #1 failed %d (%s)" % (e.errno,e.strerror) sys.exit(1) #---make a clean process--- os.chdir('/') os.setsid() os.umask(000) child_in =open('/dev/null','r') child_out=open('/dev/null','w') os.dup2(child_in.fileno(), sys.stdin.fileno()) os.dup2(child_out.fileno(), sys.stdout.fileno()) os.dup2(child_out.fileno(), sys.stderr.fileno()) #---second fork--- try: pid = os.fork() if pid > 0: #---second parent--- sys.exit(0) except OSError,e: print >>sys.stderr, "fork #2 failed %d (%s)" % (e.errno,e.strerror) sys.exit(1) #---in clean child--- x=MyApp() x.run() 2. To talk to that daemon, you can use a) files at known locations, b) pipes (see popen), c) sockets with ad hoc protocols (see asyncchat and SocketServer), d) predefined protocols (see Internet Protocols and Services). The various "server" modules have the setup code from "1" above builtin, so you can ignore that level of detail. ["see" references can be found in the normal python documentation's Library Reference"]. 3. Once you have a working daemon, you need a way to start and stop it. You could manually start it each time you need it and then "kill" it when done. More commonly you would do it (in Linux and UNIX) via a boot-time initialization script (typically found in /etc/init.d). Each *NIX has its own flavor of setting these up, so you need to look at existing services and maybe copy-and-edit a working script. 4. If security is an issue (it probably is), you may also want to hide the service behind xinetd. That is a whole setup story in its own right. And if security is really troublesome, you may need to assure the python interpreter itself is safe. That kind of consideration is way out of my league. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From sross at connectmail.carleton.ca Sat Jan 3 16:31:17 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 3 Jan 2004 16:31:17 -0500 Subject: Integer math question References: <3987e01c.0401030832.114c6f2a@posting.google.com> <11EJb.20461$Vl6.3782481@news20.bellglobal.com> <5sFJb.20923$Vl6.3818930@news20.bellglobal.com> Message-ID: "Sean Ross" wrote in message news:5sFJb.20923$Vl6.3818930 at news20.bellglobal.com... > "Rainer Deyke" wrote in message > news:kTEJb.724242$HS4.5376202 at attbi_s01... > >>> a = 5 > >>> b = -10 > >>> q,r = divmod(a,b) > >>> q > -1 > >>> r > -5 > >>> > > Here, the division algorithm does not apply (b is a negative integer). > Perhaps there's some other theorem for this case? > b I think you're supposed to do something like this a = bq + r, 0<= r < |b| 5 = (-10)q + r -5 = -(-10)q - r -5 = 10q - r But, then, q would be 0 and r would be 5. From __peter__ at web.de Mon Jan 19 04:25:18 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jan 2004 10:25:18 +0100 Subject: "\b" behaviour at end of string, was RE: Simple (?) Regular Expression Question References: Message-ID: Tim Peters wrote: > [Steve Zatz] >> Is '@' a special character in regular expressions? > > Nope. > >> I am asking because I don't understand the following: >> >> >>> import re >> >>> s = ' @' >> >>> re.sub(r'\b@','*',s) >> ' @' >> >>> s = ' a' >> >>> re.sub(r'\ba','*',s) >> ' *' > > \b matches a "word boundary", meaning it has to have a word character on > one side (something that matches \w), and a non-word character on the > other > (something that matches \W), regardless of order. ' @' contains two > non-word characters (' ' and '@'), so \b doesn't match anything in it. ' > a' contains a non-word character (' ') followed by a word character ('a'), > so \b matches (an empty string) betwen those two characters. Playing around with it a bit, I noticed that finditer() runs forever for the "\b" regular expression: Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> r = re.compile(r"\b") >>> [m.start() for (i, m) in zip(range(10), r.finditer("alpha"))] [0, 5, 5, 5, 5, 5, 5, 5, 5, 5] >>> Bug or feature? Peter From danb_83 at yahoo.com Mon Jan 26 07:06:26 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Jan 2004 04:06:26 -0800 Subject: delta time = time stop - time start References: Message-ID: engsol wrote in message news:... > I'm using Python to parse a bunch of s/w test files and make csv files for later report generation by MS ACCESS....(my boss > loves the quick turn-around compared to C). Each log file may contain one or more 'sessions', and each session may contain > one or more 'nodes'. > > Each session in the log has an ASCII start and stop time, as does each node. > I have the basic parse part done for parameters, errors, etc., but noticed my routine for determining how long each > session/node took (delta time) was a bit repetitive, so decided to make a 'stand-alone' routine to handle this. > > The time format from the log is in the format of: > hh:mm:ss > and is a string with leading zeros where appropiate. Date is never a factor. The longest "delta" is maybe 5 hours. > > The routine I came up with is below, but seems a bit clunky. > Is there a better way of doing this? I think it relies too much on integers rounding off in the proper direction, a la > d_time_hr = d_time / 3600 below. It also relies on -Qold. Please use the // operator for integer division. Or you're going to regret it when you upgrade to Python 3.0. > Also, this will have to transition to Linux, if that makes a difference. In your code, it makes no difference. I'm using a Linux box right now. > START CODE: > > import string Unless you have a very old version of Python, this is no longer needed; string.atoi has been officially replaced with the "int" constructor. > def deltatime(start, stop): > > t_start = (string.atoi(start[0:2]) * 3600) + (string.atoi(start[3:5]) * 60) + string.atoi(start[6:8]) > t_stop = (string.atoi(stop [0:2]) * 3600) + (string.atoi(stop [3:5]) * 60) + string.atoi(stop [6:8]) Rather than count character positions, take advantage of the fact that the strings are colon-delimited. def toSeconds(timeString): hour, min, sec = map(int, timeString.split(':')) return (hour * 60 + min) * 60 + sec t_start = toSeconds(start) t_stop = toSeconds(stop) > if t_start < t_stop: > d_time = t_stop - t_start > else: > d_time = (86400 - t_start) + t_stop You can eliminate the if-else test by taking advantage of Python's % operator d_time = (t_stop - t_start) % 86400 > d_time_hr = d_time / 3600 > d_time_min = (d_time - d_time_hr * 3600) / 60 > d_time_sec = (d_time - d_time_hr * 3600) - (d_time_min * 60) Rather than calculate remainders the hard way, use the % operator. Or since you need both the quotient and remainder, use the divmod function. d_time_min, d_time_sec = divmod(d_time, 60) d_time_hr, d_time_min = divmod(d_time_min, 60) > return str(d_time_hr) + 'hr ' + str(d_time_min) + 'min ' + str(d_time_sec) + 'sec' A more concise way of writing this is return '%dhr %dmin %ssec' % (d_time_hr, d_time_min, d_time_sec) The complete rewritten function is def deltatime(start, stop): def toSeconds(timeString): hour, min, sec = map(int, timeString.split(':')) return (hour * 60 + min) * 60 + sec t_start = toSeconds(start) t_stop = toSeconds(stop) d_time = (t_stop - t_start) % 86400 d_time_min, d_time_sec = divmod(d_time, 60) d_time_hr, d_time_min = divmod(d_time_min, 60) return '%dhr %dmin %ssec' % (d_time_hr, d_time_min, d_time_sec) which is still too verbose for my tastes; I would rewrite it as: def deltatime(start, stop): def toSeconds(timeString): hour, min, sec = map(int, timeString.split(':')) return (hour * 60 + min) * 60 + sec d_time_min, d_time_sec = divmod(toSeconds(stop) - toSeconds(start), 60) d_time_hr, d_time_min = divmod(d_time_min, 60) return '%dhr %dmin %ssec' % (d_time_hr % 24, d_time_min, d_time_sec) From paul at prescod.net Sat Jan 31 20:23:22 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 31 Jan 2004 17:23:22 -0800 Subject: Python vs. Io In-Reply-To: <711c7390.0401311220.763be80a@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> Message-ID: <401C550A.7080106@prescod.net> I've always presumed that if I wanted an ultra-pure OO language I would use Smalltalk. Obviously IO's big difference is prototype rather than class-based inheritance. But that's a difference, not (necessarily) a benefit. Could you please describe what would attract one to IO over Smalltalk? Paul Prescod From alf at calvin.fayauffre.org Mon Jan 5 09:23:50 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Mon, 5 Jan 2004 14:23:50 +0000 (UTC) Subject: UML tools for python References: <13dc97b8.0312301543.39192aa2@posting.google.com> Message-ID: Le 30-12-2003, Andy Bulka a ?crit?: > Whilst almost responding to the 'dream project' thread I decided that > this post warranted its own thread. What about a solid UML tool with > round trip functionality for the Python Community? > > Some attempts at reverse engineering python are > PyReverse http://www.logilab.org/projects/pyreverse/ > PyReverse is hard to use, misses a lot of > basic information and then what do you do with the XML files? - who > will read these? I have to edit them manually to import them into > Enterprise Architect Well, I think the first thing you could do if you have specific problems with any of the tools you mention is getting in touch with the developers, and try to talk with them. Since we've never heard of your problems with pyreverse, there's hardly any chance that we will do anything for you. Logilab's python-project mailing list is waiting for your posts (http://lists.logilab.org/mailman/listinfo/python-projects to subscribe) > Do we think that having a solid UML tool with full round trip > facilities plus gorgeous GUI - build specifically for Python is a > worthy goal? Is anybody going to bother to build such a tool for > free? Now, let's be reasonable. If this what you want (what you really really want), since this is the OS world, your options are: * code it yourself and share it with others * code it with some other people, and share it with others * commission (i.e. pay) someone else to code it for you, and share it with others * wait until someone codes it and shares it with you. But just saying "all existing tools suck, we (i.e., I) need someone to build some cool free tool with " won't get you anywhere. Happy new year -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From exarkun at intarweb.us Sat Jan 24 12:06:42 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 24 Jan 2004 12:06:42 -0500 Subject: sort profile stats by percall In-Reply-To: References: Message-ID: <20040124170642.GB7002@intarweb.us> On Sat, Jan 24, 2004 at 03:23:04AM +0000, Lee Harr wrote: > > Is there an easy way to sort the stats returned from > the hotshot.Profile() by the percall column? > statsObj.sort_stats('calls') Jp > -- > http://mail.python.org/mailman/listinfo/python-list > From donn at drizzle.com Tue Jan 13 02:18:52 2004 From: donn at drizzle.com (Donn Cave) Date: Tue, 13 Jan 2004 07:18:52 -0000 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <7xhdz08xgy.fsf@ruckus.brouhaha.com> Message-ID: <1073978329.887910@yasure> Quoth Paul Rubin : ... | The one attempt I know of to write a substantial Python application | competitive with similar applications written in C was the Grail web | browser, and AFAIK that was a complete failure. However, for small to | medium sized projects which don't have to run fast, Python is great. Well, egads. Grail is a Python/Tcl/Tk hybrid, and I think one of the problems with that it complicates the optimization phase. Plus the official objective never did seem to be to compete with similar applications, rather they would say they were primarily writing a document viewing tool for CRNI and it was just a coincidence that it happened to be a nice web browser. Was a bit slow, but did have some nice touches. But at any rate, I thought we were talking about huge projects involving many programmers, and I don't think Grail was of that sort at all. I don't know what kind of programmer resources were allocated to it, but I bet it was actually a smashing success in those terms. As for its size, I'd have to look, I have the code around somewhere, but I'd guess it was smaller than Mailman or Zope. Small enough that one programmer could become pretty thoroughly acquainted with the whole thing. Donn Cave, donn at drizzle.com From usenet at -OBFUSCATION-joefrancia.com Mon Jan 12 10:54:26 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Mon, 12 Jan 2004 15:54:26 GMT Subject: [Webware] FormKit - dynamic fields problem In-Reply-To: <5lb5001v1j64v6kdbteaas235d5sj6lan2@4ax.com> References: <5lb5001v1j64v6kdbteaas235d5sj6lan2@4ax.com> Message-ID: JZ wrote: > I use Webware and FormKit. I have a problem with dynamic added field > to the form. The following code creates one input field and two submit > buttons. I would like to add more (up to 4) input fields after > pressing "more" button. It does not work and I have no idea how to > solve it. > You also may want to post this question to the WebWare list, if you haven't already: http://lists.sourceforge.net/lists/listinfo/webware-discuss If you don't want to join yet another mailing lists, you can access the WebWare list in your newsreader by pointing it to news.gmane.org and subscribing to gmane.comp.python.webware. From sandskyfly at hotmail.com Tue Jan 20 08:38:51 2004 From: sandskyfly at hotmail.com (Sandy Norton) Date: 20 Jan 2004 05:38:51 -0800 Subject: personal document mgmt system idea Message-ID: Hi folks, I have been mulling over an idea for a very simple python-based personal document management system. The source of this possible solution is the following typical problem: I accumulate a lot of files (documents, archives, pdfs, images, etc.) on a daily basis and storing them in a hierarchical file system is simple but unsatisfactory: - deeply nested hierarchies are a pain to navigate and to reorganize - different file systems have inconsistent and weak schemes for storing metadata e.g. compare variety of incompatible schemes in windows alone (office docs vs. pdfs etc.) . I would like a personal document management system that: - is of adequate and usable performance - can accomodate data files of up to 50MB - is simple and easy to use - promotes maximum programmibility - allows for the selective replication (or backup) of data over a network - allows for multiple (custom) classification schemes - is portable across operating systems The system should promote the following simple pattern: receive file -> drop it into 'special' folder after an arbitrary period of doing the above n times -> run application for each file in folder: if automatic metadata extraction is possible: scan file for metadata and populate fields accordingly fill in missing metadata else: enter metadata store file every now and then: run replicator function of application -> will backup data over a network # this will make specified files available to co-workers # accessing a much larger web-based non-personal version of the # docmanagement system. My initial prototyping efforts involved creating a single test table in mysql (later to include fields for dublin-core metadata elements) and a BLOB field for the data itself. My present dev platform is windows XP pro, mysql 4.1.1-alpha, MySQL-python connector v.0.9.2 and python 2.3.3 . However, I will be testing the same app on Mac OS X and Linux Mandrake 9.2 as well. The first problem I've run into is that mysql or the MySQL connector crashes when the size of one BLOB reaches a certain point: in this case an .avi file of 7.2 mb . Here's the code: import sys, time, os, zlib import MySQLdb, _mysql def initDB(db='test'): connection = MySQLdb.Connect("localhost", "sa") cursor = connection.cursor() cursor.execute("use %s;" % db) return (connection, cursor) def close(connection, cursor): connection.close() cursor.close() def drop_table(cursor): try: cursor.execute("drop table tstable") except: pass def create_table(cursor): cursor.execute('''create table tstable ( id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), data BLOB );''') def process(data): data = zlib.compress(data, 9) return _mysql.escape_string(data) def populate_table(cursor): files = [(f, os.path.join('testdocs', f)) for f in os.listdir('testdocs')] for filename, filepath in files: t1 = time.time() data = open(filepath, 'rb').read() data = process(data) # IMPORTANT: you have to quote the binary txt even after escaping it. cursor.execute('''insert into tstable (id, name, data) values (NULL, '%s', '%s')''' % (filename, data)) print time.time() - t1, 'seconds for ', filepath def main (): connection, cursor = initDB() # doit drop_table(cursor) create_table(cursor) populate_table(cursor) close(connection, cursor) if __name__ == "__main__": t1 = time.time() main () print '=> it took total ', time.time() - t1, 'seconds to complete' >pythonw -u "test_blob.py" 0.155999898911 seconds for testdocs\business plan.doc 0.0160000324249 seconds for testdocs\concept2businessprocess.pdf 0.0160000324249 seconds for testdocs\diagram.vsd 0.0149998664856 seconds for testdocs\logo.jpg Traceback (most recent call last): File "test_blob.py", line 59, in ? main () File "test_blob.py", line 53, in main populate_table(cursor) File "test_blob.py", line 44, in populate_table cursor.execute('''insert into tstable (id, name, data) values (NULL, '%s', '%s')''' % (filename, data)) File "C:\Engines\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "C:\Engines\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "C:\Engines\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') >Exit code: 1 My Questions are: - Is my test code at fault? - Is this the wrong approach to begin with: i.e. is it a bad idea to store the data itself in the database? - Am I using the wrong database? (or is the connector just buggy?) Thanks to all. best regards, Sandy Norton From gerrit at nl.linux.org Tue Jan 20 06:52:25 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 20 Jan 2004 12:52:25 +0100 Subject: SystemError while execing bad code Message-ID: <20040120115225.GA3340@nl.linux.org> Hi, I found a cool way to trigger a SystemError: >>> exec CodeType(0,0,0,0,"",(),(),(),"","",0,"") XXX lineno: 0, opcode: 0 Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/", line 0, in File "/usr/lib/python2.2/site-packages/", line 0, in SystemError: unknown opcode The documentation says: You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception's associated value) and if possible the source of the program that triggered the error. Although it probably shouldn't be taken literally in this case... ...or should it :-)? Hmm, and this actually *hangs*: >>> exec CodeType(0,0,0,0,"",(),(),(),"","",2**31-1,"") XXX lineno: 2147483647, opcode: 0 Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/", line 2147483647, in ... But I guess this is a case of "so don't do it" :-)? yours, Gerrit. -- 263. If he kill the cattle or sheep that were given to him, he shall compensate the owner with cattle for cattle and sheep for sheep. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From ben at transversal.com Wed Jan 7 09:09:15 2004 From: ben at transversal.com (Ben) Date: Wed, 07 Jan 2004 14:09:15 +0000 Subject: PEP 310 suggestions References: <3ffbd106$0$15344$afc38c87@news.easynet.co.uk> Message-ID: <3ffc1304$0$397$afc38c87@news.easynet.co.uk> Michael Hudson wrote: > Ben writes: > > Hmm, that's an idea I hadn't had. Limiting the "on exit" code to just > one expression and the disadvantage you mention mean I'm not sure I > like it that much, though... > >> Any comments? The main reason I like these methods is that they are >> both more explicit than the PEP, and don't require the addition of >> any more special functions. However I can see the disadantages as >> well! > > Well, thanks for your comments, but I'm not sure I want to incorporate > your ideas... I'll add the "onexit" idea as an alternative. > > Cheers, > mwh > Cheers for the feedback. I suppose I just wanted to make sure all the options had been considered ( which you already appear to have done in great detail ) as this is something which I consider really important for the language. That and I have an irrational dislike of millions of special methods :) Do you have a link to the big discussion you mention? I read the one in the PEP but thats only a couple of messages long. ( I may be going blind though!) Ben --- From bart_nessux at hotmail.com Thu Jan 8 22:36:04 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 08 Jan 2004 22:36:04 -0500 Subject: convert a list to a string References: <3FFE1E29.20801@hotmail.com> <7xwu81dcr7.fsf@ruckus.brouhaha.com> Message-ID: <3FFE21A4.7040208@hotmail.com> Paul Rubin wrote: > Bart Nessux writes: > >>number = random.sample(range(count), 1) >> >>This makes 'number' into a one entry list (I don't know why as 'count' >>is an integer). Is there an easy way to convert 'number' back to an >>int? > > > number = number[0] > > But why are you using random.sample for that? And making a list of > size count, just to throw it away? It sounds like you just want a > random number between zero and count. Do that with: > > number = random.randint(count) Forgot to say thanks! the number[0] thing is great! From ELabuschagne at gmsonline.co.za Wed Jan 21 08:24:57 2004 From: ELabuschagne at gmsonline.co.za (Etienne Labuschagne) Date: Wed, 21 Jan 2004 15:24:57 +0200 Subject: Interfacing with Voice modem Message-ID: Hi all, A callcenter-like app that we are writing in Python will need recording functionality for voice conversations. I am thinking of doing this through a voice modem. Any suggestions on how to interface with a voice modem from Python? Thanks Etienne From tonym1972 at club-internet.fr Fri Jan 9 12:45:12 2004 From: tonym1972 at club-internet.fr (chitanom chantavong) Date: Fri, 9 Jan 2004 18:45:12 +0100 Subject: urllib - changing the user agent References: <8089854e.0401090509.3dd74859@posting.google.com> Message-ID: <3ffee8ad$0$6974$7a628cd7@news.club-internet.fr> "Fuzzyman" wrote in message news:8089854e.0401090509.3dd74859 at posting.google.com... > I'm writing a function that will query the comp.lang.python newsgroup > via google groups....... (I haven't got nntp access from work..) > > I'm using urllib (for the first time)..... and google don't seem very > keen to let me search the group from within a program - the returned > pages all tell me 'you're not allowed to do that' :-) > > I read in the urllib manual pages : > > class URLopener( [proxies[, **x509]]) > > Base class for opening and reading URLs. Unless you need to support > opening objects using schemes other than http:, ftp:, gopher: or > file:, you probably want to use FancyURLopener. > By default, the URLopener class sends a User-Agent: header of > "urllib/VVV", where VVV is the urllib version number. Applications can > define their own User-Agent: header by subclassing URLopener or > FancyURLopener and setting the instance attribute version to an > appropriate string value before the open() method is called. > > > Could anyone tell me how to subclass this correctly with the version > attribute set and what text string I should use to mimic Internet > explorer and/or mozilla ? > > > Ta > > Fuzzy I normally use something like this for crawling webpages. import urllib urllib.URLopener.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; T312461)' urllib.FancyURLopener.prompt_user_passwd = lambda self, host, realm: (None, None) Anthony McDonald From jarausch at skynet.be Tue Jan 27 12:53:09 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 27 Jan 2004 18:53:09 +0100 Subject: raw_input - why doesn't prompt go to stderr In-Reply-To: References: Message-ID: <4016A585.6050109@skynet.be> Terry Reedy wrote: > "Helmut Jarausch" wrote in message > news:bv2smu$leh$1 at nets3.rz.RWTH-Aachen.DE... > > >>when using an interactive Python script, I'd like the prompt given by >>raw_input to go to stderr since stdout is redirected to a file. > > > This is not the usual behavior, so I presume that you or the code author > (if not the same) have done some non-standard redirection. Ofcourse I did the redirection of stdout. And here is an example which I give in my C++ courses when I tell the students to use 'cerr' for outputting a prompt (in Python) FileName= raw_input('please enter the name of data file') input= open(FileName,'r') ... print tons of output And this is very handy. While testing I don't redirect stdout and so can see the output immediately. Then I just redirect stdout for a 'production' run. Tell me any advantage in raw_input's prompt is going to stdout instead of stderr? Thanks for your comments, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From http Fri Jan 16 21:38:13 2004 From: http (Paul Rubin) Date: 16 Jan 2004 18:38:13 -0800 Subject: YA string interpolation and printing idea Message-ID: <7x3caf5mga.fsf_-_@ruckus.brouhaha.com> How about adding a string interpolation method and a some print methods to strings. 'hello world'.print([fd]) => same as "print 'hello world'". With optional fd arg, print to file object 'hello world'.write([fd]) => same as "sys.stdout.write('hello world')" i.e. print with no trailing newline 'hello $name'.interp() => like "'hello %s'%name" 'hello $name'.fprint([fd]) => like ('hello %s'%name).print([fd]) 'hello $name'.fwrite([fd]) => like ('hello %s'%name).write([fd]) From francisgavila at yahoo.com Tue Jan 13 17:42:13 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 13 Jan 2004 17:42:13 -0500 Subject: C++ bad-mouthing (was: Why learn Python ??) References: <40029dad$0$28706$a729d347@news.telepac.pt> <7xisjh1e3i.fsf@ruckus.brouhaha.com> <10064loqc7sd7e3@corp.supernews.com> <7xeku496wx.fsf@ruckus.brouhaha.com> <40041576.D070723E@engcorp.com> <87oet7it2n.fsf@pobox.com> Message-ID: <1008t48id1hmk43@corp.supernews.com> John J. Lee wrote in message <87oet7it2n.fsf at pobox.com>... >Forgot to add: what happened to all those Python interface proposals? > >At least one was PEPed, wasn't it? > >I suppose it's waiting for Guido-bandwidth. I think the general opinion of Guido was, yes, we need something like this, but it's important enough to require his full and undivided attention, and this must be given later, when a major revision comes up. I also think he wasn't fully satisfied with all the options. I forget where I read this. Maybe the pep-parade, or maybe one of the peps themselves? -- Francis Avila From steve at ninereeds.fsnet.co.uk Fri Jan 30 11:03:55 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 30 Jan 2004 16:03:55 +0000 Subject: PEP 327: Decimal Data Type References: Message-ID: <6ltk10h30riel0lghd18t5unjco2g26spi@4ax.com> On Fri, 30 Jan 2004 09:49:05 -0300, "Batista, Facundo" wrote: >I'll apreciate any feedback. Thank you all in advance. My concern is that many people will use a decimal type just because it is there, without any consideration of whether they actually need it. 95% of the time or more, all you need to do to represent money is to use an integer and select appropriate units (pence rather than pounds, cents rather than dollars, etc) so that the decimal point is just a presentation issue when the value is printed/displayed but is never needed in the internal representation. That said, there are cases where a decimal type would be genuinely useful. Given that, my only comment on the PEP is that a decimal literal might be a good idea - identical to float literals but with a 'D' appended, for instance. I wouldn't mention it now, seeing it as an issue for after the library itself has matured and been proven, except for the issue of implicit conversions. Having a decimal literal would add another class of errors with implicit conversions - it would be very easy to forget the 'D' on the end of a literal, and to get an imprecise float implicitly converted to decimal rather than the precise decimal literal that was intended. I don't know what the solution should be, but I do think it needs to be considered. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Tue Jan 6 07:55:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Jan 2004 07:55:16 -0500 Subject: OT: Vertical Tab was Re: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> <3FF9E883.BC8AB864@engcorp.com> <3FF9F0D0.3AA099CD@alcyone.com> Message-ID: <3FFAB034.E8513A36@engcorp.com> Erik Max Francis wrote: > > Samuel Walters wrote: > > > What exactly *is* a vertical tab? I don't think I've ever seen it on > > a > > keyboard or used in the wild. I think I may have seen it on the > > keybindings for a mainframe terminal I once used, but I didn't really > > dig > > too deep because, as far as operating the mainframe was concerned, I > > was a > > well trained monkey who could check and restart failed jobs. > > It's a whitespace control character, whose precise meaning is, as far as > I know, left to the implementation. I have or once had an absolutely excellent book on serial communications programming in C (probably called that, too) which made an excellent case for replacing all the myriad ways in which we represent end-of-line with a simple \v, since it is used effectively for no other purpose at this point. The idea will probably get as far as the Dvorak keyboard has, unfortunately... -Peter From try_vanevery_at_mycompanyname at yahoo.com Wed Jan 14 16:46:36 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 14 Jan 2004 13:46:36 -0800 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> <40051cb3$1@news.012.net.il> Message-ID: "G.I.L" wrote in message news:40051cb3$1 at news.012.net.il... > Brandon J. Van Every wrote: > > "G.I.L" wrote in message > > news:40047290$1 at news.012.net.il... > >> > >> Brandon, why the fuck on Earth couldn't you spend that exact amount > >> of time doing what you did BEFORE posting and arguing with the > >> entire newsgroup? > > > > Hey GIL, you're here wasting time of your own free will. Don't look > > to me to be the purveyor of your quality discourse. To me this is > > just hours between implementing stuff. > > Partially implementing stuff. > > > Although actually, there's another agenda. I know *someone* out > > there is going through the same shit I have / I am. The posts are > > for their benefit, to give them warnings / inklings. > > Are you applying to be a martyr, St. Brandon? I'm very much alive, thank you. > >> It > >> was an unbelievable waste of time, since you've managed to convice > >> (maybe still wrongfully) all the people that you are completely > >> clueless. > > > > Why, because I turned around a project in 3 weeks while having the > > flu half the time? > > No, because you dumped the project because it was boring. You're a fool then. What's your school of advice, keep working on things no matter how much of a boring waste of time they become? > This may kill any credit you may have had with people. Getting "credit" was a goal? News to me. > > You try to do something big, you put your money on the line to do it, > > you fail or don't entirely succeed, you give postmortem, you lay all > > your cards out for others to examine... *then* I will worry about > > your opinion. > > You state that you will follow only those who fail after putting their own > money on projects? Read it again, and put up or shut up. If you don't have the balls to allow postmortems of your *own* projects, don't expect me to care about your flak. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA When no one else sells courage, supply and demand take hold. From llothar at web.de Mon Jan 12 08:42:22 2004 From: llothar at web.de (Lothar Scholz) Date: 12 Jan 2004 05:42:22 -0800 Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> Message-ID: <6ee58e07.0401120542.5d79090d@posting.google.com> Samuel Walters wrote in message news:... > I know very little about numeric processing, and even less about Fortran. > It's true that my background is in mathematics, but in *pure* mathematics > where pointer-based languages tend to be helpful, not hurtful. Okay seems that you don't know a lot about compiler writing. A C compiler only knows a little bit about the context so it must always assume that a data inside a member can be referenced from another place via an alias pointer. Fortran does not have this problem so a lot of optimizations can be done and values can be hold in registers for a much longer time, resulting in much greater speed. Remember that on supercomputers a 25% spped enhancement (which a good fortran compiler is faster then C) can mean a few million dollars of saved hardware costs. The coding time is not importing compared to the running time. So real hard numerics are always done in Fortran. GNU Fortran is a stupid project because it translates the Fortran code to C. Python for hardcore numerics, even with PyNumerics, is simply a very bad solution. From kkto at csis.hku.hk Sun Jan 4 21:14:10 2004 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 05 Jan 2004 10:14:10 +0800 Subject: Why does this fail? References: Message-ID: <7i8ykn3zwt.fsf@enark.csis.hku.hk> >>>>> "Dave" == Dave Murray writes: Dave> New to Python question, why does this fail? Thanks, Dave Dave> f = urllib.open(URL) urllib does not have an open function. Instead, it has a constructor called URLopener, which creates an object with such a method. So instead, you have to say opener = urllib.URLopener() f = opener(URL) Regards, Isaac. From __peter__ at web.de Fri Jan 9 11:42:39 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Jan 2004 17:42:39 +0100 Subject: __init__, __slot__ and **keywordargs References: Message-ID: Zunbeltz Izaola wrote: > Peter Otten <__peter__ at web.de> writes: > >> >> You misspelt: in fact it's __slots__, and it will work as expected. As >> far > > Hurg!!! :-( This kine of mistakes will become me crazy. > >> as I know slots are an optimization technique that is useful to save some >> space, when you have many (that would be millions) of small objects. It's >> not meant as a safety belt for the programmer. > > But, I think it can be considered "a safety belt for the programmer" , > When you do It can, but I think it's contrary to the Python style, which relies heavily on unit tests. If you to want ensure a limited set of attributes, then why would you allow both an integer and a Date for the Birthday - if you follow this road, you end up programming in Java, because it's designed for that kind of safety. Most Pythonistas think that you are spending too much time on errors that comprise only a small fraction of what goes wrong in real programs. > instance.attribute > > you get and AttributeError if attribute is not in the __slots__ > (It would help to avoid misspells, like i've done!!) Note that you already get an AttributeError for read access. Write access aka rebinding is used only in a fraction of all accesses and prohibiting it for arbitrary attribute names IMHO significantly impairs the usefulness of Python's object model. >> In your case, I wouldn't use it, but rather not initialize the attributes >> not given as constructor - __init__() - arguments. Also, I would consider >> the ability to provide additional arguments, say "Nickname", not a >> bug but > > What do you mean with additional arguments? (My code was not the full > code) Let's assume you have mandatory arguments Firstname and Surname but want to allow for other information. A constructor reflecting that would then be def __init__(self, Firstname, Surname, **OptionalAttributes) It's up to the clientcode to decide what these optional attributes may be, so they could vary in different contexts. This in turn makes your class useful for a broader range of usecases. Peter From tjreedy at udel.edu Thu Jan 15 19:00:28 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Jan 2004 19:00:28 -0500 Subject: python & mathematical methods of picking numbers at random References: Message-ID: <59idnYa3_eQMtJrd4p2dnA@comcast.com> "Bart Nessux" wrote in message news:bu6rvn$njg$1 at solaris.cc.vt.edu... > Jeff Epler wrote: > > But why are *you* using > > random.sample(range(len(x)), 25) > > instead of > > random.sample(x, 25) > > ? > Because it works and it's fast and len(count) changes every drawing. I think you missed Jeff's point, which is that you are repeating part of the work that sample tries to do for you. From the Lib Ref: " sample(sequence, k): Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. New in version 2.3. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). " When you get the sample from range(n), you have to use them as indexes into x to get the actual list of names. But the indexing and extraction is what sample would do if you gave it x instead of range(x)! Terry J. Reedy From paul at prescod.net Tue Jan 20 21:42:58 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 20 Jan 2004 18:42:58 -0800 Subject: Pyrex without Python (was Re: calling Pyrex results from C) In-Reply-To: <20040121014129.GB27424@unpythonic.net> References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> <20040121014129.GB27424@unpythonic.net> Message-ID: <400DE732.3040302@prescod.net> Jeff Epler wrote: > > 1. my {} keys are broken, so it's perfect to not use C and to use an > environment where I can't use dicts either > 2. the people programming small machines are all out do to crazy stuff, > and so programming mine in "Python" (pyrex) would be along those lines. ;) If we were to think of Pyrex as its own language unrelated to Python we'd have to say it is a language that allows you to span the gamut from a "little more high level than C" (i.e. C with GC) to "a little more low-level than Python" (a few of Python's features are missing). I think that's actually an amazing range and I think more people should try to use it as its own language as Kyler is. On the other hand, using as a language MORE low-level than idiomatic C is a fun hack but won't probably save you any time or effort. But there's nothing wrong with doing something merely because it is a fun hack! Paul Prescod From clifford.wells at comcast.net Mon Jan 26 10:27:12 2004 From: clifford.wells at comcast.net (Cliff Wells) Date: Mon, 26 Jan 2004 07:27:12 -0800 Subject: Class returning None ? In-Reply-To: References: <2r4Rb.286342$e6.11127748@twister2.libero.it> Message-ID: <1075130832.13581.1062.camel@devilbox.homelinux.net> On Mon, 2004-01-26 at 06:33, Aahz wrote: > In article , > Cliff Wells wrote: > > > >from exceptions import Exception > >class SomeError(Exception): pass > > BTW, there's no need to do this. ``Exception`` lives in the built-in > namespace. Er, explicit is better than implicit? ;-) Somehow I never noticed that. Regards, Cliff -- So sad, love lies there still -Bauhaus From kbass at midsouth.rr.com Wed Jan 21 19:27:21 2004 From: kbass at midsouth.rr.com (kbass) Date: Wed, 21 Jan 2004 18:27:21 -0600 Subject: Python and writing a CSV file References: <20040121232549.GA28328@mail.theserver.ath.cx> Message-ID: <009501c3e07e$80b62e30$97443d42@homebass1> I am new to Python and would like to attempt to write to a CSV file. I have reviewed the documentation at http://www.object-craft.com.au/projects/csv/ for the csv 1.0 module but I didn't see any information referring to writing (oe creating) a CSV file with this module. Does this module have the capability to write a CSV file? Thanks! Kevin From arigo at tunes.org Thu Jan 15 06:20:29 2004 From: arigo at tunes.org (Armin Rigo) Date: Thu, 15 Jan 2004 11:20:29 +0000 Subject: What psyco is goot at [Was: Rookie Speaks] In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE0106375B@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE0106375B@au3010avexu1.global.avaya.com> Message-ID: <20040115112029.GA16143@vicky.ecs.soton.ac.uk> Hello Timothy, On Fri, Jan 09, 2004 at 09:51:07AM +1100, Delaney, Timothy C (Timothy) wrote: > The benchmarks with `from psyco.classes import __metaclass__` are > interesting - they're counter to what one would expect from the docs - > increased memory usage and decreased performance. Is this a known thing > Armin, or is something going screwy on my box? It's happening consistently. Pystone is a contrieved example of Python code, but I still don't really understand what is going on here. Psyco is definitely much faster with the Record class being left as an old-style class, which is the part that I don't grasp. > The main functions only get called one time each (which is probably the > killer) and the bulk of the work is done inside while loops in those > functions. Here too I'm not sure what is going on. This should not be the killer, because psyco.profile() is able to detect that a lot of time is spent in the loops while they are running, and it can start the compilation in the middle of the execution of a function. There are several parameters to psyco.profile(), see the documentation; you could try increasing 'parentframe' up to 0.5. This has the effect that time spent in sub-function counts a bit more as time (indirectly) spent in the calling function as well. All these parameters are a bit arbitrary, so I'd love to hear about values that worked better for you. A bientot, Armin. From none at none.com Tue Jan 13 09:28:14 2004 From: none at none.com (Derek) Date: Tue, 13 Jan 2004 09:28:14 -0500 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <100655fo84c2211@corp.supernews.com> <87d69og2jl.fsf@pobox.com> Message-ID: "John J. Lee" wrote: > [...] > > All I know is that there are thousands of extremely large > > projects written in C++, some consisting of millions of > > lines of code written by hundreds of developers. C++, > > while far from perfect, has proven its worth on a huge > > scale. Python, at the very least, has yet to do so. > > See a recent thread here listing some fairly large Python > projects. > > Of course, taking lines of code at face value is rather like > talking about waiting lists instead of waiting times... Point taken. I once worked on a project where we implemented a production system in C++ and then implemented it again in Python for QA purposes. It took about 150k lines of C++ code and 10k lines of Python. Python took less code because so many modules are bundled with the language, but the C++ system ran many times faster. It's all about picking the right tool for the job. From jzgoda at gazeta.usun.pl Sun Jan 18 05:24:32 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 18 Jan 2004 10:24:32 +0000 (UTC) Subject: [Q] Pyython and curses/ncurses/snack/tinter/... References: Message-ID: Chris Burkert pisze: > Now what would you prefer as UI-library? I'm searching for a > highlevel library with buttons, text boxes, dialog boxes, > progress bars, ... > > I have heard of: > - curses, ncurses ... low-level > - snack ... wrapper for newt and slang > - tinter > > Do you know of any other good library that is widely available? > > I have seen a lot of examples for curses and ncurses but not for > the others. > > Snack seems to be only available for Linux and not well documented?!? Snack should compile on any platform where SLang runs -- except Windows, of course. If you mean "Windows, Linux, MacOS, MacOSX, OS/2 and any other system where Python runs", there is no such library. In fact, if you mean "Windows and Linux", there's nothing here also. Text-mode interfaces are rather rare animals now. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From aienthiwan at mountaincable.net Sun Jan 18 04:24:03 2004 From: aienthiwan at mountaincable.net (Aienthiwan) Date: 18 Jan 2004 01:24:03 -0800 Subject: CGI Python user/group permission weirdness Message-ID: Ok - this one's a baffling one. I have a Python script run in cgi, it accesses a directory... /var/foo. The permissions on /var/foo are 770 with an ownership of mark:dbtest. The permissions on /var are 755. In my /etc/group file, www-data is part of the www-data, dbtest, fusion and cvs groups. I get an exception thrown with a permission denied on /var/foo. I have confirmed that it's the www-data user by calling a os.system('whoami') in my script for debugging. When I su www-data at the terminal, I can access /var/foo just fine. What's even weirder, if I switch the ownership of /var/foo to any of the other groups (except the cvs and the dbtest one), the script works! The only inconsistancy is in dbtest and cvs. I have attempted to rename them, adjust their ids, pretty much everything I thought of. I'm out of ideas. HELP! ~ Aienthiwan. From skip at pobox.com Thu Jan 29 11:26:53 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 29 Jan 2004 10:26:53 -0600 Subject: Get number of iteration In-Reply-To: References: Message-ID: <16409.13389.698178.710013@montanaro.dyndns.org> Florian> If I iterate through a list, is there a way I can get the Florian> number of the iteration: first, second, third, ... Sure: >>> for i, what in enumerate(["three", "four", "five", "six"]): ... print i, what ... 0 three 1 four 2 five 3 six Skip From candiazoo at comcast.net Fri Jan 2 14:20:01 2004 From: candiazoo at comcast.net (Zoo Keeper) Date: Fri, 02 Jan 2004 19:20:01 GMT Subject: Problem building on BeOS... References: Message-ID: O.K! After some tips from you folks, I found that the problem ONLY occurs with line continuation in "extern" statements. Works fine for DEFINEs... Mike In message , Zoo Keeper wrote: > For some reason, the Python preprocessing balks on the "\" line continuation > character. Any ideas/thoughts? Is it just that my version of gcc is not > supported? > > I don't "need" numeric in my current project, but it is a nice package to > have! > Apps that do not need to be compiled install and run fine. Actually, > SQLite > built and installed fine... > > Thanks, in advance. > > Mike > > Python 2.2.2 (#13, Dec 6 2002, 00:42:47) > [GCC 2.9-beos-991026] on beos5 > > $ python setup.py build > running build > running build_py > not copying Lib/ArrayPrinter.py (output up-to-date) > not copying Lib/LinearAlgebra.py (output up-to-date) > not copying Lib/MLab.py (output up-to-date) > not copying Lib/Matrix.py (output up-to-date) > not copying Lib/Numeric.py (output up-to-date) > not copying Lib/Precision.py (output up-to-date) > not copying Lib/RandomArray.py (output up-to-date) > not copying Lib/UserArray.py (output up-to-date) > not copying Lib/numeric_version.py (output up-to-date) > not copying Packages/FFT/Lib/FFT.py (output up-to-date) > not copying Packages/FFT/Lib/__init__.py (output up-to-date) > not copying Packages/MA/Lib/MA.py (output up-to-date) > not copying Packages/MA/Lib/MA_version.py (output up-to-date) > not copying Packages/MA/Lib/__init__.py (output up-to-date) > not copying Packages/RNG/Lib/Statistics.py (output up-to-date) > not copying Packages/RNG/Lib/__init__.py (output up-to-date) > running build_ext > building '_numpy' extension > gcc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include > -I/boot/home/config/include/python2.2 -c Src/_numpymodule.c -o > build/temp.beos-5.0.4-BePC-2.2/_numpymodule.o > In file included from > /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:4: > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:234: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:239: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:241: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:244: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:247: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:251: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:253: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:255: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/arrayobject.h:257: stray > '\' > in program > In file included from > /boot/home/Downloads/Numeric-23.1/Src/_numpymodule.c:6: > /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:101: stray > '\' > in program > /boot/home/Downloads/Numeric-23.1/Include/Numeric/ufuncobject.h:103: stray > '\' > in program > error: command 'gcc' failed with exit status 1 > $ > From xerolimit126 at earthlink.net Thu Jan 29 19:29:18 2004 From: xerolimit126 at earthlink.net (Xero Limit 126) Date: Fri, 30 Jan 2004 00:29:18 GMT Subject: Easy way to make EXEs... References: <4017C45F.D7501215@engcorp.com> Message-ID: "What don't you understand about py2exe? How it works, or how to actually execute it? Or something else? If you have trouble with it, perhaps there could be some improvements in the documentation... but nobody will know unless you help us figure out what the problem is. -Peter" Okay, I created the following setup file: --- file setup.py from distutils.core import setup import py2exe setup( console = ["calculator1.py"], ) Then, I get the following error: ------------------------------- Traceback (most recent call last): File "C:/WINDOWS/Desktop/Programming/Python/Programs/setup", line 4, in ? setup( File "C:\WINDOWS\DESKTOP\PROGRAMMING\PYTHON\BASE\lib\distutils\core.py", line 137, in setup raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg SystemExit: usage: setup [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup --help [cmd1 cmd2 ...] or: setup --help-commands or: setup cmd --help error: no commands supplied -------------------------- I also get a pop up window to the effect "Do you want to exit all together, Yes/No"... I have a feeling that Im just inputing somthing incorectly, or I have somthing installed incorrectly... (Sorry for not going too indepth before) From klappnase at web.de Fri Jan 16 06:53:17 2004 From: klappnase at web.de (klappnase) Date: 16 Jan 2004 03:53:17 -0800 Subject: Tkinter: modal ok in windows, but not in Linux References: Message-ID: DoubleM wrote in message news:... > Hi, > > I'm running Python2.3.3c1 on Mandrake 9.1 > > The following code is designed to bring up a window with a button labeled > "popup". Clicking on the popup buttons triggers a secondary window with a > button labeled "ok". The second window is supposed to be modal - it should > not be possible to reset the focus back to the first window or close the > first window without first closing the second. The program works just fine > in Windows XP home, but in Linux I can close the first window while the > second one is still active. > > This seems to be a bug, or am I doing something wrong. I searched google > for Tkinter Linux modal, but found nothing relevant. > > Thanks for your help. > > Here's the code, copied and pasted from IDLE. > > ############################# > from Tkinter import * > > makemodal = 1 > > def dialog(): > win = Toplevel() > Label(win, text = "Secondary").pack() > Button(win, text = "Ok", command = win.destroy).pack() > if makemodal: > win.focus_set() > win.grab_set() > win.wait_window() > print "dialog exit" > > root = Tk() > Button(root, text = 'popup', command = dialog).pack() > root.mainloop() > ################################# > > Mike > mmoum-xxxspam.woh.rr.com Hi Mike, I guess you should use root.wait_window(win) instead of win.wait_window() Cheers Michael From jjl at pobox.com Fri Jan 2 18:12:16 2004 From: jjl at pobox.com (John J. Lee) Date: 02 Jan 2004 23:12:16 +0000 Subject: Simulation library in Python References: Message-ID: <8765fukkrz.fsf@pobox.com> Samir Patel writes: [...] > If one wants to create a new simulation program, what > are different packages to use: [...] > simulation model creation (preferable data flow) - > dia, Pyut, OGL sketch, maybe. [...] > graph - > http://navi.picogui.org/svn/misc/trunk/rtgraph/ > http://matplotlib.sourceforge.net/ *Lots* more. More than you can shake a stick at... But, when I was using them, I never found any free graph plotting libraries that did everything I wanted (Python or no Python). It's a hard thing to do well. > animation - Blender?, VTK, VPython Pygame. [...] > GIS - ? I think Bernhard Herzog has released some free GIS code in Python recently. And IIRC, Fredrik Lundh sells GIS code of some kind. > Storage - ZODB xsdb (very new, though). Plus of course, all the usual relational suspects, and Gadfly, Sleepycat BSDDB (in standard library), etc. > Import/Export - ? - of what? John From gerrit at nl.linux.org Sun Jan 18 11:52:55 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 18 Jan 2004 17:52:55 +0100 Subject: Some kind of mail->html converter for python? In-Reply-To: References: Message-ID: <20040118165255.GA23339@nl.linux.org> Jan Kesten wrote: > Is was looking around for a tool like mhonarc[1], but implemented > in python (musn't be such powerful). Somebody know such a tool? You're looking for pipermail. Ancient, but it works. There is a dead project for rewriting it, called ng-arch (ng-arch at amk.ca). yours, Gerrit. -- 215. If a physician make a large incision with an operating knife and cure it, or if he open a tumor (over the eye) with an operating knife, and saves the eye, he shall receive ten shekels in money. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From mgrayson at daedalus.sis.utk.edu Tue Jan 20 12:51:28 2004 From: mgrayson at daedalus.sis.utk.edu (Matt Grayson) Date: Tue, 20 Jan 2004 12:51:28 -0500 Subject: simple class question In-Reply-To: References: Message-ID: <4620DBAA-4B71-11D8-BEDC-000A95983E14@daedalus.sis.utk.edu> On Jan 20, 2004, at 12:34 PM, C GIllespie wrote: > Dear all, > > I'm new to both python and OOP, so could I ask a simple question. > > I have class: > > class species: > __init__(self,pop=0): > self.pop=pop > Now I want to do something like this: > > X=species(pop=10) > Y=species(pop=X.pop) > OK, but now I want to update X.pop and have that mirrored in Y.pop, > i.e. if > X.pop=5, Y.pop now equals 5. > > What is the best/nicest/simplest way of doing this? Instead of declaring Y as a new instance of species, just set Y equal to X: x = species(pop=10) y = x x.pop = 15 print y.pop > > Many thanks > > Colin > > > -- > http://mail.python.org/mailman/listinfo/python-list ------------------------------------------------ Matt Grayson School of Information Sciences, University of Tennessee ------------------------------------------------- From newsgroups at jhrothjr.com Sun Jan 4 18:06:15 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Jan 2004 18:06:15 -0500 Subject: Creating a capabilities-based restricted execution system References: Message-ID: "Serge Orlov" wrote in message news:bta2ng$16v7$1 at nadya.doma... > > "John Roth" wrote in message news:vvg0h93ue63c0b at news.supernews.com... > > > > What I *haven't* seen in this thread is very much consideration of > > what people want from a security implementation. > > I think Sean is talking about his own implementation. I didn't > see anywhere he said he's going to write general implementation > for other people. He said what he wants from his implementation. I see that point, and now that it's been made explicit (I missed it the first time around, sorry,) I'm ok with it. > > One problem I've been playing around with is: how would you > > implement something functionally equivalent to the Unix/Linux > > chroot() facility? The boundaries are that it should not require > > coding changes to the application that is being restricted, and it > > should allow any and all Python extension (not C language > > extension) to operate as coded (at least as long as they don't > > try to escape the jail!) Oh, yes. It has to work on Windows, > > so it's not a legitimate response to say: "use chroot()." > > I don't see any unsolvable problems. Could you be more specific > what is the problem? (besides time, money, need to support > alternative python implementation, etc...) Well, I don't see any unsolvable problems either. The biggest sticking point is that the Unices use hard links to create a directory tree that has the necessary programs availible. Windows does not have this capability, so an implementation would have to build a virtual directory structure, intercept all paths and map them to the virtual structure backwards and forwards. The reason I find it an interesting problem is that I can't see any way to do it with the kind of "generic" facility that was in the Python Restricted execution facility, at least without a complete redesign of the file and directory functions and classes in the os module. Without that, it would require code in the C language implementation modules. Right now the file and directory management modules are a real mess. John Roth > > -- Serge. > > From kamikaze at kuoi.asui.uidaho.edu Fri Jan 2 16:34:12 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 2 Jan 2004 21:34:12 GMT Subject: ANN: Python Language Reference References: Message-ID: Will Stuyvesant wrote on 29 Dec 2003 01:09:18 -0800: >> [Aahz] >> That's why you should use Lynx. Then you don't have any options. ;-) > But isn't Lynx text-only? I want to see the pics! Even though I am > not the kind of pervert that want to do things to them with the mouse. Opera can be completely keyboard-driven. And to search, you can type /TEXT, just like you would in lynx or any other proper viewing or editing tool. -- Mark Hughes "God, I think. God. He doesn't answer, and I'd be justifiably scared--but not in a panic!--if he did, since I would know it really was Resuna, or a tiny brain tumor, or some boo-boo in my mix of neurotransmitters." -John Barnes From ny_r_marquez at yahoo.com Sat Jan 3 08:49:36 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 3 Jan 2004 05:49:36 -0800 Subject: Rekall Binary References: <8a27e309.0312310529.3c1f43a8@posting.google.com> <8a27e309.0401010633.20271486@posting.google.com> <6ee58e07.0401011433.5ce91221@posting.google.com> Message-ID: <8a27e309.0401030549.7e88a350@posting.google.com> llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0401011433.5ce91221 at posting.google.com>... > "The Kompany" wasn't able to pay the developer for month with non GPL > software, why do you think they can do it with GPL now (if you say > yourself that it will be less then in the BOS days) ? Yes, I think the Kompany is in a difficult spot. I think they waited too long to release Rekall as GPL. The reality today is that we live in the shadows of a huge monoply. Basically, the only way that I (and many others) see to compete with an application that is part of that monopoly is through Open Source/Free software. I am not against closed source or proprietary software in principle (except on the Operating System layer where I think that closed source has no place since it prevents a level playing field). I am happy that developers have the choice. But, until the grip of the monopoly is relaxed, or Linux takes off, I see no point in trying to compete with them that way. There are already products appearing on the same space that are going to give Rekall even more competition in the cross platform space (e.g. Omins Studio, Kylix, etc). I want to see Rekall succeed, mainly because it uses Python. So, at this point I think it would be better for the developers to provide it for free and build up a loyal base of users and bug/patch submitters. > In fact i believe that a main stream desktop tool like "Rekall" has no > future when it must live on support contracts only. If you need > support then the product has an error, but i don't want to use > errounous software. This is the reason why GPL does not work for a lot > of software products. I think Rekall has great potential. With a little imagination and creativity it could offer things such as a plug in mechanism that would allow it to perform many things beyond the basics. The developers could offer some of these pluggins in a closed source fashion if they chose, without alienating the rest of the Rekall community, and without sacrificing quality. Any way, this are my two cents worth. -Ruben From cpl.19.ghum at spamgourmet.com Sun Jan 4 07:31:42 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 4 Jan 2004 13:31:42 +0100 Subject: Scripting C++ Game AI object using Python Generators References: Message-ID: Nick, I am not able to understand your request fully (problem on my side, I'm not into Game Programming) ... but many of your keywords I heard last time in a talk by Chris Tismer, speaking about http://www.stackless.com/ stacklass Python at Europython in Charleroi. Maybe you should look there and maybe send your request directly to him? I saw him demonstrating a large game application with microthreads and generators and whatsoever (I just remember the words :)) ) Harald From mhammond at skippinet.com.au Mon Jan 19 17:46:08 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 20 Jan 2004 09:46:08 +1100 Subject: Multithreaded COM server problem... In-Reply-To: References: <5a90009ufdd66okc8osajrn1a5kokp86mk@4ax.com> <0pr700ddfdf3op14oulk7u82cthaped040@4ax.com> Message-ID: John Lull wrote: > Now I'm *really* confused. > > Perhaps I need to clarify a bit. The sleep() method in my sample > server is a perhaps-too-simplified substitute for what the real server > is doing. It provides a variety of high-level operations on a piece of > hardware. Some of the operations take as long as several dozen > seconds, others take a millisecond or so. I need the client to block > waiting for completion of each operation, regardless of how long the > operation takes. I cannot break one of the long operations up into a > series of calls from the client -- it must be implemented as a single > call. My example would, perhaps, have been clearer if I'd named the > method someLongRunningMethod() instead of sleep(). Is there any way you can do it asynchronously? The main thread spawns a second thread to do the work. The main thread then spins around a MsgWaitForMultipleObjects, with an object set by the second thread. The main thread will then be able to run a message pump, but also detect when the second thread is done. Apart from that, I am afraid I am out of ideas. I believe however that you are hitting pure COM issues, and nothing related to Python. Looking for the answer beyond the Python world may be fruitful. Mark. From rodrigob at elo.utfsm.cl Wed Jan 28 21:44:22 2004 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Wed, 28 Jan 2004 23:44:22 -0300 Subject: Web Service in Python References: <87hdyffzlp.fsf@tulip.whu.ca> Message-ID: <40186fa5_1@nova.entelchile.net> what do you call "web service" ? have you looked www.twistedmatrix.com ? "Peter Wu" escribi? en el mensaje news:87hdyffzlp.fsf at tulip.whu.ca... > I'd like to write a Web Service in Python just for my personal interest > now. Is there any reference or document on this? > > -- > ,,, > (o o) Peter Wu > ---ooO-(_)-Ooo--- Powered by GNU/Linux 2.4.22 From peter at engcorp.com Fri Jan 9 17:09:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Jan 2004 17:09:37 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <3FFF26A1.943DEA84@engcorp.com> Iwan van der Kleyn wrote: > > In other words: it would be nice if Python on average would run faster > so the need for optimisation would lessen. I disagree with the above. My opinion has long been that Python runs adequately fast and that few people should need to spend much time on optimization. Maybe that sort of view should be put to the test. This is my "straw poll" question: Do you spend a "significant" amount of time actually optimizing your Python applications? (Significant is here defined as "more than five percent of your time", which is for example two hours a week in a 40-hour work week.) Note the distinction between "actually optimizing" and "worrying about optimization" and such things. If you pause briefly during coding and rewrite a line to use a more efficient idiom, I don't consider that to be "optimization" for purposes of this question. Optimization would require roughly (a) noticing that performance was inadequate or actual profiling your code, and (b) rewriting specifically to get adequate performance. Algorithmic improvements that you would make regardless of implementation language do not qualify, and wasting time optimizing a script that you run once a year so it takes ten seconds instead of fifteen also does not qualify because you certainly didn't need to do it... Yes or no answers suffice, but feel free to follow up with a paragraph qualifying your answer (or quantifying it!). :-) -Peter From leo at lspace.org Thu Jan 22 04:45:06 2004 From: leo at lspace.org (Leo Breebaart) Date: Thu, 22 Jan 2004 09:45:06 +0000 (UTC) Subject: Side note: Praise to the contibuters to this group References: Message-ID: "Amy G" writes: > I just wanted to take a second and thank all of the contributors to this > awesome newsgroup. "You know, some statements just _require_ that a small amount of bandwidth be sacrificed to the "Me too" gods, and that's one of 'em. Yeah, what she said." -- William December Starr on rec.arts.sf.written -- Leo Breebaart From RAV at ns.artphila.com Wed Jan 28 03:30:53 2004 From: RAV at ns.artphila.com (RAV at ns.artphila.com) Date: Wed, 28 Jan 2004 10:30:53 +0200 Subject: RAV AntiVirus scan results Message-ID: <200401280830.i0S8UrLr005530@ns.artphila.com> RAV AntiVirus for Linux i686 version: 8.3.2 (snapshot-20020108) Copyright (c) 1996-2001 GeCAD The Software Company. All rights reserved. Registered version for 2 domain(s). Running on host: ns.artphila.com ----------------------- RAV Antivirus results ----------------------- The infected file was saved to quarantine with name: 1075278653-RAVi0S8UmLr005525. The file (part0002:file.zip)->file.pif attached to mail (with subject:MAIL DELIVERY SYSTEM) sent by python-list at python.org to phila at artphila.com, is infected with virus: Win32/Mydoom.A at mm. Cannot clean this file. Cannot delete this file (most probably it's in an archive). The mail was not delivered because it contained dangerous code. ------------------------ this is a copy of the e-mail header: Scan engine 8.11 () for i386. Last update: Tue Jan 27 05:03:51 2004 Scanning for 89279 malwares (viruses, trojans and worms). To get a free 60-days evaluation version of RAV AntiVirus v8 (yet fully functional) please visit: http://www.ravantivirus.com From michael at foord.net Tue Jan 13 03:50:54 2004 From: michael at foord.net (Fuzzyman) Date: 13 Jan 2004 00:50:54 -0800 Subject: Python Utils - A simple config file parser and output object References: <8089854e.0401070044.1e8116ad@posting.google.com> <8089854e.0401090212.4826925d@posting.google.com> Message-ID: <8089854e.0401130050.68273bac@posting.google.com> [snip..] > > Some news servers allow connections on port 80 or other alternatives. > (The free news.readfreenews.net server does, but it doesn't allow posting,) Interesting... I wonder if I'll be able to configure free agent to read from it :-) > > Also comp.lang.python is linked to the python mailing list: > I don't think I could cope with all of this group by email... but thanks. Fuzzyman From jacek.generowicz at cern.ch Tue Jan 13 04:07:44 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz's alter ego) Date: 13 Jan 2004 10:07:44 +0100 Subject: Why learn Python ?? References: <40029dad$0$28706$a729d347@news.telepac.pt> <87hdz0g2zk.fsf@pobox.com> Message-ID: Jacek Generowicz writes: > jjl at pobox.com (John J. Lee) writes: > > > Jacek Generowicz writes: > > [...] > > > If you want to perform miracles, then learn Lisp. If you > > > merely want to write programs that rock, then learn Python. > > [...] > > > > ...and then somebody argues that macros aren't a programming language > > feature, but a harmful means of inventing new languages, and then we > > get into that endless macro thread again... > > Well they're all Nazis. Godwin's Law ! You lose ! Nah na-na naaa nah ! Game over. (And I'll predend I've never heard of Quirk's Exception, so I'm outa here.) From tim.one at comcast.net Sat Jan 24 16:38:46 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 24 Jan 2004 16:38:46 -0500 Subject: Perl vs. Python for text manipulation In-Reply-To: <20040124185827.GE32445@unpythonic.net> Message-ID: [Jeff Epler] > The "unlocked I/O" mentioned earlier refers to locking inside the > standard C library, so Python can't avoid it except by calling > non-portable functions such as getc_unlocked* or by using lower-level > I/O primitives such as posix read(2)/write(2). Current Pythons do use getc_unlocked() on platforms that have it. ... > * Actually, my getc_unlocked() manpage says that the function is in > POSIX.1, so this may be as portable as read/write would be Alas, it isn't. Python uses read()/write() on all platforms (there is no known Python platform that doesn't supply them). getc_unlocked() is rarer. See fileobject.c for the dreadful hack used if getc_unlocked() isn't available (but, hack or not, on some platforms that's faster than using getc_unlocked; there are #defines you can play with to try it both ways). From adalke at mindspring.com Tue Jan 13 16:43:51 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 13 Jan 2004 21:43:51 GMT Subject: Python is far from a top performer according to benchmark test... References: <6ee58e07.0401092129.302cb9d4@posting.google.com> <95aa1afa.0401130424.49749912@posting.google.com> Message-ID: Jacek Generowicz, quoting Kent Pitman > -- > ...Please don't assume Lisp is only useful for Animation and Graphics, > AI, Bioinformatics, ... just because these are the only things they > happened to list. And as I continue to point out, *Python* is more often used in bioinformatics than Lisp, and Perl dominates that field, followed by C/C++ then Java a distant third. Andrew dalke at dalkescientific.com From dialtone#NOSPAM#.despammed at aruba.it Fri Jan 16 18:18:26 2004 From: dialtone#NOSPAM#.despammed at aruba.it (Valentino Volonghi aka Dialtone) Date: Sat, 17 Jan 2004 00:18:26 +0100 Subject: Make a function call itself after set amount of time References: Message-ID: <87isjbv5x9.fsf@vercingetorix.caesar.org> Bart Nessux writes: > How do I make a function call itself every 24 hours. Also, is there a > way to start the program automatically w/o depending on the OS > functions like 'Task Scheduler' or 'Start Up Items'... this is on > Windows 2k and xp. Below is an example of what I'm trying to do. [snip] Never seen twisted? Here is a little tip: from twisted.internet import reactor def doSomething(mystring): print mystring reactor.callLater(5, doSomething, mystring) doSomething("ciao") reactor.run() Twisted also has a lot of already implemented protocols for almost everything related to net so maybe you can think of a new version of your app using twisted's protocols. www.twistedmatrix.com -- Valentino Volonghi, Regia SpA, Milan Linux User #310274, Gentoo Proud User From merkosh at hadiko.de Mon Jan 19 19:43:24 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 20 Jan 2004 01:43:24 +0100 Subject: speedy Python strings? Message-ID: Hi, thanks to previous help my wrapper for an abstract file type with variable record length is working now. I did some test runs and its awfully slow: I didn't want to read in the whole file at once and I didn't like to read it step by step (contains 32 bit length terminated strings (Delphi) and 32bit integers), so I read in i.e. 2MB, work on that buffer and if the buffer goes empty i load some more 2MB, etc. For this buffer I use ordinary strings: class myFile(file): def read(self, *args): ... self.buffer += file.read(self, *args) ... and after reading information from the buffer I remove the read part from it: text = struct.unpack("L", self.buffer[:4]) self.buffer = self.buffer[4:] During debugging I saw the program accelerating when the buffersize grew smaller, thus my conclusion: since strings are immutable the string operations are so slow. I tested different sizes of the buffer and it performed best when I didn't use that buffering system (which is sad, since I spend so much time on it). Is there anything else I can use instead of normal strings that'll speed this up? What do you suggest how to deal with this situation? Do you suggest I remove any buffering of the data? Thanks for any comments Yours Uwe From tzot at sil-tec.gr Fri Jan 16 08:49:16 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 16 Jan 2004 15:49:16 +0200 Subject: TUPLE & LIST References: <%7xNb.55$Uw3.50@newsr2.u-net.net> <100dpuer745vfa0@corp.supernews.com> Message-ID: On Thu, 15 Jan 2004 14:18:36 -0500, rumours say that "Francis Avila" might have written: > >Gerrit Holl wrote in message ... >>Christos TZOTZIOY Georgiou wrote: >>> Examples: >>> Use a list for a list of names. >>> Use a tuple for (x,y) coordinates in some area. >>> Use a list of (name,phone,address) tuples for your poor man's address >>> book which you will implement in python. >> >>What if someone moves away? >>That is, I think one could better use a mutable type for the address book. > >That's why it's a "poor man's" address book. :) Thanks, Francis :) To Gerrit: if the context was "help me make an address book", I believe it is obvious I wouldn't suggest what I suggested. It was just an example of concurrent tuple and list usage, where list stands for database table and tuple for database row... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From buzzard at urubu.freeserve.co.uk Fri Jan 30 23:21:45 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 31 Jan 2004 04:21:45 -0000 Subject: timeit Message-ID: This is possibly a stupid question, but I need to get this working quickly, and I guess I'm just too tired / pressured to see what I'm doing wrong. Clearly (from the output below) I can't pass the statement to an instance of timeit.Timer, but I can execute it using exec(). Any idea what I need to do to get this timed (using timeit). Cheers. >>> import SDC_table >>> import subtract >>> import timeit >>> t = SDC_table.RandomTable(1, 12, (2,3,4)) >>> s = """\ p = subtract.p_risk(t.values, 10) """ >>> tim = timeit.Timer(stmt=s) >>> tim.timeit(10) Traceback (most recent call last): File "", line 1, in -toplevel- tim.timeit(10) File "C:\Python23\lib\timeit.py", line 158, in timeit return self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'subtract' is not defined # yet >>> exec(s) >>> p 0.242621453769059 From gagenellina at softlab.com.ar Mon Jan 5 20:17:30 2004 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Mon, 05 Jan 2004 22:17:30 -0300 Subject: Quck question In-Reply-To: <3125790e.0401051610.5e24de28@posting.google.com> Message-ID: <5.2.1.1.0.20040105220232.0270eb30@192.168.0.115> At 5/1/2004 16:10, you wrote: >I have the following information in a file : >r1kcch Serial0/0/0 propPointToPointSerial >Mon Jan 5 13:15:03 PST 2004 InOctets.1 0 >Mon Jan 5 13:15:05 PST 2004 OutOctets.1 0 > >I want to be able to extract each line into a comma delimited list. ...into a list. The you may *show* the list in a comma-delimited format. >Bellow i am trying to print out my list print currentList but nothing >is comming out. I added a line after print test to make sure the file >has the information. Can someone help me with this? > > >#Read a file >true = 1 Notice that True (capitalized) is a builtin in v2.3 >in_file = open("test.txt","r") >text = in_file.read() This reads the full contents of the file, and there is nothing left for the next readline() to read... Just omit this. >while true: > in_line = in_file.readline() Try using: for in_line in in_file.readlines(): > if in_line == "": > break > currentList = string.split(in_line,",") There are no "," in the sample lines, just spaces. currentList = in_line.split() # default separator is space > #print out the contents of the current list > print currentList just fine... > #make the inline stop reading > in_line = in_line[:-1] ???? >in_file.close() Gabriel Genellina Softlab SRL From markus_wankus at hotmail.com Tue Jan 13 15:22:55 2004 From: markus_wankus at hotmail.com (Markus Wankus) Date: Tue, 13 Jan 2004 15:22:55 -0500 Subject: Visual Jython idea brainstorming welcome References: <1db780c8.0401130936.88d1da4@posting.google.com> Message-ID: On 13 Jan 2004 09:36:57 -0800, Victor wrote: > Hi all, > > I had this idea two minutes ago. I am proprosing an idea to build an > IDE called "Visual Jython" with Eclipse technology. This IDE is > targeted towards building enterprise client applications running any > Java platform mostly non-web based clients. > > My background is diversed in UNIX variants, Java and Python. Here are > something off the top of my head. > > 1. Basically from UI perspective, it will be like as name implied > "Visual Studio" like. > > 2. plug in architecture > This IDE should define or use a componenent architecture to plug & > play component written in Java confining to a Jython Plug in API. For > instance, we can develop plug in for ODBC, Oracle, DB2, Informix, MQ, > SAP etc for enterprise uses. > > > 3. gluing languag--Jython > maybe we need funding to support Jython for this matter to make it > commerical quality. > > > 4. .NET integration? > Should this IDE generate code that can run on top of .NET to attract > more VB/.Net programmers into this field? > > > > Welcome comments on features this IDE should have. > You should check out this project - perhaps you are headed in the same direction? http://ejython.tigris.org/ From the website: Description The eJython project was formed to accommodate two goals. First to provide rich scripting functionality to Java developers using Eclipse. The second goal is to build a functioning Jython (Java based Python) development environment inside Eclipse. The ultimate vision is to realize the following requirements. Provide a view with a Jython interpreter built into the view. Integrate Jython as a scripting language for complex operations on documents open in the Eclipse Editors. Provide a development environment for developing Jython based projects using Eclipse. Attach Jython to upcoming refactoring extension points to allow developers to easily write their own refactoring tools. -- Markus From Pieter.Claerhout at Creo.com Sun Jan 4 13:00:21 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Sun, 4 Jan 2004 19:00:21 +0100 Subject: Cheetah best for templating? Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D3E@cseexch01.cse.creoscitex.com> I personally prefer Preppy from the guys at ReportLab. I find the syntax a little more pythonic and the module is just a single .py file. I'm using Preppy as the template engine in my Jython servlets and found that it performed a lot better than Cheetah under those conditions. Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Wilk [mailto:wilkSPAM at OUTflibuste.net] Sent: 04 January 2004 13:38 To: python-list at python.org Subject: Re: Cheetah best for templating? "Roger Jack" writes: > I have just finished reading Code Generation In Action which uses Ruby for > code generation. I would like to use Python instead. Is Cheetah the best > tool to use for templating source code files and then generating code? Is > there something more mature or better? My graphist and me found it excellent, fast, clear, simple, stable : Pythonic ! We found the others engines too verbose, more perlish ;-) Like python, the best is to try somes engines, you will see quickly wich one you need. First, like everybody, i did my own engine, but Cheetah was finaly a better wheel ! I use it to generate html, latex and xml -- Wilk - http://flibuste.net -- http://mail.python.org/mailman/listinfo/python-list From cognizor at cognizor.com Fri Jan 16 14:41:16 2004 From: cognizor at cognizor.com (cognizor at cognizor.com) Date: Fri, 16 Jan 2004 12:41:16 -0700 Subject: plebe comment re [Python-Dev] SF patch 864863: Bisect C implementation Message-ID: <20040116124116.69cef8ca.cognizor@cognizor.com> As a Python, not a C user, I'd chime in on behalf of non-developers especially to say Yes, please keep the python versions of std library modules. They are much used. In pro: The python implementations are legible. They can be followed step by step in the interpreter, with added printout statements, that amazing debug, to understand What the commands do and what else they could do or not do. It's not always obvious otherwise what data-structures they expect. The python modules are especially useful because they include descriptions of how they came about and what the parameters are for the different cases, who wrote them and what the problems in use are. Even the dates help figure out whether they'll fit with other pieces. Just getting things to work comes way before speed considerations when you're not so expert [yet ;-]. So for developers to be putting them routinely through [unit] tests is good, because it'd be terribly hard to figure them out if they didn't work! Thanks for suggesting in the python-dev summary, Brett, that we can add our comments. And thanks to all the developers who care and do such a thorough job. -- ;););) blessed are the geeks -- for they shall inherit the source code :):):) From __peter__ at web.de Sun Jan 11 03:57:32 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Jan 2004 09:57:32 +0100 Subject: readling newlines References: Message-ID: Alessandro Crugnola *sephiroth* wrote: > Hi, I'm trying to detect the newlines method of a file opened. > I'm using the 'U' mode as parameter when opening a file, but for every > file opened the result is always "\r\n", even if the file has been saved > with the "\n" newline method. Is there i'm missing? > > I'm on Windows with python 2.3.3 Here's what I get (on Linux): >>> for nl in ["\n", "\r\n", "\n\r", "\r"]: ... dst = file("tmp.txt", "wb") ... dst.write("one%stwo" % nl) ... dst.close() ... print repr(file("tmp.txt", "U").read()) ... 'one\ntwo' 'one\ntwo' 'one\n\ntwo' 'one\ntwo' >>> >From the documentation of file(): If Python is built without universal newline support mode 'U' is the same as normal text mode. So maybe you have a version without universal newline support? Peter From fBechmann at web.de Sat Jan 10 06:25:16 2004 From: fBechmann at web.de (Frank Bechmann) Date: 10 Jan 2004 03:25:16 -0800 Subject: LC_MONETARY formatting References: <3FFF38DE.1050603@v.loewis.de> Message-ID: this http://oss.software.ibm.com/icu/ is - as far as I know - *the* OS catch-all project for encoding-conversion and localisation tasks. It's written in C++, has a C wrapper and Java's functionality on these topics is based on ICU. I don't know whether there's a python wrapper for it, but IIRC the gnue-project (which is mainly written in Python) uses ICU. but as stated above often in commercial applications the problem is not the currency formatting but to provide the complete information of amount, source currency and target currency throughout the complete flow of the program. From francisgavila at yahoo.com Mon Jan 5 16:33:17 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 5 Jan 2004 16:33:17 -0500 Subject: ASCII characters in my hex output References: Message-ID: nuvodido wrote in message ... >I am using pyserial to work with a device on my serial port. the >output is a mixture of ASCII and hex: > >Ex. '\x10\x00*' > > >I need conver the \x00* nuber in to decimal. Is there way to >convter this value striat forward? You're not being specific enough. Here are some things to look at: Pyserial for your serial port-ing needs. Struct module for C-structs. Array module for homogenous binary data. Have a look also at ctypes and xstruct (both external modules). chr() and ord() builtins; shift and binary arithmetic operators. I suspect what you are asking is something like: struct.unpack('=bh', '\x10\x00*') -> (16, 10752) But again, how can I know? -- Francis Avila From michael at foord.net Fri Jan 30 08:05:25 2004 From: michael at foord.net (Fuzzyman) Date: 30 Jan 2004 05:05:25 -0800 Subject: Simple Database Package References: <8089854e.0401280622.4e145267@posting.google.com> Message-ID: <8089854e.0401300505.5f49d490@posting.google.com> Jamey Cribbs wrote in message news:... > Fuzzyman wrote: > > Anyone able to reccomend a simple module / package I can use... ? > > I've never done any database work before and am ken to learn - but > > most of the ones I've seen seem to rely on a database engine buit into > > a server.. I need a simple stand alone engine. Of course I could just > > build the functions I need - but that would be a bit of a waste and > > not so extendable........ > > Have a look at KirbyBase (http://www.netpromi.com/kirbybase.html). It's > written in Python, can be either embedded in your application or used in > a multi-user/client server mode, and stores its data as plain-text files > that can be opened by any text editor. I'm probably a little biased > because I wrote it, but, if your needs are simple, it might prove useful. > > Jamey Just as I'd decided to use Metakit as well :-) I *do* like the idea of a pure python solution (cross platform distribution in 1 package) and a text datafile.. I'll have a look at it anyway... don't be offended if I decide to use metakit though - it looks pretty good. Thanks for your help. Fuzzy From lubowiecka at go2.pl Thu Jan 8 04:03:40 2004 From: lubowiecka at go2.pl (Sylwia) Date: 8 Jan 2004 01:03:40 -0800 Subject: "Interrupted function call" exception while relogging :( Message-ID: Hi! I need your help... I have the following problem. I've implemented the python Windows Service which behaves like a log supervisor. If the space used by log files is bigger than a given upper limit, then it starts to delete log files until the space is less than a given lower limit. I configured the service to start up automatically on system boot. The script checks the space used by log files every 1000 secs. After analyse of the space, it falls asleep (time.sleep(1000)). Everything works OK, except one thing... Since the service is not tied to the user ID of the person starting it, the service should remain open even when that person who started it logs off. So I made an experiment and relogged. After that it turned out that the service stopped working. The Event Viewer returned the error: "SvcDoRun time.sleep(1000) exceptions.IOError: [Errno 4] Interrupted function call " I use Window XP OS and Python and Python 2.3.2 I guess that some asynchronous signal was caught by the process during the execution of an interruptible function (time.sleep(1000)). Maybe it happened while pressing Ctrl+Alt+Del sequence during logging? Maybe I should add some signal handling? Unfortunately the Windows signal implementation is limited to 6 signals(???): SIGABRT Abnormal termination SIGFPE Floating-point error SIGILL Illegal instruction SIGINT CTRL+C signal SIGSEGV Illegal storage access SIGTERM Termination request Please help me... Best wishes, Sylwia From ketulp_baroda at yahoo.com Mon Jan 12 06:44:56 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda) Date: Mon, 12 Jan 2004 11:44:56 -0000 Subject: what is best for web development?? Message-ID: i am developing an issue tracking system the primary requirements are 1)it should be platform independent which i think python will take care of 2)it should have customizeable gui .I am thinking of using templates for this like Cheetah. Is there any other better solution to Cheetah? The problem i am facing here is i dont know what to use for development of the application. I came across many ways to develop web application in python which I already specified like i)the cgi module in python ii)Python Server Pages iii)Quixote iv)WebWare v)Zope etc. I want to choose such an environment so that i dont have to install other softwares to run my application.For eg. I think if I develop using zope then the client also has to install zope to run my software and i dont want this. From swalters_usenet at yahoo.com Sun Jan 18 07:46:37 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 12:46:37 GMT Subject: Python used in Freedom Force References: <4BDF2B3C-464A-11D8-B48D-000A959CB2EC@netmail.to> <4006911e$0$327$e4fe514c@news.xs4all.nl> Message-ID: | Alan James Salmoni said | > Perhaps all this stuff could be put onto the "Python Success Stories" > part of the python.org website? It's not public, but if the language > is clearly being used... I like this idea. Each high-profile project for which Python is being used lends some credibility to the language as being worthy of system-critical functions. Elsewhere, in comp.lang.scheme, someone mentioned that he was trying to hack a CL interpreter into the quake engine. The idea was that he wanted to teach his kids to program things they found interesting, so he wanted to have them create quake-bots. Sort of a new-school Logo. :-P Are there any games out there with Python engines that are particularly hackable? Especially from a novice point of view? Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From wweston at att.net Thu Jan 22 09:08:02 2004 From: wweston at att.net (wes weston) Date: Thu, 22 Jan 2004 14:08:02 GMT Subject: Side note: Praise to the contibuters to this group In-Reply-To: References: Message-ID: <6PQPb.691$6O4.14466@bgtnsc04-news.ops.worldnet.att.net> Sweet From andrearo at stud.ntnu.no Mon Jan 19 05:05:51 2004 From: andrearo at stud.ntnu.no (=?ISO-8859-1?Q?Andreas_R=F8sdal?=) Date: Mon, 19 Jan 2004 11:05:51 +0100 Subject: parse binary file in python? In-Reply-To: References: Message-ID: On Sun, 18 Jan 2004, "Martin v. L?wis" wrote: > Andreas R?sdal wrote: > > I want to parse a binary file in python. Does > > python have some built in methods for doing this easily? > > Any links to example code would be nice.. > > Depends on the kind of parsing you want to do. Python > can naturally represent binary files in string objects, > e.g. > > f = open("binaryfile.bin", "rb") # notice the b for binary mode > data = f.read() > f.close() > > You can then look at the individual bytes by index. Thanks. Just wanting to know if I understood your answer correctly; will the data variable above be an array of binary data, eg. data[220] == 0, and data[221] == 1 etc? Andreas R?sdal From jjl at pobox.com Fri Jan 23 07:37:55 2004 From: jjl at pobox.com (John J. Lee) Date: 23 Jan 2004 12:37:55 +0000 Subject: Accessing Microsoft Word from Python References: Message-ID: <878yjy6dss.fsf@pobox.com> Rene Pijlman writes: > Mickel Gr?nroos: > >Does anybody have any good pointers on where I can find information > >about accessing Word-documents (or other Microsoft Office applications) > >from Python? > > This book: http://safari.oreilly.com/1565926218 explains how to access > Excel from Python. It also explains COM-interfacing in general. [...] O'Reilly used to have a book on Word's object model by Steven Roman. Haven't read it, and I don't know if it's still published/up-to-date, but I know Roman's book on MS Access is good (haven't looked, but I guess the ref you give above is another book by the same author). John From skip at pobox.com Thu Jan 15 10:58:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Jan 2004 09:58:58 -0600 Subject: Why gmp is not in the standard library? In-Reply-To: <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> References: <4f0a9fdb.0401150211.615a7f45@posting.google.com> <4006b54e$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <16390.47298.480563.106963@montanaro.dyndns.org> >> Licensing? IIRC, GMP is GPL. Brian> So is bsddb and that is included with python. Bsddb is the name of Python's module which wraps Sleepycat's Berkeley DB, commonly abbreviated as bdb. Bsddb is in Python and maintained by the current developer (Greg Smith), so I assume any necessary accommodations were made. A quick glance as a few of the Python files in the bsddb package didn't make it look like GPL. Bdb's license is not GPL: http://www.sleepycat.com/download/oslicense.html Skip From cy.fbp.eryvtvne at ncbybtrglxn.pbz Thu Jan 15 03:51:46 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Thu, 15 Jan 2004 09:51:46 +0100 Subject: best book References: Message-ID: On Wed, 14 Jan 2004 23:31:32 GMT, Terry Carroll wrote: >>What is the best book to start with python ? i am have been working since 1 yr with Perl. > >My favorite to start is O'Reilley's "Learning Python." Yes. It's the good starting point. And for previous Perl programmer another good choice is "Python Essential Reference" by David M. Beazley. Check also this list: http://www.awaretek.com/book.html and those reviews: http://www-106.ibm.com/developerworks/linux/library/l-cp12.html -- JZ From skip at pobox.com Wed Jan 28 10:28:48 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Jan 2004 09:28:48 -0600 Subject: isinstance() bug In-Reply-To: <20040128132225.GA10842@foof.i3.cz> References: <20040128132225.GA10842@foof.i3.cz> Message-ID: <16407.54576.283608.505067@montanaro.dyndns.org> Michal> how is it possible that it IS important how you imported a Michal> class definition for isinstance() to work? it's insane! You imported the module twice (look at sys.modules) so you have two different A classes. I believe isinstance() uses the __class__ attribute and the class's __bases__ attribute to work its way up the class chain looking for a match. Even though they are defined identically, you have two different A classes. An instance of one can't also be an instance of the other. Skip From theller at python.net Fri Jan 16 11:47:54 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Jan 2004 17:47:54 +0100 Subject: Very strange unicode behaviour References: Message-ID: Syver Enstad writes: > Thomas Heller writes: > >> > Is this behaviour the same on Python 2.3? >> >> No, it behaves correctly as it seems: > > That's a relief. See my later post to see why the first report I gave > was *very* confusing. It looks like an ignored exception somewhere without calling PyErr_Clear(). Thomas From shaleh at speakeasy.net Fri Jan 30 10:18:54 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Fri, 30 Jan 2004 07:18:54 -0800 Subject: Sort by key, then by content In-Reply-To: <20040130093639.GA3385@nl.linux.org> References: <9A8139BC-52F3-11D8-9115-000A959CB2EC@netmail.to> <200401292348.57424.shaleh@speakeasy.net> <20040130093639.GA3385@nl.linux.org> Message-ID: <200401300718.54219.shaleh@speakeasy.net> On Friday 30 January 2004 01:36, Gerrit Holl wrote: > Sean 'Shaleh' Perry wrote: > > >>> contents = zip(d.keys(), d.values()) > > How does this differ from d.items()? > it doesn't, I just forgot it existed. From gerrit at nl.linux.org Mon Jan 19 17:13:50 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 19 Jan 2004 23:13:50 +0100 Subject: Getting a process's output In-Reply-To: <82104858-4ACB-11D8-A692-0003934ACDEC@zdome.net> References: <82104858-4ACB-11D8-A692-0003934ACDEC@zdome.net> Message-ID: <20040119221350.GB11631@nl.linux.org> Dietrich Epp wrote: > Is there any easy way to get all the output of a process? Ideally, the > function takes parameters like exec(), calls fork(), wait()s for the > process to complete, and returns the process's stdout, stderr, and exit > status. By stdout and stderr I don't mean file objects or > descriptors... I mean strings containing the entire output. > > I would try to do it myself, but I'm not sure how to interleave the > operations. Try commands.getstatusoutput() or the various popen functions. yours, Gerrit. -- 272. If any one hire a cart alone, he shall pay forty ka of corn per day. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From newsgroups at jhrothjr.com Tue Jan 20 16:59:00 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 20 Jan 2004 16:59:00 -0500 Subject: New to Python: my impression v. Perl/Ruby References: Message-ID: <100r97l2cgdag73@news.supernews.com> "Ville Vainio" wrote in message news:du71xpue3rm.fsf at mozart.cc.tut.fi... > >>>>> "Phil" == Phil Tomson writes: > > Phil> Different strokes for different folks, I guess. I remember > Phil> that one of the first things I saw about Ruby was that even > Phil> interger literals were objects that can receive messages and > Phil> thinking how wonderful that was. As you say, you're not > > Ints are objects in python too: > > >>> a=1 > >>> a.__lshift__(1) > 2 > > Though "sending messages" to int literals is a syntax error. > > Phil> 10.times do something end > > Phil> is somehow so clear. It's almost zenlike. > > It's cute and fun to write, but less cute for people who have to read > lots of such code in short time. I have a soft spot for such style > also; I kinda like Python's "\n".join(["foo","bar"]), even if most > seem to consider it a wart for readability reasons. Tacking an iterator on an integer isn't all that bad from a readability viewpoint - ***except*** for the .step iterator. .times, .upto and .downto read very nicely, but .step is a monstrosity. Conceptually, .step has three parameters, and separating them that way simply doesn't read right. It's also not consistent with the .each iterator attached to range objects in Ruby, which is at least intelligible, and is consistent with the way iterators are done with all other objects. The trouble with .join() in Python is that it reads backwards, at least to me. The arguement that .join isn't a natural list method makes sense, but nobody seems to want to consider that there are other solutions that read fairly well. Of course, they're also consequences of fairly generic changes to the language. John Roth > > -- > Ville Vainio http://tinyurl.com/2prnb From chris.lyon at spritenote.co.uk Sat Jan 17 13:49:26 2004 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 17 Jan 2004 10:49:26 -0800 Subject: Does anyone else not find the fun in programming...? References: Message-ID: > (Actually typing this was quite fun, so perhaps) Well, well ,well, what an interesting response ! I have taken a walk down the canal, I have totally ignored the Gov't and have gloried in the fabulous Wolverhampton Wanderers win today as football (association). Apparently we beat some team from the Manchester area. Who would have thought it! With regard to the actual pursuit of happiness via programming I can acknowlege certain aspects of the pleasure to be derived from a neat solution and python has certainly provided me with real solutions. It has never run out of power for anything I have asked it. If you have been following over the past couple of years I have attempted to ask it some pretty stupid questions (for which I hang my head in shame, Medusa forgive me!) My own limitations are what I will obviously tend to concentrate on and I think I am just too lazy to ever programme with true confidence. However during the days, now long in the past, when I did right stuff for fun which as it happened sorted out problems at work, I wish Python had been my language of choice rather than Basic which I did actually use. But of course... A word of caution however I think the word fun is a dangerous one to employ as I have seen it instill, at the very least, nervousness in managements as they feel they are getting another crazed take on the world rather than the carefully studied approach that the feel their particular problem really requires. Perhaps work will always be that way. p.s I wrote my bilge pump measuring website in Python and I did have a lot of fun with that :) From __peter__ at web.de Sat Jan 10 16:56:39 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Jan 2004 22:56:39 +0100 Subject: Newbie question on self in classes References: Message-ID: Klaus Oberpichler wrote: > Hello Python community, > > my simple question is: When is the self reference to a class valid? > During playing around with python I got the following error message: > >>>> class Test: > ... value = 1000 > ... self.value = 2 > ... > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in Test > NameError: name 'self' is not defined > > When I do it a different way no error occurs: > >>>> class Test: > ... value = 1000 > ... def f(self): > ... self.value = 2 > ... >>>> > > When is the reference to its own class is generated and valid? What is the > reason bihind that behaviour? The name "self" is just a convention. Python passes the instance to a method, i. e. a def ... inside the class as its first parameter: >>> class Test: ... def method(self): ... self.value = 2 ... So you could say that self is accessible inside (normal) methods. Now let's create an instance: >>> t = Test() Calling the method: >>> t.method() This is just a shortcut for: >>> Test.method(t) with the important difference that the first form will automatically pick the "right" method when inheritance comes into play. Now to the value attribute. The way you defined it, it is a class attribute, something that ist best avoided at this early state of the learning curve. What you want is rather an instance attribute, i. e. something that may be different for every instance of the class. These are initialized in the __init__() method, which is called implicitly when you say Test(): >>> class Test: ... def __init__(self): ... self.value = 1000 ... def method(self, newvalue): ... self.value = newvalue ... >>> t = Test() >>> t.value 1000 >>> t.method(1234) >>> t.value 1234 >>> Test.method(t, 3210) >>> t.value 3210 Peter From steve at ferg.org Thu Jan 8 10:38:51 2004 From: steve at ferg.org (Stephen Ferg) Date: 8 Jan 2004 07:38:51 -0800 Subject: what is Python's module search path? Message-ID: I need a little help here. I'm developing some introductory material on Python for non-programmers. The first draft includes this statement. Is this correct? ----------------------------------------------------------------- When loading modules, Python looks for modules in the following places in the following order: * Python's built-in modules, including modules in the standard library * in the /python23/Libs/site-packages directory * the directory from which your main module was loaded * in directories in PYTHONPATH ------------------------------------------------------------------ Thanks in advance! -- Steve Ferg From aahz at pythoncraft.com Thu Jan 22 01:11:53 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 Jan 2004 01:11:53 -0500 Subject: an example of a singleton design pattern in python? References: Message-ID: In article , Jeff Epler wrote: >On Wed, Jan 21, 2004 at 07:38:26PM -0500, Aahz wrote: >> >> * Within a single module, use a global class as your singleton object. > >This is a little bit inconvenient, because you must either mark all >methods as staticmethod (and refer to the class by name), or you must >mark all methods as classmethod. That's assuming one needs methods, of course; many times, the singleton is just used for storing attributes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From __peter__ at web.de Mon Jan 19 12:08:14 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Jan 2004 18:08:14 +0100 Subject: subclassing "file" References: Message-ID: Oops, hit the wrong button. The example goes like so: >>> class myfile(file): ... def __init__(self, op, *args): ... file.__init__(self, *args) ... self.op = op ... def write(self, s): ... file.write(self, self.op(s)) ... >>> f = myfile(lambda s: "-".join(s), "tmp.txt", "w") >>> f.write("a foolish consciousness") >>> f.close() >>> file("tmp.txt").read() 'a- -f-o-o-l-i-s-h- -c-o-n-s-c-i-o-u-s-n-e-s-s' >>> Of course I used *args only because I'm to laze to name the actual arguments one at a time :-) Peter From nospam at nowhere.hu Sun Jan 25 15:22:50 2004 From: nospam at nowhere.hu (Miklós) Date: Sun, 25 Jan 2004 21:22:50 +0100 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: Jack Schofield is an opinionated jackass who spreads Holloween FUD. Guardian's journalists are usually better than that. Best, Mikl?s "malcolm" wrote in message news:64cff82f.0401251143.328388bd at posting.google.com... > Why you can't get something for nothing > Jack Schofield Jan 22 2004 > cheaper but more powerful off-the-shelf packages. From that point of > view, open source is a throwback." > > - http://www.guardian.co.uk/online/story/0,3605,1127802,00.html From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Jan 14 16:07:15 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 14 Jan 2004 22:07:15 +0100 Subject: Quick question..... In-Reply-To: <379178f1.0401141303.62713fbf@posting.google.com> References: <379178f1.0401141303.62713fbf@posting.google.com> Message-ID: <4005af81$0$318$e4fe514c@news.xs4all.nl> Narsil wrote: > I have a list, which consists of just numbers. > > Is there a command that will allow me to total up these numbers and get an average? > > Say for example, the list looks thus: > > numberlist = [10, 2, 5, 7, 3, 46, 4, 5, 87, 5] > > How would I get the total, and how would I get the average? You could have guessed? >>> numberlist=[10, 2, 5, 7, 3, 46, 4, 5, 87, 5] >>> print sum(numberlist) 174 >>> print sum(numberlist)/len(numberlist) # watch out, integer result 17 >>> print float(sum(numberlist))/len(numberlist) # force float result 17.4 --Irmen From donn at u.washington.edu Thu Jan 15 16:09:34 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 15 Jan 2004 13:09:34 -0800 Subject: baffling os.system behavior - differs from command line References: <604fc0ca.0401141750.4dc57782@posting.google.com> Message-ID: In article <604fc0ca.0401141750.4dc57782 at posting.google.com>, even at pondie.com (Ben Floyd) wrote: ... > The command is Slackware's package creation utility, makepkg. It uses > the > current working directory as package source and takes a filename as an > argument to output the newly created package to. Makepkg is > essentially > a tarball creator, wrapped in a nice command. Simple stuff. Here is my > code: > > I have a for loop that reads a file list, like so: > pkg_srcdir = '/packages_source' > pkg_dir = '/packages_tgzs' > ls = os.listdir(pkg_srcdir) > > for name in ls: > build_src = pkg_srcdir + '/' + name > new_filename = pkg_dir + '/' + name + '.tgz' > > # Valid directory? > if not os.path.isdir(build_src): > sys.exit("\nInvalid directory \'" + pkg_srcdir + "\'\n") > > # Go into the new directory > try: os.chdir(build_src) > except os.error, value: > sys.exit("\nInvalid directory: \'" + build_src + "\': " + value[1]) > > # I then execute the command on each result, like so: > # new_filename is correctly assembled, which i can verify > # from printing it out on each loop iteration > os.system('/sbin/makepkg --chown n --linkadd y ' + new_filename) Well, I don't know. In casual inspection I don't notice anything obviously wrong, but then for all I know this isn't the exact code that has the problem anyway. What I could suggest is substitute your own shell script for makepkg, something that prints out its arguments, current working directory and whatever you think might be interesting. The object is to find out exactly what you're asking makepkg to do, since that is evidently a problem. Actually a Python program might be a little better, because "print sys.argv" gives you less ambiguous information than "echo $*", more like "for arg do echo $arg; done" but on one line. The two usage points that occur to me are 1. chdir() affects Python module path resolution. If you chdir to a directory with an "os.py", that would be an obvious if unlikely problem, but also some installations rely on Python's library finding heuristics in a way that is kind of fragile. I may be wrong about that, I don't even want to think about wasting time on this misguided feature. 2. system() can be replaced with spawnv() for an increase in command parameter list reliability. What if some file has spaces? In spawnv(), you don't care, but in system() it's your job to quote it. This is also a security related issue. Donn Cave, donn at u.washington.edu From hove at bccs.no Wed Jan 21 07:42:53 2004 From: hove at bccs.no (Joakim Hove) Date: Wed, 21 Jan 2004 13:42:53 +0100 Subject: Checking for duplicate instances of a script... References: <400e4638$0$19274$626a54ce@news.free.fr> Message-ID: <4ywu7l5v76.fsf@skjellgran.ii.uib.no> "Guillaume Dargaud" writes: > Hello, python beginner here, > How can I make sure that a given script is never run more than once at the > same time in a system ? This can probably be done in *many* different ways, maybe there is even an agreed upon on best solution. This is a small suggestion based on fcntl.flock() (Unix only I am afraid): #!/usr/bin/python import struct, fcntl import sys lockfile = "/tmp/.lock" ## Open a file-descriptor for the lock file. lockH = open(lockfile,"w") ## Try to aquire an exclusive lock on the lock file. try: fcntl.flock(lockH , fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError,e: sys.exit("Lockfile %s already locked - an instance is probably already running" % lockfile) ## ## Your code ... ## ## Release the lock again fcntl.flock(lockH, fcntl.LOCK_UN) -- /--------------------------------------------------------------------\ / Joakim Hove / hove at bccs.no / (55 5) 84076 | \ | Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 | | CMU | 5231 Paradis | \ Thorm?hlensgt.55, 5020 Bergen. | 55 91 28 18 / \--------------------------------------------------------------------/ From nohmad at sub-port.net Sun Jan 11 02:37:25 2004 From: nohmad at sub-port.net (Gyoung-Yoon Noh) Date: 10 Jan 2004 23:37:25 -0800 Subject: Problem in directory working Message-ID: <92ed2954.0401102337.1e705338@posting.google.com> I've written Unix's find-like function using recursive os.listdir() call and generator expression. It seems that error happens in generator expression. Below codes do not work. walk.next() generates StopIteration. When I replace 'yield' with 'print', it works fine. Why this does not work? I've had successively implemented unix-find using os.path.walk(). But I want to combine recursive call and generator expressions. Any comments are welcome. [snip] import os def find(path): if not os.path.exists(path): raise StopIteration if os.path.isdir(path): for l in os.listdir(path): fullpath = os.sep.join((path, l)) find(fullpath) else: yield path if __name__=='__main__': #find('/home/myhome'); raise SystemExit() walk = find('/home/myhome') for i in walk: print i.next() From tjreedy at udel.edu Thu Jan 8 13:55:24 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Jan 2004 13:55:24 -0500 Subject: Descriptor puzzlement References: Message-ID: "John Roth" wrote in message news:vvqjj92il4o1d0 at news.supernews.com... > Using Python 2.2.3, I create this script: > > [beginning of script] > > class AnObject(object): > "This might be a descriptor, but so far it doesn't seem like it" > def __init__(self, somedata): > self.it = somedata > def __get__(self, obj, type=None): > print "in get method" > return self.it > def __set__(self, obj, it): > print "in set method" > self.somedata = it Did you mean to set self.it to match the __init__ and __get__ methods? Or am I missing something about the esoterics of properties? Terry J. Reedy From mark at mceahern.com Sun Jan 18 19:38:54 2004 From: mark at mceahern.com (Mark McEahern) Date: Sun, 18 Jan 2004 18:38:54 -0600 Subject: Printing variable names In-Reply-To: References: Message-ID: <1074472733.5354.2.camel@dev.internal> [Me] > There's no simple answer to this. Consider the fact that you can have > more than one name bound to any given mutable instance. [Dan Bishop] > Why did you specify "mutable"? The same applies to immutable > instances. I didn't think through the immutable issue, that's all. So, in short, no good reason. Cheers, // m From tim.one at comcast.net Sun Jan 18 19:01:00 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 18 Jan 2004 19:01:00 -0500 Subject: Simple (?) Regular Expression Question In-Reply-To: <6747bc9d.0401181545.2b4ffb14@posting.google.com> Message-ID: [Steve Zatz] > Is '@' a special character in regular expressions? Nope. > I am asking because I don't understand the following: > > >>> import re > >>> s = ' @' > >>> re.sub(r'\b@','*',s) > ' @' > >>> s = ' a' > >>> re.sub(r'\ba','*',s) > ' *' \b matches a "word boundary", meaning it has to have a word character on one side (something that matches \w), and a non-word character on the other (something that matches \W), regardless of order. ' @' contains two non-word characters (' ' and '@'), so \b doesn't match anything in it. ' a' contains a non-word character (' ') followed by a word character ('a'), so \b matches (an empty string) betwen those two characters. From cookedm+news at physics.mcmaster.ca Fri Jan 9 15:19:04 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 09 Jan 2004 15:19:04 -0500 Subject: Lua: further investigation and comparisons with Python and Forth References: Message-ID: At some point, "John Benson" wrote: > In the future, you may be able to buy some hardware, talk to a > little Forth kernel in ROM somewhere, decide how to load a real machine > BIOS, and then set it going prior to the actual OS boot. Time machine strikes again! I bought one of those last year. All recent Apple machines do this. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mwilson at the-wire.com Thu Jan 22 10:16:59 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 22 Jan 2004 10:16:59 -0500 Subject: Assignment to slice References: <20040121130236.D8E3.JCARLSON@uci.edu> <20040121185145.C648.JCARLSON@uci.edu> Message-ID: In article <20040121185145.C648.JCARLSON at uci.edu>, Josiah Carlson wrote: > >All 'different' language features are 'unusual' until people get used to >them. While you are currently saying, "I can't believe people don't >think this is strange", the rest of us got over it, and may even be >using the feature to get the job done. I really do rely on asking Python "What's in positions 100 to 103 of this string?" and have Python reply "Nothing". It never occurred to me to try to assign to non-existent slices.. but I'll accept the present behaviour if it means Python stays simple and consistent. The rule for `a=[]; a[4:5]=[1,2,3,4]` seems to result in concatenating a[:4], then [1,2,3,4], then a[5:]. That is: nothing, followed by 1, 2, 3, and 4, then more nothing. >Hell, I think that Perl variables are f-ing weird. In the dozen >languages I've learned over the years, Perl is the only one where you >have to say hey, you this variable I'm accessing now, it is a scalar, >not a string. What the hell is that? On the other hand, Perl users >have gotten used to it, and don't think it is strange. This seems to have emerged from a Perl tendency to implement values as strings wherever possible. You're saying "Use the stringness of this variable, rather than, say, its intness." Weak typing, but it's what lets Perl automatically fill in missing array values with some assurance that it won't all go kaboom in the next statement. Regards. Mel. From none at none.com Tue Jan 13 18:28:20 2004 From: none at none.com (Derek) Date: Tue, 13 Jan 2004 18:28:20 -0500 Subject: I come not to bury C++, but to praise it... References: Message-ID: "John Benson" wrote in message... > I think that C++ was a great exercise, but software > engineering has advanced. Why not take advantage of the > latest packaging of OOP and enjoy the smoother ride? Pick > Java, or Python or whatever pleases you. I'm happy using > C for projects that fit it, and Python for more ambitions > OOP stuff. C++ was a great way to move OOP forward, > but now it looks more like a transitional form than a > best-of-breed. Sic transit gloria mundi, which is Latin for > "when you're hot, your hot; when you're not, you're not" or > something like that. Apples and oranges; there are lots of things C++ does better than Python (or Java) and vice versa. There are lots of factors to consider, not just the "smoother ride" up the learning curve. You also seem to have a narrow view of C++ as a strictly OO language when in fact it supports several programming paradigms (write whatever you want: template metaprograms, modules, procedures, classes, etc.). And while C++ may seem "traditional" compared to fast-moving feature-of-the-week-rich languages, stability can be a Good Thing. That being said, I'm a big fan of Python (and even Java), but I think writing a eulogy for C++ is a bit premature. From cappy2112 at yahoo.com Sun Jan 11 03:41:20 2004 From: cappy2112 at yahoo.com (Tony C) Date: 11 Jan 2004 00:41:20 -0800 Subject: Running pydoc from the Windows XP command line (dos box) Message-ID: <8d3e714e.0401110041.12ede45f@posting.google.com> According to the help for pydoc, it can be run as a script, from the command line. "Or, at the shell command line outside of Python: Run "pydoc " to show documentation on something" However, when I run pydoc from the Windows XP command line, it launches my editor (Codewright) and displays pydoc.py in the editor. I want to be able to use it to display docstrings in my modules, from OUTSIDE of the interactive interpreter. How do I keep my editor from launching when I type pydoc at the command line ? thanks From ben at transversal.com Wed Jan 7 04:27:42 2004 From: ben at transversal.com (Ben) Date: Wed, 07 Jan 2004 09:27:42 +0000 Subject: PEP 310 suggestions Message-ID: <3ffbd106$0$15344$afc38c87@news.easynet.co.uk> I hope its not too late to make these comments as I know the PEP has been around for a while! I've just been reading PEP 310 and have found it very interesting, as the problem it attepts to solve is one of the few things I find annoying about languages like python (coming from a C++ background). It would have been nice to be about to use __init__ and __del__ pairs, but having read the discussion I see that this would be effectively immpossible. While I was reading the PEP a few ideas popped into my head and I wondered if something like them had already been considered. They are probably rubbish, but I thought I would throw them into the mix! 1) If Python had code blocks, something like this would be possible def open_file(file, code_block): try: code_block() finally: file.close() then, f = file("foo") with open_file(f): #Note only passing one argument # do stuff with f This would only work if the code_block could be executed in the scope in which it was written, and not in the one in which it was called. This seems to be more general than the current PEP, but introduces quite massive changes into the language. The idea is that: with func(args): suite goes to func(args, suite) 2) Exit handler blocks. These are kind to backwards try-finally blocks that allow the "close" function to be written close to the "open" one. They also have the advantage that no extra special functions are needed. e.g l = lock.aquire() onexit l.release(): # do stuff while locked is eqivalent to l = lock.aquire() try: # do stuff while locked finally: l.release() The obvious disadvantage is that it may be non-obvious that the release call is delayed to the end of the block Any comments? The main reason I like these methods is that they are both more explicit than the PEP, and don't require the addition of any more special functions. However I can see the disadantages as well! Cheers Ben --- From rganesan at myrealbox.com Sun Jan 11 01:07:38 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Sun, 11 Jan 2004 11:37:38 +0530 Subject: Help with if statement References: Message-ID: >>>>> "Jikosan" == Jikosan writes: > I can't get my "if" statement to work indicated below. What happens is no > matter what the value random is, neg gets incremented by 1. > for x in range(0,N): > random = uniform(-1, 1) > print random > if random < 1.0: <--- Not working > neg = neg+1 Since uniform will return numbers in the interval [-1, 1), all instances of random will be less than 1.0. May be you meant to say random < 0.0? Ganesan -- Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/ 1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832 6798 15E0 02BA 5D8C 12EA From engsolnom at ipns.com Tue Jan 6 20:40:47 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Tue, 06 Jan 2004 17:40:47 -0800 Subject: Finaly found a simple enough task for python, took the plunge, but..... References: <3FFB5312.1030803@connection.com> <3FFB8071.9070107@connection.com> Message-ID: (top posting..sorry) I tried Vincent's suggested code and it works just fine with Win2000, Python2.3. I did change the code to return the path to a selected file, rather than just a directory. Shows the value of the newsgroups...I was unaware (of course us newbies are unaware of lots of things) of tkFileDialog...and was about to write a tk interface to do the same thing. Saved a ton of time, and probably newsgroup bandwidth. Thanks, Vincent! Norm On Tue, 06 Jan 2004 19:43:45 -0800, Sambo wrote: >It did get rid of the blank window but it also does not appear on the task bar( >or get focus), but I can ALT+TAB to it. >maybe it is my Vind-Blows 95. > >Thanks , Sam. > >vincent wehren wrote: > >> "Sam" schrieb im Newsbeitrag >> news:3FFB5312.1030803 at connection.com... >> | Only 2 weeks messing around with it ( thanks to programs like SYNCHRONEX >> and >> | BITORRENT ), and already trying to create windows ( the paths are just too >> long >> | for me to want to type them ). >> | After much trial and error I finaly got the following code to open the >> 'get dir' >> | dialog , but I am getting another blank window titled 'tk' and "NOT >> RESPONDING" >> | When I kill it (end task), I get reiniit/restart (CTRL+F6) in my shell >> window >> | What am I doing wrong? Do I need to do anythink to clean up after using >> the >> | dialogs? >> >> Take a look at the tkFileDialog module. Or better, use it for convenience. >> It already provides some "standard" dialogs. You code would then look >> similar to: >> #----------------------- >> import Tkinter >> import tkFileDialog >> >> def me(): >> root = Tkinter.Tk() >> root.withdraw() # do this to remove the "blank screen" you mention >> dirname = tkFileDialog.askdirectory() >> return dirname >> >> print me() >> #------------------------ >> >> HTH >> >> Vincent Wehren >> >> >> > From peter at engcorp.com Mon Jan 26 14:51:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Jan 2004 14:51:18 -0500 Subject: Guardian: open source is a throwback says Jack Schofield References: <64cff82f.0401251143.328388bd@posting.google.com> Message-ID: <40156FB6.F71C19B0@engcorp.com> Josiah Carlson wrote: > > > Either that or Microsoft. ;-) Or he's plain stupid. > > > > Mikl?s > > Never underestimate the power of stupidity (or ignorance, or denial, or...). > > Speaking of which... > http://www.whitehouse.gov/news/releases/2004/01/20040122-5.html > > - Josiah I'm sorry, really, to bring this up, but as a Canadian I might be a little thick on this point, so help me out: was that site hacked? Or is this for real? -Peter From CousinStanley at hotmail.com Sat Jan 3 08:40:17 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 3 Jan 2004 06:40:17 -0700 Subject: Graph in wxPython References: Message-ID: John .... Perhaps I can add another verse to that song I've been writing called The GTK/PyGtk/wGlade/Wx/MatPlotLib Blues .... You know a couple of verses already .... :-) >>> >>> import matplotlib >>> >>> matplotlib.use( 'WX' ) unrecognized backend WX. Use one of PS, GD, GTK, Template -- Cousin Stanley Human Being Phoenix, Arizona From jcarlson at nospam.uci.edu Fri Jan 23 00:46:35 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 21:46:35 -0800 Subject: cgi concurrency approaches? In-Reply-To: <7x7jzjgso7.fsf@ruckus.brouhaha.com> References: <7x7jzjgso7.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I'm wondering if folks here have favorite lightweight ways of dealing > with concurrency in cgi's. Take a simple case: > > You want to write a cgi that implements a simple counter. The first > time it's called, it prints "1". The next time, "2", etc. The naive > implementation looks something like: > > fd = open("counter.num", "rw") > n = int(fd.read()) > fd.seek(0, 0) > fd.write("%d"% n+1) > print "Content-type: text/html\n\n" > print n > > but of course there's the obvious race condition if two people hit the > cgi at the same time. > > Fancier solutions include running an transactional database in another > process and connecting to it, setting up a daemon that remembers the > counter value in memory and serializes access through a socket that > the cgi opens, using a file-system specific hack like linking to > counter file to lock it, having a timeout/retry if the counter is > locked, with a possible hangup if a lock file gets left around by > accident, etc. Each is a big pain in the neck. > > Anyone have some simpler approaches? I'd just run Xitami (www.xitami.org) and connect a LRWP (Long-Running Web Process). I'm not familliar with Apache, so I don't know if mod_python is equivalent. - Josiah From nav+posts at bandersnatch.org Fri Jan 16 08:49:41 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 16 Jan 2004 08:49:41 -0500 Subject: New candidate for Python mascot References: <5ukkd1-e53.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber writes: > Especially the second... being in the "It will take me home" > category... for dinner... "We used to have three dogs, but then the Python guys changed the mascot..." 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 nhodgson at bigpond.net.au Sat Jan 10 17:46:03 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 10 Jan 2004 22:46:03 GMT Subject: Python And Internationalization maybe a pre-pep? References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Brian Kelley: > I made a new python string type and got enough working on the parser to > accept > > string = i"whatever" I would not like to see strings gain more interpretation prefix characters without very strong justification as the combinational growth makes code interpretation more difficult. The "i" would need to be used in conjunction with the "u" or "U" Unicode prefix and possibly the "r" or "R" raw prefix. The order of interpretation here is reasonably obvious as the internationalization would be applied after the treatment as Unicode and raw. However, when used in conjunction with other proposed prefix characters such as for variable interpolation, the ordering becomes more questionable. Neil From harry.g.george at boeing.com Fri Jan 9 05:29:46 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 9 Jan 2004 10:29:46 GMT Subject: Debugging Python References: <3FFEBDBC.2F9DFD03@engcorp.com> Message-ID: Peter Hansen writes: > Ashley Lloyd wrote: > > > > What do people generally use to debug their Python programs? I haven't seen > > anything out there that walks through the code, but perhaps I'm looking in > > the wrong places? > > When I need to, which is rare, I either use print statements (a very > solid technology dating from, oh, last century sometime ;-), or the > Python debugger module: pdb. > > Actually, all I ever do with pdb is this: > > # this is just before the code that I think is failing > import pdb > pdb.set_trace() > > # code that I'm about to trace through goes here > > > And about the only features of pdb I've had to use are "r", "n", and > the ability to inspect arbitrary variables. > > I'm not sure about others, but when I design and code using test-driven > development (TDD), I tend not to need to debug almost ever. The need > to debug is usually when you aren't sure where a typo, or logic error, > or other mistake has actually occurred. When using TDD, it's exceedingly > rare that when a test fails, I don't know exactly where the problem is > without having to resort to traditional (slow, tedious, annoying) debugging. > > -Peter Interesting. A python newbie asked me the same thing yesterday and I told him almost exactly what you said: If you are doing test-based (whether or not it is with someojne else and thus Agile), you don't get into those grim debug sessions that are part of life in C/C++ land. Actually what I said was something like "If you don't make mistakes, you don't need a debugger. The way to avoid mistakes is to test everytime you edit a line or two of code. "If you need to, use my homegrown debug statements (which print the module and method/function name, the message, and then flush). If you really get stuck, there is a debugger, but typically you just need debuggers to solve memory problems. Python mistakes tend to be much higher level, and pretty obvious once you see the data values." -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From amy-g-art at cox.net Fri Jan 23 18:07:38 2004 From: amy-g-art at cox.net (Amy G) Date: Fri, 23 Jan 2004 15:07:38 -0800 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: Some extra info... when I get this >>> import sys >>> sys.path ['', '/usr/local/lib/python2.2', '/usr/local/lib/python2.2/plat-freebsd5', '/usr/local/lib/python2.2/lib-tk', '/usr/local/lib/python2.2/lib-dynload', '/usr/local/lib/python2.2/site-packages'] Doesn't that mean that the directory is already in the path??? "Michael Spencer" wrote in message news:K4ydna_ey7rvOIzdRVn-jw at comcast.com... > "Amy G" wrote in message > news:PRgQb.16209$AA6.9881 at fed1read03... > > No it won't. Unfortunatly I don't necessarily have a comma delimited date > > string. Thanks for the input though. > > > > The following three date strings is another example of the various date > > formats I will encounter here. > > > > Thursday, 22 January 2004 03:15:06 > > Thursday, January 22, 2004, 03:15:06 > > 2004, Thursday, 22 January 03:15:06 > > > > All of these are essentially the same date... just in various formats. I > > would like to parse through them and get a comparable format so that I can > > display them in chronological order. > > > > > > "wes weston" wrote in message > > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net... > > > Amy, > > > I hope there is a better way but, if you go here: > > > > > > http://www.python.org/doc/current/lib/datetime-date.html > > > > > > The new datetime module may help. This and the time mod > > > should get you where you want to go. > > > > > > list = strdate.split(", ") > > > daystr = list[0] > > > daynum = int(list[1]) > > > monthstr = list[2] > > > year = int(list[3]) > > > #funct to get a month int is needed > > > > > > d = datetime.Date(y,m,d) > > > > > > wes > > > > > > --------------------------------------- > > > > > > Amy G wrote: > > > > I have seen something about this beofore on this forum, but my google > > search > > > > didn't come up with the answer I am looking for. > > > > > > > > I have a list of tuples. Each tuple is in the following format: > > > > > > > > ("data", "moredata", "evenmoredata", "date string") > > > > > > > > The date string is my concern. This is the date stamp from an email. > > > > The problem is that I have a whole bunch of variations when it comes > to > > the > > > > format that the date string is in. For example I could have the > > following > > > > two tuples: > > > > > > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 > > 03:15:06") > > > > > > > > I know there is some way to use the date string from each of these to > > get a > > > > date usable by python, but I cannot figure it out. > > > > I was trying to use time.strptime but have been unsuccesful thus far. > > > > > > > > Any help is appreciated. > > > > > > > > > > > > > > > > > This was asked and answered earlier today > > See: https://moin.conectiva.com.br/DateUtil > > >>> from dateutil.parser import parse > >>> parse("Thursday, 22 January 2004 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> parse("Thursday, January 22, 2004, 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> parse("2004, Thursday, 22 January 03:15:06") > datetime.datetime(2004, 1, 22, 3, 15, 6) > >>> > > > From and-google at doxdesk.com Fri Jan 23 07:06:32 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 23 Jan 2004 04:06:32 -0800 Subject: cgi.fieldstorage not getting POST data References: <606892f8.0401221004.68aac4e2@posting.google.com> Message-ID: <2c60a528.0401230406.42f13efc@posting.google.com> astoltz at yahoo.com (Al Stoltz) wrote: > #!d:/python/python.exe I don't know if this is related to your problem (I haven't tried 2.3 or ActiveState's kit for CGI on Windows), but what you probably want is: #!d:/python/python.exe -u To ensure that newline characters are not fiddled with. This will certainly be necessary if you are dealing with file upload POST requests; see if it also fixes the problem with plain url-encoded POSTs. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From amy-g-art at cox.net Tue Jan 27 21:28:09 2004 From: amy-g-art at cox.net (Amy G) Date: Tue, 27 Jan 2004 18:28:09 -0800 Subject: Confused about a list.sort() Message-ID: I have a list of numbers... actully I have two lists, List 1 is a list of number strings and List2 is one of numbers. List 1 example: List1 = [ '20040124123000', '20040124123001', '20040125012456'] List 2 example: List2 = [ 20040124123000L, 20040124123001L, '20040125012456L] When I try either: List1 = List1.sort ... or List2 = List2.sirt and then... print List1... or print List2 I get None. Why is this? How do I remedy this problem? From carroll at tjc.com Tue Jan 20 14:56:55 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue, 20 Jan 2004 19:56:55 GMT Subject: New to Python: my impression v. Perl/Ruby References: <87ad4kxees.fsf@pobox.com> <100pahdc7d98q58@corp.supernews.com> Message-ID: <8v1r00pf2ubhk4reqcrk5058ufceoe428m@4ax.com> On Mon, 19 Jan 2004 23:09:06 -0500, "Francis Avila" wrote: >Some time ago I wrestled with the Ruby-Python claim-counterclaim to "purity" >in >http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=vug18vkm >jpiice%40corp.supernews.com&rnum=1&prev=/groups%3Fq%3D%2522Francis%2BAvila%2 >522%2Bruby%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3Dvug18vkmjpii >ce%2540corp.supernews.com%26rnum%3D1 > >(Whew) http://tinyurl.com/2exx8 From ptmcg at users.sourceforge.net Wed Jan 21 18:18:40 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Wed, 21 Jan 2004 23:18:40 GMT Subject: Need help with Python class idioms References: <200401212051.50411.james@logicalprogression.net><200401212101.33605.james@logicalprogression.net> Message-ID: "Jonathan Daugherty" wrote in message news:mailman.611.1074719029.12720.python-list at python.org... > # P.S. Since you're asking about idiom, it would be more Pythonic to write: > # > # if self.mandatoryVar1 is None: > # > # using the identity test "is" rather than equality test "==", since there is > # only one None. > > I'd write > > if not self.mandatoryVar1: > > but the first method works, too. > > -- > > Jonathan Daugherty > http://www.cprogrammer.org > > "It's a book about a Spanish guy called Manual, you should read it." > -- Dilbert > ... what if mandatoryVar1 was set to False? -- Paul From reply.in.the.newsgroup at my.address.is.invalid Sun Jan 4 20:14:35 2004 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 05 Jan 2004 02:14:35 +0100 Subject: Need Help Optomizing Code References: Message-ID: Andrew: >and was wondering if anyone out there could help me optomize this code. [...] > self.db = MySQLdb.connect("localhost", "", "", "guestbook") > self.c = self.db.cursor() > self.c.execute("DELETE FROM guests WHERE id LIMIT 1;") ^^^^^^^^^^^^^^^^ What does that mean? > self.results = self.c.fetchall() In general, it's unwise to reconnect to a database server for every single data manipulation. Keep the connection open, and perhaps even the cursor. But I'm not sure if and how this works precisely with MySQL, I prefer PostgreSQL myself. Also, you seem to be forgetting the commit and disconnect. -- Ren? Pijlman From alloydflanagan at comcast.net Mon Jan 26 14:58:29 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 26 Jan 2004 11:58:29 -0800 Subject: I support PEP 326 References: <10105bn3bsi63c9@news.supernews.com> Message-ID: "John Roth" wrote in message news:<10105bn3bsi63c9 at news.supernews.com>... > Just in case anyone can't find the PEP - it's the one that proposes > specific objects that will always sort highest and lowest. > > I'm mildly in favor; it seems to be useful for some cases, and it > also seems easy enough to do. Of course, it would make None > the second smallest object. > > John Roth +1 on the PEP. The names Max and Min seem fine to me, but I'm not married to them. What would be the consequence of making Min and None compare equal? Then the "None as second lowest" issue goes away. I can't think of an example where that would cause problems, but there probably are some... From premshree_python at yahoo.co.in Mon Jan 12 12:07:18 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 12 Jan 2004 17:07:18 +0000 (GMT) Subject: Using switches with exec? In-Reply-To: Message-ID: <20040112170718.38245.qmail@web8310.mail.in.yahoo.com> --- "Diez B. Roggisch" wrote: > > I need to run a Python program dynamically within > > another program. I am using exec for the purpose. > Is > > there a way to pass parameter switches to exec? > > You can pass a globals-dictionary to exec, which can > hold the switches > values. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list Could you please elucidate with a sample script. Suppose I need to pass the switch "-w" to the dynamically loaded code (using eval()/exec()). Any help is appreciated. -Premshree ________________________________________________________________________ Yahoo! India Mobile: Download the latest polyphonic ringtones. Go to http://in.mobile.yahoo.com From peter at engcorp.com Wed Jan 28 09:27:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Jan 2004 09:27:58 -0500 Subject: Distributing Python programs References: <4017abb7$0$9394$ed9e5944@reading.news.pipex.net> Message-ID: <4017C6EE.E7F1B27@engcorp.com> NEWS wrote: > > Can I install Python on a networked server and have any user run Python > programs without having to go through the 9Mb client install? Yes, we run dozens of machines from a single network installation. Depending on what extensions you need to install (e.g. win32all) you may need to make some small manual adjustments to get it to work, but in essence you can just do a "non-admin" local install, then copy the entire directory tree to the network. > What are my options for distributing Python programs to my users? py2exe: http://starship.python.net/crew/theller/py2exe/ the Macmillan Installer: http://www.mcmillan-inc.com/installer_dnld.html etc... -Peter From computer.problemen at skynet.be Thu Jan 8 17:50:37 2004 From: computer.problemen at skynet.be (broebel) Date: Thu, 8 Jan 2004 23:50:37 +0100 Subject: python newbie Message-ID: <3ffddcfd$0$16662$ba620e4c@news.skynet.be> hey, I'm a newbie in the programming world. I just started and already I'm in a whole lot of problems. first problem is the fact that I started out with a little program who was part of a course but the problem is when I launch the program. I don't have the time to see the result because the screen closes immediately. Can anyone explain what's happening. thanks in advance me, # Een bedrag gepast betalen met zo min mogelijk euromunten bedrag = input ( 'Geef bedrag tussen 0 en 500 eurocent: ' ) for munt in 200, 100, 50, 20, 10, 5, 2, 1 : aantal = 0 while bedrag >= munt : aantal = aantal + 1 bedrag = bedrag - munt if aantal > 0 : print aantal, 'x', munt From tchur at optushome.com.au Fri Jan 9 16:44:22 2004 From: tchur at optushome.com.au (Tim Churches) Date: 10 Jan 2004 08:44:22 +1100 Subject: Python is far from a top performer according to benchmark test... In-Reply-To: References: Message-ID: <1073684662.1185.11.camel@emilio> On Sat, 2004-01-10 at 08:05, Carl wrote: > "Nine Language Performance Round-up: Benchmarking Math & File I/O" > http://www.osnews.com/story.php?news_id=5602 > > I think this is an unfair comparison! I wouldn't dream of developing a > numerical application in Python without using prebuilt numerical libraries > and data objects such as dictionaries and lists. Benchmarks like those reported are nearly worthless, but nevertheless, it would be interesting to re-run the them using Numeric Python and/or Pyrex. I notice that the author of those benchmarks, Christopher W. Cowell-Shah, has a PhD in philosophy. Perhaps Python's very own philosophy PhD, David Mertz, might like to repeat the benchmarking exercise for one of his columns, but including manipulation of more realistic data structures such as lists, arrays and dictionaries, as Carl suggests. I'm sure it would be a popular article, and provide a counterpoint to the good Dr Mertz's previous articles on Psyco. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From robert_dodier at yahoo.com Sat Jan 31 10:46:00 2004 From: robert_dodier at yahoo.com (Robert Dodier) Date: 31 Jan 2004 07:46:00 -0800 Subject: Safe to modify globals(), or not? References: <6714766d.0401291559.45413e0d@posting.google.com> Message-ID: <6714766d.0401310746.7be60dd3@posting.google.com> Peter Otten <__peter__ at web.de> wrote: [...] > > import sys > import __main__ > setattr(sys.modules["__main__"], "name", "value") > __main__.anotherName = "another value" > Thanks a lot, Peter, this is just the right thing. I guess modifying globals() is a non-issue, as it turns out. I appreciate your help. Robert Dodier From tr at jotsite.com Sat Jan 24 10:44:05 2004 From: tr at jotsite.com (Hoang) Date: Sat, 24 Jan 2004 15:44:05 GMT Subject: progress bar References: <59e5b87.0401231329.6e084d6f@posting.google.com> Message-ID: <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> > > Try Venster: > http://venster.sourceforge.net > > IIRC the test_coolbar.py script includes a progress bar. I wonder what possessed someone to start another GUI framework. Aren't there more than enough existing ones? The reasoning for it wasn't immediately apparent on the web page. Hoang Do http://jotsite.com From scottdog at nospam.com Tue Jan 20 18:21:27 2004 From: scottdog at nospam.com (Dog@will.hunt) Date: Tue, 20 Jan 2004 15:21:27 -0800 Subject: Installing SpamBayes References: <400c399b_2@newsfeed.slurp.net> <400c451a_1@newsfeed.slurp.net> <20040120135921.1C3F.JCARLSON@uci.edu> <400c5790_1@newsfeed.slurp.net> <20040120150005.1C48.JCARLSON@uci.edu> Message-ID: <400c6146_1@newsfeed.slurp.net> I think that may be my problem. I am not sure how to change the path to where the setup.py file is... "Josiah Carlson" wrote in message news:20040120150005.1C48.JCARLSON at uci.edu... > > That didnt work either and the file assoc. are correct. > > > > > If you are in windows and your associations are correct, try: > > > setup.py install > > Steps for you to help us help you: > 1. Open up a console. > 2. Change to the proper path. > 3. Run (without the single quotes) > 'python setup.py install' > if that doesn't work, try > 'setup.py install' > 4. Copy and paste the output in a message here. > > - Josiah > From val at vtek.com Wed Jan 28 15:21:07 2004 From: val at vtek.com (val) Date: Wed, 28 Jan 2004 15:21:07 -0500 Subject: Webhosting with Python References: <8089854e.0401280834.6fd4f972@posting.google.com> Message-ID: Sorry, i didn't find any mention of Python. Can you please point me in right direction? val val at vtek dot com "Kevin Ballard" wrote in message news:bv8pch$2lhu$1 at bigboote.WPI.EDU... > On 2004-01-28 11:34:43 -0500, michael at foord.net (Fuzzyman) said: > > > I've recently starting using a very cheap web hoster who has python > > 2.2 installed.... almost free hosting (but not quite)..... > > > > Thought some of you guys might be interested.......... > > > > http://www.xennos.com > > > > Fuzzyman > > How do you plan to make money off of this? From jepler at unpythonic.net Tue Jan 20 20:41:29 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Jan 2004 19:41:29 -0600 Subject: Pyrex without Python (was Re: calling Pyrex results from C) In-Reply-To: <400DD5DE.90405@prescod.net> References: <20040121005749.GA27424@unpythonic.net> <400DD5DE.90405@prescod.net> Message-ID: <20040121014129.GB27424@unpythonic.net> On Tue, Jan 20, 2004 at 05:29:02PM -0800, Paul Prescod wrote: > What exactly would Pyrex buy you if you can't afford to > use its high-level features like memory management, constructors and OO? Two reasons, both of them tongue in cheek: 1. my {} keys are broken, so it's perfect to not use C and to use an environment where I can't use dicts either 2. the people programming small machines are all out do to crazy stuff, and so programming mine in "Python" (pyrex) would be along those lines. The closest to a real reason would be along the lines of 1, the pleasure of avoiding the C syntax. But since I write enough C/C++ at work that I'll never stop being familiar with it, that isn't too important for me. Seriously, it's probably not that useful. But it is something that's been bubbling around in my skull off and on. Jeff From jiba at tuxfamily.org Thu Jan 8 09:08:35 2004 From: jiba at tuxfamily.org (Jiba) Date: Thu, 8 Jan 2004 15:08:35 +0100 Subject: unicode keys in dicts Message-ID: <20040108150835.7242ef01.jiba@tuxfamily.org> Hi all, is the following behaviour normal : >>> d = {"?" : 1} >>> d["?"] 1 >>> d[u"?"] Traceback (most recent call last): File "", line 1, in ? KeyError: u'\xe9' it seems that "?" and u"?" are not considered as the same key (in Python 2.3.3). Though they have the same hash code (returned by hash()). And "e" and u"e" (non accentuated characters) are considered as the same ! Jiba From frank at pc-nett.no Fri Jan 9 17:19:37 2004 From: frank at pc-nett.no (frank) Date: Fri, 9 Jan 2004 23:19:37 +0100 Subject: wxpython AttributeError! Message-ID: need help with wxpython. wxpython code is made with boa-constructor when i run the code i get this error message: Traceback (most recent call last): File "wxApp1.py", line 24, in ? main() File "wxApp1.py", line 20, in main application = BoaApp(0) File "K:\Python23\lib\site-packages\wxPython\wx.py", line 1945, in __init__ _wxStart(self.OnInit) File "wxApp1.py", line 13, in OnInit self.main = wxFrame1.create(None) File "wxFrame1.py", line 12, in create return wxFrame1(parent) File "wxFrame1.py", line 220, in __init__ self._init_ctrls(parent) File "wxFrame1.py", line 157, in _init_ctrls EVT_RIGHT_DOWN(self.treeCtrl1, self.OnTreectrl1RightDown) AttributeError: wxFrame1 instance has no attribute 'OnTreectrl1RightDown' 23:06:44: Debug: c:\PROJECTS\wx\src\msw\app.cpp(439): 'UnregisterClass(canvas)' failed with error 0x00000584 (class still has open windows.). this is the code have this code: self.treeCtrl1 = wxTreeCtrl(id=wxID_WXFRAME1TREECTRL1, name='treeCtrl1', parent=self.splitterWindow1, pos=wxPoint(2, 2), size=wxSize(200, 610), style=wxTR_HAS_BUTTONS, validator=wxDefaultValidator) self.treeCtrl1.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxNORMAL, False, 'Microsoft Sans Serif')) EVT_RIGHT_DOWN(self.treeCtrl1, self.OnTreectrl1RightDown) EVT_TREE_SEL_CHANGED(self.treeCtrl1, wxID_WXFRAME1TREECTRL1, self.OnTreectrl1TreeSelChanged) and the event EVT_RIGHT_DOWN code is: def OnTreectrl1RightDown(self, event): dosomething() event.Skip() the "OnTreectrl1RightDown" is in the wxframe class what to do? thanx in advance From ark at acm.org Thu Jan 15 10:53:25 2004 From: ark at acm.org (Andrew Koenig) Date: Thu, 15 Jan 2004 15:53:25 GMT Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> <8765ferltj.fsf@pobox.com> Message-ID: > The argument runs like this: If you don't have near-100% test > coverage, you are missing many bugs that static typechecking will not > catch. So don't do that (the fact that it's perfectly feasible to > have near-100% coverage, when given support from bosses where > relevant, has been repeatedly demonstrated recently). OTOH, if you do > have 100% coverage, the set of bugs that *are* caught by the static > typechecks, but *not* by the tests is usually very small, in practice. There is a subtle fallacy in this argument, at least in the context of C++ and Python, namely that there is a significant category of errors that static type checking (as C++ and some other languages do it) can detect but can escape even 100% test coverage. Before you get out your flame-thrower, please hear me out -- I am not saying that this reasoning applies to all errors, or even a majority of them, but only to a significant category. That category consists of programs where the types of key objects are not known when the program is written, but are known when the program is compiled. Here's an example. Suppose you're writing a library sort function, which you intend to be able to work with any kind of sequence. Suppose further that you test it only with vectors. Then you might well have 100% test coverage, but the code might break when you call it with another kind of sequence, because it relies on some property of vectors that not all sequences share. In practice, C++ programmers often solve such problems by using templates, which defer type checking until the last possible moment during the compilation process. In effect, the compiler looks at each call to our hypothetical sort function, and verifies that the type assumptions that the sort function makes are valid in the context of that particular call. The result is that the compiler can detect type errors that would show up in a dynamically typed environment only if the function were tested with the specific types that revealed the error. The price one pays for this extra checking, of course, is that one cannot call such a sort function with an argument with a type that is known only at run time. But in practice, there are many cases where being able to defer type checking until the end of compilation is just as useful as being able to defer it until run time. I believe that many people who dislike static type checking are unaware of this distinction. From h.goebel at crazy-compilers.com Sat Jan 3 14:15:17 2004 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Sat, 03 Jan 2004 20:15:17 +0100 Subject: Simple way to get the full path of a running script? In-Reply-To: References: Message-ID: <3ff713bc$0$17557$9b4e6d93@newsread4.arcor-online.net> Hi, Wolfgang Lipp schrieb: > import inspect > print inspect.getsourcefile( lambda:None ) Nice idea! Enhancement: when using inspect.getfile() the snippet will work even for module without sourcefile, too. -- Regards Hartmut Goebel | Hartmut Goebel | We build the crazy compilers | | h.goebel at crazy-compilers.com | Compiler Manufacturer | From python at hitmedia.com Wed Jan 28 17:55:03 2004 From: python at hitmedia.com (Python Baby) Date: Wed, 28 Jan 2004 14:55:03 -0800 Subject: looking for a good freelance teacher (paid) for OOP consulting Message-ID: <20040128225503.GA71050@mail.hitmedia.com> I'm learning Python and Object-Oriented Programming from books and online resources. But I really need a good teacher or consultant to have conversations about the OO design of my current projects, and using Python to its best. I would probably need 1-2 hours a week of time, and could pay OK, though not a fortune. It would have to be someone with both teaching experience (good at explaining) and real-world programming experience (good at doing.) Phone calls are fine. Doesn't need to be in person. If interested, please reply to this email (python at hitmedia.com) - keeping the subject header the same, so I don't miss it. Thanks! From gerrit at nl.linux.org Thu Jan 15 09:18:09 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 15 Jan 2004 15:18:09 +0100 Subject: TUPLE & LIST In-Reply-To: <%7xNb.55$Uw3.50@newsr2.u-net.net> References: <%7xNb.55$Uw3.50@newsr2.u-net.net> Message-ID: <20040115141809.GA4156@nl.linux.org> Hi Yomanium Yoth Taripo?t II (cool name!), Yomanium Yoth Taripo?t II wrote: > 1) what are the differences between list and tuple? > 2) how to concatenate tuple and list? no method, no op?rator? > 3) im looking the fucking manual, and cant add value in my tuple, when it > already created :/ > how to do it? This question is answered in the FAQ: http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, os.listdir('.') returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory. Tuples are immutable, meaning that once a tuple has been created, you can't replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list's elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys. yours, Gerrit. -- 198. If he put out the eye of a freed man, or break the bone of a freed man, he shall pay one gold mina. -- 1780 BC, Hammurabi, Code of Law -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From p at trick.lu Sat Jan 3 08:44:30 2004 From: p at trick.lu (Patrick Useldinger) Date: Sat, 03 Jan 2004 14:44:30 +0100 Subject: Text-to-HTML processing program References: Message-ID: <7ohdvv097e8pq6bmncjtvlluh8hsnaoq4c@4ax.com> On Sat, 3 Jan 2004 05:51:33 +0000, philh at invalid.email.address (phil hunt) wrote: >Does anyone know of a text-to-HTML processing program, ideally >written in Python because I'll probably be wanting to make small I like http://txt2tags.sourceforge.net/, used it to design my homepage. -- http://www.homepages.lu/pu/ From EP at zomething.com Sun Jan 25 23:47:07 2004 From: EP at zomething.com (EP) Date: Sun, 25 Jan 2004 20:47:07 -0800 Subject: Unique ID for CD or DVD In-Reply-To: <69TQb.15674$Le1.6291@newssvr27.news.prodigy.com> Message-ID: <5.2.0.9.0.20040125203226.00b7ed50@mail.zomething.com> Hoang Do, apparently unapprised of the conspiracy wrote: >Does anyone know of an existing algorithm/module for generating a unique ID >for a given CD or DVD? This would be something akin to CDDB where a CD is >recognized based on its content. I could be wrong, but I think CDDB is just >based on file size or disk size and this alone is not unique enough. If the >solution is in Python, all the better. The music industry uses a unique "key" called The International Standard Recording Code (ISRC) number for CDs and it is my understanding that Gracenote/CDDB was using that key in their database, though I'm not sure if that's the current schema. I'd bet it is though. Not sure about DVD's. Eric "Who'd be thrilled to talk music/programming projects offline" From colarte at telesat.com.co Sat Jan 24 09:11:13 2004 From: colarte at telesat.com.co (camilo olarte) Date: Sat, 24 Jan 2004 09:11:13 -0500 Subject: [Q] Pyython and curses/ncurses/snack/tinter/... Message-ID: <200401241410.i0OEASax025797@loky.telesat.com.co> check this links, : http://pdcurses.sourceforge.net/ curses for window: http://flangy.com/dev/python/curses/ http://www.gnuenterprise.org/~jcater/snapshots/nstti/README.txt Camilo Olarte From timr at probo.com Sun Jan 11 20:59:58 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 11 Jan 2004 17:59:58 -0800 Subject: Using .seek(0) to read. References: <5PHLb.63142$BQ5.4900@fed1read03> Message-ID: <9pv300pcgguanquore1bfmkq3kf14u9ej4@4ax.com> "Amy G" wrote: > >I got this respnse on a prior post. Peter was correct about not needing to >compare the old contents, and I was able to easily fix my code by taking out >any read. > >However, now I need to open the file in "r+" mode and do a >.seek(0) on it. I am opening up the .procmailrc file for each >user in a database that has a "save_junkmail" == 1 and inserting some lines. >They need to be inserted in the correct spot and each user has a different >number of lines in their .procmailrc. Everything prints out correctly. I >now want to write the lines instead of printing to stdout. You can't easily insert data in the middle of a text file. What you need to do is create a NEW file, and copy the data from OLD to NEW, adding your new lines at the appropriate spot. Then close both files, and rename them into place: os.remove( '.procmailrc.was' ) os.rename( '.procmailrc', '.procmailrc.was' ) os.rename( '.procmailrc.new', '.procmailrc' ) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From lubowiecka at go2.pl Thu Jan 8 04:43:54 2004 From: lubowiecka at go2.pl (Nazgul) Date: Thu, 8 Jan 2004 10:43:54 +0100 Subject: "Interrupted function call" exception in Python service while relogging Message-ID: Hi! Sorry if I posted it twice... I need your help... I have the following problem. I've implemented the python Windows Service which behaves like a log supervisor. If the space used by log files is bigger than a given upper limit, then it starts to delete log files until the space is less than a given lower limit. I configured the service to start up automatically on system boot. The script checks the space used by log files every 1000 secs. After analyse of the space, it falls asleep (time.sleep(1000)). Everything works OK, except one thing... Since the service is not tied to the user ID of the person starting it, the service should remain open even when that person who started it logs off. So I made an experiment and relogged. After that it turned out that the service stopped working. The Event Viewer returned the error: "SvcDoRun time.sleep(1000) exceptions.IOError: [Errno 4] Interrupted function call " I use Window XP OS and Python and Python 2.3.2 I guess that some asynchronous signal was caught by the process during the execution of an interruptible function (time.sleep(1000)). Maybe it happened while pressing Ctrl+Alt+Del sequence during logging? Maybe I should add some signal handling? Unfortunately the Windows signal implementation is limited to 6 signals(?): SIGABRT Abnormal termination SIGFPE Floating-point error SIGILL Illegal instruction SIGINT CTRL+C signal SIGSEGV Illegal storage access SIGTERM Termination request Please help me... Best wishes, Sylwia From james at logicalprogression.net Fri Jan 16 13:23:34 2004 From: james at logicalprogression.net (James Henderson) Date: Fri, 16 Jan 2004 18:23:34 +0000 Subject: data structures module In-Reply-To: <92c59a2c.0401152306.1c6a17f5@posting.google.com> References: <92c59a2c.0401152306.1c6a17f5@posting.google.com> Message-ID: <200401161823.34095.james@logicalprogression.net> On Friday 16 January 2004 7:06 am, MetalOne wrote: > Today, I wanted a priority queue. > I notice that Python does not have any sorted lists. > I know that I can call list.sort(), but that seems rather inefficient > to call every time an element is added. You've already had several good suggestions. I'll just add: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87369 In the paper version of the Python Cookbook Tim says he has a special fondness for it, so it must be good! > I am wondering why there is not a module or modules containing many > common data structures. Has such a thing been decided against? Is it > that just nobody has done it? Has nobody else suggested the need for > it? The python-dev list has been discussing the introduction of a data structures package. Looking at the thread called "collections module" might give you an insight to the thought processes involved. James -- James Henderson, Logical Progression Ltd. http://www.logicalprogression.net/ From jepler at unpythonic.net Wed Jan 28 16:09:48 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jan 2004 15:09:48 -0600 Subject: executing an external app In-Reply-To: References: Message-ID: <20040128210948.GZ18498@unpythonic.net> Try one or more of these: os.system, os.spawn*, popen2.*, os.fork + os.exec* (where os.fork is supported, at least), popen5 (third-party module, posix/unix only), win32??? (not sure of name, included in win32all, for Windows only) Jeff From __peter__ at web.de Sun Jan 4 09:11:05 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jan 2004 15:11:05 +0100 Subject: how to make a code object a function References: Message-ID: Diez B. Roggisch wrote: > Hi, > > I've got code objects that are created from strings at runtime that look > like this: > > def p_op1(_, args): > _.add_dependency('p_op1') > > As you migth guess, p_op1 is supposed to become an instance method. Now > how do I make this code object a function-object that can be set into the > instances __dict__ to make it a callable method? Too lazy to type self? >>> import types >>> class T(object): ... def add_dependency(self, name): ... print "adding dependency", name ... >>> t = T() >>> def p_op1(_, args): ... _.add_dependency("p_op1") ... >>> t.p_op1 = types.MethodType(p_op1, t) >>> t.p_op1(1) adding dependency p_op1 >>> By the way, types.MethodType and new.instancemethod seem to be equivalent. Peter From virusalert at chaseonline.chase.com Tue Jan 27 07:39:53 2004 From: virusalert at chaseonline.chase.com (virusalert at chaseonline.chase.com) Date: Tue, 27 Jan 2004 07:39:53 -0500 Subject: Virus Alert - ScanMail for Lotus Notes-->hello Message-ID: Dear Chase Customer, Recently, you sent Chase an e-mail through the Chase Online Message Center that included an attached file. For protection, our e-mail system automatically scans all incoming e-mail messages using an anti-virus program. This scan indicated that a virus was present within your attachment. The attachment was deleted however the remainder of your message has still been delivered to Chase and will be responded to. Thank you, Thank you, Chase Banker Date: 1/27/2004 7:39:53 Subject: hello Virus: WORM_MIMAIL.R File: message.zip From: python-list at python.org To: signup_confirm at chaseonline.chase.com; Action: Uncleanable, Quarantined; Scanned by ScanMail for Lotus Notes 2.5 with scanengine 6.150-1001 and patternfile lpt$vpn.743 From miki.tebeka at zoran.com Thu Jan 15 05:11:11 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 15 Jan 2004 02:11:11 -0800 Subject: Why gmp is not in the standard library? Message-ID: <4f0a9fdb.0401150211.615a7f45@posting.google.com> Hello All, On a different thread Skip wrote: > Yes, you're right. Starting at 2**1000 I found three safe primes quite > quickly. Using my version I gave up waiting after seeing one safe prime > float by. Which made me think why Python don't use gmp as it's primary math package - we'll get fast results, a lot of number types and much more. Can't think of any reason why Python is implementing its own long numbers... Can you enlighten me? Thanks. Miki From sross at connectmail.carleton.ca Sat Jan 31 15:28:59 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 31 Jan 2004 15:28:59 -0500 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> <711c7390.0401311134.26cd0a11@posting.google.com> Message-ID: "Daniel Ehrenberg" wrote in message news:711c7390.0401311134.26cd0a11 at posting.google.com... [snip] > (everything is public and methods > can be called with just references), Okay. So, is there no way to have private attributes/operations? Or, like in Python, is there just a convention? "_slotName" [snip] >Also, when initializing variables, > their scope must be specified (which is the whole reason for the > difference between := and =), so id := allocated should probably be > self id := allocated. self, along with a few other variables, is > implicitly sent to all functions (and do). Okay. So, if I set 'self id', like so self id := allocated and want to update it later in the same block I can use id = "updated self 'id' slot value" But, if I later use id := "set new local 'id' slot value" in the same block I get a new local variable. Is that how it works? Or does the first use of a slot determine its assignment scope for the duration of the block? self a := "unchanged" a := "changed" write("self a is ", self a) # changed or unchanged? From mwh at python.net Thu Jan 8 08:01:08 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 8 Jan 2004 13:01:08 GMT Subject: Descriptor puzzlement References: Message-ID: "John Roth" writes: [snippety] > It doesn't look like the descriptor protocol is getting > invoked at all. > > What's happening here? Descriptors need to be attached to classes. Cheers, mwh -- 6. Symmetry is a complexity-reducing concept (co-routines include subroutines); seek it everywhere. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From michael at foord.net Wed Jan 28 08:57:04 2004 From: michael at foord.net (Fuzzyman) Date: 28 Jan 2004 05:57:04 -0800 Subject: Cross Platform Browser Launcher References: Message-ID: <8089854e.0401280557.29e60991@posting.google.com> Pieter Claerhout wrote in message news:... > Take a look at the webbrowser module... > http://www.python.org/doc/current/lib/module-webbrowser.html > > Cheers, > Great - looks good. Thanks Fuzzy > > pieter > > Creo > pieter claerhout | product support prinergy | tel: +32 2 352 2511 | > pieter.claerhout at creo.com | www.creo.com > > IMAGINE CREATE BELIEVE(tm) > > > -----Original Message----- > From: michael at foord.net [mailto:michael at foord.net] > Sent: 28 January 2004 10:18 > To: python-list at python.org > Subject: Cross Platform Browser Launcher > > > I've written a simple application in python with an HTML help file. > > I'm looking for a cross platform way of launching the help file. > > On windows I'd use : > os.system('start help.html') > > Which automatically opens the file with the users browser. > > Is there a cross-platform way of doing the same thing ? > I can do a platform test and use different techniques for different > systems - but I don't know how to achieve the same effect on a Linux > (Unix ? Mac ?) machine..... > > Any help appreciated. > > Fuzzy > > -- > > > 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.voidspace.org.uk/atlantibots/pythonutils.html > Python functions - home of dateutils, ConfigObj, StandOut, CGI-News > and more.... > > -- > > 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 lbates at swamisoft.com Wed Jan 28 14:54:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 28 Jan 2004 13:54:07 -0600 Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Message-ID: ReportLab Graphics is nice (www.reportlab.org). -Larry "Lothar Scholz" wrote in message news:6ee58e07.0401280403.3d52a9e0 at posting.google.com... > Hello, > > is there something like "JpGraph" for python ? > For those who don't know this PHP library: It is a high level > drawing library that generates gif files with all kind of charts. > > Or (maybe better) is there a C library doing this. I think i > read about something like this a while ago. From swalters_usenet at yahoo.com Sun Jan 18 17:03:19 2004 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Sun, 18 Jan 2004 22:03:19 GMT Subject: Using python for _large_ projects like IDE References: <930ba99a.0401180625.5863acd4@posting.google.com> <22zOb.2835$Zk3.135@newssvr29.news.prodigy.com> Message-ID: | DilbertFan said | > If you do write this IDE, please include a compiler warning that catches > the missing () at the end of a function that doesn't have arguments. I've > sunk into a dark world of a diabolically mind-destroying hysteria while > trying to troubleshoot some scripts, and then realizing that a python > function was not executing because I was calling it without '()'. But > Python doesn't complain, or give you a message or anything,... it simply > doesn't execute that function! Try PyChecker. It should warn you about such things. http://pychecker.sourceforge.net/ HTH Sam Walters. -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From christianjauvin at videotron.ca Wed Jan 21 11:55:21 2004 From: christianjauvin at videotron.ca (Christian Jauvin) Date: Wed, 21 Jan 2004 11:55:21 -0500 Subject: newbie: "File Buffered" Text widget Message-ID: Hello, I need a "File Buffered" Text widget (in Tkinter), that is a window over a buffered text file which would behave as if the entire file was loaded in memory (permitting the user to browse huge corpora text files). Before writing one from scratch, I would like to be sure that there is no such thing available somewhere. Thanks! From skip at pobox.com Fri Jan 2 11:01:48 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 2 Jan 2004 10:01:48 -0600 Subject: optparse bug? In-Reply-To: References: Message-ID: <16373.38380.162607.757665@montanaro.dyndns.org> Andres> script foo: Andres> Andres> Andres> script bar: Andres> from foo import some_function Andres> Andres> When I do ./bar --help I get foo's options! Perhaps you expect foo to be executed standalone? If so, wrap the script init stuff in if __name__ == "__main__": That way you can run it standalone (when you do need optparse) and import it as a module (when you don't need optparse). Skip From dck at gazeta.pl Mon Jan 26 06:32:17 2004 From: dck at gazeta.pl (DCK) Date: 26 Jan 2004 03:32:17 -0800 Subject: TELNET instead PING Message-ID: <5f505344.0401260332.184d4225@posting.google.com> Hello :) Into group-archive i found most e-mails, which touches PINGing. In my work i've used TELNET for testing if host is operational. Sometimes, for unknown reasons, workstation doesn't respond for PINGing. But in WinNT network, all hosts has a nbsession listening on port 139. I always use this script instead PING command (hope, will be usefull for someone :) ): """ TelPing.py - Simple Python script to probe workstation in WinNT Network (c) 2004 Michal Kaczor (26.01.2004) dck at gazeta.pl """ import telnetlib import sys def tel_ping(tn_host,tn_port): try: tn = telnetlib.Telnet(tn_host,tn_port) print 'Host:',tn_host,' Port:',tn_port,' <-- CONNECTED' tn.close() except: print 'Host:',tn_host,' Port:',tn_port,' <-- Error: NO CONNECTION' def main(): if (len(sys.argv)==3): tel_ping(sys.argv[1],sys.argv[2]) else: print 'Usage: telping.py ' if __name__ == "__main__": main() From d.chirila at finsiel.ro Fri Jan 30 09:16:12 2004 From: d.chirila at finsiel.ro (Dragos Chirila) Date: Fri, 30 Jan 2004 16:16:12 +0200 Subject: NEWLINE character problem Message-ID: <011101c3e73b$9da26c20$2f01a8c0@dchirila> Hi I have a string and I want to split it by NEWLINE character. It is knowned that "Microsoft Windows, Apple's Macintosh OS and various UNIX, all use different characters to mark the ends of lines in text files. Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a two-character sequence of a carriage return plus a newline". So, PLEASE don't tell me to use 'split' by '\n' because it won't work. I know about the Python support, opening files with 'U' flag, for reading in universal newline mode. But this is not the case. My script receives a string, can be the content of a file text from Windows or Unix system. I want to make sure that I can split this string by NEWLINE character. Any idea will be appreciated. Thanks a lot. Dragos From bignose-hates-spam at and-benfinney-does-too.id.au Thu Jan 22 05:21:43 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 22 Jan 2004 21:11:43 +1050 Subject: Side note: Praise to the contibuters to this group References: Message-ID: On Wed, 21 Jan 2004 17:41:56 -0800, Amy G wrote: > So, thank you. Thank you to all who have helped me, and to all who > have helped others to better understand this awesome programming > language. Seconded. I think that the subject matter itself (the programming language Python) bears a significant part of the credit. Its design has at least two effects that contribute to the helpfulness of comp.lang.python denizens. One is that the language is so much easier to get things done in, than many other languages. Python programmers are less stressful, less defensive of "tricks", less jealous of arcane knowledge -- because all those things are not so common in Python. Things just work, without tricks, far more often than with other languages. Another is that it's possible to experiment directly at the Python prompt to prove a point, or verify the behaviour being described by someone seeking explanation; and then to cut & paste the result directly in a reply. This leads to a much reduced effort to help someone asking a question, leading to more responses, and better ones. But the bulk of the credit must go to the contributors' willingness to help. Thanks, all. -- \ "I went to a general store. They wouldn't let me buy anything | `\ specifically." -- Steven Wright | _o__) | Ben Finney From shaleh at speakeasy.net Fri Jan 30 02:48:57 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Thu, 29 Jan 2004 23:48:57 -0800 Subject: Sort by key, then by content In-Reply-To: <9A8139BC-52F3-11D8-9115-000A959CB2EC@netmail.to> References: <9A8139BC-52F3-11D8-9115-000A959CB2EC@netmail.to> Message-ID: <200401292348.57424.shaleh@speakeasy.net> On Thursday 29 January 2004 23:12, Wayne Folta wrote: > As an experiment, I've written a Python script which reads my mailboxes > and prints a report on how many messages I've gotten from from each > unique sender. I use a dictionary with a key of the email address and > each entry is a list with the 0th element being the user's name (if > known) and the 1st being the count. > > At the end, I print the report, sorted by email address. But then I > want to print it sorted by frequency of message. What would be the most > efficient, idiomatic, iterative, functional way to do that. After some > head-twisting (it's way past my bedtime), I finally figured that > heapq's would help me, but it seems there should be a cool way to turn > the dict into a list (map) and also turn it inside out at the same > time... > > > Any suggestions? How's this? >>> d = {'shaleh@': ['Sean Perry', 12], 'lesley@': ['Lesley Perry', 34], 'dean@': ['Dean Perry', 100]} >>> contents = zip(d.keys(), d.values()) >>> contents.sort() >>> contents [('dean@', ['Dean Perry', 100]), ('lesley@', ['Lesley Perry', 34]), ('shaleh@', ['Sean Perry', 12])] >>> contents.sort(lambda x,y: cmp(x[1][1], y[1][1])) >>> contents [('shaleh@', ['Sean Perry', 12]), ('lesley@', ['Lesley Perry', 34]), ('dean@', ['Dean Perry', 100])] From jepler at unpythonic.net Fri Jan 9 15:15:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 9 Jan 2004 14:15:13 -0600 Subject: Tcl/Tk Support In-Reply-To: References: Message-ID: <20040109201513.GC2810@unpythonic.net> try installing the RPM called tkinter-2.2.2-26.i386.rpm Jeff From diego.andrade at smartech.com.br Fri Jan 9 14:32:33 2004 From: diego.andrade at smartech.com.br (Diego Ribeiro de Andrade) Date: Fri, 9 Jan 2004 17:32:33 -0200 Subject: Tcl/Tk Support References: Message-ID: <003101c3d6e7$547eee60$7900a8c0@smartech.com.br> Yes... I typed import Tkinter too but the output was the same! how I do to install support for Tkinter? Can I download the Tkinter.py file and paste in the include directory of Python2.2? "Aahz" escreveu na mensagem news:btms6u$9rr$1 at panix2.panix.com... > In article , > Diego.andrade wrote: > > > >Im not a Python programer, but I need to use Python on some aplications CVS > >related. Im trying to install ViewCVS who need Tkinter library. But It > >doesnt Work. Im using RedHat 9 Default Installation, to test if Tcl/Tk > >suport for Python is working I Type in the Python console import tkinter and > >received the following output: > > > >[root at Diego-Linux root]# 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 tkinter > >Traceback (most recent call last): > >File "", line 1, in ? > >ImportError: No module named tkinter > >>>> > > What happens when you type "import Tkinter" (note initial capital) > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > A: No. > Q: Is top-posting okay? > -- > http://mail.python.org/mailman/listinfo/python-list > From deets_noospaam at web.de Wed Jan 28 13:25:12 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 28 Jan 2004 19:25:12 +0100 Subject: Curious string behavior References: Message-ID: > address2 = ' ' > line = 'function, dealer, type, firstname, lastname, vin, blank' > print 'Address2 Type (first check): ', type(address2) > function, dealer, type, firstname, lastname, vin, blank = ^^^^^ Here you rebind the name type (which is initially bound to , that can be called with an argument to get its type) to the string ' '. Hence the second type(address2) doesn't work. You can do this on all symbols/names in python, which can cause confusing errors. Diez From nospam at nowhere.hu Mon Jan 26 16:46:03 2004 From: nospam at nowhere.hu (Miklós) Date: Mon, 26 Jan 2004 22:46:03 +0100 Subject: Advice on XML API integration project? Message-ID: Hi Pythonist software gurus out there, Seems like I need to build some glue software between an XML based web service and some third party client software/platform. My planned man-in-the-middle has to exchange XML messages with a site which has a well defined but baroquesc XML API, actually a set of XML messages posted to that site and the response gets parsed. The XML API however could change sometimes, there's versioning, etc. I want the other end to have a rock solid constant API, I'm thinking XML-RPC, so that the client side doesn't need to be changed or rather that it wouldn't be complicated because of the need to do all that message processing, API tracking, etc. So the other aim of this glue layer is to dramatically simplify the client side. (The client side is not in Python but some obscure language..) The XML API has examples for all the message exchanges, so I thought this could be used to track possible changes so that the code of the man-in-the-middle preferably doesn't need to be changed, only it's configuration. Could you suggest software, libraries, contribute ideas, etc? Thanks for any input in advance, Mikl?s From dave at pythonapocrypha.com Fri Jan 30 11:00:26 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 30 Jan 2004 09:00:26 -0700 Subject: Simple list question References: Message-ID: <01c601c3e74a$2d7c68b0$6401fea9@YODA> C GIllespie wrote: > I have a list something like this: ['1','+','2'], I went to go through and > change the numbers to floats, e.g. [1,'+',2]. What's the best way of doing > this? The way I done it seems wrong, e.g. > > nod=['1','+','2'] > i=0 > while i if nod[i] !='+' or nod[i] !='-' or nod[i]!='*' or nod[i] != '/' or > nod[i] != '(' or nod[i] != ')': > nod[i] = float(nod[i]) > i = i + 1 How about: >>> nod = ['1','+','2'] >>> for i in range(len(nod)): ... try: ... nod[i] = float(nod[i]) ... except ValueError: pass ... >>> nod [1.0, '+', 2.0] -Dave From usenet_spam at janc.invalid Fri Jan 16 22:48:09 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 17 Jan 2004 03:48:09 GMT Subject: Searching for UTF8 capable font for REPORTLAB References: Message-ID: Andreas Jung schreef: > Reportlab has some problems with creating PDFs from UTF8 encoded text. > For this reason they are using a truetype font rina.ttf which looks > *very ugly*. Does anyone know of a suitable free available truetype > font that works with UTF8? AFAIK a "UTF8 capable TrueType font" doesn't exist; but most modern TrueType fonts have Unicode character tables? (From the screenshots in the userguide.pdf Rina doesn't look ugly IMHO, but it's clearly not intended for large pieces of body text. :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From LittleDanEhren at yahoo.com Thu Jan 29 16:01:06 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 29 Jan 2004 13:01:06 -0800 Subject: Python vs. Io Message-ID: <711c7390.0401291301.3f95794@posting.google.com> Io (www.iolanguage.com) is a new programming language that's purely object-oriented (but with prototypes), has a powerful concurrency mechanism via actors, and uses an extremely flexible syntax because all code is a modifiable message tree. Like Python, it is dynamically typed, has a very clean syntax, produces short code, and is excruciatingly slow (on the same level as eachother). Io has a unique syntax combining Lisp's idea of functions for flow control with traditional function syntax and smalltalk-like syntax to get slots of objects. Io has no keywords and everything, even multiple lines of code, can be used as an expression. Even as a beginner to Io, I was able to write something in just 43 lines to let you do something like this (and more) in Io: each((key, value) in map(x=1, y=2, z=3), write(key, ": ", value, "\n") ) Neither the each function nor the map function were built in (Io has other mechanisms for that kind of thing, but they are less efficient). Can anyone show me how to so much as alias "for" to "each" in Python or allow block syntax at all without hacking the C source code? Io doesn't use __methods_with_this_annoying_syntax__ because nothing is supposed to be for internal use only and there are only about three functions that would cause a problem if overridden. For embedding, Io doesn't have to use Py_ALL_CAPS, instead it just uses IoCamelCase, which looks much better. Interfaces to C are much more object oriented. Many users of Io (myself included) have switched over from Python for these reasons. I guess there are still the obvious advantages of Python over Io, including *large community *more bindings to stuff *strict coding conventions *inflexible so everything is the same *no need to close blocks But unless there are other problems, the first two go away soon (considering that Io was first created just two years ago). The last three are somewhat trivial and may even be to Io's advantage. Daniel Ehrenberg From elainejackson7355 at home.com Sat Jan 31 00:57:39 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 31 Jan 2004 05:57:39 GMT Subject: conditional expression sought References: Message-ID: Thanks. I've got this straightened around in my head now. I just sort-of 'panicked' when I saw a boolean literal where I didn't expect one to be (ie: returned by the expression with the A's and B's when all the A's are False). I realized later that that's what I should have expected, and that you could always just add "...or undefined()" to such an expression, where def undefined(): raise "undefined conditional expression" This is all just part of my newbie efforts to assimilate the language. Anyway, thanks again for your help. Peace "Dave K" wrote in message news:ulnl10teov6ceq1q52laduq13d7u9edddd at 4ax.com... | On Fri, 30 Jan 2004 01:06:55 GMT in comp.lang.python, "Elaine Jackson" | wrote: | | >Sorry to take so long but I wasn't sure what a "unit test" was (the other guy's | >post clarified it). Tell me if this isn't what you're looking for: | > | >falsies=[0,0.0,[],(),{},'',None] | >truies=[49,3.14,[1,2,3],(4,5,6),{7:8,9:10},'nonempty'] | > | >def demo(A,B): | > print "If A is ",A | > print "and B is ",B | > print "then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = ", | > print (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) | > | >A=[] | >from random import randint | >for i in range(3): | > A.append(bool(randint(0,1))) | >B=truies[0:3] | >demo(A,B) | > | >A=[False,False,False] | >B=falsies[0:3] | >demo(A,B) | >print "I would have liked this to be B[2] = ",B[2] | > | (snip) | | Do you mean that the expression should return the last element in B if | all elements in A are false? If all subexpressions before the last are | false, the whole conditional reduces to: | A[-1] and B[-1] | | So simply force (a copy of) A[-1] to always be true. Instead of | rewriting demo, I'll cheat by modifying the call: | | >>> A=[False, False, False] | >>> B=[0, 0.0, []] | >>> demo(A[:-1]+[True], B) | If A is [False, False, True] | and B is [0, 0.0, []] | then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = [] | >>> print A | [False, False, False] | | For complete generality, you should also consider the case where | len(A) != len(B). Truncate the longer list, or extend the shorter? | Does it matter which list is shorter? Or forget the whole mess and | raise an exception? There are lots of reasonable possibilities, but | they won't all lead to the same result for certain input values. | You're in charge of this project, you decide :) | | Dave From timr at probo.com Wed Jan 14 02:31:31 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 13 Jan 2004 23:31:31 -0800 Subject: building strings with variable input References: <400273B8.E991F41D@alcyone.com> <2szMb.6443$k4.143679@news1.nokia.com> Message-ID: <3rr900dm9s7th7kgq4muj76d5ocs5uep3b@4ax.com> Olaf Meyer wrote: > >I just found out another way ;-) Using the locals() has the disadvantage >that I cannot use more complex variable parameters (e.g. certain values >of a dictionary). The following works well: > >cmd = (executable + " -start " + startTime + " -end " + endTime + > " -dir " + options.dir) Yes, that works, but you should bear in mind that it is slower than the %s option. The "+" operations are all separate interpreter steps, while the "%" operation is done in C. At least, it was that way when I asked this same question several years ago. If it has changed, I'm sure someone will point out my error. Sometimes, it can make sense to write it this way: cmd = ' '.join(( executable, "-start", startTime, "-end", endTime, "-dir", options.dir )) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paul at prescod.net Fri Jan 23 01:57:23 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 22 Jan 2004 22:57:23 -0800 Subject: I support PEP 326 In-Reply-To: References: <401081A1.E4C34F00@alcyone.com> Message-ID: <4010C5D3.9060702@prescod.net> Andrew Koenig wrote: >>I suppose you could special-case min() and max() to return the >>appropriate singletons if called with no arguments. >> >>There's something very nice about that. There's also something very >>ugly about it. I'm having a hard time deciding which is stronger :-) > > > I'm afraid it's not right, because calling min() with no arguments should > return Max and calling max() with no arguments should return Min. > > This behavior is correct because it preserves the intuitive property that if > s1 and s2 are (possibly empty) sequences, min(min(s1),min(s2)) should be > equal to min(s1+s2), and similarly for max. If you like, Max is the > identity element for min and Min is the identity element for max. Calling min with no arguments need not be the same as calling it with an empty sequence argument. That is not necessarily an argument for making the empty function call return something arguably strange... Paul Prescod From CousinStanley at hotmail.com Thu Jan 1 13:19:53 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Thu, 1 Jan 2004 11:19:53 -0700 Subject: Where to go from here? newbee References: Message-ID: Richard .... A good way to get started with Python is to use the interpreter in command-line mode and experiment with it just by trying different things .... Anything that works using the interpreter interactively will also work by coding the commands in a text editor and saving as a Python source file with the .py extension .... To execute a saved program, open a DOS window, and enter .... python someProg.py You may have to include your python installation directory in the Windows path environment variable .... set path=%path%;x:\yourPath\PythonXXX A sample interactive session follows .... You can copy/paste it into a text editor, whack out the >>> and ... prompt characters, save it as a .py file, and then execute for a test .... -- Cousin Stanley Human Being Phoenix, Arizona >>> >>> # Lines beginning with the pound sign ... # are comments .... ... # ... # Create some named objects ... # and bind these names ... # to their values ... >>> root2 = 2**0.5 >>> r = 42.0 >>> x = r / root2 >>> y = x >>> z = ( x**2 + y**2 )**0.5 >>> >>> >>> # Define a function to print objects ... >>> def fprint( arg ) : ... print ' ' , arg ... >>> # Create a list of objects ... >>> list_objects = [ r , x , y , z ] >>> >>> # Print the objects ... >>> for this_object in list_objects : ... fprint( this_object ) ... 42.0 29.6984848098 29.6984848098 42.0 >>> >>> From tim.one at comcast.net Mon Jan 19 16:41:35 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 19 Jan 2004 16:41:35 -0500 Subject: secure unpickle? In-Reply-To: <87zncjabmu.fsf@pobox.com> Message-ID: [John J. Lee, on Gandalf's safe(r) restricted unpickling code, which assigns None to an unpickler's .find_global attr] > Aha. > > I see from past messages that this is thought to solve the security > problems (for this restricted case), at least by Martin v. Loewis, but > also that Paul Rubin believes a careful audit would be required to > have confidence in it (whether that's FUD, as Martin accuses, or > sensible caution, I have no idea...). Oh, who knows. Start by defining "security problem" -- I don't know what exactly people mean by that, although I do know I lose interest long before they finish demanding impossibilities <0.6 wink>. For example, I wouldn't be surprised if some otherwise idle postdoc found a way to trick cPickle into segfaulting by constructing an enormously large and/or enormously deeply nested composition of simple scalar types, lists, tuples and dicts. I don't know whether that's possible, but long experience certainly suggests that virtually all C programs have problems with "too much" of anything. > http://www.google.com/groups?threadm=mailman.1012591743.10841.python-list%40 python.org In the specific case discussed there of unpickling a string, I agree with Martin that there's no plausible attack, perhaps apart from creating a pickle that unpickled to a multi-gigabyte string (will the system malloc() properly return NULL if it can't satisfy the request? even if it does, will cPickle deal with the NULL return correctly? will cPickle screw up by failing to account for the possibility of integer overflow when adding the size of the string header to number of string bytes requested? etc -- beats me). I expect this is because Martin and I are both familiar with the actual front-end code that parses a string, and Paul isn't. Familiarity doesn't *always* breed contempt . From yf110 at vtn1.victoria.tc.ca Sun Jan 25 02:08:29 2004 From: yf110 at vtn1.victoria.tc.ca (Malcolm Dew-Jones) Date: 24 Jan 2004 23:08:29 -0800 Subject: perl bug File::Basename and Perl's nature References: <7fe97cc4.0401242131.22acf485@posting.google.com> Message-ID: <40136b6d@news.victoria.tc.ca> Xah Lee (xah at xahlee.org) wrote: : Just bumped into another irresponsibility in perl. : the crime in question this time is the module File::Basename. : Reproduction: : 1. create a directory containing a file of this name: "cdrom.html". : 2. "use File::Basename;", with the line: : ($name,$path,$suffix) = fileparse($File::Find::name, ('.html', : '.m')); : 3. Notice that your cdrom.html will be parsed into "cdr" with suffix : "om.html". Well, that's what you asked for, isn't it. : expletive Perl and Perl slinging morons. : Now, if you peruse the "documentation" of "perldoc File::Basename", : you'll see that it shouldn't be so. AND, the writting as usuall is : fantastic incompetent. To illustrate, i quote: : --begin quote : fileparse : The fileparse() routine divides a file : specification into three parts: a leading path, a : file name, and a suffix. The path contains : everything up to and including the last directory : separator in the input file specification. The : remainder of the input file specification is then : divided into name and suffix based on the : optional patterns you specify in : @suffixlist. Each element of this list can be a : qr-quoted pattern (or a string which is : interpreted as a regular expression), and is : matched against the end of name. If this : succeeds, the matching portion of name is removed : and prepended to suffix. By proper use of : @suffixlist, you can remove file types or : versions for examination. : --end quote Well it sounds to me like it says it will do what it did. : Note the last sentence: "By proper use of @suffixlist, you can remove : file types or versions for examination." Now, this is in sync with the : usual verbiages of unix man pages, of mentioning irrevalent things. How is it irrelevent to mention the purpose of the parameter? : Why the fuck do i need to know what is version, or examination what?? If you don't need to know the version then don't ask the routine to parse it off of the file name. As for "or examination what", it takes some pretty obscure, poetical parsing of english to make sense of this, so I will instead merely assume you lacked the ability to understand what you read. : Not every morons in this world is using unix with its morinic : convention of appending things to file names as a versioning system, Well that's right isn't it. Some of us morons use other moronic systems, such as VMS sometimes. I must admit though, I rather find VMS's "moronic", automatic, operating system supported _versioning_ of every file is an extremely nice feature, allowing me (potentially) to examine, recover, or reuse, any one of the versions of every file I ever touched (since the last PURGE, anyway). And you're right, one has no need to know the version number of a file for any normal operation on VMS any more than a unix programmer normally needs to know the inode number of a file, but on the other hand, when you do certain file manipulations then you do need to know it, and since the easiest way to access it is via the file name then it looks to me that in that case the version number returned for my _examination_ by the above mentioned module might be a good way to do that. (You sure are rude by the way.) : and not every moron in this world need to "exam" things. "exam" is a noun, and therefore this is also sort of true, but only because it's a bit of a tautology to say that somene doesn't need to do something nonsensical. : The unix : irrevalency, inprecision, driveling are paragoned above. : Here is a better documentation for the fileparse subroutine. : fileparse : fileparse divides a file name into 3 parts: : directory string, file name, file name : suffix. fileparse($filename, @suffixes) returns a : array of 3 elements ($name, $dir_path, : $suffix). The concocted result of : "dir_path$name$suffix" is guaranteed to equal to : $filename. The @suffixes is a array of strings, : for example ('\.html', '\.txt', '\.png'). These : strings are interpreted to be regular : expressions, and is matched against the end of : $filename. "concocted"? : But NOOO, ... morons are too enamored with driveling well well, what do we find at the end, sure enough, this also is true. From tdelaney at avaya.com Wed Jan 7 17:55:22 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 8 Jan 2004 09:55:22 +1100 Subject: Pre-PEP: Dynamically evaluating default function arguments Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01063550@au3010avexu1.global.avaya.com> > From: Gerrit Holl > > Delaney, Timothy C (Timothy) wrote: > > IMO it's not a waste of time for this PEP to be written. > Unfortunately, not many people are willing to formally > document something that they would like to see when the > guaranteed result is that it will be rejected. > > PEP 313? PEP 313 is not an (overly) serious proposal. My point was that Daniel obviously wants this change. However, it would be highly unlikely for Daniel to write up a PEP that contained enough detail for it to be useful for us to point to in the future with the knowledge (not just expectation) that it will be rejected. OTOH, there's no real motivation for me to write a PEP either, because I'm happy with the status quo. Tim Delaney From enrique.palomo at xgs-spain.com Tue Jan 27 10:37:57 2004 From: enrique.palomo at xgs-spain.com (Enrique) Date: Tue, 27 Jan 2004 16:37:57 +0100 Subject: python As400 In-Reply-To: Message-ID: <002101c3e4eb$8a44fb90$6c010a0a@epalomo> Hi all again. I tried python for as400 and it works! Now, 2 questions: 1.- for debuging, how can i see the "print" i code in a script?? Only in python console, doing execfile ("script.py") i can see, but, is there a more fair mode?? 2.- files in as400 are in ebcdic. But i need to work in ascii to sort de data later. Can i work in as400 with ascii files? (sorry, but i?m a very newbie, and a very very very newbie in as400) -----Mensaje original----- De: python-list-bounces+enrique.palomo=xgs-spain.com at python.org [mailto:python-list-bounces+enrique.palomo=xgs-spain.com at python.org]En nombre de Jarek Zgoda Enviado el: mi?rcoles, 21 de enero de 2004 20:29 Para: python-list at python.org Asunto: Re: python As400 Enrique pisze: > i checked before this website, http://www.iseriespython.com/, but found no > much information in it (docs) Sorry, I meant "check this site to read documentation for AS/400-specific modules". > worse? how much worse? more worse that can be assumed? I don't know, I never tried to measure it. > and connect python on windows with db2 in as400?? No chance except ODBC (http://www.egenix.com/) or ADO (i.e. adodbapi on SourceForge), anyway you will need Client Access installed. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ -- http://mail.python.org/mailman/listinfo/python-list **AVISO DE CONFIDENCIALIDAD** La informaci?n contenida en este mensaje y archivos es privada y confidencial estando dirigida solamente al destinatario. Si Ud. ha recibido esta informaci?n por error, por favor, proceda a su inmediata destrucci?n. Cualquier opini?n o punto de vista contenido en este mensaje corresponde al remitente y necesariamente no representa la opini?n del GRUPO XEROX. From bcd at pvv.ntnu.no Thu Jan 15 06:09:55 2004 From: bcd at pvv.ntnu.no (Bent C Dalager) Date: Thu, 15 Jan 2004 11:09:55 +0000 (UTC) Subject: ProtoCiv: porting Freeciv to Python CANNED References: Message-ID: In article , JanC wrote: > >You think "cross-platform" means "it runs out-of-the-box on all possible >platforms that ever existed, now exist, and will ever exist"? I'm still amused that some subcultures think of cross-platform as "runs on 98, NT, 2k and XP" :-) Cheers Bent D -- Bent Dalager - bcd at pvv.org - http://www.pvv.org/~bcd powered by emacs From vidar at coretrek.com Tue Jan 20 12:58:24 2004 From: vidar at coretrek.com (Vidar Braut Haarr) Date: Tue, 20 Jan 2004 18:58:24 +0100 Subject: Python T-shirt Message-ID: <400D6C40.2070802@coretrek.com> Greetings! I was looking for a Python Tshirt the other day, and I couldn't find any good ones.. Therefore I made this one: The source images can be found here: The code on the back of it was written by a very cool guy.. I don't remember who. Thanks, anyways! :) Anyways, feel free to shop! I'm not getting any profit from this. I'm not a python guy (I made the shirt as a birthday presant to a buddy), so don't ask me about the code. I also don't subscribe to this list, so if you reply, please include me as To/Cc. Enjoy -- Vidar Braut Haarr http://www.coretrek.com http://www.corelets.com "Programmers don't die, they just GOSUB without RETURN." From peter at engcorp.com Mon Jan 5 17:43:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Jan 2004 17:43:15 -0500 Subject: indendation question References: <20031226033210.GA24039@mrna.tn.nic.in> Message-ID: <3FF9E883.BC8AB864@engcorp.com> Sean 'Shaleh' Perry wrote: > > On Thursday 25 December 2003 19:32, km wrote: > > Hi all, > > > > What is the standard and recommended way of indendation one should get to > > use in python programming ? is it a tab or 2 spaces or 4 spaces ? i am > > confused. kindly enlighten > > > > thanks, > > KM > > Well the "official" standard can be seen in the python files distributed with > python -- 4 spaces. > > That said, Python will use any whitespace you want as long as you are > consistent. 3 spaces, a tab, whatever. Well, *almost* any whitespace. :-) >>> import string >>> string.whitespace '\t\n\x0b\x0c\r ' Of those, only '\t' and ' ' are going to be much help, I think, when trying to indent. Linefeed, carriage return, vertical tab, and form feed are most likely not well supported yet. ;-) -Peter From faizan at jaredweb.com Sat Jan 24 23:38:17 2004 From: faizan at jaredweb.com (Fazer) Date: 24 Jan 2004 20:38:17 -0800 Subject: Text Animation Message-ID: <7b454334.0401242038.11404dac@posting.google.com> Hello, I was wondering if anyone has done any simple text-based animation? I mean things such as text-based pre-loaders. One example would be when you use the *nix utility called `wget.` You get that fancy " ====> " type of animation as you download a large file. Or maybe even a rotating " | " that I have seen before in some installation programs. Any ideas how these effects can be achieved? Thanks a lot! Faizan From km at mrna.tn.nic.in Mon Jan 19 08:47:50 2004 From: km at mrna.tn.nic.in (km) Date: Mon, 19 Jan 2004 19:17:50 +0530 Subject: Tkinter Message-ID: <20040119134750.GA30270@mrna.tn.nic.in> Hi all, Is there any good online tutorial which is a good intro for Tkinter programming in Python ? regards, KM From ramen at lackingtalent.com Fri Jan 9 11:21:43 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 09 Jan 2004 16:21:43 -0000 Subject: Python and Jython are kinda different References: <87wu81jjg2.fsf@pobox.com> Message-ID: In article <87wu81jjg2.fsf at pobox.com>, John J. Lee wrote: > Dave Benjamin writes: > [...] >> Is there anyone here that works on Jython? Do you need help? What kind of > > They certainly need help. I suppose that was a redundant question. =) >> help do you need? What's your estimation of the amount of work needed? Is > > Asking on the Jython list seems like a good idea. Yes. But I think that c.l.p is an appropriate place to bring this issue up in general, because if CPython and Jython are truly--as they are often represented in books and tutorials--just two implementations of the Python language, we all ought to be more concerned with unifying them. I never see Jython advertised as a limited subset of Python. >> the work done with PyPy helpful? I'm really curious. > > PyPy is a research effort, so not immediately useful. It may have big > payoffs if successful, of course. Well, my thinking is that, since it's an implementation of Python written in Python, many of the new features of CPython that don't require syntactical or fundamental object-model changes could be ported from PyPy to Jython as a temporary fix, to be eventually recoded in Java. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From llothar at web.de Wed Jan 14 09:43:01 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Jan 2004 06:43:01 -0800 Subject: Myth or Urban Legend? Python => Google [ was: Why learn Python ??] References: <40029dad$0$28706$a729d347@news.telepac.pt><100655fo84c2211@corp.supernews.com><87d69og2jl.fsf@pobox.com> <1009fum3evnc96a@corp.supernews.com> Message-ID: <6ee58e07.0401140643.2f5a8586@posting.google.com> "Francis Avila" wrote in message news:<1009fum3evnc96a at corp.supernews.com>... > EP wrote in message ... > >Is it true that the original Google spider was written in Python? > > I don't know *what* Google uses Python for, but it uses Python. > The old version of the google toolbar showed a special hint when hovering over the page rank icon. At least the first spider was written in python - there is nothing like a urban legend about this fact. And it seems that python was used enthusiastic by the google team. I remember an article about google's spider in a pre 1998 issue of germans 'CT' or 'IX' magazine, can't remember which one. From nosmapplease at somewhere.com Sat Jan 3 10:23:39 2004 From: nosmapplease at somewhere.com (Psymaster) Date: 3 Jan 2004 15:23:39 GMT Subject: Import problems Message-ID: I'm working on projects using pygame and I encounter the following problem: In (almost) every file of my source I have to "include pygame" because every file uses some function from pygame. Is there another way to do this? Does it provide overhead to my app? From jcarlson at nospam.uci.edu Sat Jan 24 04:12:47 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 24 Jan 2004 01:12:47 -0800 Subject: efficient matching of elements a list In-Reply-To: <7xzncd67sj.fsf@ruckus.brouhaha.com> References: <7xzncd67sj.fsf@ruckus.brouhaha.com> Message-ID: >>Suppose I have a lists of tuples >>A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)] >>and an int >>i=1 >>What is the fastest way in python to get out all the tuples from the >>list whose first element is equal to i? > > > t = [x for x in A_LIST if x[0] == i] Before list comprehensions, we had to do it all with filter... t = filter(lambda x:x[0]==i, A_LIST) List comprehension seem to be around 33% faster. Long live list comprehensions. - Josiah From Mike at DeleteThis.Geary.com Tue Jan 20 23:10:20 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 20 Jan 2004 20:10:20 -0800 Subject: Help, *.CHM, etc References: <90f2d9db.0401201803.6f2adbf8@posting.google.com> <20040120181009.060C.JCARLSON@uci.edu> <20040120182610.060F.JCARLSON@uci.edu> Message-ID: <100rutd6kge1g9f@corp.supernews.com> Josiah Carlson wrote: > > Personally, I would suggest: > > os.startfile("c:\\path\\help.chm") > > > > It is documented to do exactly what you want it to do, > > open up the help file with the microsoft help file viewer. > > That is, if .chm files are associated with the microsoft > help file viewer. > > Technically os.system("c:\\path\\help.chm") and > os.system("start c:\\path\\help.chm") also work, though > are less intuitive. No, os.system is the wrong way to do it. That function launches a new command shell, which in turn runs the program you want. Because of that, if you're not already running in a console window, it will open a new console window. You had it right with os.startfile. That calls the ShellExecute function in Windows, which is the way you would do it in a native Windows application written in C. -Mike From http Sun Jan 4 10:40:04 2004 From: http (Paul Rubin) Date: 04 Jan 2004 07:40:04 -0800 Subject: Sending e-mail with python 1.5.2 References: Message-ID: <7xisjrsox7.fsf@ruckus.brouhaha.com> I thought 1.5.2 had the smtp package. If not, how about just using popen to send the mail through /bin/mail. From fumanchu at amor.org Fri Jan 16 10:46:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Jan 2004 07:46:09 -0800 Subject: Bug or feature? Message-ID: Alexey wrote: > Does anybody agree that this is a python problem and not a programmer > problem? I don't agree. The programmer has a problem stuffing too much activity into a single expression. Why return a value from a method (your 'delta' arg) when you just sent that value to the method? But I'll give further advice anyway... :) > So I proposing to make a change into python and reverse the order of > calculations. > Just for sure: > === Order used now === > ## a+=a.Sub(b) > 1. evaluate value of 'a' > 2. evaluate value of 'a.Sub(b)' > 3. evaluate the sum > 4. store the result into 'a' > === Proposed order === > ## a+=a.Sub(b) > 1. evaluate value of 'a.Sub(b)' > 2. evaluate value of 'a' > 3. evaluate the sum > 4. store the result into 'a' You'll have to be more rigorous than that in your description. Given this single instance, you might be proposing: 1) Evaluate right-to-left instead of left-to-right? 2) Evaluate a.method before a.attribute? 3) Evaluate all calls before all LOAD_FAST? 4) Change the order only for +=? So a = a + a.Sub(b) would be unchanged, or not? What happens if a programmer writes: ## a = a + a.Sub(b) ## a = a + a.Sub(b) + a ## a += a.Sub(b) + a + a.Mult(b)? and on and on. Robert Brewer MIS Amor Ministries fumanchu at amor.org From newsgroups at jhrothjr.com Thu Jan 15 22:09:48 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Jan 2004 22:09:48 -0500 Subject: Redefining __call__ in an instance References: <73b00f0c.0401151529.676347b6@posting.google.com> Message-ID: <100elhmkfph1te7@news.supernews.com> "Robert Ferrell" wrote in message news:73b00f0c.0401151529.676347b6 at posting.google.com... > I have a question about assigning __call__ to an instance to make that > instance callable. I know there has been quite a bit of discussion > about this, and I've read all I can find, but I'm still confused. > > I'd like to have a factory class that takes a string argument and returns > the appropriate factory method based on that string. I'd like the > instances to be callable. Like this: > > fact = Factory('SomeThing') > aSomeThing = fact(some args) > > anotherFact = Factory('SomeThingElse') > anotherThing = anotherFact(some other args) > > The way I thought to do this was to assign the __call__ attribute of > the fact instance to the appropriate factory method in __init__. That does not > work, as many others have pointed out. I know there are workarounds. > The appended code shows the variants I know of. I can use one of > them, but they are not quite what I am looking for. > > Have I missed the key message that explains how to make new-style > classes callable, with the called method unique to each instance? Basically, the system does not look in the instance for the __call__ method for new style classes. I'm not sure why not, or where this is defined, but that's the way it works. To get a different callable for each instance, you need to do something like this: class fubar(object): def __init__(self, callable): self.myfunc = callable def __call__(self, *a, **b): self.myfunc(*a, **b) > > thanks, > -robert From davesum99 at yahoo.com Sat Jan 24 11:59:20 2004 From: davesum99 at yahoo.com (smarter_than_you) Date: 24 Jan 2004 08:59:20 -0800 Subject: Tkinter Base Window References: <401257c4$0$26116$afc38c87@news.optusnet.com.au> Message-ID: Peter Moscatt wrote in message news:<401257c4$0$26116$afc38c87 at news.optusnet.com.au>... > Ok.... I am pretty new to Python (as you may have gathered from previous > posts). So now it time for another one of my ridiculous questions.... :-) > > When using 'Tkinter', what is used as the base window to work from, meaning > what widget do I use to place all other widgets onto to create a custom > dialog ? > > Pete see http://www.pythonware.com/library/tkinter/introduction/hello-tkinter.htm then click 'details' to see the explanation of root=Tk(), which creates the root window in your native OS. Note that you can create multiple root windows if you need them, and have them appear at specific locations on the screen using the .geometry method (this is dangerous though unless know what your user's screen setup is) -dbm From mhammond at skippinet.com.au Wed Jan 21 17:55:13 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 22 Jan 2004 09:55:13 +1100 Subject: PyTime Object and Application Crashing In-Reply-To: References: Message-ID: Robert Brewer wrote: > Ryan Scott wrote: > >>When I run a query against an access database and the default >>date for >>my date/time field is 12/30/1899 the application crashes. >>Changing this >>to a different date like 03/03/2003 works. >>The output of the query when returned as a list is as follows: > > > AFAICT all dates on or before that date will crash. That is a new one for me :) I have fixed the crash here, but calling Format() (which print does under the covers) will still fail for those dates - but with a ValueError. Mark. From cfox at cfconsulting.ca Fri Jan 9 19:01:12 2004 From: cfox at cfconsulting.ca (Colin Fox) Date: Sat, 10 Jan 2004 00:01:12 GMT Subject: LC_MONETARY formatting References: <3FFF38DE.1050603@v.loewis.de> Message-ID: On Sat, 10 Jan 2004 00:27:26 +0100, Martin v. Loewis wrote: > Colin Fox wrote: <..> >> I would like to be able to print "$12,345.60" >> >> Is there a format string, or function, or *something* that will take >> advantage of the monetary formatting info in the locale object? > > No. I can't believe that I'm the first person who ever wanted to print a number as a currency value. Why go to the great lengths of what's provided in localeconv(), only to leave it up to every single programmer to re-implement the solution? What a waste of time and effort! I can't see any reason not to provide a monetary converter within locale, particularly when it's obviously got all the info it needs. > > IOW, LC_MONETARY is useless for financial applications - if the amount > is in ?, using the locale's currency symbol would be wrong. That's true whether you use LC_MONETARY or not. Unless you know the units your number is in, you can't assign a symbol to it. In my case, I have numbers that are always in either Canadian or US dollars, so the dollar sign is fine, and the thousands-separator value is fine. cf From jacek.generowicz at cern.ch Wed Jan 7 07:56:41 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2004 13:56:41 +0100 Subject: Why ' '.some_string is often used ? References: Message-ID: "St?phane Ninin" writes: > Hi all, > > This is not the first time I see this way of coding in Python and > I wonder why this is coded this way: > > Howto on PyXML > (http://pyxml.sourceforge.net/topics/howto/node14.html) > shows it on this function, but I saw that in many other pieces of code: > > def normalize_whitespace(text): > "Remove redundant whitespace from a string" > return ' '.join(text.split()) > > Is there a reason to do instead of just returning join(text.split()) ? One reason for preferring the former over the latter might be that the former works, while the latter doesn't: >>> text = ' this is a late parrot ' >>> ' '.join(text.split()) 'this is a late parrot' >>> join(text.split()) Traceback (most recent call last): File "", line 1, in ? NameError: name 'join' is not defined You can make it work of course ... >>> from string import join >>> join(text.split()) 'this is a late parrot' But you shouln't really be polluting your globals with stuff from modules, so you'd probably prefer to import string rather than from string import join (or, heaver forbid from string import * !) In which case you would end up writing string.join(text.split()) which is a whole whopping 3 characters longer than ' '.join(text.split()) :-) If you are too zealous in your interpretation of the second line of the Zen of Python[*], then you might also prefer the latter as it is more explicit than the former. [*] try: >>> import this From afriere at yahoo.co.uk Mon Jan 26 20:27:39 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 26 Jan 2004 17:27:39 -0800 Subject: "Lecture Preparation" Discussions on Python References: <1010a26.0401212246.3cac7d06@posting.google.com> Message-ID: <38ec68a6.0401261727.1c0f835e@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <1010a26.0401212246.3cac7d06 at posting.google.com>, > > While I'm generally interested in such discussions, I won't be > participating because I hate web boards. I vastly prefer netnews, with > grudging use of e-mail lists. Nice for those who can get it. The (educational) institution where I work have, in their wisdom, decided not to make netnews available, so I have to access even this newsgroup via a web board (GoogleGroups). In any case it is good to see Python getting such a strong plug at UNSW. Nice collection of Python links on that page BTW. From amichail at cse.unsw.edu.au Thu Jan 22 01:46:42 2004 From: amichail at cse.unsw.edu.au (Amir Michail) Date: 21 Jan 2004 22:46:42 -0800 Subject: "Lecture Preparation" Discussions on Python Message-ID: <1010a26.0401212246.3cac7d06@posting.google.com> Hi, We are planning to have "lecture preparation" discussions in comp3141 at UNSW, where anyone can participate -- not only students taking the subject. There is a heavy python component in this class and I was wondering whether anyone is interested in participating in these discussions. We are looking for both python beginners and experts. You can find the subject and a description of "lecture preparation" discussions here: http://www.cse.unsw.edu.au/~cs3141/ The class has about 200 3rd year software engineering students and I hope many of them will become convinced of just how powerful and simple python is. Amir From guido at python.org Fri Jan 30 10:40:57 2004 From: guido at python.org (Guido van Rossum) Date: Fri, 30 Jan 2004 07:40:57 -0800 Subject: LAST CHANCE! PyCon Early bird registration ends Sunday Message-ID: <200401301540.i0UFevo02863@c-24-5-183-134.client.comcast.net> If you're planning to come to PyCon DC 2004, make sure to REGISTER by Sunday, Feb 1. The early bird registration fee is only $175 ($125 for students). Monday it goes up to $250!!! To register, visit: http://www.pycon.org/dc2004/register/ Speakers, you too!!! DC 2004 will be held March 24-26, 2004 in Washington, D.C. The keynote speaker is Mitch Kapor of the Open Source Applications Foundation (http://www.osafoundation.org/). There will be a four-day development sprint before the conference. For all PyCon information: http://www.pycon.org/ --Guido van Rossum (home page: http://www.python.org/~guido/) From loredo at somewhere.cornell.edu Fri Jan 23 14:18:17 2004 From: loredo at somewhere.cornell.edu (Tom Loredo) Date: Fri, 23 Jan 2004 14:18:17 -0500 Subject: [Numpy-discussion] Status of Numeric References: Message-ID: <40117379.90CD5732@somewhere.cornell.edu> Paul Dubois wrote: > > Having two array classes around is a terrible idea. Once you have two > popular array classes the entire world bifurcates. This plot package > accepts those and that FFT accepts these, ad nauseum. I agree with this sentiment. I write C modules that interface with arrays, and presently use Numeric, but even with this investment in Numeric I'd like to see the community as a whole move to numarray. I don't want to have to keep two different C APIs in my head for dealing with arrays, one within scipy, the other for numarray. Speaking as an astronomer (with Python growing increasingly popular in astronomy), I think it would be Very Bad to have scipy use one type of array, and much astronomical software use another (numarray is being developed at Space Tel Science Inst., driven largely by the needs of astronomers). The Space Tel work is likely to make astronomers a big part of Python's scientific computing user base, and thus a big part of scipy's user base. Having to learn two array APIs (even if just on the C module level) will be an obstacle to developers and users alike. -Tom Loredo -- To respond by email, replace "somewhere" with "astro" in the return address. From jjl at pobox.com Mon Jan 12 16:16:50 2004 From: jjl at pobox.com (John J. Lee) Date: 12 Jan 2004 21:16:50 +0000 Subject: How to know if a system command doesn't exist? References: <8KzMb.1701$PK6.16708@nnrp1.uunet.ca> Message-ID: <87r7y450l9.fsf@pobox.com> Nicolas Fleury writes: > Nicolas Fleury wrote: [...] > > How can I know if a system command doesn't exist? All the ways > > I have tried behave like if the system command was existing but > > returning one. I don't want to sound provocative, but open in Perl [...] Haven't tried popen(), but I assume C's system() (of which os.system() is a trivial wrapper, on posix-y OSes) is implemented in terms of popen() (or both are implemented in terms of similar lower-level stuff). I get different return codes from system() depending on whether the program exists or not, as expected: >>> os.system("nonsense") sh: nonsense: command not found 32512 >>> os.system("ls") [...snip directory listing...] 0 >>> os.system("ls nonsense") ls: nonsense: No such file or directory 256 >>> John From paul at prescod.net Sat Jan 31 12:40:04 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 31 Jan 2004 09:40:04 -0800 Subject: Python vs. Io In-Reply-To: <711c7390.0401301726.3e38da27@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301726.3e38da27@posting.google.com> Message-ID: <401BE874.3080704@prescod.net> Daniel Ehrenberg wrote: > "Sean Ross" wrote > \> > I'm not sure how to tell you this so I'll just give a heavily > commented example (comments in Io are with #, //, or /* */) > > parentProto := Object clone //makes parentProto a new object > //:= is used for creating new variables > parentProto shared := 5 //parentProto's new slot shared holds 5 Do you know why the creator of IO decided not to use the now-ubiquitous "." operator? I don't know whether I can define a "." operator that has the appropriate behaviour but that wouldn't help anyhow. Paul Prescod From skip at pobox.com Fri Jan 16 10:44:42 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 16 Jan 2004 09:44:42 -0600 Subject: Bug or feature? In-Reply-To: <20040116153606.GA25928@intarweb.us> References: <3dtid1-594.ln1@beastie.ix.netcom.com> <1ljkd1-053.ln1@beastie.ix.netcom.com> <20040116153606.GA25928@intarweb.us> Message-ID: <16392.1770.961806.256593@montanaro.dyndns.org> >> Now that you mention it... Yeah... Can you imagine trying to figure >> out what something like >> >> alist = ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] >> res = alist[:5] + alist.sort() + alist[5:] >> >> was supposed to return? ... >> The only "known" is that the middle is supposed to be abcdefghij, but >> the left and right ends depend solely on order of evaluation... That's easy. You get a TypeError exception, because alist.sort() returns None. Like Jp said: Jp> Doesn't seem to be a problem, after all. Skip From lkcl at lkcl.net Sun Jan 25 08:02:48 2004 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Sun, 25 Jan 2004 13:02:48 +0000 Subject: [ANN] Custom 0.8-1 Released Message-ID: <20040125130248.GA9327@lkcl.net> Custom 0.8-1 ------ custom is an e-commerce solution for small to medium-sized businesses that provides: - a customisable web front-end for customers and Point-of-Sale staff to place orders - for warehouse staff to manage stock - for accountants and sales staff to manage and generate invoices - for purchasing managers to keep track of suppliers and competitive pricing. Download -------- http://sf.net/projects/custom http://sf.net/projects/pysqldb OS Requirements --------------- Custom is a pure Python application with no critical OS dependencies. Therefore it is entirely your choice as to what OS you use, but it must obviously run python (see http://python.org). Python is known to run on GNU/Linux, all version of Unix, all the BSDs, BEOS, MAC/OS 10, and many others. Software Requirements --------------------- This package requires or uses some additional software packages, which can all be obtained as RPMs, Debian Packages or compiled from Source if you feel the need. At each site, RPMs, DEBs and source are all typically available for download. You will need: - An up-to-date web server capable of SSL (if you need it) and also capable of running CGI-bin scripts. e.g. Apache2 (http://apache.org) - Python 2.1 or greater (http://python.org) - the pysqldb package version 0.6 or greater (http://sf.net/projects/pysqldb) - EITHER: - MySQL client libraries (http://mysql.org) - Andy Dustman's MySQLdb package (requires MySQL client) (http://sf.net/projects/mysqldb) OR: - Pysxqmll (a Python / MS-SQL / XML client for MS-SQL 2000) (http://sf.net/projects/pysxqmll) [what a stupid name.] - The mxDateTime and DateTime packages (http://www.egenix.com/files/python/mxDateTime.html) - PyCrypto version 1.9a1 or greater (http://sf.net/projects/pycrypto) - Python HTML-TMPL (generates HTML from templates) In case you were wondering, PostgreSQL and SAPdb are under investigation to be added into the database abstraction system that custom uses. custom uses some features in the SocketServer class that were introduced in Python 2.1. If you wish to stick with Python 2.0, you may wish to copy over the SocketServer.py file from the distribution of Python 2.1 or greater, and use that (making sure that you back up your original SocketServer.py file!) Debian install ------ It's a lot easier if you are using Debian: here is a list of the package names. It'll be even easier once the Debian packaging is released. - python-crypto - python-egenix-mxdatetime - python-mysqldb - python-htmltmpl - apache or apache2 - python-pysqldb If you install the three python packages using apt-get or dselect, that should be enough to pull in all the dependencies (including Python 2.3 and MySQL) except for python-pysqldb which you will likely still need to manually download from http://sf.net/projects/pysqldb SQL --- You must also install MySQL or MS-SQL 2000 on a server, where you may wish to install the SQL server on a separate system. If you do so, as noted above you will need to put the MySQL or MS-SQL client libraries onto the Custom Server. For various reasons, a high-availability cluster pair is recommended for your SQL system. You WILL be able to run the Back Office program monitord.py, on a HA cluster, because it is designed to cope with several concurrent copies of monitord.py running off the same SQL server. monitord.py is smart enough to lock the job scheduling table in the SQL database before taking a scheduled job out of the queue, so if running a SQL cluster it must obviously support table locking - you need to check! From RAWBOBB at hotmail.com Sun Jan 4 21:42:23 2004 From: RAWBOBB at hotmail.com (bobb) Date: 4 Jan 2004 18:42:23 -0800 Subject: Copying a blob from one mysql record to another with a where clause Message-ID: <521cddac.0401041842.32f633b7@posting.google.com> (I'm a long term newbie :) ) I wanted to copy a blob's contents in mysql in python from one record to another. I had a heck of a time with it, so I wanted to post it for others. The where clause was the tricky part for me. It probably has poor syntax, but it works. (Obviously) it can be used cross table and across db's. import MySQLdb con0 = MySQLdb.connect(host="localhost",user="",passwd="",db="in") con1 = MySQLdb.connect(host="localhost",user="", passwd="", db="in") sourcefield = 'logo' sourceid = 2514 # A string s = 2515 curs0=con0.cursor() selectstring = "select %s from table where id = %s" % (sourcefield, sourceid) curs0.execute(selectstring) sourceresult = curs0.fetchone() cursor1 = con1.cursor() s1 = "update table set "+ sourcefield + " = %s where id = " s2 = s1 + str(s) tup = s2 cursor1.execute(tup[::],(sourceresult )) con0.close() con1.close() From seanl at chaosring.org Sun Jan 4 18:05:10 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sun, 04 Jan 2004 15:05:10 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: Message-ID: Serge Orlov wrote: > "Sean R. Lynch" wrote in message news:srudnTjvU9BOH2qiRVn-uA at speakeasy.net... > >>Ok, I think you've pretty much convinced me here. My choices for >>protected attributes were to either name them specially and only allow >>those attribute accesses on the name "self" (which I treat specially), >>or to make everything protected by default, pass all attribute access >>through a checker function (which I was hoping to avoid), and check for >>a special attribute to define which attributes are supposed to be >>public. Do you think it's good enough to make all attributes protected >>as opposed to private by default? > > > Are you talking about C++ like protected fields and methods? What if > untrusted code subclasses your proxy object? Hmmm. I was thinking you'd trust those you were allowing to subclass your classes a bit more than you'd trust people to whom you'd only give instances, but now that you mention it, you're right. I should make all attributes fully private by default, requiring the progammer to declare both protected and public attributes, and I should make attributes only writable by the class on which they're declared. I guess I also need to make it impossible to override any attribute unless it's declared OK to do so. I wonder if each of these things can be done with capabilities? A reference to a class is basically the capability to subclass it. I could create a concept of "slots" as well. This would require a change in syntax, however; you'd be calling setter(obj, value) and getter(obj), and this isn't really something I could cover up in the compiler. I think I'll forget about this for now because E just uses Java's own object encapsulation, so I guess I should just stick with creating Java-like object encapsulation in Python. I need to implement a callsuper() function as well, because I don't want to be giving programmers access to unbound methods. > Thinking about str.encode I conviced myself that global state shouldn't > be shared by different security domains so that means codecs.py and > __builtins__ must be imported into each security domain separately. > It's pretty easy to do with codecs.py since it's python code. But importing > __builtins__ more than once is pretty hard since it wasn't designed > for that. Global *mutable* state shouldn't be shared, AFAICT. I believing making sure no mutable state is reachable through __builtins__ and having a new globals dict for each security domain should be enough. Any modules that are imported would need to be imported separately for each domain, which should be possible with a modified __import__ builtin. I don't have any intention of allowing import of unaudited C modules. From martin at v.loewis.de Sun Jan 11 04:10:45 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 11 Jan 2004 10:10:45 +0100 Subject: Python And Internationalization maybe a pre-pep? In-Reply-To: References: <3ffede43$0$563$b45e6eb0@senator-bedfellow.mit.edu> <3FFF36A1.40303@v.loewis.de> Message-ID: <40011315.7070000@v.loewis.de> Brian Kelley wrote: > I don't see too much difference between using > _("STRING") > > to indicate a string to be internationalized and > i"STRING" > > Except that the later will be automatically noticed at compile time, not > run-time. I'm not really sure what "compile time" is in Python. If it is the time when the .pyc files are generated: What happens if the user using the pyc files has a language different from the language of the administrator creating the files? Or, what precisely does it mean that it is "noticed"? >> Using what textual domain? >> > I am using the same mechanism as gettext but tying it into the "import > locale" mechanism. That does not answer my question? How precisely do you define the textual domain? In gettext, I typically put a function at the beginning of each module def _(msg): return gettext.dgettext("grep", msg) thus defining the textual domain as "grep". In your syntax, I see no place to define the textual domain. > I think this happens fine in both cases. The mechanism for > internationalizing with wxPython just didn't feel, well, pythonic. It > felt kind of tacked into place. Of course I feel the same way about > most C macros :) Can you be more specific? Do you dislike function calls? > Perhaps I am optimizing the wrong end of the stick. Why is this an optimization in the first place? Do you make anything run faster? If so, what and how? > Compile-time generation just feels safer to me. The code-analyzer might > miss special cases and what not, but if it is generated at compile time > it will work all the time. Please again elaborate: What is compile-time, and what is generation, in this context? > Since you brought it up, how does gettext handle multiple users? Does > each user get a different gettext library (dll) instance? Gettext, in Python, is a pure Python module - so no DLL. The gettext module provides the GNUTranslation object. You can have multiple such objects, and need to explicitly use the language's object on gettext() invocation, e.g. print current_language.gettext("This is good") If you can be certain that users will be subsequent, you can do def _(msg): return current_language.gettext(msg) print _("This is good") There might be other ways to determine the current context, e.g. by looking at thread state. In that case, you still can use the _ function, but implement it in looking at the thread state. Regards, Martin From mhammond at skippinet.com.au Fri Jan 30 18:40:33 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 31 Jan 2004 10:40:33 +1100 Subject: win32com - .ocx won't Dispatch... In-Reply-To: References: Message-ID: Ray Schumacher wrote: > So, the util class Dispatches, but all calls (properties and functions) give 'Catastrophic failure' > Is this really some sort of types problem with this OCX? > "pywintypes.com_error: (-2147418113, 'Catastrophic failure', None, None)" My guess is that your OCX is a true OCX, and therefore needs a full GUI environment. Pythonwin can host these - see the pythonwin\pywin\demos\ocx directory, and modify one of these to suit. wxPython can also apparently host OCX controls in a similar way, but I have no details. Mark. From fsc at fuentez.com Tue Jan 27 01:23:05 2004 From: fsc at fuentez.com (fsc at fuentez.com) Date: Tue, 27 Jan 2004 01:23:05 -0500 Subject: EMAIL REJECTED Message-ID: <200401270623.i0R6Mgiv022802@wmsc.fuentez.com> Violation found in email message. From: python-list at python.org To: hildjj at fuentez.com From lists at andreas-jung.com Fri Jan 16 07:28:15 2004 From: lists at andreas-jung.com (Andreas Jung) Date: Fri, 16 Jan 2004 13:28:15 +0100 Subject: Searching for UTF8 capable font for REPORTLAB Message-ID: <2147483647.1074259695@[192.168.0.102]> Reportlab has some problems with creating PDFs from UTF8 encoded text. For this reason they are using a truetype font rina.ttf which looks *very ugly*. Does anyone know of a suitable free available truetype font that works with UTF8? -aj From jseale18 at insightbb.com Mon Jan 19 15:39:18 2004 From: jseale18 at insightbb.com (Jeff Seale) Date: Mon, 19 Jan 2004 20:39:18 GMT Subject: Tkinter color names/codes Message-ID: I just happend to notice that there are very FEW colors that you have to generate using #hex codes. But I was wondering, how many colors have names assigned to them in Tkinter and what are their #hex translations? It'd be nice to know these so I don't accidentally create a color that already has a name. From km at mrna.tn.nic.in Wed Jan 14 17:02:31 2004 From: km at mrna.tn.nic.in (km) Date: Thu, 15 Jan 2004 03:32:31 +0530 Subject: best book Message-ID: <20040114220231.GA15846@mrna.tn.nic.in> Hi all, What is the best book to start with python ? i am have been working since 1 yr with Perl. kindly enlighten, thanks, KM From mcfletch at rogers.com Fri Jan 9 19:35:31 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 09 Jan 2004 19:35:31 -0500 Subject: Straw poll on Python performance (was Re: Python is far from a top performer ...) In-Reply-To: References: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> <3FFF26A1.943DEA84@engcorp.com> <026e01c3d702$970ec5a0$6401fea9@YODA> Message-ID: <3FFF48D3.2000106@rogers.com> Rene Pijlman wrote: >Mike C. Fletcher: > > >>I am often found optimising. >> >> > >By an unoptimized or by an optimizing coworker? :-) > > Well, in a perfect world, it would be by a lovely and svelte lady, missing her husband and seeking to drag me off to connubial bliss (we'll assume for propriety's sake that the husband would be me), but in my sad and lonely condition, it's normally I who finds myself late at night, feverishly optimising ;) :) . All a man really needs to be happy is work, and a woman to drag him away from it, or so I'm told, Mike(y) _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From deets_noospaam at web.de Thu Jan 22 13:12:24 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 22 Jan 2004 19:12:24 +0100 Subject: Simple requests sequentialiser? References: Message-ID: > I confess that I have spent very little time on finding a solution to > this yet. I have a feeling that this should be a piec of cake for > python possibly with twisted or even without it.... > > Is there anyone that can give me a pointer to an example or to a > specific place in the voluminous documentation of python and tools for > such a thing.... You should investigate into twisted - it is _really_ worth the effort, and not so complicated at all. BTW, there is no need for multiple threads - usually, several network connections can be processed by one thread/process. As long as you don't plan to server thousands of requests per second.... Diez From martin at v.loewis.de Fri Jan 16 18:08:21 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 17 Jan 2004 00:08:21 +0100 Subject: Retrive unicode keys from the registry In-Reply-To: <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> References: <1xpzaa8i.fsf@python.net> <69ZNb.15222$Wa.2798@news-server.bigpond.net.au> Message-ID: <40086EE5.7020708@v.loewis.de> Neil Hodgson wrote: > This is somewhat unpleasant, requiring runtime conditional code. For the > Python standard library, in posixmodule.c, places where there is a need to > branch first check that the OS is capable of wide calls with > unicode_file_names(), then check if the argument is Unicode and if it is > then it calls the wide system API. While the wide APIs do not work on 9x, > they are present so the executable will still load. I believe the story would be completely different for the registry: the wide registry functions are available on all Windows versions, AFAIK. Contributions are welcome. Regards, Martin From jcarlson at nospam.uci.edu Mon Jan 26 10:21:17 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 26 Jan 2004 07:21:17 -0800 Subject: compress string of data In-Reply-To: References: Message-ID: Piet van Oostrum wrote: >>>>>>Gerrit Holl (GH) wrote: > > >>>How i could compress string of data?. >>> >>>>>import zlib >>>>>zlib.compress("Hello, world") > > GH> 'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' > > GH> http://www.python.org/doc/current/lib/module-zlib.html > > Waw, that compresses it from 12 bytes to 20 bytes :=) There is no such thing as universal compression - some compressions result in expansion. - Josiah From ny_r_marquez at yahoo.com Thu Jan 29 15:55:24 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 29 Jan 2004 12:55:24 -0800 Subject: Simple Database Package References: <8089854e.0401290034.4d57a45d@posting.google.com> <401925bb$0$575$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <8a27e309.0401291255.aeb71b5@posting.google.com> Brian, There are several embeded database management systems available that you can use through Python. Gadfly is a pure Python database that is small and good enough for a lot of things. It is an easy way to dip your toes in the SQL language. However, I would ask you, how much "database" do you want to learn. Do you want to learn just enough to be able to write standalone applications, or do you think you will soon want to write applications on a server with multiple users accessing it simultaneously? If the latter, I would recommend that you first invest some time understanding concepts of the relational model. The DB Special Interest Group has some nice suggested books on this subject. You may then be tempted into going with a more feature rich database such as Firebird (through the Kinterbasdb python module). -Ruben From none at none.net Fri Jan 9 16:44:04 2004 From: none at none.net (Iwan van der Kleyn) Date: Fri, 09 Jan 2004 22:44:04 +0100 Subject: Python is far from a top performer according to benchmark test... In-Reply-To: References: Message-ID: <3fff234a$0$129$e4fe514c@dreader3.news.xs4all.nl> Carl wrote: > I think this is an unfair comparison! I wouldn't dream of developing a > numerical application in Python without using prebuilt numerical libraries > and data objects such as dictionaries and lists. Well, that may be true. And many applications spend most of their time in fast libraries anyway (GUI/DB/app servers) etc. Nice examples are Boa Constructor and Eric3 which are fully implemented in Python and run comfortably fast, thanks to the WxWindows and Qt libraries. But I really dont' swallow the argument. In the few years that I'm working with Python, I've encountered on several occasions performance bottlenecks. And often a solution through partial implementation in C or improvements in the algorithm is just not feasible. To paraphrase Kent Beck: in real life you make your program run, then work and then your manager says you've run out of time. You just cannot make it run as fast as you would like it as well. In other words: it would be nice if Python on average would run faster so the need for optimisation would lessen. Psyco is a nice option to have, though not as clear cut as I thought it would be: http://www-106.ibm.com/developerworks/linux/library/l-psyco.html > The greatest advantage of Python is the great increase in productivity and > the generation of a much smaller number of bugs due to the very clean and > compact structure Python invites you to produce. So dogma dictates. And I've found it to be true on many occasions, if not all. BUT, the famed Python Productivity Gain is very difficult to quantify. And for me that's a BIG but. I'm trying to push Python within my company. Nicely presented "performance benchmarks" go down well with management, bevause those are quantities which are supposedly understood. And Python does not come across very possitively in that respect. Regards, Iwan From dpryde+usenet at cis.strath.ac.uk Thu Jan 29 10:39:49 2004 From: dpryde+usenet at cis.strath.ac.uk (Daniel Pryde) Date: Thu, 29 Jan 2004 15:39:49 +0000 Subject: Printing/updating output to the screen Message-ID: <40192945$1@nntphost.cis.strath.ac.uk> Hi there. I hope this isn't a stupid question to ask, but does anyone know how to print out a string without moving to a new line each time and simply updating the first line. An example would be, if I wanted to have a percentage progress counter that was constantly updating. I'm unsure how to do this without printing to a brand new line. Any help would be greatly appreciated. Thanks. Daniel From footnipple at indiatimes.com Thu Jan 22 09:08:27 2004 From: footnipple at indiatimes.com (sdfgsd) Date: Thu, 22 Jan 2004 14:08:27 GMT Subject: python References: Message-ID: "Jess Martin" wrote in message news:mailman.626.1074743244.12720.python-list at python.org... > i need help. > im just learning to program and > every time i try to do a command more than > a line long it wont work Assuming you're using windows: Take your lines of code and put them into their own file with a .py extention (ie MyProgram.py). Then go to the command line and into the directory where MyProgram.py resides and type "python MyProgram.py". This will run your program containing as many lines of code as you like. From Johan.Vervoort at utimaco.be Wed Jan 21 03:17:57 2004 From: Johan.Vervoort at utimaco.be (Johan Vervoort) Date: Wed, 21 Jan 2004 08:17:57 GMT Subject: Reading BLOB Message-ID: <400e3510.18785312@news.eunet.be> How can I read a binary value from a blob via ODBC (Microsoft VFP driver-win32all)? The value seems to be truncated at the first '\0' TIA From peter at engcorp.com Wed Jan 14 09:54:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Jan 2004 09:54:24 -0500 Subject: error at "import anydbm" References: <40042edd$0$24038$626a54ce@news.free.fr> <4004482A.A66C2886@engcorp.com> Message-ID: <40055820.B35F9A84@engcorp.com> Paul McGuire wrote: > > "Peter Hansen" wrote in message > news:4004482A.A66C2886 at engcorp.com... > > > > Generally speaking, you should try to avoid using the same names as > > the standard library modules for your own code. > > > > > This is an understandable limitation, but for new (and some not-so-new) > Python users, it is not always obvious what module names to avoid. This gives a good summary: http://www.python.org/doc/current/modindex.html :-) I think the issue actually comes up relatively rarely. I say that partially because problems stemming from this seem relatively infrequent in the mailing list/newsgroup, and partly because the standard library modules are fairly loosely coupled, and the issue above arose (I believe) only because one standard library module was importing another which the user didn't know would be imported, and it matched a name he had used. Avoiding the basic ones, like "sys", "os", and "math", along with any that you are actually importing elsewhere in your application will probably avoid the issue 99% of the time. -Peter From amy-g-art at cox.net Fri Jan 23 18:29:27 2004 From: amy-g-art at cox.net (Amy G) Date: Fri, 23 Jan 2004 15:29:27 -0800 Subject: Various strings to dates. References: <4GfQb.16187$AA6.14368@fed1read03> Message-ID: Okay. I fixed the problem somewhat. I moved the dateutil directory over to /usr/local/lib/python2.2/site-packages and I can now import dateutil. But a call like this: from dateutil.parser import parse results in this error: ImportError: cannot import name parse I can 'from dateutil.parser import *' but cannot use parse after that. I can also 'from dateutil import parser' but that doesn't help either. Sorry for my inexperience here. Thanks for all of the help already. "Amy G" wrote in message news:PRgQb.16209$AA6.9881 at fed1read03... > No it won't. Unfortunatly I don't necessarily have a comma delimited date > string. Thanks for the input though. > > The following three date strings is another example of the various date > formats I will encounter here. > > Thursday, 22 January 2004 03:15:06 > Thursday, January 22, 2004, 03:15:06 > 2004, Thursday, 22 January 03:15:06 > > All of these are essentially the same date... just in various formats. I > would like to parse through them and get a comparable format so that I can > display them in chronological order. > > > "wes weston" wrote in message > news:MFgQb.95539$6y6.1915432 at bgtnsc05-news.ops.worldnet.att.net... > > Amy, > > I hope there is a better way but, if you go here: > > > > http://www.python.org/doc/current/lib/datetime-date.html > > > > The new datetime module may help. This and the time mod > > should get you where you want to go. > > > > list = strdate.split(", ") > > daystr = list[0] > > daynum = int(list[1]) > > monthstr = list[2] > > year = int(list[3]) > > #funct to get a month int is needed > > > > d = datetime.Date(y,m,d) > > > > wes > > > > --------------------------------------- > > > > Amy G wrote: > > > I have seen something about this beofore on this forum, but my google > search > > > didn't come up with the answer I am looking for. > > > > > > I have a list of tuples. Each tuple is in the following format: > > > > > > ("data", "moredata", "evenmoredata", "date string") > > > > > > The date string is my concern. This is the date stamp from an email. > > > The problem is that I have a whole bunch of variations when it comes to > the > > > format that the date string is in. For example I could have the > following > > > two tuples: > > > > > > ("data", "moredata", "evenmoredata", "Fri, 23 Jan 2004 00:06:15") > > > ("data", "moredata", "evenmoredata", "Thursday, 22 January 2004 > 03:15:06") > > > > > > I know there is some way to use the date string from each of these to > get a > > > date usable by python, but I cannot figure it out. > > > I was trying to use time.strptime but have been unsuccesful thus far. > > > > > > Any help is appreciated. > > > > > > > > > > From pygeek at yahoo.com Fri Jan 23 12:15:28 2004 From: pygeek at yahoo.com (Daniel Han) Date: 23 Jan 2004 09:15:28 -0800 Subject: any news client in Python? Message-ID: <2b4c49e0.0401230915.3438810f@posting.google.com> hello everybody. i've been looking around for a decent newsreader (not rss) that's written in Python. Strange, but i found none so far, i've been to sf.net, freshmeat.net, and even googled that, still nothing interesting. let me know if you know of something. i know some will tell me to use gnus and the likes, and forget about a news client in python, but i'm just curious to use one. --Daniel Han-- From jjl at pobox.com Wed Jan 14 21:35:47 2004 From: jjl at pobox.com (John J. Lee) Date: 15 Jan 2004 02:35:47 +0000 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> <100b2llg67r546f@corp.supernews.com> Message-ID: <871xq2rla4.fsf@pobox.com> claird at lairds.com (Cameron Laird) writes: > In article , > Derek wrote: [...] > Got it; thanks. There's been extensive discussion here and elsewhere > on just this point. One of us might follow-up in a bit with a refer- > ence to highlights ... [...] http://www.artima.com/weblogs/viewpost.jsp?thread=4639 http://www.mindview.net/WebLog/log-0025 (important: Bruce Eckel says "weak typing" where he really means "dynamic typing") (next two are from this group, both threads and the particular posts quoted are picked pretty much at random, except that I search for Alex Martelli's posts, which are reliably good) http://www.google.com/groups?selm=ft6tb.21351%249_.767461%40news1.tin.it&rnum=1 http://www.google.com/groups?selm=pNfIa.206219%24g92.4232233%40news2.tin.it&rnum=2 The last one (above) is part of an argument between Alex and David Abrahams, both C++ experts and well-known Pythonistas, but on opposite sides of the debate. John From aahz at pythoncraft.com Fri Jan 16 13:08:51 2004 From: aahz at pythoncraft.com (Aahz) Date: 16 Jan 2004 13:08:51 -0500 Subject: data structures module References: <92c59a2c.0401152306.1c6a17f5@posting.google.com> Message-ID: In article <92c59a2c.0401152306.1c6a17f5 at posting.google.com>, MetalOne wrote: > >Today, I wanted a priority queue. >I notice that Python does not have any sorted lists. >I know that I can call list.sort(), but that seems rather inefficient >to call every time an element is added. >I am wondering why there is not a module or modules containing many >common data structures. Has such a thing been decided against? Is it >that just nobody has done it? Has nobody else suggested the need for >it? Maybe I should search, but I am too tired now, I need sleep. There's a current discussion on python-dev about a "collections" module or package, and that's one of the structures under discussion. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From na Mon Jan 5 18:25:58 2004 From: na (Andrew) Date: Mon, 5 Jan 2004 15:25:58 -0800 Subject: mysql python Newbie Question References: <70hkc1-r33.ln1@beastie.ix.netcom.com> Message-ID: Ok Thank You "Dennis Lee Bieber" wrote in message news:uuamc1-gf4.ln1 at beastie.ix.netcom.com... > "Andrew" fed this fish to the penguins on Monday 05 January 2004 > 09:17 am: > > > > > > > Ok I was able to connect to my local server but how do I find the host > > address or port number of my remote server > > > Ask the people who own/run the server? {I know, there is an air of a > "sneer" in that question -- but your current questions are no longer > Python related, they apply to /any/ application trying to connect to > the server} > > If it is a hosting service, you could be out of luck -- the MySQL port > may be blocked by a firewall so that only HTTP (and maybe FTP) requests > can come in, with all MySQL access assumed to be performed using > scripts that are /on/ the server already. > > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From roy at panix.com Thu Jan 22 22:41:15 2004 From: roy at panix.com (Roy Smith) Date: Thu, 22 Jan 2004 22:41:15 -0500 Subject: I support PEP 326 References: <401081A1.E4C34F00@alcyone.com> <401091D5.EFA41F7@alcyone.com> Message-ID: In article <401091D5.EFA41F7 at alcyone.com>, Erik Max Francis wrote: > "David M. Cooke" wrote: > > > Or, expressing the idea that they're the ends of a number line: > > > > PosInf, NegInf > > PosInfinity, NegInfinity > > PositiveInfinity, NegativeInfinity > > > > If IEEE floating point was done correctly everywhere, I'd say make > > them the corresponding floating-point constants (Inf+ and Inf-). > > The "if" conditional here is bad. Naming something "infinity" if it > weren't the IEEE floating point constants as well would be seriously > misleading. > > After all, this _isn't_ a number line since we're talking about > comparing arbitrary objects. > > > Or, > > FreakingHuge, FreakingHugeTheOtherWay > > Don't be silly; that latter one should be FreakingUnhuge :-). You could name them Python and Perl. Then you could do stuff like: for language in allLanguages: if Perl < language < Python: print language, "is more than Perl but less than Python" From __peter__ at web.de Tue Jan 20 07:53:06 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Jan 2004 13:53:06 +0100 Subject: converting base class instance to derived class instance References: <930ba99a.0401200413.5fae6fb9@posting.google.com> Message-ID: Sridhar R wrote: > Consider the code below, > > class Base(object): > pass > > class Derived(object): I suppose that should be class Derived(Base): > > def __new__(cls, *args, **kwds): > # some_factory returns an instance of Base > # and I have to derive from this instance! > inst = some_factory() # this returns instance of Base # using brute force: inst.__class__ = Derived No guarantees, but the above seems to work. > return inst # Oops! this isn't an instance of Derived > > def __init__(self): > # This won't be called as __new__ returns Base's instance > pass > > The constrait is there is some factory function that creates an > instance of Base class. So I _can't_ call "Base.__init__(self)" in > Derived.__init__ func, as their will be _two_ instances (one created > by Derived.__init__ and other created by the factory function) As some_factory() returns an already initialized instance of Base, there should be no need to call it again from inside Derived.__init__() > Simply I want to get a derived class object, but instead of allowing > _automatic_ creation of Base instance, I want to use _existing_ Base's > instance, then use this as a Derived's instance. > > Will metaclass solve this problem? I think metaclasses will solve only metaproblems... Skeptically yours, Peter From michele.simionato at poste.it Thu Jan 22 09:43:38 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 22 Jan 2004 06:43:38 -0800 Subject: Side note: Praise to the contibuters to this group References: Message-ID: <95aa1afa.0401220643.4558d7fc@posting.google.com> "Amy G" wrote in message news:... One of the main reasons to prefer Python over other languages is its newsgroup, indeed. Michele From deets_noospaam at web.de Fri Jan 30 11:13:25 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Fri, 30 Jan 2004 17:13:25 +0100 Subject: easiest transition for a PHP website to move to Python? References: <6ee58e07.0401300555.12c07aa3@posting.google.com> Message-ID: > Most important, what can you use ? > If you are independ, this means have your own dedicated or virtual > server, then i would suggest webware which is the most sophisticated > real python (Zope is not python) solution. Twisted is more a server Where exactly is zope not "real" python? Just because it features two templating-methods that are for good reasons _not_ python embedded into html, its still a python webapp server. I never used webware, so I can't compare both, but from what I see it appears to me like tomcat (or maybe jboss) the python way. No problem with that. But object-relational-mappers are a PITA if you _must_ use them. ZODB oth is much more of a object-orientied (not relational, though) database. And thats what I love about it - simply create objects, and save them, without the need for prior mapping to anything. For purely content-driven websites, I haven't seen much better solutions than ZOPE together with some modern CMS, like PLONE or ZMS. Regards, Diez From jcarlson at nospam.uci.edu Sun Jan 25 19:48:42 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 25 Jan 2004 16:48:42 -0800 Subject: progress bar In-Reply-To: <59e5b87.0401251341.6a95b17e@posting.google.com> References: <59e5b87.0401231329.6e084d6f@posting.google.com> <9pwQb.5566$vy6.3518@newssvr29.news.prodigy.com> <59e5b87.0401251341.6a95b17e@posting.google.com> Message-ID: > Newbie questions...what is meant by the term 'GUI framework'? I'm > aware of Tkinter, wxPython and PythonCard (which, I believe builds > from a wxPython foundation). Also, it appears as though pywin.mfc has > GUI capabilities. Are Tkinter, wxPython, PythonCard and pywin.mfc > considered GUI frameworks? Based on the 'more than enough...' remark, > it sounds like there are several GUI frameworks out there...what are > some others? Really, a GUI framework is a set of stuff that allows the construction of a GUI more easily. One could, with a bitmap drawing function, get mouse click and get key press, create a GUI. This is a pain in the ass. All the GUI frameworks available allow one to do that if they want, but also allow one to use predefined sets of operations, objects, etc., commonly in a heirarchy, to produce a GUI that is easier to write and to update. There is a listing of GUI toolkits for various languages and platforms available here: http://home.pacbell.net/atai/guitool/ (I'm feeling lucky entry at google for 'python gui frameworks' ) - Josiah P.S. I very much enjoy using wxPython. From ny_r_marquez at yahoo.com Thu Jan 1 09:33:20 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 1 Jan 2004 06:33:20 -0800 Subject: Rekall Binary References: <8a27e309.0312310529.3c1f43a8@posting.google.com> Message-ID: <8a27e309.0401010633.20271486@posting.google.com> root wrote in message news:... > It looks like > > TotalRekall sells the GPL version for 15 pounds: That's my point. (Any takers for $10?) > > http://www.totalrekall.co.uk/modules.php?op=modload&name=CCart&id=16 > > Which seems in keeping with: > > "...small charge for Rekall binary distributions to cover our costs" > > By the way, it's still not clear how strong a busness model it is to > give away GPL software and expect to make money off services. Have you > seen what RedHat is now doing? How strong a buisness model is GPL software is a relative issue. If you mean making the kind of money that software developer houses used to make in the BOS (Before Open Source) days then it isn't. But you just may be able to support your family on it and pay the rent (and maybe even buy a modest house if you are really successful). I see nothing wrong with that. This are hard times you know. > > In any case, I don't think there is anything wrong with charging more > than distribution costs for a binary version of GPL'd program. Creating > binaries that work on various versions of various platforms and > providing a nice installer for them is quite a bit of work. True. And that may be so in this particular project. Still, if any one offers a $10 version they'll sweep that part of the "business model". Not a very strong model in my opinion. By going GPL, the developers made a decision to leave the old BOS way of competing and taking on the new one. > GPL is about freedom: not cheap software. The idea is that it a good > thing for all involved for users to have access to source code. That is > very different than providing inexpensive software for folks that can't > figure out how to compile something (or can't be bothered). Those folks > will not be contirbuting to the p[roject, and will not be using the code > in their own projects. However, those folks sometimes get the software into their companies and demostrate to their peers how productive it is. This in turn sometimes results in the application proliferating on the enterprise to the point where support is needed or desired by the CIO or the CEO. > That being said, I'm very happy that I can get so much open source > software in nicely packaged binary (or easy to compile) form. I only > contribute to a VERY SMALL fraction of all the free software I use. > But have you talked to others about it, or directly passed it on? That is, even in a very little way, contributing to the health of the projects in question. From seanl at chaosring.org Sat Jan 3 16:38:09 2004 From: seanl at chaosring.org (Sean R. Lynch) Date: Sat, 03 Jan 2004 13:38:09 -0800 Subject: Creating a capabilities-based restricted execution system In-Reply-To: References: <7xznd58klr.fsf@ruckus.brouhaha.com> Message-ID: Martin v. L?wis wrote: > "Sean R. Lynch" writes: > > >>RestrictedPython avoids this by removing the type() builtin from the >>restricted __builtins__, and it doesn't allow untrusted code to create >>names that start with _. > > > Ah, ok. That might restrict the usefulness of the package (perhaps > that is what "restricted" really means here :-). > > People would not normally consider the type builtin insecure, and > might expect it to work. If you restrict Python to, say, just integers > (and functions thereof), it may be easy to see it is safe - but it is > also easy to see that it is useless. > > The challenge perhaps is to provide the same functionality as rexec, > without the same problems. Well, I'm providing a same_type function that compares types. What else do you want to do with type()? The other option is to go the Zope3 route and provide proxies to the type objects returned by type(). From krawlins at ucsc.edu Thu Jan 22 17:30:44 2004 From: krawlins at ucsc.edu (Kyle Rawlins) Date: Thu, 22 Jan 2004 14:30:44 -0800 Subject: prog/lib to draw graphs In-Reply-To: References: Message-ID: <9E29AC1E-4D2A-11D8-9635-000393BC2E7A@ucsc.edu> On Jan 22, 2004, at 5:15 AM, Florian Lindner wrote: > Thanks! (to all) > Does GraphViz also support the automated optimal placement of nodes? > I'll > have many nodes... What constitutes optimal is a matter of an entire subfield of graph theory, and is pretty different depending on what type of graph you are doing. Nonetheless, graphviz does pretty well without any cues. In a project I used to use it in (a browser for large automatically learned ontologies) I would sometimes use it to render thousands of nodes, and it would usually look better than I expected. There is a problem in that highly connected large graphs result in a lot of black ink for the edges, since in such graph they will be much denser than the DPI of your screen. I'm not sure you'll find any full display of a large graph practical for interactive use without a lot of tweaking. If you do want to use it interactively, be prepared for long waits (>30s, sometimes several minutes) for very large graphs. For small graphs, it's near instantaneous. This is a problem with graph layout algorithms in general, however, and not graphviz per se - they do not scale very efficiently. People I know who used ygraph, a commercial package, told me that it was not much faster on large graphs. hope that helps, -kyle From jjl at pobox.com Sat Jan 10 12:46:52 2004 From: jjl at pobox.com (John J. Lee) Date: 10 Jan 2004 17:46:52 +0000 Subject: Asynchronous HTTP server in standard library ? References: <87eku76cp0.fsf@blakie.riol> Message-ID: <87ad4vy9v7.fsf@pobox.com> Wilk writes: > "Pierre Quentel" writes: [...] > > Any thoughts ? > > I think you'll be welcome in the web-sig !!! > http://python.org/sigs/web-sig/ Yes, certainly -- don't let it worry you that the discussion died down for the last month or so. It'll likely start up again if/when somebody posts something interesting (or, more accurately, when somebody posts something controversial ;-). John From ptmcg at users.sourceforge.net Fri Jan 9 11:03:31 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Fri, 09 Jan 2004 16:03:31 GMT Subject: how to speedup this code? References: Message-ID: "Ognen Duzlevski" wrote in message news:btmgtp$grr$1 at chessie.cirr.com... > Hi all, > > I have rewritten a C program to solve a bioinformatics problem. Portion where most of the time is spent is: > > def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): > global ONEINDELPENALTY,OPENGAPPENALTY > > for ndx1 in range(1,tlen+1): > for ndx2 in range(1,qlen+1): > delmat[ndx1][ndx2] = Min(delmat[ndx1-1][ndx2]+ONEINDELPENALTY, \ > Min(scoremat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY, \ > insertmat[ndx1-1][ndx2]+OPENGAPPENALTY+ONEINDELPENALTY)) > insertmat[ndx1][ndx2] = Min(insertmat[ndx1][ndx2-1]+ONEINDELPENALTY, \ > Min(scoremat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY, \ > delmat[ndx1][ndx2-1]+OPENGAPPENALTY+ONEINDELPENALTY)) > scoremat[ndx1][ndx2] = Min(scoremat[ndx1-1][ndx2-1], \ > Min(delmat[ndx1-1][ndx2-1], insertmat[ndx1-1][ndx2-1])) + \ > GetFitnessScore(tseq,ndx1-1,qseq,ndx2-1) > > def Min(a,b): > if a< b: > return a > else: > return b > > In C this is not a big deal, delmat, scoremat and insertmat are int matrices dynamically allocated and the > loop-inside-a-loop is pretty fast. However, on python (2.3) it is very slow. So for comparison, my C version takes 8 > seconds to execute and the python version takes around 730 seconds. I have narrowed down through visual observation > (print before and print after entry into the above nested loop) that most of the time is spent in there. I have also > tried the Numeric package with their arrays. It speeded things up somewhat but not considerably. > > Any suggestions? > > Thank you, > Ognen I'm a big fan of "knowing one's blind spots." It looks to me like you are using Python, but still thinking in C. Here are some things Python will be able to do that C wont. 1. No need to define your own Min() routine - Python has a built-in min() function that works fine. 2. And even better, the Python min() will accept an arbitrary number of arguments, not just two. So instead of calling Min(a,Min(b,c)) you can just call min(a,b,c). (This should help quite a bit, as function call overhead in Python is relatively high.) 3. Access to locals is faster than globals (I'm told). Try copying ONEINDELPENALTY and OPENGAPPENALTY to local vars. Also, since you are not updating them, the global declaration of ONEINDEL... and OPENGAP... is not strictly necessary - but I like to include these declarations anyway, as a reminder that these are globals being accessed. 4. Look at repeated operations, especially in your inner loop. You recalculate ndx1-1 many times - how about doing it once in the outer loop before the second for statement, something like ndx1_1 = ndx1-1, and then reference ndx1_1 instead (and similar for ndx2-1 and OPENGAPPENALTY+ONEINDELPENALTY). 5. Look into using the psyco package. It is very low overhead, non-intrusive, and can give remarkable results. 6. More performance tips at http://manatee.mojam.com/~skip/python/fastpython.html, or by Googling for "python performance". -- Paul From OlafMeding at compuserve.com Thu Jan 8 09:40:37 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 8 Jan 2004 06:40:37 -0800 Subject: Name of the function Message-ID: <9e5ea2c4.0401080640.64ef5d58@posting.google.com> I am looking for a way to get at the name of the function (while executing code inside the function) without (!) knowing the name of the function. The code below works, but requires the name of the function. I am looking for a way to do the same w/o specifying the name of the function. def olaf(): # requires name of the function print olaf.__name__ # this does not work print self.__name__ From eric.brunel at N0SP4M.com Mon Jan 12 04:26:01 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 12 Jan 2004 10:26:01 +0100 Subject: Moving widgets in Tkinter References: Message-ID: Adonis wrote: > I wish to manually move widgets in Tkinter, now I have successfully done it, > but with odd results, I would like to move the widgets with a much smoother > manner, and better precision. > > Any help is greatly appreciated. > > -- > > here is snip of working code: > > from Tkinter import * > > class blah: > > def MoveWindow(self, event): > self.root.update_idletasks() > self.f.place_configure(x=event.x_root, y=event.y_root-20) event.x_root & event.y_root will give you the coordinates of the event in the *screen*, which is apparently not what you want. The name "root" traditionally used for Tkinter main windows is somewhat confusing here: the window called "root" in tk/Tkinter methods is the screen, not your main window. > def __init__(self): > self.root = Tk() > self.root.title("...") > self.root.resizable(0,0) > self.root.geometry("%dx%d%+d%+d"%(640, 480, 0, 0)) > > self.f = Frame(self.root, bd=1, relief=SUNKEN) > self.f.place(x=0, y=0, width=200, height=200) > > self.l = Label(self.f, bd=1, relief=RAISED, text="Test") > self.l.pack(fill=X, padx=1, pady=1) > > self.l.bind('', self.MoveWindow) > self.f.bind('', self.MoveWindow) > > self.root.mainloop() > > x = blah() Doing what you want is a bit more complicated than what you've already done: the best way to use event.x_root and event.y_root here is relatively to a former recorded position. What I'd do would be the following: ----------------------------------------- from Tkinter import * class blah: def startMoveWindow(self, event): ## When the movement starts, record current root coordinates self.__lastX, self.__lastY = event.x_root, event.y_root def MoveWindow(self, event): self.root.update_idletasks() ## Use root coordinates to compute offset for inside window coordinates self.__winX += event.x_root - self.__lastX self.__winY += event.y_root - self.__lastY ## Remember last coordinates self.__lastX, self.__lastY = event.x_root, event.y_root ## Move inside window self.f.place_configure(x=self.__winX, y=self.__winY) def __init__(self): self.root = Tk() self.root.title("...") self.root.resizable(0,0) self.root.geometry("%dx%d%+d%+d"%(640, 480, 0, 0)) ## Record coordinates for window to avoid asking them every time self.__winX, self.__winY = 0, 0 self.f = Frame(self.root, bd=1, relief=SUNKEN) self.f.place(x=self.__winX, y=self.__winY, width=200, height=200) self.l = Label(self.f, bd=1, relief=RAISED, text="Test") self.l.pack(fill=X, padx=1, pady=1) ## When the button is pressed, make sure we get the first coordinates self.l.bind('', self.startMoveWindow) self.l.bind('', self.MoveWindow) self.f.bind('', self.startMoveWindow) self.f.bind('', self.MoveWindow) self.root.mainloop() x = blah() ----------------------------------------- HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From pmagic at snet.net Tue Jan 27 20:49:51 2004 From: pmagic at snet.net (Paul M) Date: Tue, 27 Jan 2004 20:49:51 -0500 Subject: Python 2.3.3 : Win32 build vs Cygwin build performance ? In-Reply-To: <4016d8a3$0$19263$626a54ce@news.free.fr> References: <4016a71d$0$15004$afc38c87@news.easynet.fr> <4016d8a3$0$19263$626a54ce@news.free.fr> Message-ID: Nicolas Lehuen wrote: > I have reproduced this on another machine. I tried playing with the > optimizer options (-O, -OO) and the result is the same : on pystone, Cygwin > 1.5.6-1 + Python 2.3.3-1 is nearly twice as better as the standard Python > 2.3.3 distribution for Win32... > > I have checked that both distribution are psyco-free. Does anyone have an > idea of what is going on there ? Better compilation optimisation settings ? > GCC 3.3.1 producing faster code than MSVC 6 (allright, I can imagine that, > but twice faster ???) ? > > Regards > Nicolas > I get results opposite yours (though with an oddity in the CPU seconds reported on the Win32 build -- see below). I'm also using Cygwin 1.5.6-1 + 2.3.3-1 and the stock Python 2.3.3 distribution for Win32. Here's my cygwin results: $ time python /usr/lib/python2.3/hotshot/stones.py Pystone(1.1) time for 50000 passes = 2.813 This machine benchmarks at 17774.6 pystones/second 850004 function calls in 5.825 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 50000 2.148 0.000 2.207 0.000 pystone.py:184(Proc6) 50002 1.102 0.000 1.102 0.000 pystone.py:45(__init__) 1 0.662 0.662 5.825 5.825 pystone.py:79(Proc0) 50000 0.435 0.000 4.188 0.000 pystone.py:133(Proc1) 50000 0.340 0.000 0.340 0.000 pystone.py:208(Proc8) 150000 0.182 0.000 0.182 0.000 pystone.py:203(Proc7) 150000 0.181 0.000 0.181 0.000 pystone.py:221(Func1) 50000 0.170 0.000 0.226 0.000 pystone.py:229(Func2) 50000 0.163 0.000 1.265 0.000 pystone.py:53(copy) 50000 0.152 0.000 0.214 0.000 pystone.py:160(Proc3) 50000 0.103 0.000 0.103 0.000 pystone.py:149(Proc2) 50000 0.072 0.000 0.072 0.000 pystone.py:177(Proc5) 50000 0.059 0.000 0.059 0.000 pystone.py:246(Func3) 50000 0.056 0.000 0.056 0.000 pystone.py:170(Proc4) 1 0.000 0.000 5.825 5.825 pystone.py:67(pystones) 0 0.000 0.000 profile:0(profiler) real 0m35.403s user 0m34.827s sys 0m0.233s And my Win 32 results: C:\Documents and Settings\pmagwene>python c:\Python23\Lib\hotshot\stones.py Pystone(1.1) time for 50000 passes = 2.44903 This machine benchmarks at 20416.3 pystones/second 850004 function calls in 6559.446 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 1689.491 1689.491 6559.412 6559.412 pystone.py:79(Proc0) 50000 987.212 0.020 2610.494 0.052 pystone.py:133(Proc1) 50000 775.010 0.016 775.010 0.016 pystone.py:208(Proc8) 50000 416.668 0.008 637.938 0.013 pystone.py:53(copy) 150000 409.522 0.003 409.522 0.003 pystone.py:221(Func1) 50000 406.804 0.008 535.380 0.011 pystone.py:229(Func2) 150000 396.484 0.003 396.484 0.003 pystone.py:203(Proc7) 50000 310.752 0.006 445.215 0.009 pystone.py:160(Proc3) 50000 290.596 0.006 410.274 0.008 pystone.py:184(Proc6) 50000 239.539 0.005 239.539 0.005 pystone.py:149(Proc2) 50002 221.310 0.004 221.310 0.004 pystone.py:45(__init__) 50000 150.247 0.003 150.247 0.003 pystone.py:170(Proc4) 50000 146.099 0.003 146.099 0.003 pystone.py:177(Proc5) 50000 119.678 0.002 119.678 0.002 pystone.py:246(Func3) 1 0.033 0.033 6559.446 6559.446 pystone.py:67(pystones) 0 0.000 0.000 profile:0(profiler) The Pystone time and machine benchmark shows that my Win32 build is faster, though I don't understand the CPU seconds readout -- the pystone benchmark did not last 1.5 hrs! Maybe it's something odd about my setup? -- dual Xeons (hyperthreading enabled), 2.5 GB ram, WinXP... --Paul From tjreedy at udel.edu Tue Jan 20 12:40:34 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 Jan 2004 12:40:34 -0500 Subject: python As400 References: Message-ID: <3o-dneda6Oma9ZDdRVn-jw@comcast.com> "Enrique" wrote in message news:mailman.538.1074596683.12720.python-list at python.org... >I'm very interested in python for AS/400. I must migrate an application that >is running under windows to AS/400. >Has anyone worked with python in that platform?? Python has been ported to just about everything. As with many questions asked here, google is your friend. You can search both the web and clp archives. tjr From kbass at midsouth.rr.com Sat Jan 24 15:21:28 2004 From: kbass at midsouth.rr.com (kbass) Date: Sat, 24 Jan 2004 14:21:28 -0600 Subject: Python and writing a CSV file References: <20040121232549.GA28328@mail.theserver.ath.cx> <009501c3e07e$80b62e30$97443d42@homebass1> <16399.7079.192926.761791@montanaro.dyndns.org> Message-ID: <000c01c3e2b7$a6eabcc0$97443d42@homebass1> ----- Original Message ----- From: "Skip Montanaro" To: "kbass" Cc: "Python List" Sent: Wednesday, January 21, 2004 6:39 PM Subject: Re: Python and writing a CSV file > > Kevin> I am new to Python and would like to attempt to write to a CSV > Kevin> file. I have reviewed the documentation at > Kevin> http://www.object-craft.com.au/projects/csv/ for the csv 1.0 > Kevin> module but I didn't see any information referring to writing (oe > Kevin> creating) a CSV file with this module. Does this module have the > Kevin> capability to write a CSV file? > > Yes, but you should upgrade to 2.3 (if you haven't already) and just use the > csv module which comes with it: > > http://www.python.org/doc/current/lib/module-csv.html > > Skip Thanks for responding. Currently we do not have Python 2.3 installed on our server, is there another way to perform this task with another module or without a module? Thanks! Kevin From kevin at sb.org Thu Jan 29 13:42:47 2004 From: kevin at sb.org (Kevin Ballard) Date: Thu, 29 Jan 2004 13:42:47 -0500 Subject: Python & XML & DTD (warning: noob attack!) References: Message-ID: <2004012913424775249%kevin@sborg> On 2004-01-29 07:04:44 -0500, Igor Fedorow said: > I tried xml.dom.ext.PrettyPrint, but it produces only > > > > > ... > > > actually lacking the document type definition. Why not simply use that, then replace the with the DTD? I'm sure you can parse it out from the original file. -- "Remember, no matter where you go, there you are." -Buckaroo Banzai Kevin Ballard http://kevin.sb.org From rune.froysa at usit.uio.no Mon Jan 12 02:41:43 2004 From: rune.froysa at usit.uio.no (Rune Froysa) Date: 12 Jan 2004 08:41:43 +0100 Subject: Unicode and exception strings References: Message-ID: Terry Carroll writes: > On 09 Jan 2004 13:18:39 +0100, Rune Froysa > wrote: > > >Assuming an exception like: > > > > x = ValueError(u'\xf8') > > > >AFAIK the common way to get a string representation of the exception > >as a message is to simply cast it to a string: str(x). This will > >result in an "UnicodeError: ASCII encoding error: ordinal not in > >range(128)". > > > >The common way to fix this is with something like > >u'\xf8'.encode("ascii", 'replace'). However I can't find any way to > >tell ValueErrors __str__ method which encoding to use. > > Rune, I'm not understanding what your problem is. > > Is there any reason you're not using, for example, just repr(u'\xf8')? The problem is that I have little control over the message string that is passed to ValueError(). All my program knows is that it has caught one such error, and that its message string is in unicode format. I need to access the message string (for logging etc.). > _display_text = _display_text + "%s\n" % line.decode('utf-8')) This does not work, as I'm unable to get at the 'line', which is stored internally in the ValueError class (and generated by its __str_ method). Regards, Rune Fr?ysa From jcarlson at uci.edu Thu Jan 22 11:59:45 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Jan 2004 08:59:45 -0800 Subject: newbie,cgi,os.system,cdrecord References: <400fe08c$0$326$e4fe514c@news.xs4all.nl> Message-ID: <20040122085927.026A.JCARLSON@uci.edu> On Thu, 22 Jan 2004 15:39:47 +0100 Rik van der Helm wrote: > Hello, > > I am trying to make a backupscript in python, which I want to manage via a > webform (cgi). In my script I use os.system to execute the following > shellscript: > "cdrecord -s -dev=0,1,0 -blank=fast -speed=2 fs=8m file.tgz" > > When I execute the pythonscript in the shell, it gets executed well and I > get some output from cdrecord. Which I don't understand because I put > cdrecord at silent (-s !) I thought. > > When I execute the pythonscript in a webbrowser via cgi, cdrecord also gets > executed well but I get an 'Internal Server Error' of Python and in > '/var/log/httpd/error_log' it says: > "malformed header from script. Bad header=Cdrecord 1.11a19 etc....." > > I think I understand what is going wrong. Apache tries to print the output > of cdrecord and finds something wrong and stops executing the script. Is > this correct ? If this is correct how do I get cdrecord stop making output > texts ? > > All suggestions are welcome > > Thanks, Rik > Try: "cdrecord -s -dev=0,1,0 -blank=fast -speed=2 fs=8m file.tgz > /dev/null" From spamsucks at Ih8it.com Wed Jan 14 00:23:56 2004 From: spamsucks at Ih8it.com (WTH) Date: Wed, 14 Jan 2004 00:23:56 -0500 Subject: ProtoCiv: porting Freeciv to Python CANNED References: <40047290$1@news.012.net.il> Message-ID: <6k4Nb.26887$v16.20922@bignews5.bellsouth.net> > You try to do something big, you put your money on the line to do it, you > fail or don't entirely succeed, you give postmortem, you lay all your cards > out for others to examine... *then* I will worry about your opinion. You are seriously delusional. You seem to be one of those people who is constantly seeking persecution of some sort. The kind that feels the need to bear a cross that no-one seems to think needs bearing (of course they're all delusional and YOU'RE the sane one...) Occam's razor...? WTH From donn at u.washington.edu Wed Jan 14 17:50:18 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 14 Jan 2004 14:50:18 -0800 Subject: I come not to bury C++, but to praise it... References: <100aq779r2h2c9e@corp.supernews.com> <100b266i0r70g86@corp.supernews.com> Message-ID: In article <100b266i0r70g86 at corp.supernews.com>, claird at lairds.com (Cameron Laird) wrote: ... > Great! *What* more? When I look at Python and C++, I see the > former as having *stricter*, if more dynamic, typing, so I don't > understand what advantage C++ has in this one regard apart from > time-of-detection. > > I apologize, by the way, for writing "compile-type" where I > intended "compile-time". Oops, so that was only an accident! Well, I mean that the semantics of types are different between C++ and Python. When we say Python has "dynamic typing", and C++ has "static typing", I guess that's the generally accepted way to describe what they do, but it makes it sound like they're doing the same thing, only on a different schedule. Of course they are not at all doing the same thing. It might be more accurate to use a table, like static dynamic C++ yes no Python no yes Objective C yes yes Python may have stricter dynamic typing than C++ has static typing, but that's hard to quantify. On the other hand, Python has no static typing at all. There is no way to tell it ``this function must be applied to a string and must return an int.'' If applied to a list instead, there's a non-trivial chance it will manage to do something absurd with it. If it returns None under certain circumstances, there's a non-trivial chance that value will be stashed away somewhere and you'll later wonder where the heck that None came from. Whether that's an advantage for C++ depends on 1) how important you think that is, and 2) how well you think C++ does it. Between those two, I think I'd have to agree it isn't much of an advantage, but then I'm just a hacker. Of course C++ is an easy target, but then that's the nominal subject here. Donn Cave, donn at u.washington.edu From dlmurray at micro-net.com Sun Jan 4 21:58:18 2004 From: dlmurray at micro-net.com (Dave Murray) Date: Sun, 4 Jan 2004 19:58:18 -0700 Subject: Why does this fail? References: Message-ID: Thank you all, this is a hell of a news group. The diversity of answers helped me with some unasked questions, and provided more elegant solutions to what I thought that I had figured out on my own. I appreciate it. It's part of a spider that I'm working on to verify my own (and friends) web page and check for broken links. Looks like making it follow robot rules (robots.txt and meta field exclusions) is what's left. I have found the library for html/sgml to be not very robust. Big .php and .html with lot's of cascades and external references break it very ungracefully (sgmllib.SGMLParseError: expected name token). I'd like to be able to trap that stuff and just move on to the next file, accepting the error. I'm reading in the external links and printing the title as a sanity check in addition to collecting href anchors. This problem that I asked about reared it's head when I started testing for a robots.txt file, which may or may not exist. The real point is to learn the language. When a new grad wrote a useful utility at work in Python faster than I could have written it in C I decided that I needed to learn Python. He's very sharp but he sold me on the language too. Since I often must write utilities, Python seems to be a very good thing since I normally don't have much time to kill on them. Dave From Nikola.Milutinovic at ev.co.yu Sun Jan 4 11:10:18 2004 From: Nikola.Milutinovic at ev.co.yu (Nikola Milutinovic) Date: Sun, 4 Jan 2004 17:10:18 +0100 Subject: PROBLEM: compiling C programs that link to Python Message-ID: <002e01c3d2dd$43f04110$c53da8c0@home> Hi all. I'm not subscribed to the list, so all replies to me mail directly. I ran into a small problem, for which we have found a workaround. I was compiling PostgreSQL v7.4.1 and it's PL/Python module. Compilation failed on lines which had this: typedef struct PLyPlanObject { PyObject_HEAD; ... } PLyPlanObject; The problem was in that semicolon following "PyObject_HEAD", since that is a CPP define which expands to this: typedef struct PLyPlanObject { int ob_refcnt ; struct _typeobject * ob_type ; ; ... } PLyPlanObject; That extra ";" breaks compiling on strict ANSI-C compilers (or at least on mine - DEC CC on Tru64 UNIX). The workaround was to remove the ";" from plpython.c source file. It could be that GNU C is not complaining on this, since it is more lenient on C irregularities. The idea I'd like to float here is that you guys remove the trailing ";" from your "#define ...". The source looks much more natural with a semicolon at the end. I know that this idea is going to create resistance, "it is working for us", "it is working on GCC", "it will create other changes in existing source base", "you've solved your problem". The only argument in my favour I can give is that, well, C standard doesn't recognize "; ;" in "structs". So, if you want to create CPP constructs like that "#define", create them so they can be used without breaking the standards. TYIA, Nix. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andymac at bullseye.apana.org.au Mon Jan 19 17:07:35 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 20 Jan 2004 09:07:35 +1100 (EST) Subject: Python 2.3.3 on FreeBSD 4.8 In-Reply-To: <20040119030514.48456.qmail@web60501.mail.yahoo.com> References: <20040119030514.48456.qmail@web60501.mail.yahoo.com> Message-ID: <20040120090330.F48694@bullseye.apana.org.au> On Sun, 18 Jan 2004, Taylor Leese wrote: > I am trying to compile Python 2.3.3 on FreeBSD 4.8 and > I am getting this compiling error. Anybody have any > ideas? How did you configure? I've built both 2.2.3 & 2.3.3 on FreeBSD 4.8 without the problems you mention. Having unpacked the tarball and changed into the top level directory of the source tree, I just do: ./configure --with-fpectl make You should also be able to build using the ports framework if you've updated the ports components. -- 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 exarkun at intarweb.us Sat Jan 31 15:38:02 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 31 Jan 2004 15:38:02 -0500 Subject: Python vs. Io In-Reply-To: <711c7390.0401311220.763be80a@posting.google.com> References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> Message-ID: <20040131203802.GA1664@intarweb.us> On Sat, Jan 31, 2004 at 12:20:52PM -0800, Daniel Ehrenberg wrote: > > Perhaps it isn't more flexible. On the other hand, it does allow anyone > > to read your code and know that there isn't any magical syntax that is > > usable on one Python x.y installation, that isn't on another. > > > > - Josiah > > What are you talking about? There's tons of new "magical syntax" in > Python. Examples for "magical syntax" features that don't work on > 1.5.2 include: > *List comprehensions Yep. > *String methods Nope. The syntax is identical. Strings just happen to have more useful attributes new. > *Generators Yep. > *Emulating numeric types Nope. Never seen __coerce__? :) > *Nested scopes Hmm. Not really a syntactic difference... The syntax is the same, after all, but the behavior is definitely different. > * * and ** in function declarations Yep. > *for line in this_file Nope. Same as with strings, the iterator protocol, a set of methods with a defined meaning, was added, and file objects were made to implement it. No syntactic changes. > *Subclassing types > This is another iffy one. The syntax is no different, the behavior has just been changed. "str", "int", etc, used to be builtin functions, not type objects. You also couldn't subclass types in Python, but if you could have, the syntax would have been identical to what it is today. > There's tons of stuff still being added to Python. Definitely. But "stuff" isn't always the same as "magical syntax". Jp From john at doe.com Wed Jan 21 21:21:54 2004 From: john at doe.com (Brian Donovan) Date: Thu, 22 Jan 2004 02:21:54 GMT Subject: Identifing current function Message-ID: Hi all, Is there a way to identify the current function. For example: class A: def B(self): print current_function_name From tcdelaney at optusnet.com.au Sat Jan 10 19:49:56 2004 From: tcdelaney at optusnet.com.au (Tim Delaney) Date: Sun, 11 Jan 2004 11:49:56 +1100 Subject: xrange() syntactic sugar References: <338366A6D2E2CA4C9DAEAE652E12A1DE0106382C@au3010avexu1.global.avaya.com> Message-ID: <40009db3$0$27237$afc38c87@news.optusnet.com.au> "Gerrit Holl" wrote: > > There is, by Thomas Wouters: > > PEP 204: Range Literals > 14 Juli 2000, rejected. Hah - that's what I get for relying on my faulty memory rather than actually checking :) Tim Delaney From nhodgson at bigpond.net.au Sat Jan 31 15:43:39 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 31 Jan 2004 20:43:39 GMT Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia References: <2da21d6c.0401310807.671be3b7@posting.google.com> Message-ID: <%rUSb.37510$Wa.14668@news-server.bigpond.net.au> Mikl?s: > Software patents are evil. > Hell to them. Unfortunately, software patents are part of the business landscape now. They often seem to be comfort blankets for investors ("we have something unique that absolutely preserves our market position") rather than anything real. To succeed in an interview, one must avoid laughing at the claims to uniqueness and refrain from pointing out that the patent actually describes a sub-optimal solution. Neil From aldo123 at onet.pl Tue Jan 13 10:51:04 2004 From: aldo123 at onet.pl (mic) Date: Tue, 13 Jan 2004 16:51:04 +0100 Subject: catching msie NewWindow2 event Message-ID: I'm trying to catch the MSIE NewWindow2 event using win32com interface. The code I use is basically something like below: from win32com.client import DispatchWithEvents class Events: Browser = None def OnNewWindow2(self, ppDisp, Cancel): #catching the new window and trying to place it onto my own ppDisp = Events.Browser #Cancel = True - this doesn't work either (should prevent popup from opening) ie1 = DispatchWithEvents('InternetExplorer.Application', Events) ie2 = DispatchWithEvents('InternetExplorer.Application', Events) Events.Browser = ie2 ie1.Navigate('http://jaak.sav.net/test.html') #url to the html document that opens its own window I know that setting ppDisp value should work (at least I've seen it working in C# code) but using it this way gives no results. What's more depending on the url I use the event is triggered or not (other standard events work okay). I've seen ctypes COM implementation demo that makes similiar things but it looks so much more complicated than win32com api. Hope somebody has some insight on that... Regards, Michal From jacek.generowicz at cern.ch Tue Jan 6 09:27:06 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Jan 2004 15:27:06 +0100 Subject: metadocumentation (keyword help) Message-ID: Where can I find concise, clear documentation[*] describing what one has to do in order to enable Python's internal help to be able to provide descriptions of Python keywords ? I am in a situation where I have to give Python novices the ability to fix this for themselves easily. [*] Failing "concise" and "clear", how about "complete and correct" ? From maarten at remove_this_ws.tn.tudelft.nl Mon Jan 19 04:55:31 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Mon, 19 Jan 2004 10:55:31 +0100 Subject: Looking for very simple general purpose tokenizer Message-ID: Hi group, I need to parse various text files in python. I was wondering if there was a general purpose tokenizer available. I know about split(), but this (otherwise very handy method does not allow me to specify a list of splitting characters, only one at the time and it removes my splitting operators (OK for spaces and \n's but not for =, / etc. Furthermore I tried tokenize but this specifically for Python and is way too heavy for me. I am looking for something like this: splitchars = [' ', '\n', '=', '/', ....] tokenlist = tokenize(rawfile, splitchars) Is there something like this available inside Python or did anyone already make this? Thank you in advance Maarten -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From marks.pryorSHRUB at CHENEYverizon.net Wed Jan 21 02:32:05 2004 From: marks.pryorSHRUB at CHENEYverizon.net (Mark S Pryor) Date: Wed, 21 Jan 2004 07:32:05 GMT Subject: python tool for ultraedit Message-ID: dear c.l.p, I'm posting a Py script to change the wordfile from inside the UE editor. Define this into the adv. tool menu. I found 100 posts in groups.google discussing Python and UltraEdit. Since UltraEdit is only happy with 10 parts in a Wordfile, it is convenient to have multiple wordfiles, with no more than 10 styles per wf. To keep a wf associated to a script, add a tag in the comment header: """ wordfile: e:/path/mywordfile.txt """ http://mysite.verizon.net/res1ur2j/SwitchWF.zip ------ begin SwitchWF.py ------------ #!e:/Python22/python """ script: SwitchWF.py keywords: enum window win32api handle callback author: tlviewerSHRUB at CHENEYyahoo.com relatedDoc=Selkey.png wordfile: "C:/Progra~1/UltraEdit/WORDFILE.TXT" 3 UE macro to highlight the wf tag ------- start macro ------ InsertMode ColumnModeOff HexOff UnixReOn GotoLine 1 Find RegExp "\swordfile:" IfFound Find RegExp "\S" StartSelect Key END EndSelect EndIf ------ end macro --------- synopsis: (2 arguments) python SwitchWF.py "path to new wf" Ind-of-Ext-SynHighlight """ import os, sys import win32api as ap import win32gui as wi import win32ui as ui import win32con as wc import win32clipboard myhwnd = 0 myti = '' mycl = '' # function callback #################### def Callback(hwnd, skip): global myhwnd global myti ti = wi.GetWindowText(hwnd) if ti.find(skip) >=0: myhwnd = hwnd myti = ti print myhwnd, "uedit32 found",skip return 0 else: #print myhwnd, ti return 1 # function pysendkey ####################### """ pysendkey is a pure-python replacement for the WSHShell SendKeys method! """ def pysendkey( keycode ): dwFlags= wc.KEYEVENTF_EXTENDEDKEY bVk = keycode ap.keybd_event( bVk, bScan, dwFlags, 0) dwFlags= wc.KEYEVENTF_EXTENDEDKEY | wc.KEYEVENTF_KEYUP ap.keybd_event( bVk, bScan, dwFlags, 0) # function menu_activate ######################## """ use below for activating sub menu items of the UE main menu. mid = main menu id iid = sub item id """ def menu_activate(myhwnd, mymenu, mid, iid ): pya = mymenu.GetSubMenu(mid) print pya.GetHandle() #vid = mymenu.GetMenuItemID(mid) #res = wi.SendMessageTimeout( myhwnd,wc.WM_COMMAND, vid, 0, 2, 75 ) # configuration menu item id cid = pya.GetMenuItemID(iid) print "cid=", cid #check for OS, and pack the ID if necessary env = os.environ if env['WINDIR'].find('WINNT'): print "Got NT" else: print "Win98 pack the ID" res=wi.SetForegroundWindow(myhwnd) try: res = wi.SendMessageTimeout( myhwnd,wc.WM_COMMAND, cid, 0, 2, 75 ) print "res=", res except: print "done - error " # ok ap.Sleep(50) # Main ######################## try: wi.EnumWindows(Callback, "UltraEdit-32") except: print "error", myhwnd print myti, myhwnd # get a Python handle object # enumwindows was needed above since FindWindowEx is broken in Python 2.2- # must use the --exact-- title or fail (not the case in VB) pyhw = ui.FindWindowEx( None, None, None, myti ) pymenu = pyhw.GetMenu() # when called from the UE tool menu, we need a valid selection if sys.argv[1] == '%sel%': sys.exit(0) menu_activate(myhwnd, pymenu, 9, 0) # get the hwnd of the UltraEdit Configuration dialog #hwuc = cM.FindWindowLike( cl, "UltraEdit Configuration" ) hwuc = wi.FindWindowEx(0, 0, "#32770", "UltraEdit Configuration" ) print "ue config=", hwuc # get handle to the child systabcontrol32 class hwtab = wi.FindWindowEx( hwuc , 0, "SysTabControl32", None ) print hwtab # open the 7 item via message # TCM_FIRST= &h1300 #Const TCM_SETCURFOCUS As Long = (TCM_FIRST + 48) # not found in Win32Con TCM_SETCURFOCUS = 0x1330 SYNTAX_HIGHLIGHT = 7 wi.PostMessage( hwtab, TCM_SETCURFOCUS, SYNTAX_HIGHLIGHT , 0) # get the myhwnd to the SynHigh dialog hwsh = wi.FindWindowEx( hwuc, 0, "#32770", "Syntax Highlighting") print "SynHigh myhwnd=",hwsh # get the myhwnd to its only edit box hwedit = wi.FindWindowEx( hwsh, 0, "Edit", None) res = wi.SetForegroundWindow(hwedit) # set the focus here lres = wi.SendMessageTimeout(hwedit, wc.WM_SETFOCUS , None , None , 2 , 50 ) ## press down ######### dwFlags= wc.KEYEVENTF_EXTENDEDKEY bVk = wc.VK_SHIFT bScan = 1 # or 0 ap.keybd_event( bVk, bScan, dwFlags, 0) bVk = wc.VK_END bScan = 1 # or 0 ap.keybd_event( bVk, bScan, dwFlags, 0) ########### end down keys################# # up the two keys ################ dwFlags= wc.KEYEVENTF_EXTENDEDKEY | wc.KEYEVENTF_KEYUP ap.keybd_event( bVk, bScan, dwFlags, 0) bVk = wc.VK_SHIFT ap.keybd_event( bVk, bScan, dwFlags, 0) ########### end up keys ################## # press BACKSPACE up , then down pysendkey( wc.VK_BACK ) #################################### #print sys.argv[1] if len(sys.argv)>1: win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(sys.argv[1]) win32clipboard.CloseClipboard() # paste the clipboard, then push enter # lres = wi.SendMessageTimeout(hwedit, wc.WM_PASTE, 0 , 0 , 2 , 50 ) pysendkey( wc.VK_RETURN ) print "done" print sys.argv[1] # if len(sys.argv)>2: # # get the View menu # menu_activate( myhwnd, pymenu, 5, int(sys.argv[2])) # ap.Sleep(50) ------ end script ------------ good luck, Mark Pryor From myfirstname at mylastname.com Sun Jan 4 00:47:04 2004 From: myfirstname at mylastname.com (Dan Bullok) Date: Sun, 04 Jan 2004 05:47:04 GMT Subject: Parametrized inheritance References: <2AJJb.725692$HS4.5422608@attbi_s01> Message-ID: Mike C. Fletcher wrote: > You can find more information about these kinds of patterns by searching > for "Mix-In Class" and/or "Multiple Inheritance". Python 2.2 changed how > multiple inheritance graphs are constructed in Python, BTW. If you used > old-style classes the mro would have been [MySub, Sub, Base, MyBase, Base] > IIRC. Well, I thought of doing this, but after looking up resolution order (sec 9.5.1 of the tutorial) I found that resolution is done "depth-first, left-to-right", In my example, that would have given [MySub, Sub, Base, MyBase, Base], but, I checked, using mro(), and found that it was indeed [MySub, Sub, MyBase, Base], just as I needed it. (thanks for the mro() tip - didn't know about that one). Unless I've gone crosseyed (possible, it's late), this is NOT depth-first, left-to-right. So is the tutorial out of date? From jensthiede at webgear.co.za Sun Jan 11 13:45:40 2004 From: jensthiede at webgear.co.za (Jens Thiede) Date: 11 Jan 2004 10:45:40 -0800 Subject: Variable Scope 2 -- Thanks for 1. References: Message-ID: OK, thanks for sorting that out, but what do I replace in the following to avoid referancing: x = [[0]*5]*5 x is [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] and after x[0][0] = 1; x is [[1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0], [1,0,0,0,0]] is there a shorthand way to avoid referance or do I have to use a loop or: x = [[0]*5]+[[0]*5]+[[0]*5]+[[0]*5]+[[0]*5] which is obviously stupid to try and do when the second cofficiant is large or a variable. Help would be much appreciated, Jens Thiede From elainejackson7355 at home.com Fri Jan 30 00:49:29 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 30 Jan 2004 05:49:29 GMT Subject: conditional expression sought References: Message-ID: This is just for theoretical interest. The A_i's and B_i's were meant as metavariables. "Corey Coughlin" wrote in message news:a8623416.0401291625.594a9768 at posting.google.com... | "Elaine Jackson" wrote in message news:... | > If bool(B_i)==True for 1<=i<=n and j is the smallest i with bool(A_j)==True, | > then the evaluation of (A_1 and B_1) or ... or (A_n and B_n) returns B_j without | > evaluating any other B_i. This is such a useful mode of expression that I would | > like to be able to use something similar even when there is an i with | > bool(B_i)==False. The only thing I can think of by myself is ( (A_1 and [B_1]) | > or ... or (A_n and [B_n]) )[0], and I can't be satisfied with that for obvious | > reasons. Does anybody know a good way to express this? Any help will be mucho | > appreciado. | > | > Peace | | Oh, this must be part of your truth table script. Interesting, | looking for something like a fast SOP evaluator, or more like a | function evaluation mechanism? It would probably be most useful to | share your containers for A and B. Are you really going to have | variables named A_1 to A_n, or will you just have a vector A[0:n]? | The vector would probably be easier to deal with. Using integer | representations for your boolean vectors is a good idea, and will | probably buy you enough speed that you won't need a more serious form | of short circuit evaluation, I imagine. Unless your vectors are very | large indeed. Hmm... From rmkrauter at yahoo.com Wed Jan 21 12:01:42 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed, 21 Jan 2004 09:01:42 -0800 (PST) Subject: Assignment to slice Message-ID: <20040121170142.55936.qmail@web40104.mail.yahoo.com> I do not understand why python behaves the way it does in the following code: Here, Python doesn't like that I'm assigning out-of-range. OK. That's fine. >>> x = [] >>> x[5] = 3 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range However, the following seems very strange. Assigning to a slice, over non-existent array indexes, sets x[0] and x[1]. >>> x[2:5] = [3,4] >>> x [3,4] >>> x[1000:9000] = [5] >>> x [3, 4, 5] Why does assigning to a slice of non-existent array elements fill in the array, starting with the first empty array position? (Acts like [].append() or [].extend()?) Why not raise an out-of-bounds exception here too? Wouldn't that be more consistent with the first case, in which I tried to assign out-of-range, and got an exception? IMO, at least the first index in the slice should be required to exist in the array. If not, raise an exception. That way, assigning to the slice fills in the array in a predicatable way without having to do len() checks first to ensure that you know where in the array the slice is actually going to be inserted. But I'm sure it is the way it is for a good reason. Hopefully someone can clue me in. Thank you in advance. Rich __________________________________ Do you Yahoo!? Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes http://hotjobs.sweepstakes.yahoo.com/signingbonus From __peter__ at web.de Thu Jan 29 11:28:41 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Jan 2004 17:28:41 +0100 Subject: Get number of iteration References: Message-ID: Florian Lindner wrote: > If I iterate through a list, is there a way I can get the number of the > iteration: first, second, third, ... > > l = ["three", "four", "five", "six"] > for x in l > print x > print x.iteration() # <- That's what I'm looking for! > print "next" >>> sample = "tree for five".split() >>> for index, item in enumerate(sample): ... print index, item ... 0 tree 1 for 2 five You are looking for enumerate(). Counting starts at 0, though. Peter From nid_oizo at yahoo.com_remove_the_ Tue Jan 27 17:43:45 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 27 Jan 2004 17:43:45 -0500 Subject: Portable /dev/null? Message-ID: Hi everyone, Is there an object in some standard library that would be the portable equivalent of "file('/dev/null','w')" or do I have to create my own class and object to do it? If it doesn't exist, do you think it would be a good idea to have such an object in a standard library? Thx and Regards, Nicolas From mark at mceahern.com Fri Jan 23 04:54:01 2004 From: mark at mceahern.com (Mark McEahern) Date: Fri, 23 Jan 2004 03:54:01 -0600 Subject: Batch commands on Windows In-Reply-To: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> References: <7A3Qb.4870$AK2.3953@newssvr29.news.prodigy.com> Message-ID: <1074851641.5354.166.camel@dev.internal> On Fri, 2004-01-23 at 00:56, Moosebumps wrote: > So, after reading some messages about os.system, and looking at the popen > stuff and trying it a bit, I still have not found a way to keep a command > window open for several commands (on Windows 2000/XP), while seeing the > normal output in a command window. All I want to do is do what a batch file > does, but I want to actually have functions and associative arrays and all > the other niceties of python. 1. Open file whatever.py, put this in it: print "Hello world" 2. Open cmd.exe, navigate to where whatever.py is and type: whatever.py What happens? // m p.s. It's likely I've misunderstood your question because on the face of it, as I understand your question, what you're saying is a glaring hole in Python are aspects of Python I use effortlessly every day. From guettli at thomas-guettler.de Tue Jan 13 08:18:09 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 13 Jan 2004 14:18:09 +0100 Subject: what is best for web development?? References: Message-ID: Am Mon, 12 Jan 2004 11:44:56 +0000 schrieb ketulp_baroda: > i am developing an issue tracking system > the primary requirements are > 1)it should be platform independent which i think python will take > care of > 2)it should have customizeable gui .I am thinking of using templates > for this like Cheetah. Is there any other better solution to Cheetah? > The problem i am facing here is i dont know what to use for > development of the application. I came across many ways to develop > web application in python which I already specified like > i)the cgi module in python > ii)Python Server Pages > iii)Quixote > iv)WebWare > v)Zope etc. > I want to choose such an environment so that i dont have to install > other softwares to run my application.For eg. I think if I develop > using zope then the client also has to install zope to run my > software and i dont want this. That's not true. Zope send HTML over HTTP to your client. You can use it with any webbrowser. I like Quixote, but don't use the forms library or the template language. I prefere python: def foo(self, request): ret=[] ret.append(self.header()) ret.append( """ HTML """) ret.append(self.footer()) return ''.join(ret) thomas From giles_brown at hotmail.com Wed Jan 28 08:44:02 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 28 Jan 2004 05:44:02 -0800 Subject: Help with Extension Class Crash Message-ID: <57de9986.0401280544.37d56ebb@posting.google.com> Hello folks, I'm tryin to write an extension class in C (been a while since I wrote some C :-). I want the class to be inheritable from Python. I've put the magic incantations into the type descriptor. But it crashes. I've tracked the crash down to a call to PyObject_GenericGetAttr. When I sub-class my class the tp_dictoffset comes out as -4 which quoting from PyObject_GenericGetAttr: """ if (dictoffset < 0) { int tsize; size_t size; tsize = ((PyVarObject *)obj)->ob_size; if (tsize < 0) tsize = -tsize; size = _PyObject_VAR_SIZE(tp, tsize); dictoffset += (long)size; assert(dictoffset > 0); assert(dictoffset % SIZEOF_VOID_P == 0); } dictptr = (PyObject **) ((char *)obj + dictoffset); dict = *dictptr; <---- crash happens here """ The class I'm trying to create is a variable size class. Everything is ok unless I sub-class it. I'm guess that maybe I haven't set the sizes up ok so its sending the dictptr off into the blue. Or I've missed setting of something, but not sure where to look. Can anyone help? Thanks, Giles From jepler at unpythonic.net Wed Jan 28 12:34:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 28 Jan 2004 11:34:46 -0600 Subject: posixpath.abspath and symlinks In-Reply-To: References: Message-ID: <20040128173446.GS18498@unpythonic.net> On Wed, Jan 28, 2004 at 10:37:39PM +0530, Sidharth Kuruvila wrote: > i dont know unix. > how does abs path work with sym-links. os.abspath does not check whether any components are symlinks. In the presence of symlinks, /a/../b and /b can refer to separate files if /a is a symlink to a directory. As far as I know, posixpath.abspath normalizes the first into the second anyway. Similarly, if you have a symlink /a -> c then posixpath.abspath("a") doesn't return /c, it still returns /a You can use os.readlink() on posix systems to get the thing a symlink points to: >>> os.readlink("/proc/self") '14717' >>> os.readlink("/") OSError: [Errno 22] Invalid argument: '/' Jeff From http Thu Jan 8 22:25:32 2004 From: http (Paul Rubin) Date: 08 Jan 2004 19:25:32 -0800 Subject: convert a list to a string References: <3FFE1E29.20801@hotmail.com> Message-ID: <7xwu81dcr7.fsf@ruckus.brouhaha.com> Bart Nessux writes: > number = random.sample(range(count), 1) > > This makes 'number' into a one entry list (I don't know why as 'count' > is an integer). Is there an easy way to convert 'number' back to an > int? number = number[0] But why are you using random.sample for that? And making a list of size count, just to throw it away? It sounds like you just want a random number between zero and count. Do that with: number = random.randint(count) From deets_noospaam at web.de Wed Jan 28 10:00:06 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 28 Jan 2004 16:00:06 +0100 Subject: Chart drawing library for Python References: <6ee58e07.0401280403.3d52a9e0@posting.google.com> Message-ID: Hi, > is there something like "JpGraph" for python ? > For those who don't know this PHP library: It is a high level > drawing library that generates gif files with all kind of charts. > > Or (maybe better) is there a C library doing this. I think i > read about something like this a while ago. there has been a thread about this lately: Many people (including me) use graphviz for that. As long as you don't need interactivity, it does a really great job. Diez From aahz at pythoncraft.com Mon Jan 19 16:51:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2004 16:51:59 -0500 Subject: stack-like file object References: <400be8f3_2@nova.entelchile.net> Message-ID: In article <400be8f3_2 at nova.entelchile.net>, Rodrigo Benenson wrote: > >I need to implement a stack on a file. Why not use a real database? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ A: No. Q: Is top-posting okay? From opengeometry at yahoo.ca Sun Jan 25 03:24:06 2004 From: opengeometry at yahoo.ca (William Park) Date: 25 Jan 2004 08:24:06 GMT Subject: Python features in Bash (request for feedback) Message-ID: I wrote a patch to Bash shell, incorporating some of Awk/Python features that I use a lot: http://home.eol.ca/~parkw/bash.diff http://home.eol.ca/~parkw/index.html I would like to get feedback as to what Python features you would like to see in Bash. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From engsolnom at ipns.com Thu Jan 8 21:28:34 2004 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Thu, 08 Jan 2004 18:28:34 -0800 Subject: Pesky reverse() Message-ID: <3t3svvs7ni8l8jnn1l1v60oogirqoaa85f@4ax.com> I need to use the built-in method 'reverse', but notice strange behavior. Foe example: print my_list.reverse() doesn't work. new_list = my_list.reverse() doesn't work. my_list.reverse() print my_list does work. (displays reversed list) But I want both a 'forward' and 'reverse' list: new_list = my+list # should save a 'forward' copy, right? Nope my_list.reverse() actually reverses both copies, since Python is a bit too helpful sometimes, and I understand why. So the question is, how do I get a forward and reverse list? Thanks......Norm. From jonas at jonasgalvez.com Thu Jan 8 19:07:02 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Thu, 8 Jan 2004 22:07:02 -0200 Subject: NNTP Server for this group References: Message-ID: > [John P. Speno] > gmane.comp.python.general on http://www.gmane.org/? Sweet! Thanks... =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team