From tim at tdw.net Fri Mar 30 09:08:40 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 30 Mar 2007 14:08:40 +0100 Subject: Sending emails to 3 addresses.... In-Reply-To: References: Message-ID: <9afea2ac0703300608n6d7e7605hb42e7ce0d63b2f91@mail.gmail.com> On 30/03/07, Boudreau, Emile wrote: > > sendMail('this is the subject line', 'the results: 71 fails, 229 pass, 300 > total.', 'user1 at mycompany.com, user2 at mycompany.com, user3 at mycompany.com') > > def sendMail(subject, body, TO, FROM="machine at mycompany.com"): > print TO > HOST = "exchange.mycompany.com" > BODY = string.join(( > "From: %s" % FROM, > "To: %s" % TO, > "Subject: %s" % subject, > "", > body > ), "\r\n") > server = smtplib.SMTP(HOST) > server.sendmail(FROM, [TO], BODY) > server.quit() > Emile, You are passing the TO addresses as 3 addresses in a single string. [TO] results in a list containing a single string - not a list containing 3 individual addresses. You need to either pass the addresses to the function as a list containing the 3 addresses as individual strings, or change [TO] to TO.split(',') HTH :) From rebeccagcox at gmail.com Sun Mar 11 19:05:50 2007 From: rebeccagcox at gmail.com (rebeccagcox at gmail.com) Date: 11 Mar 2007 16:05:50 -0700 Subject: Phase change material ... In-Reply-To: <3tEIh.4571$B25.683@news01.roc.ny> References: <1173405474.489111.139350@p10g2000cwp.googlegroups.com> <1173554707.826932.246100@30g2000cwc.googlegroups.com> <3tEIh.4571$B25.683@news01.roc.ny> Message-ID: <1173654350.311432.51480@v33g2000cwv.googlegroups.com> Hey, thermate--could you check your post on China from January and respond. Thanks. From will at willNOmcguganSPAM.com Sat Mar 10 11:24:30 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Sat, 10 Mar 2007 16:24:30 +0000 Subject: Announcing BBCode parsing module Message-ID: <45f2dbc1$0$2453$db0fefd9@news.zen.co.uk> Hi, I have written a BBCode parsing module that may be of use to some people. It turns BBCode in to XHTML snippets. See the following page if you are interested... http://www.willmcgugan.com/2007/03/10/bbcode-python-module/ Will McGugan -- blog: http://www.willmcgugan.com From n00m at narod.ru Sat Mar 17 23:54:33 2007 From: n00m at narod.ru (n00m) Date: 17 Mar 2007 20:54:33 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174189566.189546.85510@y80g2000hsf.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <1174024633.431427.236920@y66g2000hsf.googlegroups.com> <7xslc5k9cc.fsf@ruckus.brouhaha.com> <1174158002.730076.22720@y80g2000hsf.googlegroups.com> <1174166115.263201.51840@d57g2000hsg.googlegroups.com> <1174189566.189546.85510@y80g2000hsf.googlegroups.com> Message-ID: <1174190073.112097.29160@l75g2000hse.googlegroups.com> my dial-up line's too slow for downloading 4mb of shedskin-0.0.20.exe From lbates at websafe.com Thu Mar 29 12:40:05 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 29 Mar 2007 11:40:05 -0500 Subject: how can I clear a dictionary in python In-Reply-To: <460bcf46$0$23128$426a74cc@news.free.fr> References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> <460bcf46$0$23128$426a74cc@news.free.fr> Message-ID: <460BEBE5.3030607@websafe.com> Bruno Desthuilliers wrote: > Larry Bates a ?crit : >> Aahz wrote: >>> In article <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d at comcast.com>, >>> Larry Bates wrote: >>>> Marko.Cain.23 at gmail.com wrote: >>>>> I create a dictionary like this >>>>> myDict = {} >>>>> >>>>> and I add entry like this: >>>>> myDict['a'] = 1 >>>>> but how can I empty the whole dictionary? >>>> just point myDict to an empty dictionary again >>>> >>>> myDict={} >>> Go back and read Christian's post, then post a followup explaning why >>> his >>> solution is better than yours. Your explanation should use id(). >> >> I believe he (as many new to Python do) are mired in old >> programming thinking that variables "contain" things. > > Does "he" refer to Christian Tismer ? If so, you may want to use google > and correct your beliefs (hint: does 'stackless Python' ring a bell ?). > >> As I'm sure you kno, variables point to things in Python. > > (conceptually) names are keys associated with an object in a given > namespace. FWIW, be assured that Christians knows this pretty well. > >> I don't believe that there are lots of other objects >> pointing to this dictionary. > > You just cannot *know* this. This might be true now, this might be false > now, and this might change anytime. Assuming anything here is the road > to disaster. Don't assume, do the righ thing. > >> Perhaps the OP can clarify >> for us. If there aren't other objects pointing to >> this dictionary it would make NO sense to iterate over a >> dictionary and delete all the keys/values > > You don't iterate over anything. Dicts being the central datastructure > in Python, you can bet your ass they are optimized to death (or near > death). If you have any doubt, then still don't assume : verify (hint: > import timeit). And yet even if clearing a dict happens to be a bit > slower than instanciating a new one, rebinding a name and mutating an > object are still two very different concepts in Python, with very > different consequences. The OP explicitely asked for clearing a dict, > not for creating a new one. > >> so I tried to read >> between the lines > > Why ? > >> and answer what I believe the OP thought he >> was asking. > > What the OP asked was quite clear, and not subject to any > interpretation. And the correct answer is obviously not the one you gave. > >> BTW-I didn't see you posting an answer to what >> you thought was the "correct" question, just criticizing me >> for taking the time to answer what I perceived the OP was >> asking. > > If you cannot understand the difference between criticism and a friendly > correction, nor why you should actually thank the one correcting you > when you're wrong, I guess there's no point trying explaining why > correcting wrong answers on newsgroups is actually important. I stand corrected about my answer, but I'll stick to my assumption (until told otherwise by the OP) that the question that was asked wasn't precisely what the OP wanted to accomplish. It was just too simple to mean what you guys assumed (e.g. complex dictionary pointed to by lots of other objects, etc.). I don't mind being corrected with the proper information, but Aahz's post doesn't make any sense. He said "Go back and read Christian's answer...". Christian's answers were not answers to the OP's question at all. Here is what shows up in my newsreader: ''' Reading the Python docs might help. But before, I would try a dir(myDict). Maybe you will find an easter-egg which has exactly the name you are looking for? cheers - chris ''' and ''' This is wrong and not answering the question. Creating a new dict does not change the dict. He wants to clear *this* dict, and maybe he cannot know how many other objects are referring to this dict. cheers -- chris ''' You appear to be the only one that apparently posted the correct answer myDict.clear() for which I thank you. I learned two things today: 1) answer EXACTLY the question that is asked and 2) dicts have a clear method that is safer than my answer. -Larry From gagsl-py2 at yahoo.com.ar Tue Mar 27 17:50:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 Mar 2007 18:50:21 -0300 Subject: urllib timeout issues References: <1175023315.536080.276550@n76g2000hsh.googlegroups.com> <1175028104.429759.165920@n76g2000hsh.googlegroups.com> Message-ID: En Tue, 27 Mar 2007 17:41:44 -0300, supercooper escribi?: > On Mar 27, 3:13 pm, "Gabriel Genellina" > wrote: >> En Tue, 27 Mar 2007 16:21:55 -0300, supercooper >> escribi?: >> >> > I am downloading images using the script below. Sometimes it will go >> > for 10 mins, sometimes 2 hours before timing out with the following >> > error: >> >> > urllib.urlretrieve(fullurl, localfile) >> > IOError: [Errno socket error] (10060, 'Operation timed out') >> >> > I have searched this forum extensively and tried to avoid timing out, >> > but to no avail. Anyone have any ideas as to why I keep getting a >> > timeout? I thought setting the socket timeout did it, but it didnt. >> >> You should do the opposite: timing out *early* -not waiting 2 hours- and >> handling the error (maybe using a queue to hold pending requests) >> >> -- >> Gabriel Genellina > > Gabriel, thanks for the input. So are you saying there is no way to > realistically *prevent* the timeout from occurring in the first Exactly. The error is out of your control: maybe the server is down, irresponsive, overloaded, a proxy has any problems, any network problem, etc. > place? And by timing out early, do you mean to set the timeout for x > seconds and if and when the timeout occurs, handle the error and start > the process again somehow on the pending requests? Thanks. Exactly! Another option: Python is cool, but there is no need to reinvent the wheel. Use wget instead :) -- Gabriel Genellina From deets at nospam.web.de Mon Mar 5 11:49:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Mar 2007 17:49:59 +0100 Subject: worker thread catching exceptions and putting them in queue References: <45ec4936$0$323$e4fe514c@news.xs4all.nl> Message-ID: <55301nF2339mvU2@mid.uni-berlin.de> Paul Sijben wrote: > All, > > in a worker thread setup that communicates via queues is it possible to > catch exceptions raised by the worker executed, put them in an object > and send them over the queue to another thread where the exception is > raised in that scope? > > considering that an exception is an object I feel it ought to be > possible, however I do not see how to go about it. > > does anyone have a pointer towards the solution? Just raise the exception object found in the queue. Only make sure it _is_ an exception, as you can raise everything. So in your queue-putting-code you might consider discriminating between the two cases, like this: while True: try: result = 1, work() except: result = 2, sys.exc_info()[1] queue.put(result) ------- while True: kind, result = queue.get() if kind == 1: do(result) elif kind == 2: raise result Diez From steve at REMOVE.THIS.cybersource.com.au Sun Mar 25 05:48:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 25 Mar 2007 19:48:09 +1000 Subject: Idiom for running compiled python scripts? References: <1174746081.436526.64360@l75g2000hse.googlegroups.com> Message-ID: On Sun, 25 Mar 2007 07:10:23 +0000, Mark wrote: > On Sun, 25 Mar 2007 13:40:33 +1000, Steven D'Aprano wrote: >> Because this is entirely a trivial saving. Who cares? Sheesh. >> ... >> Saving 18ms on a script that takes 50ms to execute *might* be >> worthwhile, ... > > I don't understand your attitude. Sure, we are talking slight savings in > machine efficiency but I am sure the python developers have laboured > many long hours on subtle optimisations of the virtual machine, many of > which probably dwarf the issue discussed here. Tell them their work is > trivial and unnecessary. Why would I do that? As you said yourself, their optimizations dwarf the trivial issue you discuss. They, unlike you, grasp that the aim of optimization is to make significant savings in meaningful places, not waste time making insignificant savings in meaningless places. > Every little bit helps. No it doesn't. Spending hours of effort to save 18 seconds a day is a waste of both time and effort. If you have a process that takes eight hours and 18 seconds to run, and you need it to run in eight hours or less, then that 18 seconds is absolutely critical. But how likely is that? Chances are nobody will care if the process takes eight hours and ten minutes or seven minutes and fifty minutes. Saving 18ms once at startup for a single script, or 18 seconds over the course of an entire day, pales into insignificance. > Why do I concern myself > with this inefficiency - because it is there. Fine fine -- except the hours you spend solving it is an inefficiency a million times bigger than the one you are concerned with. Okay, that's not fair -- it might take you hours to solve it once, but from that moment on, you can save 18ms every time you run a script. In the course of a day, you might save 18 seconds. In just 600 working days, you'll have made that time back, and every 18ms after that is pure gain! BFD. Except, of course, that each time you type that one extra character, you lose 160ms to gain 18ms. You're actually going backwards. And that's the thing that demonstrates that for all your talk of efficiency, you're not really interested in efficiency. If you were, you'd do the maths and, having discovered that it costs you 160ms to save 18ms, you're actually *less* efficient. > Of course I realise the modern mantra that "premature optimisation is > the root of all evil" but I don't subscribe to it. That's nice. > Programmers have been > "encouraged" to not give a toss about efficiency Blathering on about saving 18ms might make you feel good, but that's not efficient. Making the code run 18ms faster at the expense of the total process running 140ms slower is a pessimation, not an optimization. -- Steven. From cjlesh at gmail.com Mon Mar 19 22:30:38 2007 From: cjlesh at gmail.com (cjl) Date: 19 Mar 2007 19:30:38 -0700 Subject: difference between urllib2.urlopen and firefox view 'page source'? Message-ID: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> Hi. I am trying to screen scrape some stock data from yahoo, so I am trying to use urllib2 to retrieve the html and beautiful soup for the parsing. Maybe (most likely) I am doing something wrong, but when I use urllib2.urlopen to fetch a page, and when I view 'page source' of the exact same URL in firefox, I am seeing slight differences in the raw html. Do I need to set a browser agent so yahoo thinks urllib2 is firefox? Is yahoo detecting that urllib2 doesn't process javascript, and passing different data? -cjl From adam at atlas.st Tue Mar 6 10:48:48 2007 From: adam at atlas.st (Adam Atlas) Date: 6 Mar 2007 07:48:48 -0800 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <1173193691.204641.206600@s48g2000cws.googlegroups.com> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> <1173193691.204641.206600@s48g2000cws.googlegroups.com> Message-ID: <1173196128.443793.170900@t69g2000cwt.googlegroups.com> Doesn't seem to work. I guess zipimport doesn't support that by default... but if I remember correctly, Setuptools adds that. Maybe I'll take a look at how it does it (I think by extracting the .so to / tmp?) and see how easy it would be to integrate it here. From davidnicolson1 at hotmail.com Wed Mar 28 10:01:05 2007 From: davidnicolson1 at hotmail.com (David Nicolson) Date: Thu, 29 Mar 2007 00:01:05 +1000 Subject: shutil.copy Problem In-Reply-To: References: <1174970535.061022.141230@l77g2000hsb.googlegroups.com> Message-ID: Hi John, That was an excellent idea and it was the cause problem. Whether this is a bug in shutil I'm not sure. Here is the traceback, Python 2.4.3 on Windows XP: > C:\Documents and Settings\G?stav>C:\python243\python Z:\sh.py > Copying u'C:\\Documents and Settings\\G\xfcstav\\My Documents\\My > Music\\iTunes > \\iTunes Music Library.xml' ... > Traceback (most recent call last): > File "Z:\sh.py", line 12, in ? > shutil.copy(xmlfile,"C:iTunes Music Library.xml") > File "C:\python243\lib\shutil.py", line 81, in copy > copyfile(src, dst) > File "C:\python243\lib\shutil.py", line 41, in copyfile > if _samefile(src, dst): > File "C:\python243\lib\shutil.py", line 36, in _samefile > return (os.path.normcase(os.path.abspath(src)) == > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in > position 27: ordinal > not in range(128) Here is the code: > import _winreg > import os > import shutil > > reg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER) > key = _winreg.OpenKey(reg, r"Software\Microsoft\Windows > \CurrentVersion\Explorer\Shell Folders", 0, _winreg.KEY_READ) > mymusic = _winreg.QueryValueEx(key, "My Music")[0] > > xmlfile = os.path.join(os.path.join(mymusic,"iTunes"),"iTunes Music > Library.xml") > print "Copying ",repr(xmlfile),"..." > > shutil.copy(xmlfile,"C:\iTunes Music Library.xml") The shutil line needed to be changed to this to be successful: > shutil.copy(xmlfile.encode("windows-1252"),"C:\iTunes Music > Library.xml" Regards, David On 27/03/2007, at 4:47 PM, John Nagle wrote: > Facundo Batista wrote: >> David Nicolson wrote: >> >> >>> Thanks, but it's definitely not the print. In original the code the >>> print statements are replaced by a call to a log method. >>> >>> Besides, the exception would be different if it was thrown >>> outside of >>> the try block. >> >> >> The best you can do is take the piece of code that has the >> problem, show >> it to us, and then copy the traceback. >> >> Regards, > > There may be some problem here with a file being recognized as > Unicode > in binary mode. That shouldn't happen, but looking at the Windows > UNICODE support, it might not be impossible. > > Information needed: > > - Platform (Windows, Linux, ...) > - Python version > - A hex dump of the first few bytes of the input file. > > John Nagle > -- > http://mail.python.org/mailman/listinfo/python-list From jnews at julius-net.net Tue Mar 6 15:07:45 2007 From: jnews at julius-net.net (Matthias Julius) Date: Tue, 06 Mar 2007 15:07:45 -0500 Subject: How to Read Bytes from a file References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1172757183.819978.219440@v33g2000cwv.googlegroups.com> <1172764725.827624.298180@j27g2000cwj.googlegroups.com> <1172771161.015437.50000@n33g2000cwc.googlegroups.com> <1172774172.389220.124170@j27g2000cwj.googlegroups.com> <1172834556.768612.164050@8g2000cwh.googlegroups.com> Message-ID: <87abyq5e5q.fsf@julius-net.net> "Gabriel Genellina" writes: > En Fri, 02 Mar 2007 08:22:36 -0300, Bart Ogryczak > escribi?: > >> On Mar 1, 7:36 pm, "gregpin... at gmail.com" >> wrote: >>> Thanks Bart. That's perfect. The other suggestion was to precompute >>> count1 for all possible bytes, I guess that's 0-256, right? >> >> 0-255 actually. It'd be worth it, if accessing dictionary with >> precomputed values would be significantly faster then calculating the >> lambda, which I doubt. I suspect it actually might be slower. > > Dictionary access is highly optimized in Python. In fact, using a > precomputed dictionary is about 12 times faster: Why using a dictionary and not a list? Matthias From rds1226 at sh163.net Thu Mar 8 21:05:01 2007 From: rds1226 at sh163.net (John) Date: Thu, 8 Mar 2007 21:05:01 -0500 Subject: any better code to initalize a list of lists? References: <7xlki7dx5m.fsf@ruckus.brouhaha.com> Message-ID: I want to radix sort non-negative integers that can fit into 32-bits. That will take 4 passes, one for each byte. So, I will need 256 "buckets" The list radix of 256 elements of list is good for this purpose. Your code is much shorter, works and probably takes less time. Thanks! John "Paul Rubin" wrote in message news:7xlki7dx5m.fsf at ruckus.brouhaha.com... > "John" writes: >> For my code of radix sort, I need to initialize 256 buckets. My code >> looks a >> little clumsy: >> >> radix=[[]] >> for i in range(255): >> radix.append([]) >> >> any better code to initalize this list? > > Typically you'd say > radix = [[] for i in xrange(256)] > > but what are you really doing? This plan to implement radix sorting > sounds a little bit odd, unless it's just an exercise. > > You could also consider using a dictionary instead of a list, > something like: > > radix = defaultdict(list) From namesagame-usenet at yahoo.com Sun Mar 18 15:17:52 2007 From: namesagame-usenet at yahoo.com (gamename) Date: 18 Mar 2007 12:17:52 -0700 Subject: Renaming or Overloading In Python Message-ID: <1174245472.666094.36850@e1g2000hsg.googlegroups.com> Hi, I'm a recent convert from TCL. One of the more powerful aspects of TCL is the ability to rename a function at will (generally for testing purposes). Example from the tcl doc: rename ::source ::theRealSource set sourceCount 0 proc ::source args { global sourceCount puts "called source for the [incr sourceCount]'th time" uplevel 1 ::theRealSource $args } So, is such a thing possible in Python? Thanks, -T From cousinstanley at hotmail.com Tue Mar 6 13:47:43 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Tue, 06 Mar 2007 12:47:43 -0600 Subject: Getting external IP address References: Message-ID: <1173206863_18689@sp6iad.superfeed.net> > I have a PC behind a firewall, and I'm trying to programmatically > determine the IP address visible from outside the firewall. > .... Steven .... Following is another alternative that might at least be worth consideration .... I use the lynx command shown as a command-line alias under Debian linux .... >>> >>> import os >>> >>> pipe_in = os.popen( 'lynx --dump http://checkip.dyndns.org' ) >>> >>> ip_addr = pipe_in.readlines() >>> >>> for this in ip_addr : ... print this ... Current IP Address: 65.39.92.38 -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From grante at visi.com Fri Mar 30 19:13:51 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 30 Mar 2007 23:13:51 -0000 Subject: Newbie Question (real-time communication between apps: audio, 3d, PD, Blender) References: <1175294306.124030.272350@l77g2000hsb.googlegroups.com> Message-ID: <130r6df92n4rp04@corp.supernews.com> On 2007-03-30, gregorywieber at gmail.com wrote: > I'm just beginning my exploration of Python and I have a rather > general question. If two particular programs have Python scripting > capabilities, does that mean those two programs can communicate in > real time through Python? No. -- Grant Edwards grante Yow! Yow! Is my fallout at shelter termite proof? visi.com From aleax at mac.com Sun Mar 18 23:54:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 18 Mar 2007 20:54:15 -0700 Subject: list comprehension help References: <1174269687.497013.249480@o5g2000hsb.googlegroups.com> Message-ID: <1hv6v32.17ahray13d45puN%aleax@mac.com> George Sakkis wrote: > On Mar 18, 12:11 pm, "rkmr... at gmail.com" wrote: > > > Hi > > I need to process a really huge text file (4GB) and this is what i > > need to do. It takes for ever to complete this. I read some where that > > "list comprehension" can fast up things. Can you point out how to do > > it in this case? > > thanks a lot! > > > > f = open('file.txt','r') > > for line in f: > > db[line.split(' ')[0]] = line.split(' ')[-1] > > db.sync() > > You got several good suggestions; one that has not been mentioned but > makes a big (or even the biggest) difference for large/huge file is > the buffering parameter of open(). Set it to the largest value you can > afford to keep the I/O as low as possible. I'm processing 15-25 GB > files (you see "huge" is really relative ;-)) on 2-4GB RAM boxes and > setting a big buffer (1GB or more) reduces the wall time by 30 to 50% > compared to the default value. BerkeleyDB should have a buffering > option too, make sure you use it and don't synchronize on every line. Out of curiosity, what OS and FS are you using? On a well-tuned FS and OS combo that does "read-ahead" properly, I would not expect such improvements for moving from large to huge buffering (unless some other pesky process is perking up once in a while and sending the disk heads on a quest to never-never land). IOW, if I observed this performance behavior on a server machine I'm responsible for, I'd look for system-level optimizations (unless I know I'm being forced by myopic beancounters to run inappropriate OSs/FSs, in which case I'd spend the time polishing my resume instead) - maybe tuning the OS (or mount?) parameters, maybe finding a way to satisfy the "other pesky process" without flapping disk heads all over the prairie, etc, etc. The delay of filling a "1 GB or more" buffer before actual processing can begin _should_ defeat any gains over, say, a 1 MB buffer -- unless, that is, something bad is seriously interfering with the normal read-ahead system level optimization... and in that case I'd normally be more interested in finding and squashing the "something bad", than in trying to work around it by overprovisioning application bufferspace!-) Alex From tiedon_jano at hotmail.com Mon Mar 5 07:39:54 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Mon, 05 Mar 2007 12:39:54 GMT Subject: Building a dictionary from a tuple of variable length In-Reply-To: <1173084222.565386.250510@h3g2000cwc.googlegroups.com> References: <1173084222.565386.250510@h3g2000cwc.googlegroups.com> Message-ID: bg_ie at yahoo.com kirjoitti: > Hi, > > I have the following tuple - > > t = ("one","two") > > And I can build a dictionary from it as follows - > > d = dict(zip(t,(False,False))) > > But what if my tuple was - > > t = ("one","two","three") > > then I'd have to use - > > d = dict(zip(t,(False,False,False))) > > Therefore, how do I build the tuple of Falses to reflect the length of > my t tuple? > > Thanks for your help, > > Barry. > Another variation: d = dict((x, False) for x in t) Cheers, Jussi From mark.english at rbccm.com Tue Mar 27 14:01:01 2007 From: mark.english at rbccm.com (MarkE) Date: 27 Mar 2007 11:01:01 -0700 Subject: Handling exception thrown by Boost.Python c-extension in Python code Message-ID: <1175018461.183511.30770@n76g2000hsh.googlegroups.com> I'm just getting started on Boost Python and may have missed this obvious looking problem somewhere. Given a c-extension "testext" written using Boost Python containing a base class "Base", a derived class "Derived", and a function "doSomething" which expects a "Derived" parameter, if I pass it a "Base" parameter an exception is thrown. This is a Boost.Python.ArgumentError. My question is how do I catch this error ? I tried the following bit of investigation: #Start code import testext b = testext.Base() try: testext.doSomething(b) except Exception, e: pass help(e.__class__) #End code which produces #Start output Help on class ArgumentError: class ArgumentError(exceptions.TypeError) | Method resolution order: | ArgumentError | exceptions.TypeError | exceptions.StandardError | exceptions.Exception | | Methods inherited from exceptions.Exception: | | __getitem__(...) | | __init__(...) | | __str__(...) #End output "print e" produces "" So I could handle this by writing an except clause for TypeError. Boost.Python doesn't exist as a module i.e. it's not in sys.modules, and I don't know how to import it - should there be a Boost.Python module somewhere on my PythonPath that I've forgotten to setup ? Is there a standard way of catching these errors by their actual type ? Is there an easy way to export the exception classes from my c- extension (testext) so that I can use that ? Thus "except testext.ArgumentError" would catch the "Boost.Python.ArgumentError" ? Thanks for any help, Mark From lucastorri at gmail.com Mon Mar 12 10:50:49 2007 From: lucastorri at gmail.com (Lucas Torri) Date: Mon, 12 Mar 2007 11:50:49 -0300 Subject: New to Python In-Reply-To: <200703120202.07810.albmont@centroin.com.br> References: <200703120202.07810.albmont@centroin.com.br> Message-ID: Something like that? z = tuple(map(lambda x,y: x+y, x, y)) On 3/11/07, Alberto Vieira Ferreira Monteiro wrote: > > Hi, I am new to Python, how stupid can be the questions I ask? > > For example, how can I add (mathematically) two tuples? > x = (1,2) > y = (3,4) > How can I get z = (1 + 3, 2 + 4) ? > > Alberto Monteiro > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsuser at stacom-software.de Fri Mar 16 09:19:56 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Fri, 16 Mar 2007 14:19:56 +0100 Subject: String formatting with fixed width Message-ID: Hello alltogether, is it possible to format stings with fixed width of let's say 7 character. T need a floating point with 3 chars before dot, padded with ' ' and 3 chars after dot, padded with '0'. Followingh is my approach >>> f = 21.1 >>> s = "%.03f" % f >>> s '21.100' But there are missing ' '. How can I get that? (For bigger numbers than 999 they might be cut: 1021 -> 021) Alexander From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 05:43:12 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 11:43:12 +0200 Subject: creating "jsp-like" tool with python In-Reply-To: <1174699131.550140.67190@l77g2000hsb.googlegroups.com> References: <1174699131.550140.67190@l77g2000hsb.googlegroups.com> Message-ID: <460795b0$0$28815$426a74cc@news.free.fr> jd a ?crit : > I'd like to create a program that takes files with "jsp-like" markup > and processes the embedded code (which would be python) to produce the > output file. There would be two kinds of sections in the markup file: > python code to be evaluated, and python code that returns a value that > would be inserted into the output. > > This seems like it would be straightforward in python, and maybe > there's even a library that I could use for this, but as a newbie to > Python, I don't know the landscape very well. I am not looking for a > big framework, just something small and simple that will do just this > job. Suggestions or pointers would be greatly appreciated. There are already quite a few Python templating solutions. You may want to look for: - Python server pages - Mighty - Mako - Jinja - Genshi - Cheetah - Newov - Zope Page Templates - SimpleTAL (standalone implementation of ZPT) - (add your favorite Python templating system here) From ptmcg at austin.rr.com Fri Mar 16 09:39:18 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Mar 2007 06:39:18 -0700 Subject: Mastering Python In-Reply-To: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> Message-ID: <1174052358.486071.163280@e65g2000hsc.googlegroups.com> On Mar 16, 6:41 am, "Gerald" wrote: > Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my > curriculum did not include Python programming yet I see many vacancies > for Python developers.I studied programming Pascal,C++ and Delphi.So I > need to catch up quickly and master Python programming.How do you > suggest that I achieve this goal?Is python platform independent?What > is the best way?And how long would it take before I can develop > applications using python?Can you recommend websites that feature a > gentle introduction to Python? Stop thinking about *how* to start and *just start*. Python is pretty intuitive, especially if you have other language background to relate to. Download the Python dist for your platform (Linux? probably already there - Windows? binary installers from python.org or activestate will install in a snap). Run through the first few pages of any of the dozen or more online tutorials to start getting your fingernails dirty. You'll need a text editor with integrated building - I find SciTE and PyScripter to be good for beginners (and I still use SciTE after 4 years of Python programming). You know C++ and Pascal? You already know the basic if-then-else, while, and for control structure concepts. Here are some C++-to- Python tips: - There's no switch statement in Python. Make do with cascading if/ elif/else until you come across the dict dispatch idiom. - There's no '?' operator in Python. If you download the latest version (2.5), there is an equivalent "x if y else z" which would map to "y ? x : z" using the ternary operator. But lean towards explict readability vs. one-liner obscurity at least for a few days. - Forget about new/delete. To construct an object of type A, call A's constructor using "newA = A()". To delete A, let if fall out of scope, or explicitly unbind the object from the name "newA" with "newA = None". - Forget about "for(x = 0; x < 10; x++)". Python loops iterate over collections, or anything with an __iter__ method or __getitem__ method. This is much more like C++'s "for(listiter = mylist.first(); listiter != mylist.end(); ++listiter)". To force a for loop to iterate 'n' times, use "for i in range(n):". The range built-in returns the sequence [0, 1, 2, ..., n-1]. Don't commit this beginner's blunder: list1 = [ 1, 2, 3 ] for i in range(len(list1)): # do something with list1[i] Instead do: for elem in list1: # do something with elem, which points to each element of # list1 each time through the loop If you really need the list index, use enumerate, as in: for i,elem in enumerate(list1): print "The %d item of the list is %s" % (i,elem) (Hey, check out those string formatting placeholders, they borrow heavily from C's printf notation. Oh, they don't teach that anymore, and you used iostreams in C++ instead? Bummer.) - Forget about braces {}'s. For some reason, this is a big deal for some people, but give it a chance. Just indent code as you would normally, and leave out the braces. Personally I set my editor to replace tabs with spaces, this is a style choice - but do NOT mix tabs and spaces. In the end, you will find this liberating, especially if you have ever been on a project that had to define a coding standard, and spent way too much time (more then 30 seconds) arguing about "where the braces should go." - Don't forget the ()'s. To invoke a method on an object, you must include the parens. This wont do anything: a = "some string" a = a.lower You need this: a = a.lower() - Stop thinking about variables as addresses and storage locations, and start thinking about them as values bound to names. Even so, I still find myself using words like "assignment" and "variable", when strictly I should be saying "binding" and "name". What does Python have that C++ doesn't? - The biggie: dynamic typing (sometimes called "duck typing"). Dynamic typing is a huge simplifier for development: . no variable declarations . no method type signatures . no interface definitions needed . no templating for collections . no method overloading by differing argument type signatures ("Imagine there's no data types - I wonder if you can..."). What? No static type-checking at compile time? Nope, not really. If your method expects an object of type X, use it like an X. If it's not an X, you may be surprised how often this is not a problem. For instance, here's a simple debugging routine: def printClassOf(x): print x.__class__.__name__ Every object has the attribute __class__ and every class has the attribute __name__. In C++, I'd have to go through extra contortions *not* to type the variable x, probably call it something non-intuitive like "void*". Or look at this example: def printLengthOf(x): print "Length of x is", len(x) x could be any collection class, or user-defined class that is sufficiently like a collection to support len (such as implementing the __len__ method). This class doesn't even have to exist when you write printLengthOf, it may come along years later. - An interactive interpreter. Awfully handy for just trying things out, without having to go through the compile/link/run cycle. Also good for getting at documentation on built-in and custom objects and methods - type "help(blah)" to get help on method or class blah. - Language built-in types for list, tuple (a type of list that is immutable), dict (akin to map in the C++ STL), and set. Since Python does dynamic typing, no need to templatize these collection types, just iterate over them and use the objects in them. . Lists look like [ 1, 2, 3, "ABC", [ 4,5 ] ] . Tuples look like ( "Bob", "Smith", "12345 River St.", 52 ) . Dicts look like { "Bob" : 52, "Joe" : 24 } . Sets look like set("A", "B", "C") - Language built-in types for string and unicode - Multiple variable assignment - you can unpack a list into individual variables using: a,b,c = 1,2,3 list1 = [ 4,5,6 ] a,b,c = list1 (will assign 4 to a, 5 to b, and 6 to c) Forget about the classic C chestnut to swap a and b: a ^= b; b ^= a; a ^= b; Just do: a,b = b,a - Compound return types - need 3 or 4 values returned from a function? Just return them. No need for clunky make_pair<> templates, or ad hoc struct definitions just to handle some complex return data, or (ick!) out parameters. Multiple assignment will take care of this: def func(): return 4,5,6 a,b,c = func() - Flexible and multiline quoting. Quoted string literals can be set of using ""s, ''s, or triple quotes (""" """, or ''' '''). The triple quote versions can extend to multiple lines. - Built-in doc strings. If you have a function written like this: def func(): "A function that returns 3 consecutive ints, starting with 4" return 4,5,6 then typing "help(func)" at the interactive interpreter prompt will return the string "A function that...". This is called the function's docstring, and just about any object (class, function, module) can have one. - A huge library of common application modules. The latest version includes support for the SQLite database. And a part of the Python "getting it" that usually takes place in the first hour or two of *just starting* is encapsulated in the Zen of Python. Type "import this" at the interpreter command line, and you'll see a list of basic concepts behind the language and its design. It is true, there are some dorky in-jokes in there, but look past them and pick up the nuggets of Python wisdom. Wow, are you still reading? Quit wasting time and go download a Python dist and get started already! -- Paul From bbxx789_05ss at yahoo.com Fri Mar 16 02:02:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Mar 2007 23:02:57 -0700 Subject: Pickle Problem In-Reply-To: References: <1173971633.305988.207530@d57g2000hsg.googlegroups.com> <1173979442.025584.282090@e65g2000hsc.googlegroups.com> Message-ID: <1174024977.766602.258380@p15g2000hsd.googlegroups.com> > I'm trying to make the transition from Java > The biggest thing that was messing me up was the > mandatory "self" input. For some reason I was thinking > that, if I had parenthesis, I would have to define it. I think things are pretty similar in Java. Java does the same thing except 'self' is invisible in Java, and in Java 'self' is called 'this'. For instance, in Java you can write: int num; void setNum(int num) { this->num = num } Where did 'this' come from? In Java, methods are passed the invisible 'this' argument, which you can then access inside the method. It looks like Python just "uncloaks" Java's 'this'. From alan.franzoni_invalid at geemail.invalid Fri Mar 2 08:45:32 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Fri, 2 Mar 2007 14:45:32 +0100 Subject: Python Source Code Beautifier References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> <1172700549.583792.41660@s48g2000cws.googlegroups.com> Message-ID: Il 28 Feb 2007 14:09:09 -0800, sjdevnull at yahoo.com ha scritto: > Seems obvious and desirable to me. Bare "=" is the way you assign a > name to an object; saying "NAME =" will rebind the name, breaking the > connection between a and b. Without it, they continue to refer to the > same object; extending the list (via += or .extend) mutates the > object, but doesn't change which objects a and b are referencing. Well... the main problem is not with the '+=' operators themselves, it's with the 'global coherence'. I would assume then, that if the '+=' operator is assumed to modify objects in-place, it would just fail on immutable objects, wouldn't I? I mean... I don't like that. I'm not really a Python expert, I found this behaviour is documented in the language reference itself: http://docs.python.org/ref/augassign.html But... I don't know, still think it's confusing and not going to use it. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From greg at cosc.canterbury.ac.nz Sat Mar 10 04:16:52 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 10 Mar 2007 22:16:52 +1300 Subject: number generator In-Reply-To: References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> Message-ID: <55fbgjF2492skU1@mid.individual.net> Steven D'Aprano wrote: > Last but not least, another possible algorithm is to start with a list of > N numbers, regardless of whether or not they add to M, and then adjust > each one up or down by some amount until they sum to the correct value. Another possibility is to generate a list of N non-random numbers that sum to M, and then adjust them up or down by random amounts. By performing up/down adjustments in pairs, you can maintain the sum invariant at each step. So then it's just a matter of how long you want to go on fiddling with them. -- Greg From steve at holdenweb.com Thu Mar 22 18:50:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 18:50:59 -0400 Subject: Python Oracle 10g odbc blob insertion problem In-Reply-To: <1174603221.600706.62210@p15g2000hsd.googlegroups.com> References: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> <1174567006.244721.115890@n59g2000hsh.googlegroups.com> <1174603221.600706.62210@p15g2000hsd.googlegroups.com> Message-ID: Godzilla wrote: > On Mar 23, 4:38 am, Dennis Lee Bieber wrote: >> On 22 Mar 2007 05:36:46 -0700, "Godzilla" >> declaimed the following in comp.lang.python: >> >>> Steve, I think I've tried what you have suggested without any luck as >>> well... The statement works fine, but what inserted is not correct... >>> it seems like only the symbol '?' was inserted into the blob field... >> You didn't have a set of 's around the ?, did you? Parameter >> substitution will add needed quotes on its own rather than you having to >> put in quotes. >> >> Also, though I find no documentation on it, odbc module cursors have >> setinputsizes() and setoutputsizes() methods -- perhaps that could >> change things... OTOH: the db-api 1.0 PEP (which is, it seems, what odbc >> module follows) says they may be do-nothing methods. >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfr... at ix.netcom.com wulfr... at bestiaria.com >> HTTP://wlfraed.home.netcom.com/ >> (Bestiaria Support Staff: web-a... at bestiaria.com) >> HTTP://www.bestiaria.com/ > > Everything seems to work fine right now... thanks all of you for > helping... Have a great day.. > Have you any idea what fixed the problem? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From me at mylife.com Tue Mar 27 14:16:45 2007 From: me at mylife.com (Jason B) Date: Tue, 27 Mar 2007 18:16:45 GMT Subject: 16bit RGB with Image module Message-ID: Hi all, I'm still new to all of this, but I'm trying to do something here that *seems* like it should be pretty simple. All I want to do is take an array of pixel data from a file (no header data or anything, just pixel data) in RGB565 format and save it off to a bitmap file - or display it, in the case below: import sys, Image if len(sys.argv) == 2: print "\nReading: "+sys.argv[1] image_file = open(sys.argv[1], "rb") pixel_data = image_file.read() im = Image.fromstring("RGB", (326, 325), pixel_data) im.show() When run, I get: ValueError: not enough image data Which I'm pretty sure is because it's expecting a 24bit image. Of course if I tune down the width and height or change the format to B&W ("L") then it *does* display an image, the B&W one even having recognizable features, just not the right one. :( I've read through the documentation a thousand times trying to understand the raw decoder and plugins, etc. but I still can't figure this out... Any help is greatly appreciated! Thanks, J From arkanes at gmail.com Tue Mar 6 13:13:35 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 12:13:35 -0600 Subject: Project organization and import In-Reply-To: <1173203395.649560.249930@p10g2000cwp.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> <1173203395.649560.249930@p10g2000cwp.googlegroups.com> Message-ID: <4866bea60703061013r7bea725fl4ba6ccc2fab792f7@mail.gmail.com> On 6 Mar 2007 09:49:55 -0800, Martin Unsal wrote: > On Mar 6, 9:19 am, "Chris Mellon" wrote: > > You do? Or do you only have trouble because you don't like using "from > > foo import Foo" because you need to do more work to reload such an > > import? > > More work, like rewriting __import__ and reload??? :) > > There's a point where you should blame the language, not the > programmer. Are you saying I'm lazy just because I don't want to mess > with __import__? You have to reload the importing module as well as the module that changed. That doesn't require rewriting the import infrastructure. It's only an issue because you're changing things at one level but you're trying to use them at a level removed from that. I never work that way, because I only have any need or desire to reload when I'm working interactively and I when I'm doing that I work directly with the modules I'm changing. The interfaces are what my unit tests are for. If you're doing stuff complicated and intricate enough in the interpreter that you need reload() to do very much more than its doing, then you're working poorly - that sort of operation should be in a file you can run and test automatically. > > > What makes you think that the exposed namespace has to be isomorphic > > with the filesystem? > > I don't; you do! > > I was clearly talking about files and you assumed I was talking about > namespace. That's Pythonic thinking... and I don't mean that in a good > way! > All the files on the PYTHONPATH will map into the namespace. However, you can have items in the namespace that do not map to files. The main reasons to do so are related to deployment, not development though so I wonder why you want to. > > If you want to break a module into multiple packages and then stick > > the files that make up the package in bizarre spots all over the > > filesystem, can you give a reason why? > > Because I have written a project with 50,000 lines of Python and I'm > trying to organize it in such a way that it'll scale up cleanly by > another order of magnitude. Because I've worked on projects with > millions of lines of code and I know about how such things are > organized. It's funny, I'm a newbie to Python but it seems like I'm > one of the only people here thinking about it as a large scale > development language rather than a scripting language. > Thats not answering the question. Presumably you have some sort of organization for your code in mind. What about that organization doesn't work for Python? If you want multiple files to map to a single module, make them a package. From michael at jedimindworks.com Fri Mar 30 15:09:29 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 30 Mar 2007 14:09:29 -0500 Subject: Inserting '-' character in front of all numbers in a string In-Reply-To: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> Message-ID: <588947CD-F526-49FF-92B7-826C0AB161CE@jedimindworks.com> On Mar 30, 2007, at 10:38 AM, kevinliu23 wrote: > I want to be able to insert a '-' character in front of all numeric > values in a string. I want to insert the '-' character to use in > conjunction with the getopt.getopt() function. > > Rigt now, I'm implementing a menu system where users will be able to > select a set of options like "2a 3ab" which corresponds to menu > choices. However, with getopt.getopt(), it'll only return what I want > if I input -2a -3ab as my string. I don't want the user have to insert > a '-' character in front of all their choices, so I was thinking of > accepting the string input first, then adding in the '-' character > myself. > > So my qusetion is, how do I change: > > "2a 3ab" into "-2a -3ab". > Will the first character always be a digit? for i in yourstring.split(): if i[0].isdigit(): yourstring = yourstring.replace(i, '-%s' % (i,)) Or are these hex numbers? From mnations at gmail.com Sun Mar 4 22:52:56 2007 From: mnations at gmail.com (Mudcat) Date: 4 Mar 2007 19:52:56 -0800 Subject: Python stock market analysis tools? Message-ID: <1173066776.884126.86810@64g2000cwx.googlegroups.com> I have done a bit of searching and can't seem to find a stock market tool written in Python that is active. Anybody know of any? I'm trying not to re-create the wheel here. From steve at REMOVE.THIS.cybersource.com.au Sat Mar 3 18:15:31 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 04 Mar 2007 10:15:31 +1100 Subject: Questions about app design - OOP with python classes References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <7xabywnugu.fsf@ruckus.brouhaha.com> <7xtzx4i43e.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 01 Mar 2007 21:53:09 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> > That still sounds like an unreliable manual type system, >> It's unreliable in the sense that the coder has to follow the naming >> convention, and must have some bare minimum of sense. If your coders are >> morons, no naming convention will save you. (For that matter, nothing will >> save you.) > > Well, type systems in programming languages have generally proven more > reliable and easier to deal with than having programmers track it all > manually-- that's why we don't all write in Forth ;-). Apps Hungarian is NOT a type system. Systems Hungarian is. It is pointless: an inefficient, manual nuisance that redundantly does what the type system already does. Even Microsoft agrees with that now. Unless there is a type system that can automatically deal with the semantic difference between (say) screen coordinates and window coordinates, or between height and width, or safe and unsafe strings, the coder still has to deal with it themselves. And even if there is such a type system, Python isn't it. [snip] > You're right that this is not exactly dimensional analysis, but it still > seems to call for types and conversion functions, rather than naming > conventions. The problem with types is that as far as the compiler is concerned, the objects are the same type. Of course it needs conversion functions. Now maybe you could argue that what Microsoft needed was a different language instead of C. Maybe so, but they were working with what they had. Just as we're working with Python. The point I'm trying to get across isn't that Apps Hungarian is the best imaginable solution to the problem of dealing with semantically different kinds of data. But it is an easy solution that works quite well (not perfectly) and (unlike relying on Haskell's type system) it can be applied to Python quite easily. -- Steven. From http Sat Mar 17 14:58:38 2007 From: http (Paul Rubin) Date: 17 Mar 2007 10:58:38 -0800 Subject: To count number of quadruplets with sum = 0 References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <1174075514.144163.211660@o5g2000hsb.googlegroups.com> <1174154723.569760.256000@y66g2000hsf.googlegroups.com> <1174157021.427429.325030@y66g2000hsf.googlegroups.com> Message-ID: <7xwt1fitnl.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > for x in e: > for y in r: > if -x-y in h: > sch += h[-x-y] I wonder whether g = h.get for x in e: for y in r: if -x-y in h: sch += g(-x-y, 0) might be a little bit faster. Also, -x-y could be saved in a variable. It's unfortunate that array.array objects don't support the .sort() operation. It would be interesting to compare the sorting-based scheme with the hashing-based one under psyco. O(n**2*log(n)) local memory references might be faster than O(n**2) hash operations and random lookups that almost always miss the cache. From jeba_ride at yahoo.com Sat Mar 10 14:49:05 2007 From: jeba_ride at yahoo.com (Clement) Date: 10 Mar 2007 11:49:05 -0800 Subject: Help Message-ID: <1173556145.150741.227160@n33g2000cwc.googlegroups.com> how to use Python/C API ............ From kyosohma at gmail.com Fri Mar 23 10:38:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Mar 2007 07:38:16 -0700 Subject: Exception passing In-Reply-To: References: Message-ID: <1174660696.288857.33710@n76g2000hsh.googlegroups.com> On Mar 23, 9:29 am, Thomas Dybdahl Ahle wrote: > Hi, I have a function, which looks like the following: > > connecting = False > def func (): > global connecting > connecting = True > try: > # Do lot of network stuff > except Exception, e: > connecting = False > raise e > > This works quite good, but it is a hell to debug. Instead of getting a > log message to the line which originally raised the exception. > > Is there anyway to reraise an exception, but preserve the log? You could import traceback and use its functionality. Lundh mentioned using sys.exc_info about an hour ago to another user. See http://effbot.org/pyref/sys.exc_info.htm Mike From paul at boddie.org.uk Sun Mar 4 15:09:49 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Mar 2007 12:09:49 -0800 Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again In-Reply-To: References: Message-ID: <1173038989.522947.196890@i80g2000cwc.googlegroups.com> John Nagle wrote: > I've been installing Python and its supporting packages on > a dedicated server with Fedora Core 6 for about a day now. > This is a standard dedicated rackmount server in a colocation > facility, controlled via Plesk control panel, and turned over > to me with Fedora Core 6 in an empty state. This is the > standard way you get a server in a colo today. You have my commiserations, and I don't mean that to be a flippant remark. > Bringing Python up in this completely clean environment is > a huge hassle, and it doesn't really work. Once upon a time, I used to manage an entire Python environment with lots of modules, additional libraries, and so on. I don't have the patience for that any more. > Fedora Core 6 ships with Python 2.4, which appears to be a > good decision on someone's part. Of course, there's no > standard RPM for a Python 2.5 install on Linux. Packaging is > someone else's problem, according to the Python developers. I managed to find a site which gives some kind of searchable index of packages: http://www.fedoratracker.org/ It's a bit like the Debian and Ubuntu package sites but seemingly unofficial and a lot slower. Once upon a time there were some contributed RPMs available from python.org, but I don't know what happened to them. [FTP server, GCC, configuration] > But "make install" does some compiles, something "install" probably > shouldn't be doing. If the original build process didn't manage to compile everything, make will revisit that part of the process. What should really happen is that make should halt and not try and do anything else. An aside on the subject of installing - something you may be aware of, but worth repeating for others who have read this far. I guess that "make altinstall" isn't necessary if you *don't* do something like this when configuring: ./configure --prefix=/usr The issue here is that if Fedora (or other distributions) has things relying on /usr/bin/python, you have to make sure that you don't overwrite it when installing. If you've been thinking that the new version of Python should live alongside the others, you have to use "make altinstall" to preserve the existing python program (the python2.4 will survive, anyway) whilst installing python2.5 alongside it. Typically, the configure script behaves as if this were typed: ./configure --prefix=/usr/local Thus, a "make install" will create /usr/local/bin/python and /usr/ local/bin/python2.5, hopefully not overwriting other things. > Some of these compiles fail, with error messages > like > "/var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.5/Modules/_curses_panel.c:271: > error: "PyCursesPanelObject" has no member named "pan" This should stop the process, but as you note... > But the install script plunges blindly on, presumably installing a broken > Python 2.5. Apparently Fedora Core 6 doesn't come with "curses" preinstalled, > but the Python installer assumes it is there. What's inexcusable is > just plowing on after failed compiles, resulting in a broken install. This might require a bug report. > It's probably necessary to install something before building Python, > but the README file is silent on this. > > OK. Plunging onward, and not really needing the "curses" library, > we try to install MySQLdb. We get that with FTP, > unpack it, go to the approprate directory, and run "python setup.py". > This fails because the MySQL headers aren't installed: > > "_mysql.c:35:23: error: my_config.h: No such file or directory" > > OK, looks like we need to install "mysql-devel", so we do that, > using "yum". This forces an update of OpenSSL, Kerberos, and > "e2fsprogs-dev". Which means we should reboot at some point. Perhaps the system wasn't up-to-date anyway. > But now we can build MySQLdb. So we build and install it. > > So then we try "import MySQLdb" in Python 2.5. And we get this: > > > /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.pyc, but /var/www/vhosts/sitetruth.com/private/downloads/MySQLdb/MySQL-python-1.2.2 is being added to sys.path > > import sys, pkg_resources, imp > > Traceback (most recent call last): > > File "", line 1, in > > File "MySQLdb/__init__.py", line 19, in > > import _mysql > > File "build/bdist.linux-i686/egg/_mysql.py", line 7, in > > File "build/bdist.linux-i686/egg/_mysql.py", line 4, in __bootstrap__ > > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 800, in resource_filename > > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 1228, in get_resource_filename > > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 1250, in _extract_resource > > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 880, in get_cache_path > > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 846, in extraction_error > > pkg_resources.ExtractionError: Can't extract file(s) to egg cache > > > > The following error occurred while trying to extract file(s) to the Python egg > > cache: > > > > [Errno 13] Permission denied: '/var/www/vhosts/sitetruth.com/.python-eggs' > > > > The Python egg cache directory is currently set to: > > > > /var/www/vhosts/sitetruth.com/.python-eggs > > > > Perhaps your account does not have write access to this directory? You can > > change the cache directory by setting the PYTHON_EGG_CACHE environment > > variable to point to an accessible directory. > > So what's going on? We've run into a conflict between an assumption of Python > and of the Plesk control panel. Plesk doesn't let the user create files > in their own home directory. This installer assumes it can. Oops. > (Plesk sets up a very locked down environment, which is a good thing on > a web server.) This is probably a setuptools/easy_install FAQ. I only know this from lurking on various mailing lists because I don't use setuptools/ easy_install. > So, becoming the super-user, we create .python-eggs and change its ownership. > Now we can import MySQLdb into Python. > > Now it turns out that we have Python 2.4 in /usr/bin, and Python 2.5 > in /usr/local/bin. That's where the installer put it. So the CGI > scripts are invoking the wrong version of Python. The scripts had to > be changed. That's possibly an environment issue, depending on what the first line of the scripts are. > At last, MySQLdb is connecting to MySQL properly. However, the SSL module > seems to be broken. Tomorrow I'll deal with that, and try to get > M2Crypto installed, always a tough job. > > This kind of nonsense is why hosting companies don't want to support Python. > Perl and PHP may be dumb, but they just work. Java has a company behind it. > Python just isn't ready. Which is embarassing, ten years on. Do hosting companies support multiple versions of Perl or PHP in the same environment? This isn't a provocative question, but I'd be interested to know what they do. > If the Python crowd wants market share, attention, and a career path, > this has to be fixed. Generally, if I were installing into a hosting environment - something I may consider doing in the relatively near future - I'd firstly choose a distribution I like working with (Debian-based, not Fedora) and use the system packaging tools to their maximum extent. I'd even create my own packages and repositories if necessary; I've done this already for my own system. Managing dependencies, especially when you get into dealing with lots of libraries from outside the Python ecosystem, is a demanding task which can be sufficiently lightened if you can make use of other people's packaging work. Really, the "Python crowd" needs to involve the distribution makers more, rather than (from time to time) calling them names, since most installed versions of Python on non-Windows platforms are distributed by those people to users, not obtained by users from python.org. One exception may involve early adopters and the very latest Python versions, however. Paul From gagsl-py2 at yahoo.com.ar Sun Mar 18 21:52:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Mar 2007 22:52:32 -0300 Subject: * operator--as in *args? References: <1174251225.056602.99810@n59g2000hsh.googlegroups.com> <1174254032.155494.228530@e65g2000hsc.googlegroups.com> <1174266469.127020.186120@l77g2000hsb.googlegroups.com> <1hv6o86.18ve0cc11prsg8N%aleax@mac.com> Message-ID: En Sun, 18 Mar 2007 22:21:41 -0300, Alex Martelli escribi?: > 7stud wrote: > >> I played around with it a little bit, and it appears the * operator >> unpacks a list, tuple, or dictionary so that each element of the >> container gets assigned to a different parameter variable. Although >> with a dictionary, only the keys appear to be assigned to the >> parameter variables, e.g.: >> >> def g(a,b,c): >> print a, b, c >> >> dict = {"x":10, "y":20, "z":30} >> g(*dict) >> >> Is that right? > > As far as it goes, yes. More generally, with any iterable x, the *x > construct in function call will pass as positional arguments exactly > those items which (e.g.) would be printed by the loop: > for item in x: print x > > [[this applies to iterators, generators, genexps, and any other iterable > you may care to name -- not just lists, tuples, dicts, but also sets, > files open for reading [the items are the lines], etc, etc]]. But the language reference says "sequence", not "iterable" (http://docs.python.org/ref/calls.html) and a dictionary is not a sequence. With Python 2.1 it was an error; it is not with 2.3 (I can't test with 2.2 right now) Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> def f(*args, **kw): ... print "args",args ... print "kw",kw ... >>> d = {"a":1, "b":2, "c":3} >>> f(**d) args () kw {'b': 2, 'c': 3, 'a': 1} >>> f(*d) Traceback (most recent call last): File "", line 1, in ? TypeError: f() argument after * must be a sequence If allowing f(*d) is actually the intended behavior, maybe the wording in the reference should be updated. If not, f(*d) should still raise an error. -- Gabriel Genellina From aleax at mac.com Thu Mar 22 10:42:23 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 22 Mar 2007 07:42:23 -0700 Subject: Garbage collection References: <1hvchlx.13gg6ie17naf4oN%aleax@mac.com> Message-ID: <1hvd9dq.dhkmc614vg15N%aleax@mac.com> Steve Holden wrote: ... > > a. fork > > b. do the memory-hogging work in the child process > > c. meanwhile the parent just waits > > d. the child sends back to the parent the small results > > e. the child terminates > > f. the parent proceeds merrily > > > > I learned this architectural-pattern a long, long time ago, around the > > time when fork first got implemented via copy-on-write pages... > > > Yup, it's easier to be pragmatic and find the real solution to your > problem than it is to try and mould reality to your idea of what the > solution should be ... "That's why all progress is due to the unreasonable man", hm?-) Alex From MonkeeSage at gmail.com Mon Mar 5 21:51:21 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 18:51:21 -0800 Subject: Is every number in a list in a range? In-Reply-To: <7xk5xvgo55.fsf@ruckus.brouhaha.com> References: <7xk5xvgo55.fsf@ruckus.brouhaha.com> Message-ID: <1173149481.694255.23350@n33g2000cwc.googlegroups.com> On Mar 5, 7:24 pm, Paul Rubin wrote: > This genexp is better than a loop because it bails out immediately > if it finds an out-of-range x. That's true: assuming that input is sequential. But if it's farily random (e.g., [10, 20, 12, 46, 202, 5, 102]), then you need a loop/ list comp. to check each index. Regards, Jordan From laurent.pointal at wanadoo.fr Sat Mar 10 09:32:31 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 10 Mar 2007 15:32:31 +0100 Subject: UTF-8 output problems References: Message-ID: <45f2c077$0$5094$ba4acef3@news.orange.fr> Michael B. Trausch wrote: > I am having a slight problem with UTF-8 output with Python. I have the > following program: > > x = 0 > > while x < 0x4000: > print u"This is Unicode code point %d (0x%x): %s" % (x, x, > unichr(x)) > x += 1 > > This program works perfectly when run directly: > > mbt at pepper:~/tmp$ python test.py > This is Unicode code point 0 (0x0): > This is Unicode code point 1 (0x1): > This is Unicode code point 2 (0x2): > This is Unicode code point 3 (0x3): > This is Unicode code point 4 (0x4): > This is Unicode code point 5 (0x5): > This is Unicode code point 6 (0x6): > This is Unicode code point 7 (0x7): > This is Unicode code point 8 (0x8): > This is Unicode code point 9 (0x9): > This is Unicode code point 10 (0xa): > (... continued) > > However, when I attempt to redirect the output to a file: > > mbt at pepper:~/tmp$ python test.py >f > Traceback (most recent call last): > File "test.py", line 6, in > print u"This is Unicode code point %d (0x%x): %s" % (x, x, > unichr(x)) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in > position 39: ordinal not in range(128) > > This is slightly confusing to me. The output goes all the way to the > end of the program when it is not redirected. Why is Python treating > the situation differently when the output is redirected? This failure > occurs for all redirection, by the way: >, >>, 1>2, pipes, and so forth. > > Any ideas? In complement to Marc reply, you can open a file with a specific encoding (see codecs.open() function), and use print >> f,... to fill that file. A+ Laurent. From steven.bethard at gmail.com Fri Mar 30 12:50:55 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 30 Mar 2007 10:50:55 -0600 Subject: Modules & positive surprises In-Reply-To: <46091c7e$1@griseus.its.uu.se> References: <46091c7e$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > But then there are a few modules that I just love to use, because > they are so "clean" from interface to function. Among them I can't help > mentioning optparse. If you like optparse, you should try argparse: http://argparse.python-hosting.com/ It has an optparse-style API, along with support for * positional arguments * sub-commands * required options * options with a variable number of args * better usage messages * a much simpler extension mechanism and more... STeVe From paddy3118 at googlemail.com Sun Mar 11 04:44:59 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Mar 2007 00:44:59 -0800 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> Message-ID: <1173602699.255167.226250@8g2000cwh.googlegroups.com> On Mar 9, 10:30 am, Nick Craig-Wood wrote: > dbhbar... at googlemail.com wrote: > > What if 2 new 'special' comment-like characters were added to Python?: > > > 1. The WIP (Work In Progress) comment: > > I use # FIXME for this purpose or /* FIXME */ in C etc. > > I have an emacs macro which shows it up in bright red / yellow text so > it is easy to see and the company has a system which makes a web page > with a list of all the FIXMEs on. > > FIXME is easy to grep for, language neutral and a lot of people use > something similar (eg XXX or TODO). > > > 2. The HALT comment: > > You can so this with triple quotes. ''' and ''' (if you normally use > """ """ for docstrings) > > Python just ignores strings that lie around. > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick Vim will highlight the following comments too: #FIXME #TODO #XXX - Paddy From r1chardj0n3s at gmail.com Thu Mar 1 12:58:35 2007 From: r1chardj0n3s at gmail.com (r1chardj0n3s at gmail.com) Date: 1 Mar 2007 09:58:35 -0800 Subject: PyCon blogs? In-Reply-To: References: Message-ID: <1172771915.765168.289370@v33g2000cwv.googlegroups.com> On Feb 27, 6:36 pm, s... at pobox.com wrote: > Was anybody blogging about PyCon (talks and/or sprints)? Got any pointers? Have you tried Planet Python? http://planet.python.org/ From nick at craig-wood.com Tue Mar 27 04:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 27 Mar 2007 03:30:05 -0500 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: Hendrik van Rooyen wrote: > so Diez is probably right that the way to go is to put the timer in the > python interpreter loop, as its the only thing around that you could > more or less trust to run all the time. > > But then it will not read as nice as Nick's wish, but more like this: > > id = setup_callback(error_routine, timeout_in_milliseconds) > long_running_stuff_that_can_block_on_IO(foo, bar, baz) > cancel_callback(id) > print "Hooray it worked !! " > sys.exit() > > def error_routine(): > print "toughies it took too long - your chocolate is toast" > attempt_at_recovery_or_explanation(foo, bar, baz) > > Much more ugly. I could live with that! It could be made to work I'm sure by getting the interpreter to check for timeouts every few hundred bytecodes (like it does for thread switching). > But would be useful to be able to do without messing with > threads and GUI and imports. > Could be hard to implement as the interpreter would have > to be assured of getting control back periodically, so a > ticker interrupt routine is called for - begins to sound more > like a kernel function to me. > Isn't there something available that could be got at via ctypes? I think if we aren't executing python bytecodes (ie are blocked in the kernel or running in some C extension) then we shouldn't try to interrupt. It may be possible - under unix you'd send a signal - which python would act upon next time it got control back to the interpreter, but I don't think it would buy us anything except a whole host of problems! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jeff at jmcneil.net Wed Mar 28 16:04:48 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 28 Mar 2007 16:04:48 -0400 Subject: newbi question on python rpc server, how it works? In-Reply-To: References: Message-ID: <82d28c40703281304w2e90b5deu315c60a78b9f106f@mail.gmail.com> I've built a bit of an account provisioning/support framework here based on SimpleXMLRPCServer (which is the one bundled w/ Python). Take a look at http://docs.python.org/lib/module-SimpleXMLRPCServer.html as it also includes a bit of a code example. It seems to work fine for my needs in that I only server between 5 - 6 requests a minute. All XML-RPC calls translate into one or more LDAP calls. I've about ten clients connecting at random times. I've set it up to run on localhost:8080 and then I use Apache+mod_ssl+htaccess+mod_proxy to provide some security. Direct requests are sent to https://user:password at rpc-server/RPC2 and proxied internally back to the XMLRPC server. Twisted might be an easier option though as you'll not have to deal with all of the daemonization details. Also, check out http://www.xmlrpc.com for protocol details. Jeff On 3/28/07, Larry Bates wrote: > > krishnakant Mane wrote: > > hello, > > searched a lot of places including google search but can't find > > answers to python-rpc. I am also very new to rpc. I am very clear > > about its meaning and where it is to be used, but not about how it is > > done. > > I have a need where I need to create a layer of business logic that > > will connect to mysql database at one end and a wxpython based thin > > client at the other end. > > can some one give me basic idea as to how I can use simple xml rpc > > server class of python and build an xml rpc server and then a client > > which I can embed in my wxpython based thin client? > > as I said I am not aware of how xml rpc works in details. > > I want to creat the wxpython client app in such a way that it only > > does the work of validation and display and only sending the data as > > is to the xml rpc server for logic and then xml rpc server will > > inturn talk to mysql. > > my business logic consists of many classes which I want to put in a > > package directory with __init__.py and all the other modules. > > do I need to create all of them as xml rpc server instances or can I > > use them into one single xml rpc server class? > > at the other end I am not really understanding how the xml rpc client > > can be used to get data in to my wx based gui? > > for example I want to fill up a list box with data that came from the > > rpc server to the client and then some how looping through the > > elements sent over and putting into a list. > > > > regards. > > Krishnakant > > I'm no expert, but maybe I can get you started. > > If you understand how a SQL database works you can extend that knowledge > to RPC. You make queries to the RPC server and it returns responses. > The format of the queries/responses is "normally" XML, but I'm pretty > sure you could invent your own if you wanted to (probably a bad idea). > Basically you define an API (like SQL queries define their API) that is > used by the clients to make requests, update information, retrieve > information, etc. > > You probably should take a look at Twisted module. It does XMLRPC with > just a few lines of code and also would scale well as you have many > users talking to the server. Download Twisted and take a look. You > might also want to pick up a copy of "Twisted Network Programming > Essentials": > > http://www.oreilly.com/catalog/twistedadn/ > > I'll bet it will be worth the purchase price if you choose to go this > direction. > > -Larry Bates > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhellwig at xs4all.nl Fri Mar 2 09:53:46 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Fri, 02 Mar 2007 15:53:46 +0100 Subject: How to update DNS record In-Reply-To: References: <45e71210$0$323$e4fe514c@news.xs4all.nl> Message-ID: <45e83a32$0$337$e4fe514c@news.xs4all.nl> Andi Clemens wrote: > > It's working!!! > Yeah! > I don't know why I didn't get this the first time I tried dnspython, but now > its working! And it's so easy, 3 lines of code: > > def make_dns_entry(pix): > update = dns.update.Update(_DOMAIN) > update.replace(pix.name, 3600, 'a', pix.outbound) > response = dns.query.tcp(update, _NAMESERVER) > > Thank you for all your help! > > Andi Glad to be of service! -- mph From fredrik at pythonware.com Tue Mar 20 11:03:53 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Mar 2007 16:03:53 +0100 Subject: class objects, method objects, function objects References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com><1174324902.778062.104610@b75g2000hsg.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > "it(the" -- argument list, not the object -- ") is unpacked again no, "it" refers to the bound method object, as 7stud would have realized if he'd read the entire paragraph. here's the relevant portion: /.../ a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, it is unpacked again /.../ From __peter__ at web.de Wed Mar 28 03:34:51 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Mar 2007 09:34:51 +0200 Subject: Python automatic testing: mocking an imported module? References: <1175033934.795913.292030@l77g2000hsb.googlegroups.com> Message-ID: Silfheed wrote: > So we have the following situation: we have a testee.py that we want > to automatically test out and verifiy that it is worthy of being > deployed. We want our tester.py to test the code for testee.py > without changing the code for testee.py. testee.py has a module in it > that we want to mock in some tests and in others use the real module. > > /foo.py: (real module) > class bar: > def __init__(self): > "I am real" > > /foo_fake/foo.py: (fake module) > class bar: > def ___init__(self): > "I am a banana" > > /testee.py: > import foo > foo.bar() > > /tester.py: > from foo_fake import foo > foo.bar() # prints I am a banana > testee.py # also prints I am a banana > import foo > foo.bar() # prints I am real > testee.py # also prints I am real > > > This isnt working as we would like, does anyone have any tips on how > to get something like this working? You can put foo_fake.foo into sys.modules as foo: import sys from foo_fake import foo assert "foo" not in sys.modules sys.modules["foo"] = foo foo.bar() # prints I am a banana import foo foo.bar() # prints I am a banana Peter From gagsl-py2 at yahoo.com.ar Mon Mar 19 10:05:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 11:05:46 -0300 Subject: any ways to judge whether an object is initilized or not in a class References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <1174293300.034362.282460@l75g2000hse.googlegroups.com> Message-ID: En Mon, 19 Mar 2007 05:35:00 -0300, momobear escribi?: >> > in C++ language we must initilized a variable first, so there is no >> > such problem, but in python if we don't invoke a.boil(), we will not >> > get self.temp to be initilized, any way to determine if it's initilzed >> > before self.temp be used. > > sorry, I should add more code to implement my ideas. > class coffee: > def __init__(self): > ''' > do something here > ''' > def boil(self): > self.temp = 80 > > a = coffer() > if a.temp > 60: > print "it's boiled" Apart from the other suggestions (ensure full initialization in __init__, using getattr, using hasattr) you may consider using a class attribute as a default value: class Coffee: temp = 50 def __init__(self): "do something" def boil(self): self.temp = 80 a = Coffee() print a.temp # 40 a.boil() print a.temp # 80 -- Gabriel Genellina From steven.bethard at gmail.com Thu Mar 15 11:19:30 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 15 Mar 2007 09:19:30 -0600 Subject: Multiline code - trailing slash usage In-Reply-To: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> References: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> Message-ID: abcd wrote: > When do I need to use a trailing slash to separate code over multiple > lines. > > For example: > > x = "hello world, this is my multiline " + \ > "string!!!!" Yes. > > x = {'name' : \ > 'bob'} No. You don't need trailing slashes whenever there's a pair of {}, [] or () wrapping things. I never use trailing slashes -- I just wrap the expression in parentheses. STeVe From goodTweetieBird at hotmail.com Tue Mar 20 13:55:54 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 20 Mar 2007 10:55:54 -0700 Subject: if __name__ == 'main': In-Reply-To: <1174410796.599687.315730@b75g2000hsg.googlegroups.com> References: <1174409383.842776.264350@b75g2000hsg.googlegroups.com> <1174410796.599687.315730@b75g2000hsg.googlegroups.com> Message-ID: <1174413354.114320.19090@n59g2000hsh.googlegroups.com> On Mar 20, 12:13 pm, "Patrick Down" wrote: > On Mar 20, 11:49 am, "gtb" wrote: > > > Hi, > > > I often see the following 'if' construct in python code. What does > > this idiom accomplish? What happens if this is not main? How did I get > > here if it is not main? > > A quick example demonstrates the usage: > > C:\code>type temp.py > > print "Module name is",__name__ > > if __name__ == "__main__": > print "I was not imported" > else: > print "I was imported" > > C:\code>python temp.py > Module name is __main__ > I was not imported > > C:\code>python > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information.>>> import temp > > Module name is temp > I was imported Thanks, all! Makes great sense. Teas all 'round the canteen now, gtb From robin at reportlab.com Fri Mar 2 12:49:45 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 02 Mar 2007 17:49:45 +0000 Subject: Sorting strings containing special characters (german 'Umlaute') In-Reply-To: <54r2c4F21fssbU1@mid.individual.net> References: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> <54r2c4F21fssbU1@mid.individual.net> Message-ID: <45E863B9.9020105@chamonix.reportlab.co.uk> Bjoern Schliessmann wrote: > Hallvard B Furuseth wrote: >> DierkErdmann at mail.com writes: ....... > > In German, there are some different forms: > > - the classic sorting for e.g. word lists: umlauts and plain vowels > are of same value (like you mentioned): ? = a > > - name list sorting for e.g. phone books: umlauts have the same > value as their substitutes (like Dierk described): ? = ae > > There are others, too, but those are the most widely used. Bj?rn, in one of our projects we are sorting in javascript in several languages English, German, Scandinavian languages, Japanese; from somewhere (I cannot actually remember) we got this sort spelling function for scandic languages a .replace(/\u00C4/g,'A~') //A umlaut .replace(/\u00e4/g,'a~') //a umlaut .replace(/\u00D6/g,'O~') //O umlaut .replace(/\u00f6/g,'o~') //o umlaut .replace(/\u00DC/g,'U~') //U umlaut .replace(/\u00fc/g,'u~') //u umlaut .replace(/\u00C5/g,'A~~') //A ring .replace(/\u00e5/g,'a~~'); //a ring does this actually make sense? -- Robin Becker From has.temp3 at virgin.net Sun Mar 25 06:54:56 2007 From: has.temp3 at virgin.net (has) Date: 25 Mar 2007 03:54:56 -0700 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174799509.212761.34380@n76g2000hsh.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <1174794013.752495.42220@o5g2000hsb.googlegroups.com> <1174794172.156941.107550@y66g2000hsf.googlegroups.com> <1hvhzvb.1qccr1i1ok96m7N%aleax@mac.com> <1174799509.212761.34380@n76g2000hsh.googlegroups.com> Message-ID: <1174820096.012747.235450@n76g2000hsh.googlegroups.com> On 25 Mar, 06:11, "7stud" wrote: > There it is. I notice there is a directory: ..../Python.framework/ > Versions/2.3/Mac/Tools/IDE > which has a bunch of files in it. Do Macs have some kind of pre- > installed Python IDE? There's no read me file, so I can't tell what > all the files are for. That's the source for the old MacPython IDE which is now defunct. Just ignore it. Apple don't bundle a Python IDE in OS X. However, the Python 2.5 installer (http://www.python.org/ftp/python/2.5/python-2.5-macosx.dmg) includes a copy of IDLE (not very Mac-like, unfortunately) and there are various third-party editors available if you want to search around. has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org http://appscript.sourceforge.net/objc-appscript.html From kyosohma at gmail.com Mon Mar 26 14:58:28 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 11:58:28 -0700 Subject: wx.grid problem In-Reply-To: <4607f550$0$5092$ba4acef3@news.orange.fr> References: <4607e4f1$0$5098$ba4acef3@news.orange.fr> <1174925041.703904.151900@y80g2000hsf.googlegroups.com> <4607f550$0$5092$ba4acef3@news.orange.fr> Message-ID: <1174935508.081326.113400@p77g2000hsh.googlegroups.com> On Mar 26, 11:30 am, BH wrote: > Yes, absolutely, but try to minimize it, and the scrollbars stays hidden !!! > > kyoso... at gmail.com a ?crit : > > > On Mar 26, 10:20 am, BH wrote: > >> Hi ! > > >> I have a small problem with wx.Grid and scrollbars. > >> Scrollbars definitively dissapears after resizing the frame. > > >> Thx for help > > >> #---------------------------------------------------------------------- > >> import wx,wx.grid > >> #---------------------------------------------------------------------- > >> class MainWindow(wx.Frame): > >> def __init__(self,parent,id,title): > >> wx.Frame.__init__(self,parent,wx.ID_ANY,title) > >> #-- > >> self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > >> self.grid.CreateGrid(numRows=10,numCols=2) > >> self.grid.Fit() > >> self.Fit() > >> #-- > >> self.Show(1) > >> #---------------------------------------------------------------------- > >> app = wx.PySimpleApp() > >> frame=MainWindow(None,-1,'Grid sizer') > >> app.MainLoop() > >> del app > > > If I understand this correctly, that is normal. Your grid is only two > > columns by 10 rows, so if you resize your frame so that it shows all > > rows and columns, the scroll bars will disappear, much like other > > apps, such as FireFox. If you enlarge the frame enough, the scrollbars > > go away. > > > Mike The code you posted works for me. I am using Windows XP Pro, Python 2.4, wxPython 2.8. When I enlarge it, the scrollbars go away and when I shrink it down, the scrollbars reappear. I tried using sizers, but that seemed to cause problems. I highly recommend that you post your questions about wxPython to the wxPython users group. They have many talented and knowledgeable people there. See http://wxpython.org/maillist.php Mike From martinunsal at gmail.com Tue Mar 6 12:49:55 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 6 Mar 2007 09:49:55 -0800 Subject: Project organization and import In-Reply-To: References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> Message-ID: <1173203395.649560.249930@p10g2000cwp.googlegroups.com> On Mar 6, 9:19 am, "Chris Mellon" wrote: > You do? Or do you only have trouble because you don't like using "from > foo import Foo" because you need to do more work to reload such an > import? More work, like rewriting __import__ and reload??? :) There's a point where you should blame the language, not the programmer. Are you saying I'm lazy just because I don't want to mess with __import__? > What makes you think that the exposed namespace has to be isomorphic > with the filesystem? I don't; you do! I was clearly talking about files and you assumed I was talking about namespace. That's Pythonic thinking... and I don't mean that in a good way! > If you want to break a module into multiple packages and then stick > the files that make up the package in bizarre spots all over the > filesystem, can you give a reason why? Because I have written a project with 50,000 lines of Python and I'm trying to organize it in such a way that it'll scale up cleanly by another order of magnitude. Because I've worked on projects with millions of lines of code and I know about how such things are organized. It's funny, I'm a newbie to Python but it seems like I'm one of the only people here thinking about it as a large scale development language rather than a scripting language. Martin From MonkeeSage at gmail.com Sun Mar 11 00:37:41 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 10 Mar 2007 21:37:41 -0800 Subject: number generator In-Reply-To: References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <55fbgjF2492skU1@mid.individual.net> <1173573654.009953.266280@30g2000cwc.googlegroups.com> <7xbqj01u9c.fsf@ruckus.brouhaha.com> <1173575978.699090.313770@64g2000cwx.googlegroups.com> Message-ID: <1173591460.941709.316540@s48g2000cws.googlegroups.com> On Mar 10, 11:26 pm, Steven D'Aprano wrote: > To compare to the "cheat" method, calculate the mean and standard > deviation of this sample, and compare to those from the other method. I belieive you (mainly because I'm too lazy to write the sieve, hehe). ;) Regards, Jordan From seberino at spawar.navy.mil Fri Mar 2 18:32:58 2007 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 2 Mar 2007 15:32:58 -0800 Subject: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles.. Message-ID: <1172878378.291106.321050@h3g2000cwc.googlegroups.com> I'm trying to extract some data from an XHTML Transitional web page. What is best way to do this? xml.dom.minidom.parseString("text of web page") gives errors about it not being well formed XML. Do I just need to add something like or what? Chris From paddy3118 at googlemail.com Thu Mar 22 02:52:47 2007 From: paddy3118 at googlemail.com (Paddy) Date: 21 Mar 2007 23:52:47 -0700 Subject: Wikipedia and a little piece of Python History In-Reply-To: References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <871wjiuz5q.fsf@pobox.com> <1174508599.250404.176510@y66g2000hsf.googlegroups.com> Message-ID: <1174546367.798807.83580@p15g2000hsd.googlegroups.com> On Mar 21, 10:31 pm, cla... at lairds.us (Cameron Laird) wrote: > In article <1174508599.250404.176... at y66g2000hsf.googlegroups.com>, > > > > Paddy wrote: > >On Mar 21, 8:20 pm, j... at pobox.com (John J. Lee) wrote: > >> "Paddy" writes: > >> > I just had a link to Tim peters first post on doctest: > >> >http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > >> > removed fromhttp://en.wikipedia.org/wiki/Doctestasit doesn't fit > >> > their guidelines for external links. > >> > I wonder, could maybe the official website be persuaded to host a copy > >> > so that it could be linked to? > > >> > Tim, would you object? > > >> It (wikipedia) is a wiki, why not edit the page and paste it in? > > >> John > > >They have rules, and periodically trawl pages and clean them. I'd like > >to stay within the rules. > > >- Paddy. > > Phaseit would be honored to memorialize a permanent URL for > that post, or even the thread from which it's taken. Is that > an appropriate resolution, Paddy? Thanks Cameron for the kind offer, but after Paul Ruben made me aware that the initial edit was done by a rogue 'bot, I reverted the page to its prior state. Maybe, if you email Tim, he might welcome you adding his post to your site anyway? - I think its wasted just being available as a newsgroup search, and should at least be available somewhere on the official Python website. Doctest is a great idea that is in harmony with the language it is expressed in. - Paddy. From openopt at ukr.net Mon Mar 19 16:13:55 2007 From: openopt at ukr.net (dmitrey) Date: 19 Mar 2007 13:13:55 -0700 Subject: looking for a fastest parallel approach for quick executing of lots small routines Message-ID: <1174335235.682491.300930@l75g2000hse.googlegroups.com> hi all, I'm looking for a way to execute a number (from 2 to thouzands, usually small) of python functions as quikly as it's possible. There seems to be lots of solutions, for example mentioned at http://www.cimec.org.ar/python/ , but first of all it would be very nice if the module is included into the scipy module or Python core, for to minimize additional software dependences. So what is the best choise? And if noone is included in Python standard distribution - why it is so and is anything intended in future Python versions: 2.6 or later? Thank you in advance, Dmitrey From __peter__ at web.de Fri Mar 23 03:30:32 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Mar 2007 08:30:32 +0100 Subject: fine grain logging cotrol References: Message-ID: Eric S. Johansson wrote: [in private mail -- please don't, Eric] > Peter Otten wrote: > > > As a general direction try to understand the logging package, the > > __new__() method (a constructor in C++), and metaclasses (a class is > > an instance of another class which is called metaclass to avoid > > confusion when talking about both) independently before jumping into > > the mix. > > I've spent a big chunk of the afternoon/evening and am ok with > metaclasses. ?but what has my knickers in a twist is the format > statement. ?how do I get the logger to let me fill in funcName. ?I've > tried what the docs say should work (but it doesn't) > > self.__logger.info("Felis.alpha", funcName="hisss") I don't understand. The logging package detects the function name without user intervention. Perhaps it's time to step back and explain what you want to achieve rather than how you proceed. Peter From steve at holdenweb.com Mon Mar 19 23:25:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 23:25:28 -0400 Subject: difference between urllib2.urlopen and firefox view 'page source'? In-Reply-To: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> References: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> Message-ID: cjl wrote: > Hi. > > I am trying to screen scrape some stock data from yahoo, so I am > trying to use urllib2 to retrieve the html and beautiful soup for the > parsing. > > Maybe (most likely) I am doing something wrong, but when I use > urllib2.urlopen to fetch a page, and when I view 'page source' of the > exact same URL in firefox, I am seeing slight differences in the raw > html. > > Do I need to set a browser agent so yahoo thinks urllib2 is firefox? > Is yahoo detecting that urllib2 doesn't process javascript, and > passing different data? > It's almost certainly a browser detection issue. This may not matter for your application. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From bbxx789_05ss at yahoo.com Mon Mar 19 00:54:18 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Mar 2007 21:54:18 -0700 Subject: class objects, method objects, function objects In-Reply-To: <1174279490.889161.39300@y80g2000hsf.googlegroups.com> References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> <1174279490.889161.39300@y80g2000hsf.googlegroups.com> Message-ID: <1174280058.796282.261980@l77g2000hsb.googlegroups.com> Darn. I made some changes to the class and I didn't change the function object. It should be: | V function object --------------------------------- | def sayHi(self): | | print "Hello " + self.name| |_________________________________| From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 1 09:18:24 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 15:18:24 +0100 Subject: How to update DNS record References: <54nkvtF21ft8aU1@mid.individual.net> <1172751262.972242.215990@p10g2000cwp.googlegroups.com> Message-ID: <54o5lgF21rhasU1@mid.individual.net> andi.clemens at gmx.net wrote: > It worked before with a perl script, but now I'm using django for > all our web services so I want to implement this update function > in Python as well. > I don't know how to do this in Python, right now I'm trying it > with twisted, but I don't what to do exactly. It would be nice if > somebody has an example for doing this. No one here knows how the server is configured or how the perl script did it before, so there's little chance someone will have an example that works for you. Regards, Bj?rn -- BOFH excuse #280: Traceroute says that there is a routing problem in the backbone. It's not our problem. From paduffy at cisco.com Fri Mar 2 13:51:26 2007 From: paduffy at cisco.com (Paul Duffy) Date: Fri, 02 Mar 2007 13:51:26 -0500 Subject: Python 2.5, problems reading large ( > 4Gbyes) files on win2k In-Reply-To: References: <1172858955.189032.73800@t69g2000cwt.googlegroups.com> Message-ID: <45E8722E.4090509@cisco.com> I am not using the universal newline. File reading loop is essentially... ifile = open("fileName", "r") for line in ifile ... Thanks Peter Otten wrote: > paduffy at cisco.com wrote: > > >> I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume). >> Reading a file of 13 GBytes, one line at a time. It appears that, >> once the read line passes the 4 GByte boundary, I am getting >> occasional random line concatenations. Input file is confirmed good >> via UltraEdit. Groovy version of the same app runs fine. >> >> Any ideas? >> > > Do you open the file in universal newline mode -- open(filename, "U") --, > and if not, does the problem persist if you do? > > Peter > From grflanagan at yahoo.co.uk Fri Mar 9 06:14:18 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 9 Mar 2007 03:14:18 -0800 Subject: catching exceptions from an except: block In-Reply-To: References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173345456.968709.128870@j27g2000cwj.googlegroups.com> <1173426599.403173.49240@v33g2000cwv.googlegroups.com> <1173436219.937145.12550@64g2000cwx.googlegroups.com> Message-ID: <1173438858.819893.268240@n33g2000cwc.googlegroups.com> On Mar 9, 11:57 am, "Gabriel Genellina" wrote: > En Fri, 09 Mar 2007 07:30:20 -0300, Gerard Flanagan > escribi?: > > >> There is a serious flaw on this approach, the function can't return any > >> false value (it would be treated as a failure). > > > I was teaching myself decorators more than anything, so it's not > > thought out to any extent, but even so I don't think it's a "serious > > flaw", rather it would be programmer error to use @onfailFalse on a > > function that may return False. Don't you think? > > I thought this was on response to the original problem, not for your own > problem. > Mea culpa. Gerard From deepblue.ar at gmail.com Sat Mar 10 14:28:42 2007 From: deepblue.ar at gmail.com (Deep) Date: 10 Mar 2007 11:28:42 -0800 Subject: Formatted Input Message-ID: <1173554922.454532.178280@n33g2000cwc.googlegroups.com> Hi all, I am a newbie to python I have an input of form space ie. 4 3 how can i assign this to my variables?? From bj_666 at gmx.net Thu Mar 1 03:40:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 01 Mar 2007 09:40:12 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> Message-ID: In <54msaoF21c6h3U3 at mid.individual.net>, Bjoern Schliessmann wrote: > Bruno Desthuilliers wrote: > >> class Toto(object): >> pass >> >> print Toto.__name__ > > Okay, I revoke my statement and assert the opposite. > > But what's it (__name__) good for? As objects don't know to which name they are bound, that's a good way to give some information in stack traces or when doing introspection. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Tue Mar 27 09:47:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Mar 2007 06:47:09 -0700 Subject: Python Error :( In-Reply-To: <1175001581.323552.37250@n59g2000hsh.googlegroups.com> References: <1175001581.323552.37250@n59g2000hsh.googlegroups.com> Message-ID: <1175003229.918435.179740@o5g2000hsb.googlegroups.com> On Mar 27, 8:19 am, "Legend" wrote: > I wasn't able to run a Python script. But then later I was able to run > it through the Shell. I was experimenting with cron jobs and set up > the python execution in as a cron. The first time it ran, It was fine > but then after that, it started giving me some errors. Now when I try > to run the script directly, I get the following error: > > Traceback (most recent call last): > File "", line 1, in ? > File "userbot.py", line 637, in ? > con = connect() > File "userbot.py", line 607, in connect > con.requestRoster() > File "user.py", line 531, in requestRoster > self.SendAndWaitForResponse(rost_iq) > File "user.py", line 326, in SendAndWaitForResponse > return self.waitForResponse(ID) > File "user.py", line 300, in waitForResponse > self.process(1) > File "xmlstream.py", line 459, in process > if not len(self.read()): # length of 0 means disconnect > File "xmlstream.py", line 398, in read > data_in=data_in+self._sslObj.read(BLOCK_SIZE).decode('utf-8') > socket.sslerror: (6, 'TLS/SSL connection has been closed') > > Any help please? I'll hazard a guess: Are you opening the socket explicitly when you run this script? If not, be sure to do so. And when you are finished doing whatever it is you're doing, be sure to close it as well. You may need to put in some kind of logic to check if the socket is still open if you are transferring large files. Mike From rhamph at gmail.com Tue Mar 13 01:39:25 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 12 Mar 2007 22:39:25 -0700 Subject: threading and iterator crashing interpreter In-Reply-To: <1173739629.570503.259110@30g2000cwc.googlegroups.com> References: <1173609124.089611.242080@h3g2000cwc.googlegroups.com> <1173617253.901671.136910@q40g2000cwq.googlegroups.com> <1173623758.054666.18190@s48g2000cws.googlegroups.com> <1173730219.561059.165340@c51g2000cwc.googlegroups.com> <1173739629.570503.259110@30g2000cwc.googlegroups.com> Message-ID: <1173764365.486438.288160@t69g2000cwt.googlegroups.com> On Mar 12, 4:47 pm, "Klaas" wrote: > On Mar 12, 1:10 pm, "Rhamphoryncus" wrote: > > >http://sourceforge.net/tracker/index.php?func=detail&aid=1579370&grou... > > > That refers to a generator crash. You are using generators, but also > > getting a weird dict error. Maybe related, maybe not. > > > I'll figure out if I've got a "fixed" version or not when I get back. The bug report mentions 2.5.1, which hasn't be released yet, so obviously I'm not using it. :) > I was the one who filed the first bug. login2 is definitely the same > bug: you have a generator running in a thread, but the thread is being > garbage collected before the generator's .close() method is run (which > references the thread state). > > Try the patch I posted in the bug above; if it works, then python > trunk/5.1maint should work. And with a fresh checkout of trunk I still get a crash with login1. login2 isn't crashing, although it's not as consistent for me anyway. From python.technofreak at gmail.com Mon Mar 26 08:42:30 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Mon, 26 Mar 2007 18:12:30 +0530 Subject: python on window In-Reply-To: <1174910454.043983.171650@y80g2000hsf.googlegroups.com> References: <1174634752.580051.272560@l75g2000hse.googlegroups.com> <1174910454.043983.171650@y80g2000hsf.googlegroups.com> Message-ID: <9d6d3deb0703260542q45aef2a2i569963e63092b8f9@mail.gmail.com> On 26 Mar 2007 05:00:54 -0700, sandeep patil wrote: > > i have written this program but i have gott following error, > in anather proram "indentation error" sir how i will indent in my > editor > > #test.py > >>> def invert(table): > index=() > for key in table: > value=table[key] > if not index.has_key(value): > index[value]=[] > index[value].append(key) > return index > > > >>> phonebook = {'sandeep':9325, 'amit':9822, 'anand':9890, 'titu': 9325} > >>> phonebook > {'titu': 9325, 'amit': 9822, 'anand': 9890, 'sandeep': 9325} > >>> print phonebook > {'titu': 9325, 'amit': 9822, 'anand': 9890, 'sandeep': 9325} > >>> inverted_phonebook = invert(phonebook) > > Traceback (most recent call last): > File "", line 1, in > inverted_phonebook = invert(phonebook) > File "", line 5, in invert > if not index.has_key(value): > AttributeError: 'tuple' object has no attribute 'has_key' > >>> interted_phonebook= invert(phonebook) > > Traceback (most recent call last): > File "", line 1, in > interted_phonebook= invert(phonebook) > File "", line 5, in invert > if not index.has_key(value): > AttributeError: 'tuple' object has no attribute 'has_key' > >>> In your code, index = () means it is a tuple. IIRC, it should be a dictionary. For that, index = {}. This is the one causing the following error in your code, if not index.has_key(value): AttributeError: 'tuple' object has no attribute 'has_key' You can not use has_key over a tuple object. But where is the "indentation error" ? I see nothing like that in the error message. -- With Regards --- Parthan.S.R. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rob at jamDOTrr.com Thu Mar 1 22:24:13 2007 From: rob at jamDOTrr.com (Rob Andrews) Date: Thu, 01 Mar 2007 21:24:13 -0600 Subject: PyCon blogs? In-Reply-To: References: Message-ID: <45e798ce$0$27057$4c368faf@roadrunner.com> Now that I've half recovered from PyCon, I've uploaded some initial prattle: http://trekkingbob.blogspot.com/2007/03/pycon-all-up-in-my-veins.html From steve at REMOVEME.cybersource.com.au Thu Mar 1 21:15:57 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 02 Mar 2007 13:15:57 +1100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> <1172741018.978417.233160@v33g2000cwv.googlegroups.com> <54nlkgF21ft8aU3@mid.individual.net> Message-ID: On Thu, 01 Mar 2007 10:44:48 +0100, Bjoern Schliessmann wrote: > Mh. I suspect there's also more to it than I see now, but this > __name__ seems quite useless to me. What if I rebind the class' > name after definition? Or is it really just for some manual > introspection? If it is, it seems a bit of an overkill to me. Overkill? Storage of a single attribute holding a (usually short) string is overkill? The thing to remember is that the link between names and objects in Python is one-way only. Names (by definition) have to know which object they are bound to. But objects don't know what name, or names, (if any) are bound to themselves. Yes, they *could* keep a list of the names bound to them, but that would be a lot of work at runtime for little benefit. So if you rebind a name, the objects can't tell. And generally you wouldn't want them to. Something like the following is rightfully quite rare: >>> int >>> int.__name__ 'int' >>> foo = int; int = "something else" >>> type(0) # Do you expect ? >>> int 'something else' Normally the reason for rebinding classes, functions etc. are (1) to save typing and (2) an optimization to save name look-ups. # slow way for item in sequence: package.module.function(item) # faster way f = package.module.function for item in sequence: f(item) When you do that, you wouldn't expect the __name__ of some.module.function to change to f, and it doesn't. The downside is that on the rare corner case where you do want the __name__ of an object to change, it doesn't. -- Steven D'Aprano From anton.vredegoor at gmail.com Thu Mar 22 13:07:01 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 22 Mar 2007 18:07:01 +0100 Subject: [JOB] Sr. Python Developer, Northern VA In-Reply-To: References: Message-ID: skip at pobox.com wrote: > I think the steady increase in the number of active listings over the > past couple years bodes well for the job prospects of Python > programmers as a whole. There are currently 99 job postings on the > job board dating back to mid-December. A year ago there were about > 60, a year before that, about 40. Agreed. There's now probably even room on the job market for those who don't belong to the select elite of early adopters. We might even root out the professionalist attitude and address the problem of tying people to their resumes. > A number of those companies seem to be fairly enlightened about the > use of open source software (search for "open"). You can't expect > the world to completely change overnight. If I never speak up there's little chance my ideas will get noticed. But there's probably some better format possible for my message. > Most companies probably still funnel external job postings through > their HR departments. As a result, a certain amount of boilerplate > text and corporate puffery is bound to turn up in many postings. Be > thankful they at least found the job board or comp.lang.python and > aren't just trying to recruit through traditional channels. Actually, I like people posting their jobs on an unmoderated forum. How else would it be possible to try and get applicants and employers to compare their ideas? I mean, not everyone is able to visit expensive high-profile hiring fests like pycon. > You'd probably never see job postings for the Space Telescope Science > Institute or The World Wide Workshop for Children's Media Technology > and Learning if they only appeared in the Washington Post or New > York Times. Sure. But my whole problem is that while I'd be immensely useful in a space telescope science institute or a genome database research institute or in an artists educational institute or in a psychological statistics institute or in a computer science or mathematics institute etc. there is no way people can see that, because they're thinking in resumes, job experience and formal education instead of in just asking themselves what needs to be done and can he do it. You know, like duck typing :-) From what I get around the 'net I gather the problem is a bit less pronounced in the US though. A. From gregpinero at gmail.com Fri Mar 9 18:07:58 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 9 Mar 2007 15:07:58 -0800 Subject: How to Start a (thread?) and Leave In-Reply-To: References: <1173471722.668943.126700@h3g2000cwc.googlegroups.com> <1173472226.698504.147260@h3g2000cwc.googlegroups.com> Message-ID: <1173481678.804795.219240@n33g2000cwc.googlegroups.com> On Mar 9, 4:57 pm, "Terry Reedy" wrote: > wrote in message > > news:1173472226.698504.147260 at h3g2000cwc.googlegroups.com... > | On Mar 9, 3:25 pm, "abcd" wrote: > Can you tell the page to auto-refresh itself every 15 seconds or so? I > have seen this as a user but don't know if it is special html code or > javascript or java or what. > > tjr This will sort of emulate the stop button, that might work: http://www.thescripts.com/forum/thread601992.html -Greg From nagle at animats.com Wed Mar 14 20:18:47 2007 From: nagle at animats.com (John Nagle) Date: Thu, 15 Mar 2007 00:18:47 GMT Subject: merits of Lisp vs Python In-Reply-To: <87odmvinhf.fsf@pobox.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> <1173581125.663707.5810@s48g2000cws.googlegroups.com> <87odmvinhf.fsf@pobox.com> Message-ID: John J. Lee wrote: > "Graham Dumpleton" writes: > >>On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: > Is it possible to ask mod_python to start separate processes to serve > requests, rather than "separate" interpreters? We couldn't see a way. That's what CGI does. John Nagle From steven.potter at gmail.com Sat Mar 17 15:39:47 2007 From: steven.potter at gmail.com (Steve Potter) Date: 17 Mar 2007 12:39:47 -0700 Subject: running python on xp command prompt In-Reply-To: <1174158944.537266.120680@d57g2000hsg.googlegroups.com> References: <1174158944.537266.120680@d57g2000hsg.googlegroups.com> Message-ID: <1174160387.834202.163920@n59g2000hsh.googlegroups.com> On Mar 17, 2:15 pm, TPh... at lbl.gov wrote: > Hi, > > I have a simple question about running python on windows xp command > prompt. The file is as follows and is named spam.py: > > print 2**8 > print 'the bright side' + 'of life' > print "hello world" > > I run this on the command prompt as follows > > C:\Documents and Settings\User>python C:\Documents and Settings\User > \Desktop\spa > m.py > python: can't open file 'C:\Documents': [Errno 2] No such file or > directory > > and get the error above. If I surround the second directory in quotes > like this > > C:\Documents and Settings\User>python "C:\Documents and Settings\User > \Desktop\spa > m.py" > > , there is no error. Does anyone know why this is. > > Thank you It is because of the spaces in the path. The command prompt assumes that when it encounters a space that is the end of the attribute. By surrounding it in quotes you are indicating that it is all one attribute. Steve From skip at pobox.com Sat Mar 10 09:55:48 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 10 Mar 2007 08:55:48 -0600 Subject: pylint: don't warn about tabs In-Reply-To: <7LnIh.327$mh7.197@trnddc04> References: <55avniF23jpl2U1@mid.individual.net> <7LnIh.327$mh7.197@trnddc04> Message-ID: <17906.50932.667513.269959@montanaro.dyndns.org> >> Finally, note this from PEP 666: Alan> I really think you should reread the PEP, which is making Alan> the opposite of your point. Quite the opposite, in fact. Laura Creighton wrote that PEP precisely with the expectation (and hope) that Guido would reject it, which he did: PEP: 666 Title: Reject Foolish Indentation Version: 1083 Last-Modified: 2001-12-12 00:40:09 +0100 (Wed, 12 Dec 2001) Author: Laura Creighton Status: Rejected Type: Standards Track Created: 3-Dec-2001 Python-Version: 2.2 Post-History: 5-Dec-2001 Note the title and status. Skip From gnewsg at gmail.com Mon Mar 5 09:21:34 2007 From: gnewsg at gmail.com (billiejoex) Date: 5 Mar 2007 06:21:34 -0800 Subject: ANN: pyftpdlib 0.1 released In-Reply-To: References: <1173102514.190879.7600@p10g2000cwp.googlegroups.com> Message-ID: <1173104494.751597.98150@p10g2000cwp.googlegroups.com> On 5 Mar, 15:13, Duncan Booth wrote: > "billiejoex" wrote: > > Hi all, > > I'm proud to announce the first beta release of pyftpdlib available at > > the following urls: > > Announcing it once will do. Three times with minor edits is a bit much. I'm sorry. I removed them by using google groups interface but maybe with no success. From whammett at nespower.com Wed Mar 7 14:51:05 2007 From: whammett at nespower.com (Hammett, Wayne) Date: Wed, 7 Mar 2007 13:51:05 -0600 Subject: Python 2.1 and Daylight saving time In-Reply-To: <17903.5426.372813.378190@montanaro.dyndns.org> Message-ID: <93D4B94043372746B559247AD6A3CC0F11CB06@bluepost.nes.nespower.nes> Thanks for the quick reply. Help me OB1, I mainly needed to know if I could avert Daylight Saving Time issues by upgrading to Python 2.5. It appears that Python gets it UTC settings from a table in the C library. Does this still hold true for Python 2.5. It looks that it will fail to recognize the new DST 2007 changes. Thanks again, Wayne Hammett - MCSE Snr. Network Engineer 1214 Church Street Nashville, TN 37246 (615) 747-3092 whammett at nespower.com -----Original Message----- From: skip at pobox.com [mailto:skip at pobox.com] Sent: Wednesday, March 07, 2007 1:41 PM To: Hammett, Wayne Cc: webmaster at python.org Subject: Re: Python 2.1 and Daylight saving time Wayne> It appears that Python 2.1 is affected by the DST 2007 issue. I Wayne> cannot really tell. Wayne> Can you point me to support documentation? Wayne, Python 2.1 is quite old and no longer supported. The last 2.1 release (2.1.3) was April 8, 2002. The current release is Python 2.5. That said, can you describe your problem clearly? Do you have a simple script that demonstrates the problem? If so, it's possible that you can get some help from the folks on the python-list at python.org mailing list. At the very least people should be able to tell you if the problem you see exists in later versions or if there's a bug in your script you can fix to avoid the problem. -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ "The hippies and the hipsters did some great stuff in the sixties, but the geeks pulled their weight too." -- Billy Bragg From stj911 at rock.com Wed Mar 14 14:38:48 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 14 Mar 2007 11:38:48 -0700 Subject: war with china? a different approach? In-Reply-To: <1173654190.949881.5110@h3g2000cwc.googlegroups.com> References: <45AC73E8.4010504@mustang.org> <1hs1e5i.1l5vmdx1ih79a7N%peter@DIESPAMMERDIE.dk> <45acf752.33126625@news-server.houston.rr.com> <2-OdnVZn--tUhzDYnZ2dnUVZ_q_inZ2d@bresnan.com> <1hs27ig.1y5o47s3rgkltN%peter@DIESPAMMERDIE.dk> <5158etF1j0n5aU3@mid.individual.net> <45ae2bf1.112133906@news-server.houston.rr.com> <1hs3c73.1yxa7c3q12khkN%peter@DIESPAMMERDIE.dk> <1hs61zt.1f267j04r1ur2N%peter@DIESPAMMERDIE.dk> <51av2lF1j1dp8U1@mid.individual.net> <45b101c8.82683109@news-server.houston.rr.com> <1169235241.943262.161690@51g2000cwl.googlegroups.com> <1173654190.949881.5110@h3g2000cwc.googlegroups.com> Message-ID: <1173897528.354755.36120@n76g2000hsh.googlegroups.com> On Mar 11, 3:03 pm, rebeccag... at gmail.com wrote: > Are you there, cause I don't want to waste my time writing a response > to that if you're not there anymore. Please respond w/ a new post if > you do check this. A lot of us other than the OP would be interested in a good analysis, if you have one From gherron at islandtraining.com Wed Mar 21 16:34:26 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 21 Mar 2007 13:34:26 -0700 Subject: Make variable global In-Reply-To: <1174506941.618827.48450@l75g2000hse.googlegroups.com> References: <1174506941.618827.48450@l75g2000hse.googlegroups.com> Message-ID: <460196D2.80402@islandtraining.com> abcd wrote: > I have a file, "a.py" > > blah = None > def go(): > global blah > blah = 5 > > >From the python interpreter I try.... > > >>>> from a import * >>>> blah >>>> go() >>>> blah >>>> >>>> > > ...i was hoping to see "5" get printed out the second time I displayed > blah, but it doesn't. Now, if I type this same code directly into the > python interpreter it works as i was hoping. what i am missing? > Since procedure go is defined in a.py, the global blah it refers to is global to that module. So import a (instead of importing * from a) and try this: >>> import a >>> a.blah >>> a.go() >>> a.blah 5 >>> Gary Herron From greg at cosc.canterbury.ac.nz Mon Mar 19 21:24:37 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 20 Mar 2007 13:24:37 +1200 Subject: XML based programming language In-Reply-To: <567h7sF287idqU1@mid.uni-berlin.de> References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> <56786fF2743atU2@mid.uni-berlin.de> <1174307748.936567.191440@e1g2000hsg.googlegroups.com> <567h7sF287idqU1@mid.uni-berlin.de> Message-ID: <568rj6F287c68U1@mid.individual.net> Diez B. Roggisch wrote: > What you are after then is the usage of a validating parser, not just > well-formed XML-documents. > > I'm not sure where element-tree stands regarding this, but I think 4suite > offers DTD, W3C-Schema and Relax-NG support. So he's effectively written his own validating parser, which is a legitimate thing to do. His programming language likely has constraints that can't be easily expressed using any of the standard W3C buzzword-compliant validation mechanisms. Also his validator has a chance to do other useful computation along the way, such as semantic analysis and/or code generation. That stuff has to be done anyway, and validation sort of comes out of that for free. So inserting an extra validation step might not be of any advantage. -- Greg From robert.kern at gmail.com Tue Mar 13 22:06:59 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 13 Mar 2007 21:06:59 -0500 Subject: Questions on migrating from Numeric/Scipy to Numpy In-Reply-To: <1173835370.353415.8000@e1g2000hsg.googlegroups.com> References: <1173835370.353415.8000@e1g2000hsg.googlegroups.com> Message-ID: vj wrote: > I've tried to post this to the numpy google group but it seems to be > down. It is just a redirection to the numpy-discussion at scipy.org list. If you just tried in the past hour or so, I've discovered that our DNS appears to be down right now. > My migration seems to be going well. I currently have one issue > with using scipy_base.insert. > >>>> a = zeros(5) >>>> mask = zeros(5) >>>> mask[1] = 1 >>>> c = zeros(1) >>>> c[0] = 100 >>>> numpy.insert(a, mask, c) > array([ 100., 0., 100., 100., 100., 0., 0., 0., > 0., 0.]) >>>> a > array([ 0., 0., 0., 0., 0.]) >>>> b > array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=int8) >>>> mask > array([ 0., 1., 0., 0., 0.]) >>>> c > array([ 100.]) > > I would have expected numpy.insert to update a so that the second > element in a would be 100. No, that's not what insert() does. See the docstring: In [1]: from numpy import * In [2]: insert? Type: function Base Class: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3569-py2.5-macosx-10.3-fat.egg/numpy/lib/function_base.py Definition: insert(arr, obj, values, axis=None) Docstring: Return a new array with values inserted along the given axis before the given indices If axis is None, then ravel the array first. The obj argument can be an integer, a slice, or a sequence of integers. Example: >>> a = array([[1,2,3], ... [4,5,6], ... [7,8,9]]) >>> insert(a, [1,2], [[4],[5]], axis=0) array([[1, 2, 3], [4, 4, 4], [4, 5, 6], [5, 5, 5], [7, 8, 9]]) The behaviour that you seem to want would be accomplished with the following: In [3]: a = zeros(5) In [4]: mask = zeros(5, dtype=bool) In [5]: mask[1] = True In [6]: mask Out[6]: array([False, True, False, False, False], dtype=bool) In [7]: a[mask] = 100 In [8]: a Out[8]: array([ 0., 100., 0., 0., 0.]) Note that the mask needs to be a bool array. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Thu Mar 1 11:28:32 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 Mar 2007 08:28:32 -0800 Subject: How to Read Bytes from a file In-Reply-To: <1172757183.819978.219440@v33g2000cwv.googlegroups.com> References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1172757183.819978.219440@v33g2000cwv.googlegroups.com> Message-ID: <1172766512.755494.215510@s48g2000cws.googlegroups.com> On Mar 2, 12:53 am, "Bart Ogryczak" wrote: > > import struct > buf = open('somefile','rb').read() > count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+ > (x&64>0)+(x&128>0) > byteOnes = map(count1,struct.unpack('B'*len(buf),buf)) byteOnes = map(count1,struct.unpack('%dB'%len(buf),buf)) From nagle at animats.com Wed Mar 7 15:30:21 2007 From: nagle at animats.com (John Nagle) Date: Wed, 07 Mar 2007 20:30:21 GMT Subject: More M2Crypto build problems Message-ID: Trying to build M2Crypto on a dedicated server running Red Hat Fedora Core 6. I'm trying to do this right, without manual patching. The error message I'm getting during build is: python setup.py build ... swig -python -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 We went through this before, but last time, the versions of OpenSSL and of SWIG on the system were old, and I was running on a shared server and couldn't update it. Eventually, M2Crypto was hammered into working, but it was ugly. It was necessary to patch "setup.py" as follows: 107,108d106 < target_cpu_str = '-D__i386__' # PATCH - assume Intel target. OpenSSL build needs this. < > 116c114 < swig_opts = [swig_opts_str,target_cpu_str] --- > swig_opts = [swig_opts_str] The problem is that the include file in OpenSSL assumes that some system ID, like __i386__, is defined, which GCC does, but SWIG does not. It might be considered a bug in SWIG. This time, everything on the dedicated server has been updated with Yum, so it ought to just work. Yum says: > > Installed Packages > openssl.i686 0.9.8a-5.4 installed > openssl-devel.i386 0.9.8a-5.4 installed > python.i386 2.4.3-9.FC5 installed > swig.i386 1.3.31-0.fc5 installed > Available Packages > openssl.i386 0.9.8a-5.4 updates All of those are later than the ones required for M2Crypto, so the system should be current. > But it doesn't. Also reported as a SWIG bug, as #1676049. John Nagle From ALEXURC at gmail.com Thu Mar 29 11:45:24 2007 From: ALEXURC at gmail.com (ALEXURC at gmail.com) Date: 29 Mar 2007 08:45:24 -0700 Subject: File deletion after 72 hours of creation Message-ID: <1175183124.401829.41330@n76g2000hsh.googlegroups.com> I'm looking for a simple method to delete a folder after 72 "Business hours" (saturday/sunday doesnt count) since its creation. Note that This is on a linux system and I realize that it will be the last modified time. These files wont be modified since their creation. Im very confused on how to work with the number easily. From khemkaamit at gmail.com Thu Mar 29 08:15:22 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 29 Mar 2007 17:45:22 +0530 Subject: Weird behavior in search in a list In-Reply-To: <1175169060.414834.235040@d57g2000hsg.googlegroups.com> References: <1175169060.414834.235040@d57g2000hsg.googlegroups.com> Message-ID: <1360b7230703290515gf47028bjb82dce9e75466dec@mail.gmail.com> On 29 Mar 2007 04:51:00 -0700, Su Y wrote: > hi all, > I can't understand how this code work, its behavior is really weird > for me... > > I want find the first number in extend[] which is larger than num, so > I wrote: > def find(num): > count=0 > for elem in extend: > if elem count+=1 > return count > > I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5, > 5.6], > it works fine: find(4) returns 3, extend[3] is 4.5. > But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6, > 4.6, 3.4, 2.1, 0.3], > find(4) returns 6, extend[6] is 3.4! > > what's going on here? I really can't understand.... Actually your function "find" returns the number of elements in list extend, which are smaller than the argument. Perhaps you wanted to 'break' when once the condition is met. def find(num): count=0 for elem in extend: if elem>num: break else: count+=1 return count Btw a concise way could be: def getfirstbigger(num): for i,x in enumerate(extend): if x>num: return i return len(extend) HTH, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From godzillaismad at gmail.com Thu Mar 22 08:36:46 2007 From: godzillaismad at gmail.com (Godzilla) Date: 22 Mar 2007 05:36:46 -0700 Subject: Python Oracle 10g odbc blob insertion problem In-Reply-To: References: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> Message-ID: <1174567006.244721.115890@n59g2000hsh.googlegroups.com> On Mar 22, 10:56 pm, Steve Holden wrote: > Godzilla wrote: > > Dear all, > > > I cannot find a solution for my problem with inserting a blob object > > (>4000 in length) into an ORACLE database via ODBC. > > > I have tried the two ways of inserting the blob object (a zip file): > > > 1) > > fp = open("c:/test/test.zip", "r+b") > > data = fp.read() > > s = odbc.odbc(cs) > > qry = s.cursor() > > qry.execute("Insert into tBlob (data) values ('%s')" % > > data.encode('hex')) > > > return the error: Input String Too Long Limit: 4096 > > > 2) > > qry.execute("Insert into tBlob (data) values (?)", > > data.encode('hex')) > > > does not return error, but it does not insert the record correctly. > > > Any help will be fully appreciated... > > I would certainly recommend that you think about using the cxOracle > package rather than relying on odbc. Most Orcale users do, with evident > satisfaction. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Recent Ramblings http://holdenweb.blogspot.com- Hide quoted text - > > - Show quoted text - Thanks guys for all your help. Steve, I think I've tried what you have suggested without any luck as well... The statement works fine, but what inserted is not correct... it seems like only the symbol '?' was inserted into the blob field... I will try the suggested cxOracle library in place of odbc as a trial... but I think since 95% of the code is using odbc, it would be hard to convince the team to chance to the new library... anyway, I will let you know how it goes. From n.emami at gmail.com Thu Mar 1 04:34:14 2007 From: n.emami at gmail.com (Nader) Date: 1 Mar 2007 01:34:14 -0800 Subject: installing "pysqlite" In-Reply-To: <1172663495.011225.76410@v33g2000cwv.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> <1172663495.011225.76410@v33g2000cwv.googlegroups.com> Message-ID: <1172741654.589821.255220@v33g2000cwv.googlegroups.com> On Feb 28, 12:51 pm, "Paul Boddie" wrote: > On 28 Feb, 12:07, Nader Emami wrote: > > > > > I am back with another problem. I suppose that I can tell it! > > I have installed both, 'sqlite' and 'pysqlite' without any problem. But > > If I try to test whether the 'pysqlite' interface works, I get the next > > error message: > > [...] > > > /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so: > > undefined symbol: sqlite3_set_authorizer > > > I don't understand it. Could you tell me how I can solve this last > > point? I hope so! > > It looks like Python (although it's really the dynamic linker) can't > locate the SQLite libraries. If you have installed SQLite into a non- > standard place, which I'm guessing is the case, then you will need to > set your LD_LIBRARY_PATH environment variable to refer to the > directory where the libraries were installed. > > So, if you installed SQLite into /usr/people/emami and you see files > like libsqlite3.so in /usr/people/emami/lib, then you need to change > your LD_LIBRARY_PATH as follows: > > export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib > > (The actual directory should be the same as the one you specified for > library_dirs in the setup.cfg file for pysqlite.) > > If you're not using bash as your shell, the syntax for the command may > be different. Don't forget to add this command to your shell > configuration file (eg. .bashrc) so that your system remembers this > information. > > Paul Hello I have expanded the LD_LIBRARY_PATH to my home lib (export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib). I have built and installed the 'pysqlite-2.3.3' with the next 'setup.cfg' : [build_ext] define= include_dirs=/usr/people/emami/include library_dirs=/usr/people/emami/lib #libraries=/usr/people/emami/lib/libsqlite3.so (this line as a comment) The resutl of this process was: running install_lib copying build/lib.linux-i686-2.4/pysqlite2/_sqlite.so -> /usr/people/ emami/lib/python2.4/site-packages/pysqlite2 running install_data This message had given after installing. I have controll the '/usr/ people/emami/lib/python2.4/site-packages/pysqlite2' whether the '_sqlite.so' has copied there. Yes it has. Okay! I go to python and I give the next command: >>> from pysqlite import test and Unfortunately I get the next error message: Traceback (most recent call last): File "", line 1, in ? File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/test/ __init__.py", line 25, in ? from pysqlite2.test import dbapi, types, userfunctions, factory, transactions,\ File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/test/ dbapi.py", line 26, in ? import pysqlite2.dbapi2 as sqlite File "/usr/people/emami/lib/python2.4/site-packages/pysqlite2/ dbapi2.py", line 27, in ? from pysqlite2._sqlite import * ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/ _sqlite.so: undefined symbol: sqlite3_set_authorizer Do you know what option I have to give to if I want to use the 'easy_install" tool? %easy_install pysqlite (with some optione with which it cab find the installed 'libsqlite.so') Nader From __peter__ at web.de Wed Mar 28 14:38:12 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Mar 2007 20:38:12 +0200 Subject: very strange syntax errors References: Message-ID: Georg Brandl wrote: > Peter Otten schrieb: >> A guess: you may have mixed Unix ("\n") and Windows ("\r\n") newlines. >> Try to ensure that every line ends with "\r\n". > > That shouldn't be a problem since Python reads source files in universal > newline mode. Oops, I should have guessed /that/. Peter From deets at nospam.web.de Sun Mar 18 11:48:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Mar 2007 16:48:40 +0100 Subject: XML based programming language In-Reply-To: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> Message-ID: <5655asF26decfU1@mid.uni-berlin.de> stefaan schrieb: > Hello, > > I have recently had to deal with an XML-based > programming language. (The programs are > generated programmatically.) > > XML leads to a "two-level" parsing problem: first > parse the xml into tokens, then parse the tokens > to grasp their meaning (based on the semantics > of the programming language). > > Basically, I used elementtree as a sophisticated "lexer" and wrote a > recursive descent parser to perform the semantic analysis and > interpretation. > (It works great.) > > But I keep wondering: do parser generator tools > exist that I could have used instead of writing > the recursive descent parser manually ? You haven't written a recursive descent parser. At least not in the sense of the word. A parser (recursive descent or otherwise) will take a string written in the language it accepts, and in the field of programming languages usually returns an abstract syntax tree. On which one works - for code-generation, interpretation, optimization. What you wrote is usually called a reducer, the part that traverses the tree, rewriting it, transforming it for interpretation and whatnot. I've been working with tools that use a XML-Schema or DTD and generate typed objects from it, that are capable of being deserialized from a XML-stream. The better of these tools generate visitors and/or matchers, which basically are objects that traverse the generated object tree in document order, via typed methods. Something like this (java pseudocode): class Visitor { public visit(Object o) { if(o instanceof Expr) { visit((Expr)o); else if(o instanceof SubExpr) { visit((SubExpr)o); } public visit(Expr e) { for(SubExpr se : e.subExpressions) { visit(se); } } public visit(SubExpr e) { // not doing anything } } This visitor you can then subclass, for example to create an interpreter. All of this is theoretically possible in python, too. Using multimethods one can create the dispatching, and so forth. I'm just not too convinced that it really is worth the effort. A simple tag-name-based dispatching scheme, together with the really nice ElementTree-api suffices in my eyes. Then you could do something like this: class Visitor(ojbect): def visit(self, node): descent = True if getattr(self, "visit_%s" % node.tag): descent = getattr(self, "visit_%s" % node.tag)(node) if descent: for child in node: self.visit(child) Then for an element "expr" you could define class Foo(Visitor): def visit_expr(self, node): ... HTH, Diez From anita_group1 at yahoo.com Thu Mar 22 13:52:36 2007 From: anita_group1 at yahoo.com (anita_group1) Date: Thu, 22 Mar 2007 17:52:36 -0000 Subject: testing Message-ID: This is a test. From chris.lasher at gmail.com Wed Mar 28 18:05:21 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 28 Mar 2007 15:05:21 -0700 Subject: PDB does not allow jumping to first statement? In-Reply-To: <1175025037.464283.260680@e65g2000hsc.googlegroups.com> References: <1174946787.291632.154690@n59g2000hsh.googlegroups.com> <1174989571.857680.318720@o5g2000hsb.googlegroups.com> <1175025037.464283.260680@e65g2000hsc.googlegroups.com> Message-ID: <1175119521.753287.55740@o5g2000hsb.googlegroups.com> I have submitted this as a bug via SourceForge: or if munged The Python folks would like a test case and/or a patch. This is well beyond my ken as a humble Python user. Could anybody more knowledgeable please contribute one or both? Duncan or Rocky, would you be able to spare time and effort? Chris From steve at holdenweb.com Thu Mar 22 14:49:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 14:49:50 -0400 Subject: Problem with time In-Reply-To: <4602bc27$0$9709$426a74cc@news.free.fr> References: <4602bc27$0$9709$426a74cc@news.free.fr> Message-ID: ian wrote: > Hi, > > i have a problem with time in python. > > 1) i got 2 values from mysql db (fields are "time" type) > 2) python get it as "" (why timedelta???) timedelta because a time doesn't represent a fixed point until it's associated with a date, I presume. > 3) i need to compare 2 fields with actual time ... EG: > if ArrOutputsAuto[i].TimeFrom >= GNow and ArrOutputsAuto[i].TimeTo <= GNow: > > i need actual time, and 2 fields from DB in datetime.time type (correct me > if i'm wrong) so i can do my test "if time>= ..." > > I think i can grab time from DB in string and parse it in > datetime.time(x,x,x) but its not very optimized > > Any idea ? > Presumably the datetime.timedelta object comes back from the database with days=0? In which case try something like import time import datetime dbtd = h, m, s = time.localtime()[3:6] timenow = s + (60 * (m + 60 * h)) Then compare timenow with dbtd.seconds. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From valentina.marotto at gmail.com Wed Mar 21 06:52:16 2007 From: valentina.marotto at gmail.com (Valentina Marotto) Date: Wed, 21 Mar 2007 11:52:16 +0100 Subject: encoding characters Message-ID: First: excuse me for my very little english! I have a problem, in my scripts python, with the encoding characters type ??????????????? I use the twisted.web package. The problem is about the insertion data into database. one of errors is: exceptions.UnicodeEncodeError: 'ascii' codec can't encode characters in position 25-26: ordinal not in range(128) help me! Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Mar 19 18:24:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 19:24:55 -0300 Subject: coverage.py problem References: <1174337929.621691.307390@p15g2000hsd.googlegroups.com> Message-ID: En Mon, 19 Mar 2007 17:58:49 -0300, Orin escribi?: > Hi, > I have a problem in using coverage.py module in my project: > > ./cov -c > Traceback (most recent call last): > File "./cov", line 10, in ? > coverage.the_coverage.command_line(sys.argv[1:]) > File "/usr/lib/python2.4/site-packages/coverage.py", line 363, in > command_line self.collect() > File "/usr/lib/python2.4/site-packages/coverage.py", line 467, in > collect > for file in os.listdir(cache_dir): > OSError: [Errno 2] No such file or directory: '' It appears that cache_dir is an empty string (and shouldn't) - that's all I can say about that unknown module (to me). -- Gabriel Genellina From esj at harvee.org Thu Mar 22 08:39:21 2007 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 22 Mar 2007 08:39:21 -0400 Subject: fine grain logging cotrol Message-ID: I need to to be able to conditionally log based on the method the log statement is in and one other factor like a log level. in order to do so, I need to be able to automatically find out the name of the method and its class but I haven't found out how to do that yet. for example, class catus(Felis): def Siamese_cat( yowl, purr, demand_food): ... log("state of litter box %s"% litter_box.smell, level = 1) If the table of methods logged contains "catus.Siamese_cat", then I would expect to see the output of the log statements in a log file. If not then I wouldn't see anything in the log. Has somebody done this already? Is it even possible to do without manually adding the class and method information for every log statement? a related question is using signals for reloading configurations etc. I have to find any good examples of how to use signals to cause a long-running process to reload external data. Any good pointers? --- eric From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Mar 9 11:16:04 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 09 Mar 2007 17:16:04 +0100 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> Message-ID: <55dfi4F23k04lU1@mid.individual.net> cesco wrote: > On Mar 9, 3:51 pm, Paul Rubin >> "cesco" writes: >>> I have to generate a list of N random numbers (integer) whose >>> sum is equal to M. If, for example, I have to generate 5 random >>> numbers whose sum is 50 a possible solution could be [3, 11, 7, >>> 22, 7]. Is there a simple pattern or function in Python to >>> accomplish that? Isn't at least one of those numbers depending on the others? > Given two positive integers, N and M with N < M, I have to > generate N positive integers such that sum(N)=M. No more > constraints. Then why must they be random? div and mod should do it. Regards, Bj?rn -- BOFH excuse #220: Someone thought The Big Red Button was a light switch. From attn.steven.kuo at gmail.com Fri Mar 2 00:53:35 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 1 Mar 2007 21:53:35 -0800 Subject: Matplotlib axes label In-Reply-To: <1172790626.088267.303150@j27g2000cwj.googlegroups.com> References: <1172790626.088267.303150@j27g2000cwj.googlegroups.com> Message-ID: <1172814815.385543.180040@j27g2000cwj.googlegroups.com> On Mar 1, 3:10 pm, "John Henry" wrote: > I've been asking this question at the matplotlib user list and never > gotten an answer. I am hoping that there are matplotlib users here > that can help. > > My problem with matplotlib's way of handling axes label is illustrated > by this example: > > http://www.scipy.org/Cookbook/Matplotlib/MulticoloredLine > > Notice that the y-axis goes from (-1.1, 1.1) but the first label is at > -1.0. (snipped) > Is there a way to force the label to start at -1.1 instead of -1.0? > > Thanks, You can try adjusting the labels and ticks using matplotlib.ticker. To the example you cited, one can add from matplotlib.ticker import MultipleLocator, FormatStrFormatter # ... minorLocator = MultipleLocator(0.1) minorFormattor = FormatStrFormatter('%0.1f') ax.yaxis.set_minor_locator(minorLocator) ax.yaxis.set_minor_formatter(minorFormattor) show() -- Hope this helps, Steven From nogradi at gmail.com Thu Mar 29 09:15:27 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 29 Mar 2007 15:15:27 +0200 Subject: YouTube showing repr() of a tuple In-Reply-To: <460b9f48$0$30100$4d3efbfe@news.sover.net> References: <460b9f48$0$30100$4d3efbfe@news.sover.net> Message-ID: <5f56302b0703290615la5456efo8d4a007653fa3e0c@mail.gmail.com> > Thought this might amuse some of you: > > > > I'd heard that YouTube uses Python, but it's fun to see proof of that, > even if it comes in the form of a minor bug. But their web frontend is (probably) in php: http://youtube.com/results.php?search_query=korect+my+speling From nagle at animats.com Sun Mar 4 01:42:38 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Mar 2007 06:42:38 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again Message-ID: I've been installing Python and its supporting packages on a dedicated server with Fedora Core 6 for about a day now. This is a standard dedicated rackmount server in a colocation facility, controlled via Plesk control panel, and turned over to me with Fedora Core 6 in an empty state. This is the standard way you get a server in a colo today. Bringing Python up in this completely clean environment is a huge hassle, and it doesn't really work. Fedora Core 6 ships with Python 2.4, which appears to be a good decision on someone's part. Of course, there's no standard RPM for a Python 2.5 install on Linux. Packaging is someone else's problem, according to the Python developers. So it's necessary to build from source. And the "python.org" FTP server is down, so even getting the source onto a remote server is a pain. So I have to download it on another machine and bring it over with FTP. Trying to install Python 2.5 yields at least the following problems: Fedora Core 6 comes with GCC 4.1.1, but the README file with Python 2.5 says this: GCC 4.1, GCC 4.2: There is a known incompatibility between Python and GCC, where GCC 4.1 and later uses an interpretation of C different to earlier GCC releases in an area where the C specification has undefined behaviour (namely, integer arithmetic involving -sys.maxint-1). As a consequence, compiling Python with GCC 4.1/4.2 is not recommended. It is likely that this problem will be resolved in future Python releases. As a work-around, it seems that adding -fwrapv to the compiler options restores the earlier GCC behaviour. OK, given that, presumably "./configure" takes care of that problem, right? Anybody know for sure? "make" runs fine after "./configure". But "make install" does some compiles, something "install" probably shouldn't be doing. Some of these compiles fail, with error messages like "/var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.5/Modules/_curses_panel.c:271: error: "PyCursesPanelObject" has no member named "pan" But the install script plunges blindly on, presumably installing a broken Python 2.5. Apparently Fedora Core 6 doesn't come with "curses" preinstalled, but the Python installer assumes it is there. What's inexcusable is just plowing on after failed compiles, resulting in a broken install. It's probably necessary to install something before building Python, but the README file is silent on this. OK. Plunging onward, and not really needing the "curses" library, we try to install MySQLdb. We get that with FTP, unpack it, go to the approprate directory, and run "python setup.py". This fails because the MySQL headers aren't installed: "_mysql.c:35:23: error: my_config.h: No such file or directory" OK, looks like we need to install "mysql-devel", so we do that, using "yum". This forces an update of OpenSSL, Kerberos, and "e2fsprogs-dev". Which means we should reboot at some point. But now we can build MySQLdb. So we build and install it. So then we try "import MySQLdb" in Python 2.5. And we get this: > /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/_mysql.pyc, but /var/www/vhosts/sitetruth.com/private/downloads/MySQLdb/MySQL-python-1.2.2 is being added to sys.path > import sys, pkg_resources, imp > Traceback (most recent call last): > File "", line 1, in > File "MySQLdb/__init__.py", line 19, in > import _mysql > File "build/bdist.linux-i686/egg/_mysql.py", line 7, in > File "build/bdist.linux-i686/egg/_mysql.py", line 4, in __bootstrap__ > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 800, in resource_filename > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 1228, in get_resource_filename > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 1250, in _extract_resource > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 880, in get_cache_path > File "/usr/local/lib/python2.5/site-packages/setuptools-0.6c5-py2.5.egg/pkg_resources.py", line 846, in extraction_error > pkg_resources.ExtractionError: Can't extract file(s) to egg cache > > The following error occurred while trying to extract file(s) to the Python egg > cache: > > [Errno 13] Permission denied: '/var/www/vhosts/sitetruth.com/.python-eggs' > > The Python egg cache directory is currently set to: > > /var/www/vhosts/sitetruth.com/.python-eggs > > Perhaps your account does not have write access to this directory? You can > change the cache directory by setting the PYTHON_EGG_CACHE environment > variable to point to an accessible directory. So what's going on? We've run into a conflict between an assumption of Python and of the Plesk control panel. Plesk doesn't let the user create files in their own home directory. This installer assumes it can. Oops. (Plesk sets up a very locked down environment, which is a good thing on a web server.) So, becoming the super-user, we create .python-eggs and change its ownership. Now we can import MySQLdb into Python. Now it turns out that we have Python 2.4 in /usr/bin, and Python 2.5 in /usr/local/bin. That's where the installer put it. So the CGI scripts are invoking the wrong version of Python. The scripts had to be changed. At last, MySQLdb is connecting to MySQL properly. However, the SSL module seems to be broken. Tomorrow I'll deal with that, and try to get M2Crypto installed, always a tough job. This kind of nonsense is why hosting companies don't want to support Python. Perl and PHP may be dumb, but they just work. Java has a company behind it. Python just isn't ready. Which is embarassing, ten years on. If the Python crowd wants market share, attention, and a career path, this has to be fixed. John Nagle From gagsl-py2 at yahoo.com.ar Sun Mar 11 13:12:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 14:12:06 -0300 Subject: Parsing Indented Text (like parsing Python) References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> <1173595945.530722.273030@30g2000cwc.googlegroups.com> <000a01c763c0$6863a560$2102fea9@Guides.local> <008f01c763de$9a1a4190$0702a8c0@Guides.local> <1173629540.341906.319060@h3g2000cwc.googlegroups.com> Message-ID: En Sun, 11 Mar 2007 13:12:20 -0300, Paul McGuire escribi?: > On Mar 11, 8:37 am, "Gabriel Genellina" > wrote: >> If you mix tabs+spaces, Python simple replaces each tab by 8 spaces. > As I recall, the number of spaces to replace a tab by is something > like 8-(col % 8) where col is the column location of the tab with the > left most column being 0. Yes, each tab advances to the next multiple-of-8 column. The problem is that "8" is fixed. -- Gabriel Genellina From lovelydiab at hotmail.com Mon Mar 5 23:27:13 2007 From: lovelydiab at hotmail.com (lovelydiab at hotmail.com) Date: 5 Mar 2007 20:27:13 -0800 Subject: Islam, the Religion of Ease Message-ID: <1173155233.348048.220690@n33g2000cwc.googlegroups.com> Excuse me!! Would you stop for a moment?! O...man...Haven't you thought-one day- about yourself ? Who has made it? Have you seen a design which hasn't a designer ?! Have you seen a wonderful,delicate work without a worker ?! It's you and the whole universe!.. Who has made them all ?!! You know who ?.. It's "ALLAH",prise be to him. Just think for a moment. How are you going to be after death ?! Can you believe that this exact system of the universe and all of these great creation will end in in nothing...just after death! Have you thought, for a second, How to save your soul from Allah's punishment?! Haven't you thought about what is the right religion?! Read ... and think deeply before you answer.. It is religion of Islam. It is the religion that Mohammad-peace upon him- the last prophet, had been sent by. It is the religion that the right Bible- which is not distorted-has preached. Just have a look at The Bible of (Bernaba). Don't be emstional. Be rational and judge.. Just look..listen...compare..and then judge and say your word. We advise you visiting : http://www.islam-guide.com http://www.thetruereligion.org http://www.beconvinced.com http://www.plaintruth.org http://english.islamway.com http://www.todayislam.com http://www.prophetmuhammed.org http://www.islamtoday.net/english/ http://www.islamunveiled.org http://www.islamic-knowledge.com From ralf at schoenian-online.de Thu Mar 8 23:35:32 2007 From: ralf at schoenian-online.de (=?ISO-8859-1?Q?Ralf_Sch=F6nian?=) Date: Fri, 09 Mar 2007 05:35:32 +0100 Subject: Python books? In-Reply-To: References: Message-ID: <45f0e403$1@news.arcor-ip.de> Have a look at: Core python programming from Wesley J. Chun printed by Prentice Hall. Ralf Schoenian From zacherates at gmail.com Mon Mar 19 21:49:02 2007 From: zacherates at gmail.com (zacherates) Date: 19 Mar 2007 18:49:02 -0700 Subject: Passing arguments to a command line from a python script In-Reply-To: <1174354958.815878.95020@d57g2000hsg.googlegroups.com> References: <1174348016.873087.179750@d57g2000hsg.googlegroups.com> <1174354958.815878.95020@d57g2000hsg.googlegroups.com> Message-ID: <1174355342.669635.302960@y80g2000hsf.googlegroups.com> On Mar 19, 9:42 pm, "Luis M. Gonz?lez" wrote: > On Mar 19, 9:25 pm, "Gabriel Genellina" > wrote: > > > > > En Mon, 19 Mar 2007 20:46:56 -0300, Luis M. Gonz?lez > > escribi?: > > > > What I want now is execute the script I just created. > > > As far as I know, the only way to execute the script is from a command > > > line and typing "setup.py py2exe". > > > A few ways: > > - os.system("commandline"). Simplest way, but you don't have much control, > > and it blocks until the process finishes. > > - os.popen[234]? or the functions in the popen2 module > > - the subprocess module - the most complete way, but simple enough for > > most cases. > > > -- > > Gabriel Genellina > > I'm sorry, but still I can't figure out this... > Would you please show me a sample usage of os.system or os.popen for > passing arguments to the command line? > In this case, I should pass to the command line "setuppy py2exe". > > Thanks! > Luis aaron at athena:~$ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> rt = os.system("ls") apps Firefox_wallpaper.png s2 tux_sshot_0.ppm xorg.conf.diff Desktop media s3 work downloads permutation.py squeak workspace Examples permutation.pyc trackers xorg.conf.aiglx >>> rt 0 >>> This implies that `os.system("setuppy py2exe")` should do what you want. From drfredkin at ucsd.edu Sun Mar 11 14:59:55 2007 From: drfredkin at ucsd.edu (Donald Fredkin) Date: Sun, 11 Mar 2007 18:59:55 GMT Subject: any better code to initalize a list of lists? References: Message-ID: John wrote: > For my code of radix sort, I need to initialize 256 buckets. My code > looks a little clumsy: > > radix=[[]] > for i in range(255): > radix.append([]) > > any better code to initalize this list? radix = [[[]]*256][0] -- From george.sakkis at gmail.com Mon Mar 5 22:26:33 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 5 Mar 2007 19:26:33 -0800 Subject: Descriptor/Decorator challenge In-Reply-To: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> References: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> Message-ID: <1173151593.219310.122180@p10g2000cwp.googlegroups.com> On Mar 5, 2:31 am, "Raymond Hettinger" wrote: > I had an idea but no time to think it through. > Perhaps the under-under name mangling trick > can be replaced (in Py3.0) with a suitably designed decorator. > Your challenge is to write the decorator. > Any trick in the book (metaclasses, descriptors, etc) is fair game. > > Raymond > > -------- how we currently localize method access with name mangling > ------ > class A: > def __m(self): > print 'A.__m' > def am(self): > self.__m() > > class B(A): > def __m(self): > print 'B.__m' > def bm(self): > self.__m() > > m = B() > m.am() # prints 'A.__m' > m.bm() # prints 'B.__m' > > -------- how I would like to localize method access with a decorator > ------ > class A: > @localmethod > def m(self): > print 'A.m' > def am(self): > self.m() > > class B(A): > @localmethod > def m(self): > print 'B.m' > def bm(self): > self.m() > > m = B() > m.am() # prints 'A.m' > m.bm() # prints 'B.m' > > --------------------- > > P.S. Here's a link to the descriptor how-to: > http://users.rcn.com/python/download/Descriptor.htm What would the semantics be if m is decorated as local only in A or only in B ? George From fsck_spam at telenet.be Sun Mar 4 10:03:35 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Sun, 04 Mar 2007 16:03:35 +0100 Subject: transfer data from one machine to another References: <1173013001.510046.42270@64g2000cwx.googlegroups.com> Message-ID: <7n3rb4-6ir.ln1@whisper.very.softly> On Sunday 04 March 2007 13:56, bahoo wrote: > I have ssh access to two linux machines (both WITHOUT root account), > and I'd like to copy data from one to another. > Since the directory structure is different, I want to specify in a > script (ideally in python, because that's what I want to learn) what > to copy over like this: > > source: /home/john/folderA > destination: /home/smith/folderB > > I'm a newbie on linux and ssh networking and python, so your > suggestions are welcome! A small working example would be appreciated! Try rsync, if you need a second run, it will only copy what has been modified in the source. rsync -var -e ssh /home/john/folderA name at computerB:/home/smith/folderB Should be enough. Remove 'v' for less verbose operation. -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From http Sun Mar 11 17:22:56 2007 From: http (Paul Rubin) Date: 11 Mar 2007 13:22:56 -0800 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> <1173635074.726444.88760@t69g2000cwt.googlegroups.com> <1hut4yc.o9f1kta318hnN%aleax@mac.com> <1hut7xu.5zs31l1cohfybN%aleax@mac.com> Message-ID: <7x3b4bv5jj.fsf@ruckus.brouhaha.com> Tim Peters writes: > 2.5 introduced a new front end and more ambitious constant-folding, and > I expect the bug showed up again due to one of those. I hope it does get fixed. Not having referential transparency in a basic math function like atan2 is pretty disturbing in a modern computer language. From http Tue Mar 6 03:57:43 2007 From: http (Paul Rubin) Date: 06 Mar 2007 00:57:43 -0800 Subject: image processing References: <1173171010.239215.130580@n33g2000cwc.googlegroups.com> Message-ID: <7xirdekauw.fsf@ruckus.brouhaha.com> "edurand" writes: > You can use it in Python, and we have provided tutorials and samples > in Python, with for exemple conversion from/to PIL image format. > Have a look at : http://filters.sourceforge.net/ Looks interesting, however the example screen shot is shrunk down so the text on it can't be read. Also there are a bunch of sample filters with example images, but no explanation at all of what the filters do. Finally, it keeps mentioning things like "dll" which suggests this is a Windows library. Is it? Maybe it can be ported to other OS's or maybe it's already multi-platform, but the web site should make the situation clear either way. From mikael at isy.liu.se Tue Mar 13 12:59:39 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 13 Mar 2007 17:59:39 +0100 Subject: Communicating with a DLL under Linux Message-ID: <45F6D87B.4070407@isy.liu.se> I am interested in peoples experience with communicating with DLLs under Linux. Situation: I'm an electrical engineer that finds pleasure in using my soldering iron from time to time. I also find programming, preferably in Python, entertaining. I wouldn't call myself a programmer, though. Now, I may have found a hobby project that could give me the pleasure from both those worlds. There's this USB development gadget for sale in my favourite electronics store, and I sure would like to have something like that connected to my lab computer (a fairly new budget computer running Kubuntu 6.06). The gadget costs about 50 Euros. It's not a lot of money, but I would not like to buy the thing if there is a substancial risk that I will not be able to make it work on that computer. From what I've read on the box, it assumes Windows (a number of versions), it includes a DLL to communicate with it, and example code in VB (iirc). For the interested, here's the gadget: http://www.elfa.se/elfa-bin/dyndok.pl?lang=en&vat=0&dok=9001.htm I have been looking at ctypes, and from what I read, I should be able to communicate with a DLL by using ctypes. It even sounds fairly easy, as long as I know what the DLL is supposed to do. I expect there to be some kind of manual for the DLL included in the box. Are DLLs universal, or are there different DLLs for Windows and Linux (I'm not a programmer, remember)? If the vendor claims that the DLL is for Windows, is it reasonable to assume that it can be made to work under Linux, from Python, that is? Or is this perhaps completely out of the question? So, who is willing share their experiences? Share advice? Is this as easy as it sounds to me? Any pitfalls around? Regards /MiO From eurleif at ecritters.biz Sat Mar 10 09:36:33 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 10 Mar 2007 09:36:33 -0500 Subject: UTF-8 In-Reply-To: <45f2bf21$0$5094$ba4acef3@news.orange.fr> References: <45f2bf21$0$5094$ba4acef3@news.orange.fr> Message-ID: <45f2c24c$0$8981$4d3efbfe@news.sover.net> Laurent Pointal wrote: > You should prefer to put > # -*- coding: utf-8 -*- > at the begining of your sources files. With that you are ok with all Python > installations, whatever be the defautl encoding. > Hope this will become mandatory in a future Python version. The default encoding specifies how Unicode strings are implicitly converted into byte strings. The code you gave specifies how Unicode string literals in a file are encoded, which is something completely different. From kyosohma at gmail.com Mon Mar 19 13:35:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Mar 2007 10:35:26 -0700 Subject: check if files are the same on Windows In-Reply-To: References: <1174320587.618875.48290@y66g2000hsf.googlegroups.com> Message-ID: <1174325726.088461.10560@e65g2000hsc.googlegroups.com> On Mar 19, 11:55 am, Shane Geiger wrote: > In the unix world, 'fc' would be like diff. > > """ > Python example of checksumming files with the MD5 module. > > In Python 2.5, the hashlib module would be preferable/more elegant. > """ > > import md5 > > import string, os > r = lambda f: open(f, "r").read() > def readfile(f,strip=False): return (strip and stripper(r(f))) or r(f) > def writefile(f, data, perms=750): open(f, "w").write(data) and > os.chmod(f, perms) > > def get_md5(fname): > hash = md5.new() > contents = readfile(fname) > hash.update(contents) > value = hash.digest() > return (fname, hash.hexdigest()) > > import glob > > for f in glob.glob('*'): > print get_md5(f) > > > A crude way to check if two files are the same on Windows is to look > > at the output of the "fc" function of cmd.exe, for example > > > def files_same(f1,f2): > > cmnd = "fc " + f1 + " " + f2 > > return ("no differences" in popen(cmnd).read()) > > > This is needlessly slow, because one can stop comparing two files > > after the first difference is detected. How should one check that > > files are the same in Python? The files are plain text. > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgei... at ncee.net | 402-438-8958 | http://www.ncee.net > > Leading the Campaign for Economic and Financial Literacy > > sgeiger.vcf > 1KDownload You can also use Python's file "read" method to read a block of each file in a loop in binary mode. Something like: file1 = open(path1, 'rb') file2 = open(path2, 'rb') bytes1 = file1.read(blocksize) bytes2 = file2.read(blocksize) And then just compare bytes to see if there is a difference. If so, break out of the loop. I saw this concept in the book: Python Programming, 3rd Ed. by Lutz. Have fun! Mike From n00m at narod.ru Fri Mar 16 02:28:04 2007 From: n00m at narod.ru (n00m) Date: 15 Mar 2007 23:28:04 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174024633.431427.236920@y66g2000hsf.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <1174024633.431427.236920@y66g2000hsf.googlegroups.com> Message-ID: <1174026484.499259.300720@o5g2000hsb.googlegroups.com> Steve, imo strangely enough but your suggestion to replace "if...: else:..." with x_y = x + y h[x_y] = h.get(x_y, 1) s=l=o=w=e=d the thing by ~1 sec. From Marko.Cain.23 at gmail.com Wed Mar 28 18:09:08 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 28 Mar 2007 15:09:08 -0700 Subject: How can I find out the size of a file Message-ID: <1175119748.481117.107910@y80g2000hsf.googlegroups.com> Hi, How can I find out the size of a file in a disk in python? i try this, but it does not work: size = open(inputFileNameDir + "/" + file, 'r').size() Thank for any help. From sickcodemonkey at gmail.com Thu Mar 8 16:31:59 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 8 Mar 2007 16:31:59 -0500 Subject: What is the best way to upgrade python? In-Reply-To: <1173388393.052558.69270@s48g2000cws.googlegroups.com> References: <1173388393.052558.69270@s48g2000cws.googlegroups.com> Message-ID: <2adc542f0703081331m478b388qe32150541e6b7243@mail.gmail.com> Have you tried to upgrade the current python RPM? rpm -Uvh .... You can also build from source. Once you get Python 2.4 up and running I am pretty sure you can do a symbolic link on the python 2.3 application (either in /usr/bin or /usr/sbin) and point it to the 2.4 python file. On 8 Mar 2007 13:13:13 -0800, yinglcs at gmail.com wrote: > > Hi, > > i am using red hat enterprise 4. It has python 2.3 installed. What is > the best way to upgrade to python 2.4? > > I think one way is to compile python 2.4 from the source, but I can't > remove the old one since when i do 'rpm -e python', i get error like > 'failed dependencies'. > > Thank you for any idea. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sat Mar 24 16:45:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 24 Mar 2007 20:45:13 GMT Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174763412.409665.19870@l75g2000hse.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <1174763412.409665.19870@l75g2000hse.googlegroups.com> Message-ID: 7stud wrote: > On Mar 24, 12:09 pm, "Greg Donald" wrote: >> On 24 Mar 2007 10:30:28 -0700, Robert Hicks wrote: >> >>> I want to upgrade to 2.5 but I don't see any unistall instructions >>> anywhere. >> You're not required to remove the old version before installing the new version. >> >> Just install the new version somewhere like /usr/local and put >> /usr/local/bin ahead of your other paths. >> >> -- >> Greg Donaldhttp://destiney.com/ > > Can you explain how that works? If you install python in /usr/local, > doesn't that leave you with something like /usr/local/python? So what > does putting usr/local/bin ahead of your other paths do? > Don't build python for OS X unless you know you need to or want a learning experience. Rolling your own python is somewhat a can of worms for the uninitiated and it will be pretty tough beyond that to make it run as cleanly as the stock builds. (E.g. you will be asking about why readline doesn't work, etc.) This stuff is especially the case for OS X, which does things a little differently than linux. Just download the 2.5 installer from python.org. Double click it and be done. A link to the new python will be created for you in /usr/local/bin. If you already had an earlier installed and the link didn't get updated, just replace the old one substituting 2.4 (or 2.3) with 2.5. Then make sure /usr/local/bin comes before /usr/bin in your path and you will be set. See also my previous post about integrating ipython. James From russell.sayers at gmail.com Tue Mar 20 21:45:16 2007 From: russell.sayers at gmail.com (russ) Date: 20 Mar 2007 18:45:16 -0700 Subject: generating stats from stdout on a regular interval Message-ID: <1174441516.876016.19360@y66g2000hsf.googlegroups.com> Hi all, Very new to Python - but excited to see what is possible - it sounds very suitable for a project of mine I need a little help with. I've got an executable which writes out data to stdout in a CSV sort of format - I'd like to grab the data from stdout and create stats from it at a regular interval, i.e. every 10 min. Probably push the stats out to a CSV file. The popen2 module can read the stdout just like a file, and the csv module can handle the reading / writing. How do I go about 'processing' the stdout every 10 min? Thanks, Russ From nogradi at gmail.com Mon Mar 19 05:02:59 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 19 Mar 2007 10:02:59 +0100 Subject: Documentation for "str()" could use some adjustment. In-Reply-To: References: Message-ID: <5f56302b0703190202m53793e3dpfd77d2f84134030d@mail.gmail.com> > The Python documentation for "str" says > "str([object]) : > Return a string containing a nicely printable representation of an > object." > > However, there's no mention of the fact that "str" of a Unicode string > with non-ASCII characters will raise a conversion exception. The > documentation (and several Python books) seem to indicate that "str" will > produce some "printable representation" for anything, not raise an > exception. > > I know, it was proposed in PEP 349 to change "str" to return Unicode > strings, and that's coming someday, along with all-Unicode Python, > but meanwhile, the documentation should be clear about this. Hi John, I'm not at all an expert around here but my understanding of the workflow is that bug reports should be submitted to the tracker at sourceforge. There is no guarantee that they will be noticed there but the chances there are much higher than for a message on the mailing list. I just mention this because I've seen your mysqld, urllib and other potentially important bug reports here with no action taken but maybe submitting them to sourceforge would attract some developers. From george.sakkis at gmail.com Sat Mar 17 23:20:25 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 17 Mar 2007 20:20:25 -0700 Subject: Automagically log changes in table In-Reply-To: <1174175976.156270.65830@e1g2000hsg.googlegroups.com> References: <1174164187.257094.236020@l75g2000hse.googlegroups.com> <1174175976.156270.65830@e1g2000hsg.googlegroups.com> Message-ID: <1174188025.545923.272900@l77g2000hsb.googlegroups.com> On Mar 17, 7:59 pm, "aspineux" wrote: > Hi > > You can get this using "triggers" and "stored procedures". > These are SQL engine dependent! This is available for long time with > postgress and only from version 5 with mysql. > This let you write SQL code (Procedure) that will be called when > "trigged" by an event like inserting new row, updating rows, > deleting .... I'd rather avoid triggers since I may have to deal with Mysql 4. Apart from that, how can a trigger know the current user ? This information is part of the context (e.g. an http request), not stored persistently somewhere. It should be doable at the framework/orm level but I'm rather green on Turbogears/SQLAlchemy. George From gagsl-py2 at yahoo.com.ar Sat Mar 17 05:59:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Mar 2007 06:59:55 -0300 Subject: import error References: Message-ID: En Fri, 16 Mar 2007 23:49:43 -0300, Nick Burns escribi?: > Quick question. I am running python on windows xp. i want to import my > own > module "mymod". However, when I try to import it i get the error message > "ImportError: > no module named mymod". > > "mymod" is located in a directory that is part of the computer's "path" > env > variable. Imports fine if 'mymod' is in the current working directory, > but not > otherwise. i had thought that by saving 'mymod'within my normal path > that it > would import successfully, but this is not the case. Python does not use the system PATH environment variable. Doing this: import sys print sys.path you will see the list of directories that Python would try. Try saving your module inside site-packages. -- Gabriel Genellina From justin.mailinglists at gmail.com Wed Mar 28 03:27:54 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 28 Mar 2007 00:27:54 -0700 Subject: wxPython, Syntax highlighting In-Reply-To: <1175064996.150578.300170@l77g2000hsb.googlegroups.com> References: <1175064996.150578.300170@l77g2000hsb.googlegroups.com> Message-ID: <1175066874.691110.141220@n76g2000hsh.googlegroups.com> On Mar 28, 2:56 pm, "Eric von Horst" wrote: > I am looking for wx widget that has the ability to show text, edit the > text (like a TextCtrl) but also does syntax highlighting (if the text > is e.g. XML or HTML). > I have been looking in the latest wxPython version but I could not > really find anything. see .\wxPython2.6 Docs and Demos\samples\ide\ActiveGridIDE.py From lbates at websafe.com Wed Mar 14 15:27:10 2007 From: lbates at websafe.com (Larry Bates) Date: Wed, 14 Mar 2007 14:27:10 -0500 Subject: os.path.basename() - only Windows OR *nix? In-Reply-To: References: <45F843AD.6050509@gmx.net> Message-ID: <45F84C8E.3020106@websafe.com> Thomas Ploch wrote: > Steve Holden schrieb: >> Clearly if form['uploadfile'] is returning the client's path information >> you do have to remove that somehow before further processing, which also >> means you need to deduce what the client architecture is to correctly >> remove path data. Of course this also leaves open the question "what >> does a Mac client return?", and you might want to cater for that also. > > I tested from linux and Mac OS, and on both os.path.basename() works as > expected (since the server it runs on is a UNIX one). That brings me to > the question, how Do I a) get the cients architecture and b) send the > architecture of the client through cgi.FieldStorage()? > >> I suspect you will also find that there are at least some circumstances >> under which a Unix browser will also include path information. > > Which ones should that be? Since os.path.basename() _is_ doing the right > thing on *nix style paths (Mac OS is not different there), I cant think > of other circumstances. > > >> I presume you are looking to use the same filename that the user >> provided on the client? Does this mean that each user's files are >> stored in different directories? Otherwise it's not always a good idea >> to use filenames provided by the user for files on the server anyway. > > Yes, each User has his own directory. Files get timestamped and then put > into the corresponding directory. It is just that having > 'C:\a\very\long\path\file.ext' as a filename on the server is not nice. > > Thomas > You will need to write some Javascript and assign something to a hidden field that gets posted. Here is some Javascript to get you started: http://www.javascripter.net/faq/operatin.htm -Larry From miki.tebeka at gmail.com Wed Mar 7 14:26:27 2007 From: miki.tebeka at gmail.com (Miki) Date: 7 Mar 2007 11:26:27 -0800 Subject: catching exceptions from an except: block In-Reply-To: <1173292373.770519.158490@8g2000cwh.googlegroups.com> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> Message-ID: <1173295587.143018.102220@p10g2000cwp.googlegroups.com> Hello Arnaud, > Imagine I have three functions a(x), b(x), c(x) that each return > something or raise an exception. Imagine I want to define a function > that returns a(x) if possible, otherwise b(x), otherwise c(x), > otherwise raise CantDoIt. Exceptions are for error handling, not flow control. > Here are three ways I can think of doing it: > ... > # This one only works because a,b,c are functions > # Moreover it seems like an abuse of a loop construct to me > def rolled_first(x): > for f in a, b, c: > try: > return f(x) > except: > continue > raise CantDoIt My vote is for that one. > I don't feel happy with any of these. Is there a more satisfying way > of doing this in Python? What I would like is something like: > > ---------- > # This one isn't correct but looks the clearest to me > def wished_first(x): > try: > return a(x) > except: > return b(x) > except: > return c(x) > except: > raise CantDoIt Again, exception are for error handling, not for flow control. As a side note, try to avoid "catch:", always catch explicit exceptions. HTH, Miki http://pythonwise.blogspot.com From barnaclejive at gmail.com Sat Mar 24 15:05:32 2007 From: barnaclejive at gmail.com (mkppk) Date: 24 Mar 2007 12:05:32 -0700 Subject: Anyone know of a MICR parser algorithm written in Python? Message-ID: <1174763132.786644.161500@y66g2000hsf.googlegroups.com> MICR = The line of digits printed using magnetic ink at the bottom of a check. Does anyone know of a Python function that has been written to parse a line of MICR data? Or, some financial package that may contain such a thing? Or, in general, where I should be looking when looking for a piece of Python code that may have already been written by someone? I'm working on a project that involves a check scanner the produces the raw MICR line as text. Now, that raw MICR needs to be parsed for the various pieces of info. The problem with MICR is that there is no standard layout. There are some general rules for item placement, but beyond that it is up to the individual banks to define how they choose to position the information. I did find an old C program written by someone at IBM... But I've read it and it is Not code that would nicely convert to Python (maybe its all the Python I'm used to, be it seems very poorly written). Here is the link to that C code: ftp://ftp.software.ibm.com/software/retail/poseng/4610/4610micr.zip I've even tried using boost to generate a Python module, but that didn't go well, and in the end is not going to be a solution for me anyway.. really need access to the Python source. Any help at all would be appreciated, -mkp From yb at icmail.net Fri Mar 16 07:04:25 2007 From: yb at icmail.net (Yury) Date: 16 Mar 2007 04:04:25 -0700 Subject: Writing python module in C: wchar_t or Py_UNICODE? Message-ID: <1174043065.189483.123640@b75g2000hsg.googlegroups.com> I am new to python and programming generally, but someday it is time to start :) I am writing a python module in C and have a question about multibyte character strings in python<=>C. I want a C function which takes a string as argument from python script: static PyObject * connect_to_server(PyObject *self, PyObject * authinfo){ wchar_t * login; /* Must support unicode */ char * serveraddr; int * port; if(!PyArgsParseTuple(authinfo, "sdu", &serveraddr, &port, &login)) return NULL; ... Will that code work? Or i should use Py_UNICODE * data type? Will it be compatible with standard C string comparison/concantenation functions? From mail at timgolden.me.uk Mon Mar 26 04:41:33 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Mar 2007 09:41:33 +0100 Subject: Create new processes over telnet in XP In-Reply-To: References: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> <46043ad8$0$27402$ba4acef3@news.orange.fr> Message-ID: <4607873D.5050107@timgolden.me.uk> Laurent Pointal wrote: > Shane Geiger a ?crit : >> This reminds me of something I once wanted to do: How can I install >> Python in a totally non-gui way on Windows (without the use of VNC)? I >> think I was telnetted into a computer (or something like that) and I was >> unable to run the usual Python installer because it uses a GUI. While I don't remember if I've actually tried it you should be able to do this with WMI. Example here... http://timgolden.me.uk/python/wmi_cookbook.html#install-a-product If I have time to do it (and then undo whatever damage it does ;) I'll give it a go later. TJG From daftspaniel at gmail.com Tue Mar 13 17:44:26 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 13 Mar 2007 14:44:26 -0700 Subject: using python to visit web sites and print the web sites image to files In-Reply-To: <1173747288.760536.60020@j27g2000cwj.googlegroups.com> References: <1173684778.539755.236130@t69g2000cwt.googlegroups.com> <1173728423.775330.164470@t69g2000cwt.googlegroups.com> <1173731204.621260.192000@30g2000cwc.googlegroups.com> <1173747288.760536.60020@j27g2000cwj.googlegroups.com> Message-ID: <1173822266.306935.199410@o5g2000hsb.googlegroups.com> > The reason I want to do simulation but not just crawling is : we have > to check many web pages' front page to see whether it conform to our > visual standard, e.g, it should put a search box on the top part of > the page. It's tedious for human work. So I want to 'crawl and save > the visual presentation of the web site automatically', and check > these image files later with human eyes. > > -Xiong Hi Xiong, I have been working on a program to do something very similar to generate thumbnails of websites. The code is in IronPython (which may put you off!) and would need modified or scripted with pywinauto to deal with multiple images. Let me know if it is of use to you and I will upload it. Cheers, Davy From hg at nospam.org Fri Mar 9 03:28:54 2007 From: hg at nospam.org (hg) Date: Fri, 09 Mar 2007 09:28:54 +0100 Subject: C++ and Python References: <1173420288.646573.327340@h3g2000cwc.googlegroups.com> Message-ID: Mandus wrote: > 8 Mar 2007 22:04:48 -0800 skrev bressert at gmail.com: >> Hi Everyone, >> >> I'm considering about generating some Python Bindings for C++ >> libraries. What are considered the best tools for doing something like >> this? I know that there are SWIG, SIP, Boost.Python, and GCC_XML. > > We are doing this quite extensively at work, and have found that in the > long run SWIG is the best solution. OMMV, but if you ask me, the answer > is SWIG. > > mvh, > -- > Mandus - the only mandus around. Hi, Why do you think it is better than ctypes ? Thanks, hg From gabriel.hase at gmail.com Fri Mar 23 07:18:59 2007 From: gabriel.hase at gmail.com (killkolor) Date: 23 Mar 2007 04:18:59 -0700 Subject: "finally" for unit test Message-ID: <1174648739.464811.7150@y80g2000hsf.googlegroups.com> hi! I have a unittest framework that tests a single function that in turn works with files (takes input and outputs in the same file, no return values). In the unittest class I assign a member with all the names of my testfiles and a testdirectory. The tests call the function (which opens and writes to the file) and then opens the file to see if everything is in order. The problem now is that after each testrun I have to copy "fresh" files into the testdirectory, since of course the function already run on all the files and made the changes. So I implemented a buffering in the unittest functions: buffer the file, call the function, make the test, write the buffered file back. This works fine for unittests that do not fail. If a unittest fails though the function stops and the writing back is never done. Is there something like a finally for unittest functions? Or could I use another approach to buffer and write back my files (for each unittest function)? thanks! gabriel From skip at pobox.com Tue Mar 27 18:39:40 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 27 Mar 2007 17:39:40 -0500 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: References: Message-ID: <17929.40236.560753.595621@montanaro.dyndns.org> Carl> Welcome to the PyPy 1.0 release... ... Carl> - A **Just-In-Time Compiler generator** able to **automatically** Carl> enhance the low level versions of our Python interpreter, Carl> leading to run-time machine code that runs algorithmic examples Carl> at speeds typical of JITs! Woo hoo! Congratulations to all the PyPynistas! Skip From openopt at ukr.net Mon Mar 19 16:17:09 2007 From: openopt at ukr.net (dmitrey) Date: 19 Mar 2007 13:17:09 -0700 Subject: looking for a fastest parallel approach for quick executing of lots small routines In-Reply-To: <1174335235.682491.300930@l75g2000hse.googlegroups.com> References: <1174335235.682491.300930@l75g2000hse.googlegroups.com> Message-ID: <1174335429.329776.153260@e1g2000hsg.googlegroups.com> I forgot to add: first of all I need sinchronious parallel calculations, not asinchronious D. From steven.bethard at gmail.com Sat Mar 31 11:40:02 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 31 Mar 2007 09:40:02 -0600 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: References: <1175346825.986685.42430@b75g2000hsg.googlegroups.com> Message-ID: <2sydnas0Uf5SHZPbnZ2dnUVZ_tPinZ2d@comcast.com> Rehceb Rotkiv wrote: >> If you want a good answer you have to give me/us more details, and an >> example too. > > OK, here is some example data: > > reaction is BUT by the > sodium , BUT it is > sea , BUT it is > this manner BUT the dissolved > pattern , BUT it is > rapid , BUT it is > > As each line consists of 5 words, I would break up the data into an array > of five-field-arrays (Would you use lists or tuples or a combination in > Python?). The word "BUT" would be in the middle, with two fields/words > left and two fields/words right of it. I then want to sort this list by > > - field 3 > - field 4 > - field 1 > - field 0 You're probably looking for the key= argument to list.sort(). If your function simply returns the fields in the order above, I believe you get the right thing:: >>> s = '''\ ... reaction is BUT by the ... sodium , BUT it is ... sea , BUT it is ... this manner BUT the dissolved ... pattern , BUT it is ... rapid , BUT it is ... ''' >>> word_lists = [line.split() for line in s.splitlines()] >>> def key(word_list): ... return word_list[3], word_list[4], word_list[1], word_list[0] ... >>> word_lists.sort(key=key) >>> word_lists [['reaction', 'is', 'BUT', 'by', 'the'], ['pattern', ',', 'BUT', 'it', 'is'], ['rapid', ',', 'BUT', 'it', 'is'], ['sea', ',', 'BUT', 'it', 'is'], ['sodium', ',', 'BUT', 'it', 'is'], ['this', 'manner', 'BUT', 'the', 'dissolved']] STeVe From steve at REMOVE.THIS.cybersource.com.au Sat Mar 24 23:40:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 25 Mar 2007 13:40:33 +1000 Subject: Idiom for running compiled python scripts? References: <1174746081.436526.64360@l75g2000hse.googlegroups.com> Message-ID: On Sat, 24 Mar 2007 22:59:06 +0000, Mark wrote: >> I timed it against running plain .py and running .pyc directly. It >> seemed to be roughly on par with running .pyc directly, and about 18ms >> faster than running .py. The file had 600 lines (21kb) of code. > > So see my point at least? I'm still not sure why this approach is > ill-favoured? Because this is entirely a trivial saving. Who cares? Sheesh. That's less than the natural variation in execution speed caused by (e.g.) network events on your PC. I've just run the same do-nothing script (a simple "pass") three times, and got times of 338ms, 67ms and 74ms. That's a variation of 271 milliseconds between runs of the same script, and you care about 18ms??? Saving 18ms on a script that takes 50ms to execute *might* be worthwhile, if you're using that script in an automated system that executes it thousands of times. If you're calling it by hand, come on now, you're not even going to notice the difference! 50ms is close enough to instantaneous that 32ms is not detectably faster to the human eye. If you save 18ms one thousand times a day, you save a grand total of ... eighteen seconds. Wow. Now you can spend more time with your family. As of 2005, the world's fastest typist Barbara Blackburn has been clocked at a peak of 212 words per minute for short bursts. Assuming an average of five key strokes per word (including the space) that's about 18 key presses per second, or 55 milliseconds per key press. A more realistic figure for the average professional typist is about six key presses per second, or 160 milliseconds per key press, and that's for pure transposition (copying). If you've got to think carefully about what you're typing, like sys admins do, the average time per key press is significantly larger. In other words, unless you can save AT LEAST 160 milliseconds, it isn't worth typing even one more character. If you have to type one extra character to save 18ms, you're actually 140ms worse off. I can't believe the number of people who are spending this amount of time worrying about such a trivial saving, and I can't believe that I've let myself be suckered into this discussion. Don't you people have lives??? -- Steven who has no life, which is why he is spending time complaining about people who have no lives. From tjreedy at udel.edu Mon Mar 19 16:31:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Mar 2007 16:31:54 -0400 Subject: Anything available that can read Microsoft .MDB files from Python? References: <56863eF27p5bmU1@mid.uni-berlin.de> <1174334517.125928.274140@l75g2000hse.googlegroups.com> Message-ID: wrote in message news:1174334517.125928.274140 at l75g2000hse.googlegroups.com... | I've read .MDB files using ODBC. I don't know how big your files are, | but I had a file with almost 3000 rows and I was able to fetch it in | 1-2 seconds. If you want to give it whirl, you just need to create an | ODBC connection and then do the following: I'll just mention that OpenOffice.org Base can make ODBC connections and output in several formats. Don't know if their ODBC works with .MDB. tjr From jm.suresh at gmail.com Thu Mar 8 09:31:45 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 8 Mar 2007 06:31:45 -0800 Subject: heapq.heappush and pop to use key Message-ID: <1173364305.281085.271320@t69g2000cwt.googlegroups.com> I wanted to have a heap of custom objects, and in different heaps I wanted to have the weights for my elements differently. So, I modified the heapq module to accept key arguments also. The untested code is here. Please let me know if you find any bug or if there is an easy way to do this. - Suresh --------------------------------------------------------------------------------------------------------------------------------------------- __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest', 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee from operator import itemgetter import bisect pass_it = lambda x: x def heappush(heap, item, key=pass_it): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1, key=key) def heappop(heap, key=pass_it): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0, key) else: returnitem = lastelt return returnitem def heapreplace(heap, item, key=pass_it): """Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement: if item > heap[0]: item = heapreplace(heap, item) """ returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup(heap, 0, key) return returnitem def heapify(x, key=pass_it): """Transform list into a heap, in-place, in O(len(heap)) time.""" n = len(x) # Transform bottom-up. The largest index there's any point to looking at # is the largest with a child index in-range, so must have 2*i + 1 < n, # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1. for i in reversed(xrange(n//2)): _siftup(x, i, key) # 'heap' is a heap at all indices >= startpos, except possibly for pos. pos # is the index of a leaf with a possibly out-of-order value. Restore the # heap invariant. def _siftdown(heap, startpos, pos, key): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if key(parent) <= key(newitem): break heap[pos] = parent pos = parentpos heap[pos] = newitem def _siftup(heap, pos, key): endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the smaller child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and key(heap[rightpos]) <= key(heap[childpos]): # **CHANGED** childpos = rightpos # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem _siftdown(heap, startpos, pos, key) From slawomir.nowaczyk.847 at student.lu.se Wed Mar 14 08:07:57 2007 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Wed, 14 Mar 2007 13:07:57 +0100 Subject: execfile locks file forever if there are any syntax errors - is it python bug? Message-ID: <20070314130014.A4F9.SLAWOMIR.NOWACZYK.847@student.lu.se> Hello, When I execfile a file which contains a syntax error, the file becomes locked and stays this way all the way until I exit the interpreter (I am unable to delete it, for example). I have tried but failed to find any way to unlock the file... Is this a bug in Python? Is there *any* way to unlock the file? It is annoying for me because I often execfile various temporary files and it is a nuisance not to be able to delete them. I have tested with Python 2.5 on Windows... do other versions of Python behave this way as well? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) I didn't fight my way to the top of the food chain to be a vegetarian. From deets at nospam.web.de Sun Mar 18 07:45:30 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Mar 2007 12:45:30 +0100 Subject: Automagically log changes in table In-Reply-To: <1174164187.257094.236020@l75g2000hse.googlegroups.com> References: <1174164187.257094.236020@l75g2000hse.googlegroups.com> Message-ID: <564n2rF27ev4rU1@mid.uni-berlin.de> George Sakkis schrieb: > This is more in the context of Turbogears/SQLAlchemy, but if anyone > has implemented something similar with other packages it might be > useful to know. SQLObject since version 0.8 lets you define event listeners for create/update/delete events on objects. You could hook into them. Diez From cfbolz at gmx.de Thu Mar 29 13:10:31 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Thu, 29 Mar 2007 19:10:31 +0200 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: References: Message-ID: <460BF307.7010104@gmx.de> Duncan Booth wrote: > Robin Becker wrote: > >> I am hugely encouraged by this >> >> C:\Python\devel\pypy-1.0.0>\python24\python \python\lib\test > \pystone.py >> Pystone(1.1) time for 50000 passes = 1.49586 >> This machine benchmarks at 33425.6 pystones/second >> >> C:\Python\devel\pypy-1.0.0>.\pypy-c.exe \python\lib\test\pystone.py >> Pystone(1.1) time for 50000 passes = 2.16123e-005 >> This machine benchmarks at 2.3135e+009 pystones/second >> >> >> :) not > > It looks like time.clock() is completely borked. time.clock was indeed borked under windows (of by a factor of 1000). fixed in svn now. Cheers, Carl Friedrich From rustybear at gmail.com Sat Mar 31 17:25:12 2007 From: rustybear at gmail.com (rustybear at gmail.com) Date: 31 Mar 2007 14:25:12 -0700 Subject: help with dates Message-ID: <1175376312.927559.10380@n76g2000hsh.googlegroups.com> [sorry about the earlier post. accidently hit enter] I'm working on a website for some firefighters that want to be able to sign-up for overtime and I need some help figuring out a date related problem. Here's the scenario: Four groups of firefighters (group1, group2, group3, group4). Each group works a 24 hr shift. So group1 works April 1, group2 works April 2, group3 works April 3, group4 works April 4, group 1 works April 5, etc. It just keeps rolling like this forever into next year, etc. I need to come up with a methodology for the following: If given a date, find out what group is working on that date. Has anyone dealt with a problem like this before? Obviously I'll need to have a starting date where group1 is associated with a starting date. Fortunately there are no surprises. Groups work in order (1,2,3,4,1,2,3,4,1,2,...) and dates go in order and there are absolutely no special exceptions for holidays and anything else. Thanks in advance for any clues. Kevin From NikitaTheSpider at gmail.com Sun Mar 4 14:21:43 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sun, 04 Mar 2007 14:21:43 -0500 Subject: How use XML parsing tools on this one specific URL? References: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> Message-ID: In article <1173030156.276363.174250 at i80g2000cwc.googlegroups.com>, "seberino at spawar.navy.mil" wrote: > I understand that the web is full of ill-formed XHTML web pages but > this is Microsoft: > > http://moneycentral.msn.com/companyreport?Symbol=BBBY > > I can't validate it and xml.minidom.dom.parseString won't work on it. > > If this was just some teenager's web site I'd move on. Is there any > hope avoiding regular expression hacks to extract the data from this > page? Valid XHTML is scarcer than hen's teeth. Luckily, someone else has already written the ugly regex parsing hacks for you. Try Connelly Barnes' HTMLData: http://oregonstate.edu/~barnesc/htmldata/ Or BeautifulSoup as others have suggested. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From psdasilvaX at esotericaX.ptX Sat Mar 24 10:02:58 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Sat, 24 Mar 2007 14:02:58 +0000 Subject: Join strings - very simple Q. In-Reply-To: References: <1174675011.244339@jubilee.claranet.pt> <1174680929.492601.140270@o5g2000hsb.googlegroups.com> Message-ID: <1174746809.657937@jubilee.claranet.pt> Steven D'Aprano escreveu: > On Fri, 23 Mar 2007 13:15:29 -0700, John Machin wrote: > .... > > Western civilization is 6,000 years old. After reading that post I wouldn't talk about civilization, western or any other :-) Regards. Paulo From gagsl-py2 at yahoo.com.ar Fri Mar 23 01:09:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 02:09:31 -0300 Subject: Still the __new__ hell ... References: <1174167360.522350@jubilee.claranet.pt> <45fe7f46$0$2138$426a74cc@news.free.fr> <1174337519.926611@jubilee.claranet.pt> <46010e1a$0$2347$426a74cc@news.free.fr> Message-ID: En Wed, 21 Mar 2007 07:51:32 -0300, Bruno Desthuilliers escribi?: > Paulo da Silva a ?crit : >> As a relatively inexperient >> in python, how could I know that a 'string' is an instance of >> basestring? > > By reading this newsgroup ?-) Or asking Python itself: >>> type("any string").mro() [, , ] -- Gabriel Genellina From adam at atlas.st Mon Mar 26 21:02:39 2007 From: adam at atlas.st (Adam Atlas) Date: 26 Mar 2007 18:02:39 -0700 Subject: Python C extension providing... Python's own API? In-Reply-To: <1174942538.061137.93130@r56g2000hsd.googlegroups.com> References: <1174936892.381509.178770@p15g2000hsd.googlegroups.com> <1174942538.061137.93130@r56g2000hsd.googlegroups.com> Message-ID: <1174957359.286188.178330@y66g2000hsf.googlegroups.com> On Mar 26, 4:55 pm, "Matimus" wrote: > I think that is what the "code" module is for. Maybe not exactly what > you were expecting, but the capability you describe is already there. > Being able to access its own interpreter is one of the things that > makes Python a dynamic language. That's not really what I'm after. Believe me, I've searched the standard library in length and breadth. :) The `code` module runs in the same interpreter, basically executing as though it were just a separate module (except interactively). What I'm interested in is accessing Python's C API for CREATING interpreters -- i.e. what mod_python or anything else embedding the Python interpreter would do. Creating a whole environment, not just a module; it has its own `sys` parameters, its own `__builtin__`, and so on, so you can safely mess with those without changing them in the parent interpreter. So far, I've tried ctypes, and it doesn't work; then I noticed the docs said it wouldn't anyway. But I think I'll try writing a C extension module. This could be interesting for sandboxing &c. From rampeters at gmail.com Thu Mar 15 20:09:55 2007 From: rampeters at gmail.com (johnny) Date: 15 Mar 2007 17:09:55 -0700 Subject: newb: Python Floating Point Message-ID: <1174003795.849903.273220@l75g2000hse.googlegroups.com> When I do the following, rounding to 2 decimal places doesn't seem to work. I should get 0.99 : >>> a =0.99 >>> a 0.98999999999999999 >>> round(a,2) 0.98999999999999999 >>> thank you. From parsons.nicholas1 at gmail.com Sat Mar 3 15:36:08 2007 From: parsons.nicholas1 at gmail.com (Nicholas Parsons) Date: Sat, 3 Mar 2007 15:36:08 -0500 Subject: pop method question Message-ID: Howdy Folks, I was just playing around in IDLE at the interactive prompt and typed in dir({}) for the fun of it. I was quite surprised to see a pop method defined there. I mean is that a misnomer or what? From the literature, pop is supposed to be an operation defined for a stack data structure. A stack is defined to be an "ordered" list data structure. Dictionaries in Python have no order but are sequences. Now, does anyone know why the python core has this pop method implemented for a dictionary type? I realize that in this context it is used for removing a specific key from the current dictionary object. But why call it pop and not something more intuitive like remove or delete? Thanks for the clarification in advance :). --Nick From http Thu Mar 8 01:57:20 2007 From: http (Paul Rubin) Date: 07 Mar 2007 22:57:20 -0800 Subject: merits of Lisp vs Python References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> Message-ID: <7xabyo5ijz.fsf@ruckus.brouhaha.com> Brian Adkins writes: > This may sound like I'm baiting you, but it's a sincere question. If > your experience with Perl was so good, why did you decide to pursue > Python? Trouble free hosting and no problems in development - sounds > like it worked out well for you. Er, because the Perl language itself is up there with Vogon poetry in bletcherousness? From orsenthil at gmail.com Wed Mar 14 12:12:56 2007 From: orsenthil at gmail.com (Phoe6) Date: 14 Mar 2007 09:12:56 -0700 Subject: print and softspace in python Message-ID: <1173888776.475236.81720@d57g2000hsg.googlegroups.com> print and softspace in python In python, whenever you use >>>print statement it will append a newline by default. If you don't want newline to be appended, you got use a comma at the end (>>>print 10,) When, you have a list of characters and want them to be printed together a string using a for loop, there was observation that no matter what there was space coming between the characters. No split or join methods helped. >>>list1=['a','b','c'] >>>for e in list1: print e, a b c >>># Without whitespace it will look like. >>>print "abc" abc The language reference says that print is designed to output a space before any object. And some search goes to find and that is controlled by softspace attribute of sys.stdout. Way to print without leading space is using sys.stdout.write() >>>import sys >>>for e in list1: sys.stdout.write(e) abc Reference manual says: A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is "\n", or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.) Question to c.l.p Am Not getting the last part as how you will write a empty string and use print not appending blank space in a single line. Am not getting the (In some cases... ) part of the reference manual section. Please help. From nmilkovits at gmail.com Tue Mar 27 10:29:51 2007 From: nmilkovits at gmail.com (Nicholas Milkovits) Date: Tue, 27 Mar 2007 10:29:51 -0400 Subject: Type allocation in extensions Message-ID: <71a75690703270729j2f3b3243td521cedaec1d96f7@mail.gmail.com> Hi everyone, I've been reading through the documentation on extending and embedding python and the C API and I have a question about how allocation occurs of one type from another type. For example lets so I make to C module foo.c and bar.c and each has a python type. If I want to define a method in foo.c that will return and new bar object how would I go about doing that. Do I need to initialize tp_call and tp_alloc in order to use PyObject_Call()? Also, If I do not supply an allocfunc but instead initialize it to 0 when I declare my PyTypeObject for foo does it automatically get set to a generic allocation function? For example: In python I want to be able to write: f = Foo.new() b = foo.bar() bar.c static PyTypeObject BarType = { PyObject_HEAD_INIT(NULL) 0, // ob_size "bar", // tp_name sizeof(bar), // tp_basicsize 0, // tp_itemsize (destructor) Bar_Free, // tp_dealloc .........snip........... 0, //tp_call .........snip........... (initproc) Bar_Init, // tp_init 0, // tp_alloc Bar_New, // tp_new 0, // tp_free static PyObject *Bar_New(PyTypeObject *type, PyObject *args, PyObject keywordArgs) { // How does this call work if I never set an allocfunc pointer when I // declared the bar type return= type->tp_alloc(type, 0); } foo.c // Is PyObject_Call what I want to use and if so // how does it work if tp_call was initialized to 0 // or not even specified in my BarType variable? static PyObject *Foo_NewBar(foo *self, PyObject *args) { PyObject *createArgs, *bar_ref; createArgs = PyTuple_New(); if (!createArgs) return NULL; Py_INCREF(self); bar_ref = PyObject_Call( (PyObject*) &BarType, createArgs, NULL); Py_DECREF(createArgs); return bar_ref; } Thanks in advace for the help, Nick From aleax at mac.com Sun Mar 11 15:12:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 11 Mar 2007 12:12:50 -0700 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> Message-ID: <1hut8e8.g1jy3a1hj5hobN%aleax@mac.com> Army1987 wrote: > "cesco" ha scritto nel messaggio > news:1173451441.077648.321270 at c51g2000cwc.googlegroups.com... > >I have to generate a list of N random numbers (integer) whose sum is > > equal to M. If, for example, I have to generate 5 random numbers whose > > sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a > > simple pattern or function in Python to accomplish that? > > > > Thanks and regards > > Francesco > > > You can initialize a list to [1, 1, 1, 1, 1], and generate 45 random > integers between 1 and 5, and every time a number is generated, increase the > Nth number in the list by one. > > Not all distinct lists will have the same chance of occurring, e.g. [46, 1, > 1, 1, 1] will be much less likely than [10, 10, 10, 10, 10]. Depending on > what you need these numbers for, it can be a good thing or a bad thing. And a1-liner way to get the numbers (net of the mandatory +1 for each) is: map([random.randrange(5) for i in xrange(45)].count, xrange(5)) i.e., this gives 5 integers (each between 0 and 45 included) summing to 45 -- add 1 to each of them to get the desired result. Without any specification regarding the distributions required for the "5 random numbers" it's really impossible to say whether these are better or worse than other proposed solutions. Alex From deets at nospam.web.de Mon Mar 19 09:24:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Mar 2007 14:24:12 +0100 Subject: XML based programming language References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> <56786fF2743atU2@mid.uni-berlin.de> <1174307748.936567.191440@e1g2000hsg.googlegroups.com> Message-ID: <567h7sF287idqU1@mid.uni-berlin.de> stefaan wrote: >> Elementtree isn't lex. You are comparing apples and oranges here. Lex >> tokenizes, yacc creates trees. Both of is covered in XML itself - it's >> defined the tokenization and parsing, built into elementtree. So, >> elemnttree is lex _and_ yacc for XML. And if your language is written in >> XML, that's all there is to it. > > I see your point. But yacc does more: I specify a grammar, and yacc > will > reject input files that do not conform to the grammar. > Elementtree OTOH will happily accept any valid XML file, all checking > has to > implememented manually by me. First of all: nearly all parsers allow syntactically more, than their languages semantics actually admit. So you will have to have certain (most of the time context sensitive) checks hand-coded. But this is a small digression. What you are after then is the usage of a validating parser, not just well-formed XML-documents. I'm not sure where element-tree stands regarding this, but I think 4suite offers DTD, W3C-Schema and Relax-NG support. All of these are grammar-specifications that allow you to define the structure of your XML-documents with more constraints. Diez From sturlamolden at yahoo.no Mon Mar 26 11:40:00 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 26 Mar 2007 08:40:00 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174923600.641523.151960@y66g2000hsf.googlegroups.com> On Mar 26, 3:20 pm, "Noma... at gmail.com" wrote: > I've been told that Both Fortran and Python are easy to read, and are > quite useful in creating scientific apps for the number crunching, but > then Python is a tad slower than Fortran because of its a high level > language nature, so what are the advantages of using Python for > creating number crunching apps over Fortran?? Fortran may be faster, but Python (with NumPy and SciPy) is often fast enough. A lot of practitioners use Matlab, which is often slower than Python. Matplotlib is an excellent Python extension for graphing data. Anyone serious about numerical computing should learn Fortran 95. But use it sparsely and only where its needed. Fortran is perfect for numerical work but useless for anything else. Usually the amount of code that will benefit from using Fortran over NumPy makes up less than a percent of the line count. You can call Fortran from Python using f2py, so you can get the best from both worlds. From ken at theoryyalgebra.com Wed Mar 7 19:10:21 2007 From: ken at theoryyalgebra.com (Ken Tilton) Date: Wed, 07 Mar 2007 19:10:21 -0500 Subject: merits of Lisp vs Python In-Reply-To: References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> Message-ID: Brian Adkins wrote: > John Nagle wrote: > >> Neither Lisp nor Python is an "industrial strength language". >> The infrastructure is too weak. Hosting providers and distro >> makers aren't concerned over whether Python works. They >> care if C, C++, Java, PHP, and Perl work, but not Python or LISP. >> Ask them. >> >> John Nagle > > > In your excitement to post a sweeping and inaccurate generalization (you > missed diss'ing Ruby), I think you may have missed the point of my post. > I surely wasn't trying to restart a dead thread, I just thought it was > funny that there was a similarity to a line from Princess Bride in the > thread (see relevant part below that you cut out). > > If you want to restart a debate, please go back and reply to some > serious post in the thread - don't hijack mine for your own evil > purposes and cut out the good parts - did you even see the movie? Yes. I think George did, too. (I was wondering what you were up to.) :) kt > > George Sakkis wrote: > > You keep using that phrase. I don't think it means what you think it > > means. > > [Vizzini has just cut the rope The Dread Pirate Roberts is climbing up] > Vizzini: HE DIDN'T FALL? INCONCEIVABLE. > Inigo Montoya: You keep using that word. I do not think it means what > you think it means. -- Well, I've wrestled with reality for 35 years, Doctor, and I'm happy to state I finally won out over it. -- Elwood P. Dowd In this world, you must be oh so smart or oh so pleasant. -- Elwood's Mom From jtauber at jtauber.com Fri Mar 9 19:26:01 2007 From: jtauber at jtauber.com (jtauber) Date: 9 Mar 2007 16:26:01 -0800 Subject: Google Summer of Code 2007 Message-ID: <1173486361.596136.324360@p10g2000cwp.googlegroups.com> Google's Summer of Code is on again! And the Python Software Foundation is again applying to be a mentoring organization. A mailing list has been set up for people who are interested in mentoring for the PSF. If you aren't able or willing to mentor but still want to participate in discussion of possible project ideas, you are more than welcome to join also. You can subscribe at: http://mail.python.org/mailman/listinfo/soc2007-mentors/ While the desire is for a decent number of projects to be directly related to core Python development, proposals of general relevance to Python are also welcome. James From dickinsm at gmail.com Sun Mar 11 13:44:34 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 11 Mar 2007 10:44:34 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: <1hut07q.1fhewdebmz1c0N%aleax@mac.com> References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> Message-ID: <1173635074.726444.88760@t69g2000cwt.googlegroups.com> On Mar 11, 1:26 pm, a... at mac.com (Alex Martelli) wrote: > [Long analysis of probable cause of the problem] Thank you for this. I was suspecting something along these lines, but I don't yet know my way around the source well enough to figure out where the problem was coming from. > In the meantime, I hope that some available workarounds for the bug are > clear from this discussion: avoid using multiple constants in a single > compilation unit where one is 0.0 and another is -0.0, or, if you really > can't avoid that, perhaps use compiler.compile to explicitly build the > bytecode you need. Yup: the workaround seems to be as simple as replacing all occurrences of -0.0 with -(0.0). I'm embarrassed that I didn't figure this out sooner. >>> x, y = -(0.0), 0.0 >>> x, y (-0.0, 0.0) Mark From jgodoy at gmail.com Tue Mar 6 17:51:33 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Tue, 06 Mar 2007 19:51:33 -0300 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <45ec933a$0$15549$426a34cc@news.free.fr> <1huivd7.7l18eh1paqp0aN%aleax@mac.com> <87k5xu37vt.fsf@gmail.com> <1hujkzp.11vuf5x1a6yz2aN%aleax@mac.com> Message-ID: <87649easui.fsf@gmail.com> aleax at mac.com (Alex Martelli) writes: > Not sure I get what you mean; when I write tests, just as when I write > production code, I'm focused (not worried:-) about the application semantics... ;-) Thanks for the correction. > functionality I'm supposed to deliver. The language mostly "gets out of > my way" -- that's why I like Python, after all:-). That's the same reason why I like it. I believe it is not a coincidence that we both like writing Python code. But there are cases where investigating is more necessary than testing. This is where I see the need of the interactive session. For program's features I also write tests. > I do generally keep an interactive interpreter running in its own > window, and help and dir are probably the functions I call most often > there. If I need to microbenchmark for speed, I use timeit (which I > find far handier to use from the commandline). I wouldn't frame this as > "worried with how to best use the language" though; it's more akin to a > handy reference manual (I also keep a copy of the Nutshell handy for > exactly the same reason -- some things are best looked up on paper). That's the same use -- and the same most used functions -- that I have here. I believe that I wasn't clear on my previous post, and this is why you saw a different meaning to it. > I don't really see "getting a bit big to setup" as the motivation for > writing automated, repeatable tests (including load-tests, if speed is > such a hot topic in your case); rather, the key issue is, will you ever It's not for writing tests. It's for investigating things. If I have to open database connections, make several queries to get to a point where I have the object that I want to "dir()", it is easier to me to put that all in a file. It isn't a test. > want to run this again? For example, say you want to check the relative > speeds of approaches A and B -- if you do that in a way that's not > automated and repeatable (i.e., not by writing scripts), then you'll > have to repeat those manual operations exactly every time you refactor > your code, upgrade Python or your OS or some library, switch to another > system (HW or SW), etc, etc. Even if it's only three or four steps, who > needs the aggravation? Almost anything worth doing (in the realm of > testing, measuring and variously characterizing software, at least) is > worth automating, to avoid any need for repeated manual labor; that's > how you get real productivity, by doing ever less work yourself and > pushing ever more work down to your computer. I won't write a script to write two commands and rerun them often. But I would for some more -- lets say starting from 5 commands I might start thinking about having this somewhere where I can at least Cut'n'Past to the interactive interpreter (even with readline's help). -- Jorge Godoy From tjreedy at udel.edu Wed Mar 21 13:29:38 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Mar 2007 13:29:38 -0400 Subject: Testing Python updates References: <1174488951.275163.305440@y66g2000hsf.googlegroups.com> Message-ID: "Matthew" wrote in message news:1174488951.275163.305440 at y66g2000hsf.googlegroups.com... | What is the methodology for testing the updates to the Python language? By who? There is an expanding /test directory in the pythonx.y/Lib directory. Core developers run these about once a day on multiple systems. People who build their own executable should run the same. People who install a prebuilt executable may do the same, and should if they suspect a problem with their installation. Application developers increasingly have their own automated test files that they run after running /Lib/test on a new installation. Terry Jan Reedy From exarkun at divmod.com Mon Mar 26 09:42:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 26 Mar 2007 08:42:11 -0500 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <20070326134211.18920.1580959398.divmod.quotient.5650@ohm> On 26 Mar 2007 06:20:32 -0700, "Nomad.C at gmail.com" wrote: >OK... >I've been told that Both Fortran and Python are easy to read, and are Python is hugely easier to read. >quite useful in creating scientific apps for the number crunching, but >then Python is a tad slower than Fortran because of its a high level Fortran is massively faster than Python. >language nature, so what are the advantages of using Python for >creating number crunching apps over Fortran?? You can get the speed of fortran in Python by using libraries like Numeric without losing the readability of Python. Jean-Paul From tjreedy at udel.edu Thu Mar 22 01:51:31 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Mar 2007 01:51:31 -0400 Subject: Python 3000 idea: reversing the order of chained assignments References: <7WjMh.318$YL5.80@newssvr29.news.prodigy.net><1hvcadb.134pbvp1y39wi3N%aleax@mac.com> Message-ID: "Mark T" wrote in message news:DvGdnQacTuMlmp_bnZ2dnUVZ_uWdnZ2d at comcast.com... | This is interesting: | | >>> class Test(object): | ... def __getattribute__(self,n): | ... print 'reading',n | ... return object.__getattribute__(self,n) | ... def __setattr__(self,n,v): | ... print 'writing',n,v | ... return object.__setattr__(self,n,v) | ... | >>> x=Test() | >>> x.a=1; x.b=2; x.c=3 | writing a 1 | writing b 2 | writing c 3 | >>> x.a=x.b=x.c | reading c | writing a 3 | writing b 3 | >>> | | I wouldn't have expected "a" to be assigned first in a right-to-left parsing | order. The result is the same in any case. The assignment order is specified in the language reference. But many never read and those who do can forget. And even if the coder reads and remembers, a code reader may not have. Which is why I suggested multiple statements in explicit order when it really matters. tjr From lbates at websafe.com Thu Mar 15 16:24:45 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 15 Mar 2007 15:24:45 -0500 Subject: problem with str() In-Reply-To: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > I can't get the str() method to work in the following code(the last > line produces an error): > > ============ > class test: > """class test""" > def __init__(self): > """I am init func!""" > self.num = 10 > self.num2 = 20 > def someFunc(self): > """I am someFunc in test!""" > print "hello" > > > obj = test() > obj.someFunc() > names = dir(obj) > print names > > methodList = [str for str in names if callable(getattr(obj, str))] > print methodList > > x = getattr(obj, methodList[0]).__doc__ > print x > print type(x) > print str(getattr(obj, methodList[0]).__doc__) > =========== > > Here is the output: > > $ python test1.py > hello > ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc'] > ['__init__', 'someFunc'] > I am init func! > > Traceback (most recent call last): > File "test1.py", line 23, in ? > print str(getattr(obj, methodList[0]).__doc__) > TypeError: 'str' object is not callable > > This is part of some code in Diving Into Python,Chapter 4. In case a > function doesn't have a __doc__ string, and therefore __doc__ returns > None, the code needs to convert each __doc__ to a string so that the > result is guaranteed to be a string. > You masked the built-in str method in your list comprehension. Try changing to: methodList = [s for s in names if callable(getattr(obj, str))] I'll bet it will work then. -Larry From lobais at gmail.com Mon Mar 26 10:50:09 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Mon, 26 Mar 2007 16:50:09 +0200 Subject: Sending ECHO_REQUEST (pinging) with python References: Message-ID: Den Mon, 26 Mar 2007 11:24:34 +0200 skrev Michal 'vorner' Vaner: > On Mon, Mar 26, 2007 at 08:30:16AM +0200, Thomas Dybdahl Ahle wrote: >> Do anybody know how to do this in python? > You need root for that and the ping command is allowed to have them by > suid bit. You can execute ping from inside python and use ping as is, if > you need. Yeah, I could execute ping, but it would lock me harder to the platform. From laurent.pointal at limsi.fr Fri Mar 23 05:23:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 23 Mar 2007 10:23:29 +0100 Subject: how can I invoke a Java code? In-Reply-To: <1174610940.971724.206900@l75g2000hse.googlegroups.com> References: <1174610940.971724.206900@l75g2000hse.googlegroups.com> Message-ID: momobear a ?crit : > A friend of my write a Java program, and I want use it in my python > program as a module. I searched the topic in Google and find maybe the > better way is use GCJ to compile it. Is there any other way for me? > the simple and speediness choice the better. thanks. See my links: http://www.limsi.fr/Individu/pointal/python.html#liens-intautlang-java You can look at * Jython * JPype * JEP * java2python From bdesth.quelquechose at free.quelquepart.fr Wed Mar 21 17:09:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 21 Mar 2007 22:09:39 +0100 Subject: Make variable global In-Reply-To: <1174506941.618827.48450@l75g2000hse.googlegroups.com> References: <1174506941.618827.48450@l75g2000hse.googlegroups.com> Message-ID: <46019697$0$763$426a34cc@news.free.fr> abcd a ?crit : > I have a file, "a.py" > > blah = None > def go(): > global blah > blah = 5 > >>From the python interpreter I try.... > > >>>>from a import * >>>>blah >>>>go() >>>>blah >>>> > > > ...i was hoping to see "5" get printed out the second time I displayed > blah, but it doesn't. Now, if I type this same code directly into the > python interpreter it works as i was hoping. what i am missing? In Python, 'global' means 'module level'. And 'variables' are name:object bindings in a namespace (mostly function, class or module). The way you import blah and go from module a creates two names (blah and go) in the current namespace, and bind these names to resp. a.blah and a.go. The fact that go rebinds a.blah doesn't impact current namespace's blah. The following session may help you understanding what happens: >>> from a import * >>> dir() ['__builtins__', '__doc__', '__name__', 'blah', 'go'] >>> import a >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'blah', 'go'] >>> dir(a) ['__builtins__', '__doc__', '__file__', '__name__', 'blah', 'go'] >>> go is a.go True >>> go() >>> blah >>> a.blah 5 >>> Note that rebinding a name and mutating a (mutable) object are two distinct operations: # b.py blah = ['42'] def go(): blah[0] = "yo" def gotcha(): global blah blah = ['gotcha'] >>> from b import * >>> import b >>> blah ['42'] >>> blah is b.blah True >>> go() >>> blah ['yo'] >>> b.blah ['yo'] >>> blah is b.blah True >>> gotcha() >>> blah ['yo'] >>> b.blah ['gotcha'] >>> To make a long story short: 1/ avoid globals whenever possible 2/ when using (module) globals, either use them as pseudoconstants or as module's 'private' variables (IOW : only functions from the same module can modify/rebind them). HTH From duncan.booth at invalid.invalid Wed Mar 21 12:17:11 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Mar 2007 16:17:11 GMT Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Message-ID: "dmitrey" wrote: > + it will not yield incompabilities with previous Python versions. So how would you write: func(-3) func(*param) with your scheme? These already have an incompatible meaning: func -3 func *param1 From khemkaamit at gmail.com Mon Mar 5 05:45:02 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 5 Mar 2007 16:15:02 +0530 Subject: Dictionary of Dictionaries In-Reply-To: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> References: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> Message-ID: <1360b7230703050245q75bf8834l40f54a3244243d80@mail.gmail.com> On 5 Mar 2007 02:22:24 -0800, bg_ie at yahoo.com wrote: > Hi, > > I have the following - > > messagesReceived = dict.fromkeys(("one","two"), {}) This will create a dictionary "messagesReceived", with all the keys referring to *same instance* of the (empty) dictionary. ( try: messagesReceived = dict( [(k,{}) for k in ('one', 'two') ] ) ) > > messagesReceived['one']['123'] = 11111 > messagesReceived['two']['121'] = 22222 > messagesReceived['two']['124'] = 43333 > > This gives: > > {'two': {'121': 22222, '123': 11111, '124': 43333}, 'one': {'121': > 22222, '123': 11111, '124': 43333}} And hence the results ! HTH, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From f.braennstroem at gmx.de Tue Mar 27 16:13:04 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Tue, 27 Mar 2007 20:13:04 +0000 Subject: pattern search In-Reply-To: References: Message-ID: Hi to all, Wojciech Mu?a schrieb am 03/27/2007 03:34 PM: > Fabian Braennstroem wrote: >> Now, I would like to improve it by searching for different 'real' >> patterns just like using 'ls' in bash. E.g. the entry >> 'car*.pdf' should select all pdf files with a beginning 'car'. >> Does anyone have an idea, how to do it? > > Use module glob. Thanks for your help! glob works pretty good, except that I just deleted all my lastet pdf files :-( Greetings! Fabian From bg_ie at yahoo.com Mon Mar 5 03:43:42 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 5 Mar 2007 00:43:42 -0800 Subject: Building a dictionary from a tuple of variable length Message-ID: <1173084222.565386.250510@h3g2000cwc.googlegroups.com> Hi, I have the following tuple - t = ("one","two") And I can build a dictionary from it as follows - d = dict(zip(t,(False,False))) But what if my tuple was - t = ("one","two","three") then I'd have to use - d = dict(zip(t,(False,False,False))) Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? Thanks for your help, Barry. From ah at hatzis.de Sat Mar 24 19:36:18 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Sun, 25 Mar 2007 00:36:18 +0100 Subject: Pattern for foo tool <-> API <-> shell|GUI In-Reply-To: <1174758918.211398.182560@l75g2000hse.googlegroups.com> References: <1174758918.211398.182560@l75g2000hse.googlegroups.com> Message-ID: <200703250036.18887.ah@hatzis.de> On Saturday 24 March 2007 18:55, kyosohma at gmail.com wrote: > On Mar 24, 10:31 am, Anastasios Hatzis wrote: > > I'm looking for a pattern where different client implementations can use > > the same commands of some fictive tool ("foo") by accessing some kind of > > API. Actually I have the need for such pattern for my own tool > > (http://openswarm.sourceforge.net). I already started restructuring my > > code to separate the actual command implementations from the command-line > > scripts (which is optparser-based now) and have some ideas how to > > proceed. But probably there is already a good pattern used for > > Python-based tools. > > > > In the case that some of you are interested into this topic and my recent > > thoughts, you may want to have a look at the description below. Any > > comments are very much appreciated. Hopefully this list is a good place > > for discussing a pattern, otherwise I would be okay to move this to > > another place. Thank you. > > > > Here we go: > > The tool package itself provides several commands, although not important > > for the pattern itself, here some examples: modifying user-specific > > preferences, creating and changing project settings files, > > project-related > > code-generation, or combinations of such commands ... later also commands > > for transformation between several XML formats etc. The classes which > > implement these commands are currently in multiple modules, each having a > > class named CmdHandler. > > > > I have some Python scripts (each having a ScriptHandler classes), for use > > via command-line. Each ScriptHandler class is responsible to add all > > related command-line options and process those provided by the user > > (based on optparse library from Python standard lib). The script then > > calls the corresponding command and provide the verified options as > > parameters. > > > > Due to the nature of the tool under specific conditions the following > > results may come during command execution: > > * successful execution, no interaction > > * critical error, execution cancelled > > * user interaction needed (e.g. prompt user to approve replace existing > > directory (yes/no), prompt user to provide an alternative option) > > > > Command-line interactions work simply with raw_input(). > > > > So far this works. Nevertheless, there are some other aspects that could > > be improved, but this is another topic: The tool uses custom exceptions > > (e.g. for critical errors) and logging features (based on logging from > > Python standard lib). Currently no automated tests, but I have to add. > > > > For the next step I plan to support not only my own command-line scripts, > > but also a GUI to access the commands, as well as 3rd-party products > > (themselves command-line scripts or GUIs, such as foo plugins for any > > 3rd-party-tools). As far as I see, these clients need to implement a > > handler that: > > (1) Collecting all required parameters and optional parameters from a > > user (2) Provide these parameters for a particular call to command API > > (3) Provides some kind of hooks that are called back from the API on > > specific events, e.g. Question with user-choice; Information with > > user-input (4) Provide a logging handler object from the tool logging > > class or a sub-class of that in the case that a client-specific logging > > object should be triggered on each debug, message, warning etc. > > > > (1) is very client-specific, e.g. in a GUI via dialogs. > > > > (2) Each command provides a signature for all required/optional > > parameters. They are all verified from the command itself, although a > > client could do some verification at the first place. > > > > (3) Example use-case: a command needs to know if the user wants the > > command to proceed with a particular action, e.g. "Do you want to delete > > bar.txt?" with "Yes", "No" and "Cancel" choice. So the client's handler > > object (which is provided as first parameter to each command) implements > > client-specific features to show the user this question (e.g. pop-up > > dialog with question and three buttons), receive the user input (clicking > > one of the buttons) and pass this choice back to the foo API. > > Alternatively some kind of text information could be required, as in > > raw_input(), so actually this probably would be two different interaction > > features to be implemented. > > > > (4) The foo API also provides a logging class. The client needs to > > initialize such an object and provide it as member of the handler object > > provided to the API. I wonder if some clients may have own logging > > features and want to include all log messages from foo tool to the own > > logs. In this case a client could its own sub-class of the foo logging > > class and extending it with callbacks to its (client-)native logging > > object. > > > > What do you think about this? > > > > Best regards, > > Anastasios > > I think if you want to use a GUI, wxpython or Tkinter would work well > for you. wxPython has more widgets from the start, but is also more > complex. Tkinter is good for quick and dirty GUIs, but gets > increasingly more complicated to deal with the more complex the GUI > has to be, in general. At least, that's what I am told. > > I started out using Tkinter. It's great for prototyping, but I had to > port VBA code to a Python GUI and Tkinter just didn't have the widgets > I needed (including the the submodules PMW and Tix). So I went with > wxPython. I personally like it quite a bit. Plus you can use XRC with > wxPython to help separate out the GUI code from the logic. > > Both toolkits can accept user input in myriads of ways and both have > standard dialogs that look almost or exactly native to the OS they are > running on. Download wxPython's demo to see all that it can do. > Tkinter is already installed and it has demos in its subdirectory > under Python. > > There's my 2 cents. > > Mike Mike, thank you for your post and taking your time. I understand the reasons for your recommendation and totally agree with your considerations. Actually I already have decided to use wxPython for the GUI job in that project. I guess I didn't make myself very clear in the OP, sorry for this, so I try again with hopefully more clarity: I'm working on a tool which is totally command-line based and consisting of multiple scripts. The user can execute a Python script in the shell, this script does some basic verification before delegating a call into my tool's package and depending on some arguments and options provided in the command-line, e.g. $python generate.py myproject --force --verbose the tool processes whatever necessary. There are multiple command handlers available in this package which are responsible for different tasks and depending of the script that has been executed one or more of these command handlers are fired to do their work ;) Now I need to extend my tool in that way, that it can be accessed not only from my own scripts, but also by other, additional "client implementations", such as my own wxPython-based GUI, as well as Python scripts and GUIs (wx, Tkinter,...) of other tools that integrate some kind of plug-in. For example there is a Python-based UML tool realized with wxGTK (AFAIR). The developers of this tool intent to create a small plug-in, so their users can access features of my tool inside of this UML tool. So, I need to create an API that can be used by clients to access specific features of my tool. And I'm looking for patterns how this could be realized in a smart Pythonic way. And I don't think that this is very trivial (at least not for my programming skill level). In the given example "generate.py" (above) the following scenario is pretty likely: (1) User works with UML tool and clicks in some dialog a "generate" button (2) UML tool triggers this event an calls a magic generate() method of my tool (via the API I provide for this purpose), like my generate.py script would do same way (3) Somewhen with-in this generate process my tool may need to get some information from the user in order to continue (it is in the nature of the features that I can't avoid this need of interaction in any case). Currently, since I have only this command-line script "user-interface", I have it that way implemented, that the command handler class (responsible to supervise the entire generate process) just prints a question to the console and prompts the user to input his choice. This is done by raw_input() called inside the command and the command handler itself receives the user response directly from the shell. As far as I understand now, instead of calling raw_input() - which would make no sense if the client would be some GUI - my command handler should call some kind of hook or delegation method in the client, e.g. the method promptUser(QuestionText, UserChoiceArgs). Any client should implement at least this method. If a client's promptUser() method is called the client would be responsible to realize the appropriate user-dialog, such as a shell input or a wxFrame or whatever reasonable for the nature of the client. Depending on the interaction of the user with this user-interface the client then passes the user-choice back to my tool as return value of promptUser(). In addition there would be other aspects, such as as triggers for logging messages a.s.o., but this is probably not that important yet. I don't know if I'm totally wrong with this design. I appreciate that it would encapsulate the logic to layers of separated concerns and with such API it would be possible to develop new clients rather easy (which would be a great benefit, I think). There is just still doubt if there isn't a better way. I would think that I'm not the first one who has a command-line based tool in Python and wants to provide an interface to additional client programs, especially GUIs. I tried to find some appropriate pattern or tutorial on the net, but haven't been successful. Thank you, again. Best regards, Anastasios From __peter__ at web.de Sun Mar 4 16:48:00 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Mar 2007 22:48:00 +0100 Subject: Perl and Python, a practical side-by-side example. References: <45eb3b34$0$1404$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > print >> output, sorted(decorated_lines, reverse=True)[0][1] Or just print >> output, max(decorated_lines)[1] Peter From israphelr at googlemail.com Tue Mar 13 18:34:04 2007 From: israphelr at googlemail.com (israphelr at googlemail.com) Date: 13 Mar 2007 15:34:04 -0700 Subject: Problem I have with a while loop/boolean/or Message-ID: <1173825244.368771.273720@e1g2000hsg.googlegroups.com> Hi all. I have a problem with some code :( ----------- hint = raw_input("\nAre you stuck? y/n: ") hint = hint.lower() while (hint != 'n') or (hint != 'y'): hint = raw_input("Please specify a valid choice: ") --------------------------------------------- so everytime I run the program, and enter my choice as y or n, I'm told to 'Please Specify a valid Choice Again' and can't get out of the loop. ----------- hint = raw_input("\nAre you stuck? y/n: ") hint = hint.lower() while (hint != 'n'): hint = raw_input("Please specify a valid choice: ") --------------------------------------------- As for here when I enter n, I can leave the while loop. Anyway I can't put my finger on this, so I'd be real grateful if someone could tell me what I've done wrong. Thanks. (I have a guy feeling it's something really silly I'm overlooking...) From johnpote at blueyonder.co.uk Tue Mar 20 21:44:41 2007 From: johnpote at blueyonder.co.uk (John Pote) Date: Wed, 21 Mar 2007 01:44:41 GMT Subject: select.poll and winXP Message-ID: Hi all, I have the standard Python 2.4.4 windows download installed on my win XP box. But the poll class in module select is not available. The docs indicate that it can work with windows as long as only sockets are used which is fine for me. Is there a reason it's not in the standard build, can I use it if I re compile the 'select' module from the source? Thanks for any help anyone can give John From bjourne at gmail.com Mon Mar 19 12:29:40 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 19 Mar 2007 17:29:40 +0100 Subject: When is List Comprehension inappropriate? In-Reply-To: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> References: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> Message-ID: <740c3aec0703190929v217d35f3ya26682f9355820b9@mail.gmail.com> On 19 Mar 2007 07:41:59 -0700, Ben wrote: > I have recently learned how list comprehension works and am finding it > extremely cool. I am worried, however, that I may be stuffing it into > places that it does not belong. > > What's the most "pythony" way to do this: > > even = [] > for x in range(0,width,2): > for y in range(0,height,2): > color = im.getpixel((x,y)) > even.append(((x,y), color)) > > versus list comprehension: > > even2 = [((x,y), im.getpixel((x,y))) for x in range(0,width,2) for y > in range(0,height,2)] I would definitely not use list comprehension in this case. While they may be faster, Psyco is great here. Also, if you have lots of 2d-loops like "for x in something: for y in something:", then it could be more beautiful to separate the iteration from the task: def iterimage(im, width, height, step = 1): for y in range(0, height, step): for x in range(0, width, step): yield (x, y), im.getpixel((x, y)) Then the list comprehension becomes a little more manageable: even2 = [(pos, col) for pos, col in iterimage(im, width, height, 2)] Although this must definitely be the slowest of all the different approaches. -- mvh Bj?rn From ntv1534 at gmail.com Thu Mar 22 03:38:46 2007 From: ntv1534 at gmail.com (MooMaster) Date: 22 Mar 2007 00:38:46 -0700 Subject: Color Segmentation w/ PIL? Message-ID: <1174549126.754309.317260@n76g2000hsh.googlegroups.com> I'm trying to write a Digital Image Processing program using the PIL library, and upon consultation of the Handbook I see that it seems to have built in functions to run Edge Detection (in the ImageFilter module), but I don't see anything about Segmentation. Are there any built-in tools to do this operation? Has anyone done this operation with PIL in the past that can lead me in the right direction? From ayaz at dev.slash.null Tue Mar 6 04:15:03 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Tue, 06 Mar 2007 14:15:03 +0500 Subject: Newbie question References: <1173117307.283564.22270@30g2000cwc.googlegroups.com> Message-ID: "Joshua.R.English at gmail.com" typed: >> Tommy Grav schrieb: >> For this case, there are list comprehensions (or map, but you shouldn't >> use it any longer): > > I didn't see anything in the docs about this. Is map going away or is > it considered un-Pythonic now? Most everywhere I've read about map() and filter() seemed to discourage their use stating that they're becoming depreciated (with the exception of Dive Into Python which advocates use of these two functions in preference to even list comprehensions, if I've read it properly). -- Ayaz Ahmed Khan Falling in love makes smoking pot all day look like the ultimate in restraint. -- Dave Sim, author of "Cerebus". From hitesh287 at gmail.com Mon Mar 12 13:58:37 2007 From: hitesh287 at gmail.com (Hitesh) Date: 12 Mar 2007 10:58:37 -0700 Subject: glob.glob output Message-ID: <1173722316.890388.67210@30g2000cwc.googlegroups.com> import string import os f = open ("c:\\servername.txt", 'r') linelist = f.read() lineLog = string.split(linelist, '\n') lineLog = lineLog [:-1] #print lineLog for l in lineLog: path1 = "\\\\" + l + "\\server*\\*\\xtRec*" glob.glob(path1) When I run above from command line python, It prints the output of glob.glob but when I run it as a script, it does not print anything.... I know that there are files like xtRec* inside those folders.. and glob.glob does spits the path if run from python command line. I tried something like this but did not work: for l in lineLog: path1 = "\\\\" + l + "\\server*\\*\\xtRec*" xtRec = glob.glob(path1) print xtRec No results... xtRec = [] for l in lineLog: path1 = "\\\\" + l + "\\server*\\*\\xtRec*" xtrec = glob.glob(path1) print xtRec No luck here either. Seems like I am doing here something reallt silly mistake.. Thank you, hj From paddy3118 at googlemail.com Thu Mar 29 01:06:31 2007 From: paddy3118 at googlemail.com (Paddy) Date: 28 Mar 2007 22:06:31 -0700 Subject: Modal value of an array In-Reply-To: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> Message-ID: <1175144791.467051.144390@r56g2000hsd.googlegroups.com> On Mar 29, 4:40 am, "datta.abhi... at gmail.com" wrote: > Hi > > How can I find out the modal value in an array. That is the value > which occurs maximum time in the sequence .. > > e.g. if my array has values like [2,3,2,2,2,4,2,2] definitely the > maximum time 2 occurs in the array. so this function should be able to > return 2 as a result .. > > So is there any function in built in python which can do that ? > > Thanks > > Abhirup With the same assumptions as Ben Finney, I came up with this: >>> import operator >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] >>> count = {} >>> for item in foo: count[item] = count.get(item, 0) +1 ... >>> maxitem = max(count.items(), key= operator.itemgetter(1)) >>> maxitem ('spam', 4) >>> I was trying to minimise the iterations through the list. - Paddy. From paddy3118 at googlemail.com Wed Mar 21 16:23:19 2007 From: paddy3118 at googlemail.com (Paddy) Date: 21 Mar 2007 13:23:19 -0700 Subject: Wikipedia and a little piece of Python History In-Reply-To: <871wjiuz5q.fsf@pobox.com> References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <871wjiuz5q.fsf@pobox.com> Message-ID: <1174508599.250404.176510@y66g2000hsf.googlegroups.com> On Mar 21, 8:20 pm, j... at pobox.com (John J. Lee) wrote: > "Paddy" writes: > > I just had a link to Tim peters first post on doctest: > >http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > > removed fromhttp://en.wikipedia.org/wiki/Doctestas it doesn't fit > > their guidelines for external links. > > I wonder, could maybe the official website be persuaded to host a copy > > so that it could be linked to? > > > Tim, would you object? > > It (wikipedia) is a wiki, why not edit the page and paste it in? > > John They have rules, and periodically trawl pages and clean them. I'd like to stay within the rules. - Paddy. From skip at pobox.com Fri Mar 30 14:04:22 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 30 Mar 2007 13:04:22 -0500 Subject: LRU cache (and other things missing from the standard library ...) In-Reply-To: <1100121983.30976.22.camel@bad.dynu.ca> References: <1100121983.30976.22.camel@bad.dynu.ca> Message-ID: <17933.20774.865681.868732@montanaro.dyndns.org> Evan> I agree that LRU caches are a data structure too frequently Evan> re-implemented in Python. I'd also like to see a "standard" cache Evan> package, either as part of the standard library or elsewhere. To Evan> that end, I've just uploaded an LRU cache package to the Python Evan> Package Index: Evan> http://www.python.org/pypi?:action=display&name=lrucache&version=0.2 Couldn't get to your website, but I've been using this one I wrote for several years: http://www.webfast.com/~skip/python/Cache.py I'm just coming to this thread, so I don't know how it compares with your requirements. Skip From bdesth.quelquechose at free.quelquepart.fr Thu Mar 1 17:23:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Mar 2007 23:23:22 +0100 Subject: Questions about app design - OOP with python classes In-Reply-To: <1172784257.370311.272620@8g2000cwh.googlegroups.com> References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <1172784257.370311.272620@8g2000cwh.googlegroups.com> Message-ID: <45e74a80$0$29387$426a34cc@news.free.fr> adriancico at gmail.com a ?crit : > On Mar 1, 9:45 pm, Bruno Desthuilliers > wrote: > > > I understand (I've been in wikipedia :-) ). Right now the Frame is the > controller as well > as the view. Yeps. Note that this is a common "simplification" of the MVC - Microsoft labelled it "Document/View". (snip) > My problem was that, altough I knew OOP basics, I didn't know how to > apply them exactly. It mostly comes out of experience IMHO. But reading the GOF (I let you google for what this TLA refers to !-) may not be a bad idea - it's probably the best book about OO design I've read so far, even if lot of the described patterns make less sens in an highly dynamic language like Python. >>Note that there's nothing Python-specific in your question. But since >>comp.object is one of the worst places on earth to ask questions about OO... > > > I am developing in Python, so it made sense to me to post here. But > you are right, the question > is off-topic. Sorry for that. Alas, the appropriate newsgroup (comp.object) has turned into one of the most unfriendly and sterile places I know on the net. From mail at microcorp.co.za Wed Mar 21 01:54:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 21 Mar 2007 07:54:28 +0200 Subject: List to string References: <1174192136.371754.85500@l75g2000hse.googlegroups.com><1174192714.014092.79380@l77g2000hsb.googlegroups.com><45fe7ddc$0$25292$426a34cc@news.free.fr><45ffcd12$0$18276$426a74cc@news.free.fr> Message-ID: <021601c76b85$61b012e0$03000080@hendrik> "Steven D'Aprano" wrote: On Tue, 20 Mar 2007 13:01:36 +0100, Bruno Desthuilliers wrote: 8< ------- confusion about left and right ------------ It gets worse. When you work on a lathe, a "right hand cutting tool" has its cutting edge on the left... And the worse part is that its for good reason. - Hendrik From psaroudakis at gmail.com Tue Mar 27 07:58:44 2007 From: psaroudakis at gmail.com (psaroudakis at gmail.com) Date: 27 Mar 2007 04:58:44 -0700 Subject: pygtk button event Message-ID: <1174996724.249456.308140@r56g2000hsd.googlegroups.com> Hi.... i am trying to implement the following: I want to be able to press a button, perform a task and return a value. my button is named button1 and I used glade to build the gui. so, something like this should work.... application=gtk.glade.XML('app.glade','app') bt=app.get_widget('button1') bt.connect('clicked',on_btClicked) def on_btClicked(widget,event): if data==0: P=1 else: P=2 return P How can I get P? Something like this doesn't work: bt.connect('clicked',P=on_btClicked) How can I return P??? Thanks! Nick From spradml at gmail.com Sat Mar 10 09:54:53 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Sat, 10 Mar 2007 20:24:53 +0530 Subject: making an "executable" for a python code (newbie) Message-ID: <80628d680703100654x209e954cmf67a03f853c2c7ae@mail.gmail.com> hello, i have some python scripts (especially, PyQt4 scripts) that i want to deploy on both linux and windows m/c's. different packaging tools that i checked (cx_freeze, distutils, pyinstaller) allow me to create "installers". however, i'm interested in creating "executables" that allow the code to be run just on "double clicking". is there any way to get this done? also, it seems that "pyexe" creates a windows executable, but how do i use it on linux? thanks for all the help! From michael at jedimindworks.com Thu Mar 22 11:12:58 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 22 Mar 2007 10:12:58 -0500 Subject: My MVC critique In-Reply-To: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> References: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> Message-ID: On Mar 22, 2007, at 9:29 AM, scott.w.white at gmail.com wrote: > mickey mouse Well, at least you spelled Mickey Mouse right... :-) From sjmachin at lexicon.net Sat Mar 17 06:29:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 Mar 2007 03:29:39 -0700 Subject: Finding the insertion point in a list In-Reply-To: <7xfy845q24.fsf@ruckus.brouhaha.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <7xird0bom3.fsf@ruckus.brouhaha.com> <7xfy845q24.fsf@ruckus.brouhaha.com> Message-ID: <1174127379.112302.227370@y80g2000hsf.googlegroups.com> On Mar 17, 5:42 pm, Paul Rubin wrote: > Steven D'Aprano writes: > > or even > > > len(filter(lambda t, y=y: y>t, x)) > > How about > > min(i for i,t in enumerate(x) if t >= y) > > or > > max(i for i,t in enumerate(x) if t <= y) > > Those are actually pretty direct. I'd hate to see "indirect". Worse, the min-using gizmoid crashes when y > x[-1] -- all your ifs are belong to False. >>> x [0, 100, 200, 1000] >>> tests = [0, 1, 100, 150, 1000, 2000] >>> [(y, max(i for i,t in enumerate(x) if t <= y)) for y in tests] [(0, 0), (1, 0), (100, 1), (150, 1), (1000, 3), (2000, 3)] Looks OK, iff one is happy with the OP's strange usage of "insert point". >>> xc = x[:] >>> xc.insert(1, 150) >>> xc [0, 150, 100, 200, 1000] Whoops. Try this for size: >>> [(y, sum(t <= y for t in x)) for y in tests] [(0, 1), (1, 1), (100, 2), (150, 2), (1000, 4), (2000, 4)] Cheers, John From rschroev_nospam_ml at fastmail.fm Mon Mar 12 05:04:04 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 12 Mar 2007 09:04:04 GMT Subject: Watching a file another app is writing In-Reply-To: References: <1173676363.653940.133030@30g2000cwc.googlegroups.com> Message-ID: <8I8Jh.61709$O92.368750@phobos.telenet-ops.be> Gordon Airporte schreef: > Nick Vatamaniuc wrote: > > You might need to look at pywin32 for Windows specific ways to listen >> to "file changed" event. >> >> On Unix a quick shortcut would be to simply read the output of 'tail - >> f ' command... > > Ah, I forgot I have Cygwin installed, so I do have tail. Unfortunately > Windows will not let most programs save to the file while tail is > watching it, and when I force it with vim :w! the output from tail -f > does not update. Maybe I'm using it wrong. Have you tried with tail -F instead of tail -f? With a big F it uses the name of the file instead of the file descriptor, and it keeps trying to open the file. I'm not sure if it will work, but it's worth a shot. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From o.ekanem at gmail.com Thu Mar 29 15:55:07 2007 From: o.ekanem at gmail.com (Otu Ekanem) Date: Thu, 29 Mar 2007 20:55:07 +0100 Subject: Web21C Python SDK - announce Message-ID: <800c1b0b0703291255x16a042b7jbfc982c906a5f9b4@mail.gmail.com> The BT Web21C python SDK is a package which abstract the SOAP/WsSecurity stack from end users allowing them to write python code to access BT plethora of webservices directly. You can use it to make phone calls, conference calls, send text messages (SMS) and locate people based on cell of origin data. I have a short introduction here http://rants.ekanem.de/2007/03/29/make-it-ring-with-python/ and the actual website is at http://web21c.bt.com/ -- Otu Ekanem http://www.ekanem.de -------------- next part -------------- An HTML attachment was scrubbed... URL: From ianmurrays at gmail.com Sun Mar 18 10:41:21 2007 From: ianmurrays at gmail.com (Synt4x) Date: 18 Mar 2007 07:41:21 -0700 Subject: Webcams and python In-Reply-To: References: <1174182674.500068.252550@p15g2000hsd.googlegroups.com> Message-ID: <1174228881.417754.26020@e65g2000hsc.googlegroups.com> On 18 mar, 04:24, Marc 'BlackJack' Rintsch wrote: > In <1174182674.500068.252... at p15g2000hsd.googlegroups.com>, Synt4x wrote: > > from VideoCapture import Device > > cam = Device() > > > while 1: > > img = cam.getImage() > > > Now, by doing this, my processor fires up to 100% load, which > > obviously makes my pc useless. > > > Is there any way or algorithm to lower the cpu load? > > Just throw a small `time.sleep()` into the loop. > > Ciao, > Marc 'BlackJack' Rintsch The problem with adding a sleep() instrucction is that the "video feed" looks lagged, if you know what I mean. It looks interrupted. From http Sat Mar 10 14:43:56 2007 From: http (Paul Rubin) Date: 10 Mar 2007 11:43:56 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <1173547852.666259@jubilee.claranet.pt> Message-ID: <7xbqj0g9z7.fsf@ruckus.brouhaha.com> Paulo da Silva writes: > May be this is what you want ... > I didn't test it enough ... but seems fine. That's way too complicated. Think about Gerald Flanagan's description of the telegraph poles, and how to implement simply. It is a two liner. From gregturn at mindspring.com Mon Mar 12 15:36:39 2007 From: gregturn at mindspring.com (Goldfish) Date: 12 Mar 2007 12:36:39 -0700 Subject: New to Python In-Reply-To: References: <55kmslF249ihcU1@mid.uni-berlin.de> <1173704503.459048.310560@t69g2000cwt.googlegroups.com> <55l63sF252nesU1@mid.uni-berlin.de> Message-ID: <1173728198.924296.287410@64g2000cwx.googlegroups.com> I read http://diveintopython.org/ online, and covered a lot of Python territory nicely with this. Greg From steve at holdenweb.com Wed Mar 21 21:24:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Mar 2007 21:24:04 -0400 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: References: Message-ID: Marcin Ciura wrote: > Steven D'Aprano wrote: >>>>> x, y, z = 1, 2, 3 >>>>> x = y = z >>>>> x, y, z >> (3, 3, 3) >> >> I certainly wouldn't expect to get (2, 3, 3). > > Neither would I. I must have expressed myself not clearly enough. > Currently > x = y = z > is roughly equivalent to > x = z > y = z > I propose to change it to > y = z > x = z > Cheers, > Marcin The difference being ... ? -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From mail at microcorp.co.za Wed Mar 14 03:15:40 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 14 Mar 2007 09:15:40 +0200 Subject: number generator References: Message-ID: <020601c7660c$b29999c0$03000080@hendrik> "Steven D'Aprano" wrote: > > Consider the distance between each paid of consecutive poles. The sum of > the distances must add up to the distance from the first to the last, and > if there are two fixed poles plus five in between, there are five > distances. No there are six distances - the fifth pole has to fit in the same hole as the last fixed one for there to be five. - Hendrik From steve at REMOVE.THIS.cybersource.com.au Tue Mar 20 09:45:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Mar 2007 00:45:38 +1100 Subject: Bullet proof passing numeric values from NMEA data stream. References: Message-ID: On Wed, 21 Mar 2007 00:29:00 +1100, Steven D'Aprano wrote: > All your examples include spurious whitespace. If that is the only > problem, here's a simple fix: > > def despace(s): > """Remove whitespace from string s.""" > return Gah! Ignore that stub. I forgot to delete it :( While I'm at it, here's another solution: simply skip invalid values, using a pair of iterators, one to collect raw values from the device and one to strip out the invalid results. def raw_data(): """Generator to collect raw data and pass it on.""" while 1: # grab a single value value = grab_data_value_from_somewhere() if value is "": # Some special "END TRANSMISSION" value. return yield value def converter(stream): """Generator to strip out values that can't be converted to float.""" for value in stream: try: yield float(value) except ValueError: pass values_safe_to_use = converter(raw_data()) for value in values_safe_to_use: print value Naturally you can extend the converter to try harder to convert the string to a float before giving up. -- Steven. From andi.clemens at gmx.net Thu Mar 1 10:37:25 2007 From: andi.clemens at gmx.net (andi.clemens at gmx.net) Date: 1 Mar 2007 07:37:25 -0800 Subject: How to update DNS record In-Reply-To: References: <1172751262.972242.215990@p10g2000cwp.googlegroups.com> Message-ID: <1172763444.358192.237770@j27g2000cwj.googlegroups.com> Hi, I'm just a trainee working here and I don't really know how the old Perl script worked. But I can post the function, maybe you can recognize what is going on there: my $domain = "wiv-dom.com"; my $nameserver = "bldc01.wiv-dom.com"; sub makeDNSEntry { my $res = new Net::DNS::Resolver; my $query = $res->query("$domain", "NS"); if ($query) { print "\nMaking entries into nameserver...\nSearching for nameservers...\n\n" if $opt{d}; foreach my $rr ($query->answer) { next unless $rr->type eq "NS"; print $rr->nsdname, "\n" if $opt{d}; } } else { print "query for Nameserver for $domain failed: ", $res- >errorstring, "\n"; } my $update = new Net::DNS::Update("$domain"); $update->push("pre", yxrrset("$snmpHostName.$domain. A")); $update->push("update", rr_del("$snmpHostName.$domain. A")); $update->push("update", rr_add("$snmpHostName.$domain. 3600 A $outbound")); $res = new Net::DNS::Resolver; $res->nameservers("$nameserver"); print "\nNameserver for $domain :" . $nameserver, "\n" if $opt{d}; my $reply = $res->send($update); if (defined $reply) { if ($reply->header->rcode eq "NOERROR") { print "Update for $snmpHostName.$domain. OK\n" if $opt{d}; } else { print "Update for $snmpHostName.$domain. ERROR : ". $reply- >header->rcode. "\n" if $opt{d}; } } else { print "RESERROR : No reply: ". $res->errorstring. "\n"; } } What I want to do is change the A-Record of existing entries in the DNS server. I'm getting all the IPs from a django database and ask them via SNMP what their outbound address is, then I want to change those settings in our DNS server like in the perl script above. Sorry for my bad explanation, but I never worked with DNS before... Andi From __peter__ at web.de Fri Mar 30 13:29:19 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Mar 2007 19:29:19 +0200 Subject: clean up html document created by Word References: <1175275249.200620.76590@o5g2000hsb.googlegroups.com> Message-ID: jd wrote: > I am looking for python code (working or sample code) that can take an > html document created by Microsoft Word and clean it up (if you've > never had to look at a Word-generated html document, consider yourself > lucky ;-) Alternatively, if you know of a non-python solution, I'd > like to hear about it. The non-python solution: http://www.w3.org/People/Raggett/tidy/ Peter From duncan.booth at invalid.invalid Fri Mar 23 08:19:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Mar 2007 12:19:15 GMT Subject: "finally" for unit test References: <1174648739.464811.7150@y80g2000hsf.googlegroups.com> Message-ID: "killkolor" wrote: > I have a unittest framework that tests a single function that in turn > works with files (takes input and outputs in the same file, no return > values). I would want to split that function into two: a) one which does the processing, but not working with a file, b) and one which handles reading and calls the processing function and then writes the file. The function it calls would be passed in as an optional parameter and defaults to function (a) Then you need two sets of tests: one to test the action of reading data from a file and then rewriting the output in-place, but you just pass in a mock function for the processing which can assert that it saw the expected inputs. and as many tests as you want for the processing, but no annoying files to get in the way. If you really cannot have the processing without reading from a file, then let it take two files, input and output as parameters, and have the (b) function choose between calling it with separate input/output files or creating a temporary file which is renamed to replace the original on completion. Then at least you can read directly from the test inputs without ever needing to write them. From steve at REMOVEME.cybersource.com.au Thu Mar 22 02:48:29 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 17:48:29 +1100 Subject: Technical Answer - Protecting code in python References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> Message-ID: On Thu, 22 Mar 2007 09:11:51 +1100, Ben Finney wrote: > "Steven D'Aprano" writes: > >> Is your program valuable? Is it worth money? Then the 90% of script >> kiddies will just wait three days, and download the program off the >> Internet after the real hackers have broken your protection. > > The real hackers wouldn't be doing that. > > The crackers, however, might. I quote Bruce Schneier: [quote] For years I have refused to play the semantic "hacker" vs. "cracker" game. There are good hackers and bad hackers, just as there are good electricians and bad electricians. "Hacker" is a mindset and a skill set; what you do with it is a different issue. [end quote] See his essay on "What is a hacker" here: http://www.schneier.com/blog/archives/2006/09/what_is_a_hacke.html In addition, virtually nobody outside of the IT hacker subculture knows what you're talking about if you talk about crackers. Out network was brought down by a biscuit??? -- Steven D'Aprano From rodin.alexander at gmail.com Wed Mar 14 14:46:15 2007 From: rodin.alexander at gmail.com (inline) Date: 14 Mar 2007 11:46:15 -0700 Subject: Constructor of object In-Reply-To: References: <1173894809.887357.165290@p15g2000hsd.googlegroups.com> Message-ID: <1173897975.419864.306930@b75g2000hsg.googlegroups.com> On Mar 14, 9:05 pm, Thinker wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > inline wrote: > > Hello! I want to assign self to object of parent class in > > constructor, like > > > def my_func(): ... return ParentClass() > > > class MyClass (ParentClass): def __init__(self): self = my_func() > > > but it not work, because "object not initialized". What i can do? > > Do you want to call constructor of super-class to initialize the object? > If it is true, you have following options. > > In old style class: > class MyClass(ParentClass): > def __init__(self): > ParentClass.__init__(self) > > In new style class: > class MyClass(ParentClass): > def __init__(self): > super(MyClass).__init__(self) > > Or > class MyClass(ParentClass): > def __init__(self): > super(MyClass, self).__init__() > > - -- > Thinker Li - thin... at branda.to thinker... at gmail.comhttp://heaven.branda.to/~thinker/GinGin_CGI.py > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (FreeBSD) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iD8DBQFF+Dls1LDUVnWfY8gRAvDaAKDVmX8LmuWUdJ4eVil7l//rjCQZLQCg8dO8 > Y77CL1ikmtdl6S3HD04GWiA= > =mvSe > -----END PGP SIGNATURE----- I know it, but i don't want call constructor of parent class - I use PyGTK and want to load window from glade file and assign it to object, parented gtk.Window: #!/usr/bin/env python import gtk import gtk.glade class HelloWindow (gtk.Window): def __init__(self): xml = gtk.glade.XML("hello.glade") xml.signal_autoconnect(self) self = xml.get_widget("window") window = HelloWindow() window.connect("delete_event", gtk.main_quit) window.show_all() gtk.main() From sgeiger at ncee.net Sun Mar 18 19:12:20 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Sun, 18 Mar 2007 18:12:20 -0500 Subject: where function In-Reply-To: <1174259087.255048.286170@l77g2000hsb.googlegroups.com> References: <1174256372.038474.274140@n59g2000hsh.googlegroups.com> <1174258135.009452.192960@e1g2000hsg.googlegroups.com> <1174259087.255048.286170@l77g2000hsb.googlegroups.com> Message-ID: <45FDC754.4080304@ncee.net> a = [0,1,2,3,4,2,8,9] # method 1 print [i for i in xrange(len(a)) if a[i]==2] def where(a,val): return [i for i in xrange(len(a)) if a[i]==val] # method 2 print where(a,2) vorticitywolfe at gmail.com wrote: > On Mar 18, 10:48 pm, bearophileH... at lycos.com wrote: > >> vorticitywo: >> >> >>> Is there a function in Python analogous to the "where" function in >>> IDL? >>> >> Python gives very elastic syntax, you can simply do: >> >> data = [0,1,2,3,4,2,8,9] >> print [pos for pos, el in enumerate(data) if el==2] >> >> Bye, >> bearophile >> > > Thank you both, a little more cumbersome than I expected, but it does > the job! Thanks! > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From goodTweetieBird at hotmail.com Wed Mar 21 15:47:06 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 21 Mar 2007 12:47:06 -0700 Subject: Printing __doc__ Message-ID: <1174506426.108098.243940@d57g2000hsg.googlegroups.com> Greetings, Don't know the daily limit for dumb questions so I will ask one or more. In a function I can use the statement n = sys._getframe().f_code.co_name to get the name of the current function. Given that I can get the name how can I print the __doc__ string? I cant use the following, it will tell me to bugger off as the string has no such attribute. def spam(self): n = sys._getframe().f_code.co_name print n.__doc__ #Wrong print __doc__ #No good either #.... thanx, gtb From gagsl-py2 at yahoo.com.ar Wed Mar 7 16:45:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 18:45:15 -0300 Subject: catching exceptions from an except: block References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <45EF260C.6000205@websafe.com> <45ef2e12$0$28891$426a74cc@news.free.fr> Message-ID: En Wed, 07 Mar 2007 19:00:59 -0300, Bruno Desthuilliers escribi?: > this kind of cose is exactly what OO polymorphic dispatch is supposed to this kind of cose? Ce genre de chose? -- Gabriel Genellina From dartsch at dicad.de Sun Mar 25 07:35:54 2007 From: dartsch at dicad.de (dartsch at dicad.de) Date: 25 Mar 2007 04:35:54 -0700 Subject: Strange behavior when printing a returned closure function In-Reply-To: References: <1174820392.652008.123550@y80g2000hsf.googlegroups.com> Message-ID: <1174822553.986885.91640@p77g2000hsh.googlegroups.com> On Mar 25, 1:04 pm, Jean-Paul Calderone wrote: > On 25 Mar 2007 03:59:52 -0700, dart... at dicad.de wrote: > > > > >Hello, > > >when I execute the following code (python 2.5) > > >def f(x): > > def g(): > > return x > > return g > > >print f(1) > >print f(2) > > >I get an output like > > > > > > > >So according to print I get the same function object returned at both > >calls. > >That's surprising, I would expect to get two distinct function objects > >because their func_closure attribute has to be different. And indeed, > >if I do > > >print f(1) is f(2) > > >instead, it prints False. Even more confusing, if I do > > >g1 = f(1) > >g2 = f(2) > >print g1 > >print g2 > > >I get something like > > > > > > > >ie. two distinct function objects are printed. > > >What's happening here? > >Some clever optimization reusing function objects in special cases or > >what ...? > > They're _not_ the same function object, just like the `is' test told you. > They just happen to have been allocated at the same memory address. > > Jean-Paul ah yes, I see, thanks From aleax at mac.com Thu Mar 29 21:58:45 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Mar 2007 18:58:45 -0700 Subject: Modal value of an array References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> <877it0u2h4.fsf@benfinney.id.au> <1hvpovd.1anin2by4gjl1N%aleax@mac.com> <1175208296.769865.186480@r56g2000hsd.googlegroups.com> Message-ID: <1hvr34h.12c953hpq7pavN%aleax@mac.com> Paddy wrote: ... > > A bit more directly: > > > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > > >>> max(foo, key=foo.count) > > > > 'spam' > > > > Alex > > This doesn't call foo.count for duplicate entries by keeping a cache > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >>> def cachecount(x, cache={}): > ... return cache.setdefault(x, foo.count(x)) > ... > >>> max(foo, key=cachecount) > 'spam' > >>> cachecount.func_defaults > ({'eggs': 2, 'beans': 1, 'spam': 4},) > >>> If you're willing to do that much extra coding to save some work (while still being O(N squared)), then the further small extra needed to be O(N) starts looking good: counts = collections.defaultdict(int) for item in foo: counts[item] += 1 max(foo, key=counts.get) Alex From gregturn at mindspring.com Tue Mar 6 14:55:41 2007 From: gregturn at mindspring.com (Goldfish) Date: 6 Mar 2007 11:55:41 -0800 Subject: Interface Implementation in Python In-Reply-To: References: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> Message-ID: <1173210940.884656.158180@t69g2000cwt.googlegroups.com> > > I would like to know the interface concept in Python.How the > > Interface is defined and implemented in Python?. One way I have implemented interfaces, is as follows: class MyInterface(object): def someMethod(self, argument): raise NotImplementedError() If anybody ever uses that class directly, or subclasses it without implementing a real version of that method, a runtime error can be expected. This bridges both interfaces and abstract classes. As others have pointed out, this isn't quite like a Java interface, but I have found it useful to state my intentions up front, and that is how I do it. The only way to truly enforce this is by following up with lots of good test cases, run often. From aahz at pythoncraft.com Wed Mar 21 18:25:42 2007 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2007 15:25:42 -0700 Subject: Garbage collection References: Message-ID: In article , Nick Craig-Wood wrote: >Steven D'Aprano wrote: >> >> Or you could just have an "object leak" somewhere. Do you have any >> complicated circular references that the garbage collector can't resolve? >> Lists-of-lists? Trees? Anything where objects aren't being freed when you >> think they are? Are you holding on to references to lists? It's more >> likely that your code simply isn't freeing lists you think are being freed >> than it is that Python is holding on to tens of megabytes of random >> text. > >This is surely just the fragmented heap problem. Possibly. I believe PyMalloc doesn't have as much a problem in this area, but off-hand I don't remember the extent to which strings use PyMalloc. Nevertheless, my bet is on holding references as the problem with doubled memory use. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From bj_666 at gmx.net Fri Mar 16 04:18:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 16 Mar 2007 09:18:33 +0100 Subject: To count number of quadruplets with sum = 0 References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <7x6491k9t3.fsf@ruckus.brouhaha.com> Message-ID: In <7x6491k9t3.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > "n00m" writes: >> h = collections.defaultdict(itertools.repeat(0).next) > > Something wrong with > h = collections.defaultdict(int) > ????? According to a post by Raymond Hettinger it's faster to use that iterator instead of `int`. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Mon Mar 19 13:59:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Mar 2007 10:59:54 -0700 Subject: tracking memory usage In-Reply-To: <45febb7f$1@nntp.zianet.com> References: <45febb7f$1@nntp.zianet.com> Message-ID: <1174327194.714032.327180@y66g2000hsf.googlegroups.com> On Mar 19, 11:34 am, "Erik Johnson" wrote: > Sort of two questions here: > > The first is about the internal view: are there Python introspection > functions that can be called such that a running script can keep tabs on how > much memory is being used? > > And the second is about using either os or system calls on Windows such > that a Python script could get similar information about other processes > (i.e., external)? > > Thanks, > -ej >From what I've found, it would seem that this is in development. See the following: http://svn.python.org/projects/python/branches/bcannon-sandboxing/PEP.txt I also found a cool recipe for doing some of what you want, but it's only been tested on Linux. You might be able to modify it for your needs, if you don't mind delving into process ids: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 Good luck! Mike From anil.jupiter9 at gmail.com Sat Mar 10 10:36:21 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 10 Mar 2007 07:36:21 -0800 Subject: Database module & multithreading In-Reply-To: References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> Message-ID: <1173540981.532013.29060@c51g2000cwc.googlegroups.com> On Mar 10, 8:16 pm, Michael Bentley wrote: > > Thanx for this pointer buddy! I have done my homework. Some Database > > modules are not actively maintained some modules does not work with > > Python 2.5. At this moment I am using Sqlite3 which is pretty fast but > > it dosent allow me to use multi threading so which database module is > > better in terms of multithreading > > Actually, I think sqlite3 just requires that each thread have its own > connection and cursor. I tried this approach with for each new thread self.c1=sqlite3.connect('urls') self.c=self.c1.cursor() check condition insert if true else ignore but no success From B.Ogryczak at gmail.com Wed Mar 21 12:17:36 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 21 Mar 2007 09:17:36 -0700 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) In-Reply-To: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Message-ID: <1174493856.663144.236880@y80g2000hsf.googlegroups.com> On Mar 21, 3:38 pm, "dmitrey" wrote: > Hi all, > I looked to the PEPs & didn't find a proposition to remove brackets & > commas for to make Python func call syntax caml- or tcl- like: instead > of > result = myfun(param1, myfun2(param5, param8), param3) > just make possible using > result = myfun param1 (myfun2 param5 param8) param3 How would you write "a = b(c())"? In my opinion it'll make code extremely obfuscaded. The great thing about Python, when comparing with eg. Perl or C, is that code is readable, even if written by experienced hacker. From attn.steven.kuo at gmail.com Sun Mar 25 18:52:13 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 25 Mar 2007 15:52:13 -0700 Subject: call to function by text variable In-Reply-To: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: <1174863133.266803.33190@n59g2000hsh.googlegroups.com> On Mar 25, 3:36 pm, "ianar?" wrote: > yeah the subject doesn't really make sense does it? > > anyway want I want to do is this: > if n == 1: > > self.operations.insert(pos, operations.Replace.Panel(self, main)) > > elif n == 2: > > self.operations.insert(pos, operations.ChangeCase.Panel(self, > main)) > > elif n == 3: > > self.operations.insert(pos, operations.Move.Panel(self, main)) > > As you can see all the different functions have the same variables, so > it would be easier if I could just make a list and use that. > # Your list would contain the unbound functions: unbound_funcs = [operations.Replace.Panel, operations.Change.Panel, operations.Move.Panel] # and invocation would be: self.operations.insert(pos, unbound_funcs[n - 1](self, main)) -- Hope this helps, Steven From richardjones at optushome.com.au Sat Mar 24 20:15:43 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sun, 25 Mar 2007 10:15:43 +1000 Subject: Python Game Programming Challenge #4 -- theme voting has started! Message-ID: <4605bf2f$0$9773$afc38c87@news.optusnet.com.au> The next PyWeek game programming challenge starts next Sunday at 00:00UTC. If you're interested, there's definitely still time to sign up to the challenge. http://www.pyweek.org/ Theme voting has started. You may now log into (or sign up to ;) the PyWeek website to lodge your vote for theme. The themes to choose from are: The only way is up Underneath the radar One way or another Don't stop till you get enough The final countdown Come along and join in the fun :) Richard From skip at pobox.com Mon Mar 19 19:15:37 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 19 Mar 2007 18:15:37 -0500 Subject: struct.pack returns nothing [3] In-Reply-To: <20070319223241.GA21961@mail.lacordilleraandina.com.ar> References: <1174331199.134156.105430@n59g2000hsh.googlegroups.com> <20070319223241.GA21961@mail.lacordilleraandina.com.ar> Message-ID: <17919.6553.505727.249115@montanaro.dyndns.org> Andr?s> I'm using the example of the site Andr?s> http://docs.python.org/lib/module-struct.html : Andr?s> import struct Andr?s> pack('hhl', 1, 2, 3) Andr?s> I should get: >>>> '\x00\x01\x00\x02\x00\x00\x00\x03' Andr?s> I get an empty line, a '\n': >>>> >>>> _ Try import struct struct.pack('hhl', 1, 2, 3) or from struct import pack pack('hhl', 1, 2, 3) instead. Skip From MonkeeSage at gmail.com Mon Mar 5 17:38:09 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 14:38:09 -0800 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <1173131863.216300.109120@s48g2000cws.googlegroups.com> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> <45ec89a4$0$2349$426a74cc@news.free.fr> <1173131863.216300.109120@s48g2000cws.googlegroups.com> Message-ID: <1173134289.131921.110320@h3g2000cwc.googlegroups.com> Adam, Sounds like a nice idea to me. Pretty ingenious use of the zip/ bytecode headers and all too. Post a message when you release it please. Regards, Jordan From aahz at pythoncraft.com Tue Mar 20 09:16:30 2007 From: aahz at pythoncraft.com (Aahz) Date: 20 Mar 2007 06:16:30 -0700 Subject: Still the __new__ hell ... References: <1174167360.522350@jubilee.claranet.pt> <568s5gF287c68U2@mid.individual.net> <1hv8x6v.1x0ceur1nnwi46N%aleax@mac.com> Message-ID: In article <1hv8x6v.1x0ceur1nnwi46N%aleax at mac.com>, Alex Martelli wrote: >Steve Holden wrote: >> >> basestring is a *type*. >> >> >>> basestring >> >> >> It's the base class of which both str and unicode are subclasses. > >I believe it used to be a tuple back in Python 2.2 (sorry, don't have a >Python 2.2 installation to check this right now). 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. >>> basestring Traceback (most recent call last): File "", line 1, in ? NameError: name 'basestring' is not defined -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From bdesth.quelquechose at free.quelquepart.fr Thu Mar 8 15:25:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Mar 2007 21:25:00 +0100 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <1173196128.443793.170900@t69g2000cwt.googlegroups.com> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> <1173193691.204641.206600@s48g2000cws.googlegroups.com> <1173196128.443793.170900@t69g2000cwt.googlegroups.com> Message-ID: <45f0690b$0$18256$426a74cc@news.free.fr> Adam Atlas a ?crit : > Doesn't seem to work. I guess zipimport doesn't support that by > default... but if I remember correctly, Setuptools adds that. Maybe > I'll take a look at how it does it (I think by extracting the .so to / > tmp?) or to another known location, IIRC. > and see how easy it would be to integrate it here. > From codecraig at gmail.com Fri Mar 9 15:45:54 2007 From: codecraig at gmail.com (abcd) Date: 9 Mar 2007 12:45:54 -0800 Subject: How to Start a (thread?) and Leave In-Reply-To: <1173472226.698504.147260@h3g2000cwc.googlegroups.com> References: <1173471722.668943.126700@h3g2000cwc.googlegroups.com> <1173471925.876213.170820@j27g2000cwj.googlegroups.com> <1173472226.698504.147260@h3g2000cwc.googlegroups.com> Message-ID: <1173473154.354891.97530@t69g2000cwt.googlegroups.com> > But a thread leaves the script running until the thread exits, right? > So the webpage would just keep saying "loading" at the bottom I think. > > -Greg give it a shot. if you spawn off a new thread your code should keep executing while the thread does its work in the "background". From john.pye at gmail.com Wed Mar 21 02:12:45 2007 From: john.pye at gmail.com (John Pye) Date: 20 Mar 2007 23:12:45 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> Message-ID: <1174457565.500159.58060@n59g2000hsh.googlegroups.com> On Mar 21, 4:49 pm, "Carl Douglas" wrote: > 1) Rebuild Python with a different compiler/linker kit so it links to > the same CRT as my project, in your case find a mingw built Python.dll > > 2) Rebuild [with MSVC] OK, so let's say that I must support EXISTING installations of Python 2.4 on computers I have no control over. And let's say that I detest MSVC and want to push on with MinGW at all costs. What then? I read something about being using '-lmsvcrt71' or '-lmsvcrt' with GCC...? JP From ptmcg at austin.rr.com Thu Mar 1 02:13:40 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Feb 2007 23:13:40 -0800 Subject: Reading csv files using SQL In-Reply-To: <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> References: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> Message-ID: <1172733220.231503.302520@8g2000cwh.googlegroups.com> On Mar 1, 12:30 am, Pablo was Paolo wrote: > Hi, > > Dennis Lee Bieber ha scritto: > > > You could maybe use SQLite to load the CSV file and process in an > > actual DBMS... > > Ok, this is the solution I'm using actually (with PostGres). > My hope is to find a way to do the same thing without using a DBMS but > working directly with the files. > > Thanks a lot, > Paolo Sqlite has an in-memory option, so that you can read in your csv, then load into actual tables. sqlite is really lightweight, you are using postgres now but sqlite in- memory will get you a lot further than writing your own SQL processor. -- Paul From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Mar 9 05:51:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 09 Mar 2007 11:51:53 +0100 Subject: Python in a Nutshell v2.5 shortcomings (was: Python books?) References: <1huohke.qr9btd1mo633vN%aleax@mac.com> Message-ID: <55cshjF23meg4U3@mid.individual.net> Alex Martelli wrote: > I do know that the 2nd edition of Python in a Nutshell tries to do > so, but falls quite a bit short on a number of important new > additions to the library Which, if I may ask? Regards, Bj?rn -- BOFH excuse #221: The mainframe needs to rest. It's getting old, you know. From sri1025 at gmail.com Thu Mar 8 00:37:51 2007 From: sri1025 at gmail.com (Srikanth) Date: 7 Mar 2007 21:37:51 -0800 Subject: Problem with Packages Message-ID: <1173332271.733596.159790@p10g2000cwp.googlegroups.com> Hi, I am learning about Python packages and I am getting an ImportError but I can't figure out the reason why. I have three modules and they are stored in a directory hierarchy as: my_apps | |--> mod3.py |--> dir1/dir1_1/mod1.py |--> dir2/dir2_2/mod2.py mod1.py defines a function called add(num1, num2) and mod2.py defines a function called multiply(num1, num2) and mod3.py makes use of the two functions defined in mod1.py and mod2.py and mod3.py's contents is as follows: ----------------------------------------------- from dir1.dir1_1 import mod1 from dir2.dir2_2 import mod2 def main(): print mod1.add(10, 34) print mod2.multiply(3, 6) if __name__ == "__main__": main() ---------------------------------------------- And the directory my_apps is included in PYTHONPATH environment variable, what am I doing wrong? I executed this code under PyDev and it's working perfectly but when I run it outside of PyDev, it fails. This is command I used to execute mod3.py: C:\> python C:\my_apps\mod3.py But I get the following error: Traceback (most recent call last): File "c:\my_apps\mod3.py", line 1, in ? from dir1.dir1_1 import mod1 ImportError: No module named dir1.dir1_1 Thanks, Srikanth From m_tayseer82 at yahoo.com Sun Mar 18 12:21:49 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Sun, 18 Mar 2007 09:21:49 -0700 (PDT) Subject: encoding - arabic(IBM 864) to UNICODE In-Reply-To: <1174221139.794726.224860@o5g2000hsb.googlegroups.com> Message-ID: <45636.13215.qm@web31107.mail.mud.yahoo.com> text_864 = "\xd1" unicode_string = unicode(text_864, encoding="cp864") # cp864 = IBM 864 The above code is working with Python 2.4. Unfortunately, it doesn't support IBM 420 & Nafitha. The mapping between IBM 864 and unicode is in Lib/encodings & the file is very simple. You can add your own easily, if you knew how to do the decoding first ;) Mohammad Tayseer http://spellcoder.com/blogs/tayseer --------------------------------- Don't be flakey. Get Yahoo! Mail for Mobile and always stay connected to friends. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wojciech_mula at poczta.null.onet.pl.invalid Sun Mar 25 18:48:19 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Mon, 26 Mar 2007 00:48:19 +0200 Subject: call to function by text variable In-Reply-To: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: ianar? wrote: > like this: > > > list = ["Replace", "ChangeCase", "Move"] > textVariable = list[n] > self.operations.insert(pos, operations.[textVariable].Panel(self, > main)) > > Is something sort of like that possible? Yes: self.operations.insert( pos, getattr(operations, textVariable).Panel(self.main) ) From lialie at gmail.com Wed Mar 14 22:34:44 2007 From: lialie at gmail.com (lialie) Date: Thu, 15 Mar 2007 10:34:44 +0800 Subject: Too slow to read an entire table from Microsoft Access Message-ID: <45F8B0C4.1080503@gmail.com> Hi, all: I read a table with 4500 rows and 12 columns using win32com.client. Reading and updating records are OK, but cost too much time.Especially making a dict as line(***). All follows done may take nearly 90s! Is there any good idea? Thanks. conn = win32com.client.Dispatch(r'ADODB.Connection') DSN='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+DB_FILE_PATH+';Persist Security Info=False;' conn.Open(DSN) record_set = win32com.client.Dispatch(r'ADODB.Recordset') record_set.Open('[Detail]', conn, 1, 3) record_set.MoveFirst() while not record_set.EOF: tmp = ((record_set.Fields(i).Name, record_set.Fields.Item(i).Value) for i in range(record_set.Fields.count)) print dict(tmp) -----------------------------------------------------------------(***) record_set.MoveNext() From starGaming at gmail.com Wed Mar 21 15:41:47 2007 From: starGaming at gmail.com (starGaming at gmail.com) Date: 21 Mar 2007 12:41:47 -0700 Subject: #!/usr/bin/env python > 2.4? In-Reply-To: References: <1174407745.208492.264020@l75g2000hse.googlegroups.com> <1174415242.455972.51400@d57g2000hsg.googlegroups.com> Message-ID: <1174506107.863399.7970@l75g2000hse.googlegroups.com> On Mar 21, 11:07 am, Jon Ribbens wrote: > In article , Stargaming wrote: > > from sys import version_info > > if version_info[0] < 2 or version_info[1] < 4: > > raise RuntimeError("You need at least python2.4 to run this script") > > That'll fail when the major version number is increased (i.e. Python 3.0). > > You want: > > if sys.hexversion < 0x020400f0: > ... error ... Yes, it was intended to be and 'and' instead of an 'or'. From sickcodemonkey at gmail.com Thu Mar 15 23:10:35 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 15 Mar 2007 23:10:35 -0400 Subject: Python Eggs on Cygwin In-Reply-To: <1174005208.972118.104860@l77g2000hsb.googlegroups.com> References: <1174005208.972118.104860@l77g2000hsb.googlegroups.com> Message-ID: <2adc542f0703152010k3801ec5er631e96460a1279cd@mail.gmail.com> Just by looking at the "permission denied" error, when you loaded the MySQLdb module, were you using a specific user (is it owned by a specific user)? On 15 Mar 2007 17:33:29 -0700, nisimura at gmail.com wrote: > > Hi, > > I'm trying to use MySQL Python module on Cygwin. Since there is no > binary package, I compiled MySQL C client library and Python module > (http://sourceforge.net/projects/mysql-python) manually. > > But when I was trying to load MySQLdb module, following errors > happened. > > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/MySQLdb/__init__.py", line > 19, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 7, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 6, in > __bootstrap__ > ImportError: Permission denied > > This seems to be Eggs/Cygwin problem. Is there any solution? > > Regards, > > -- > Kazu Nisimura > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Stuart.Taylor at disney.com Fri Mar 16 06:27:48 2007 From: Stuart.Taylor at disney.com (Taylor, Stuart) Date: Fri, 16 Mar 2007 06:27:48 -0400 Subject: Readline() In-Reply-To: <1E3F89921C854A49B8307B9716633F0105A516C1@SM-GBLO-XM32.emea.wdpr.disney.com> Message-ID: <1E3F89921C854A49B8307B9716633F0105A516C4@SM-GBLO-XM32.emea.wdpr.disney.com> for anyone who gets this same problem i managed to resolve the issue using two threads. The main program spawned a subprocess and used readlines to read the output. The process spawned was a script which executes a command using a thread. The thread reads the output from this command using readline. Within the main loop of the script there is a while loop which checks when the last output from the command was and if the time elapsed is greater than timeout the script prints to the stdout a string called timeout. In the main program the readline compares every output to see if it matches this sting. if it does kill process :) I'm sure this code could be implemented better but it works and got me out of a hole heres the thread script which contains the thread class and the time out loop: import datetime import time import threading import subprocess import os import sys class outputThread(threading.Thread): """ Thread is used to print the output of a command to the stdout """ def __init__(self,threadCommand, name="thread", *args, **kwargs): threading.Thread.__init__(self, *args, **kwargs) self.name = name self.killed = 0 self.counter = 0 self.command = threadCommand self.retval = None self.Set_Hit() def run(self): self.Proc = subprocess.Popen(self.command, cwd = os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) self.retval = None self.Set_Hit() while self.retval == None and not self.killed: line = self.Proc.stdout.readline() print line.rstrip("\r\n") sys.stdout.flush() self.Set_Hit() self.retval=self.Proc.poll() def Set_Hit(self): self.last_time = datetime.datetime.now() def Get_Hit(self): return self.last_time if __name__ == "__main__": """ This script is designed to put a timeout loop over a thread. The intention of this thread is to perform a command and have a timer loop over checking for the last text ouput from the command. If the loop exceeds the set time limit the command will stop reading the output from the thread """ command = [] timeout = 5 maxCounter = timeout curCounter = 0 strCounter = 0 if len(sys.argv) > 2: try: timeout = int(sys.argv[1]) except: print "time out value is not a float" sys.exit(1) for argPos in range(2,len(sys.argv)): print "arg = %s" % sys.argv[argPos] command.append(sys.argv[argPos]) else: print "not enough arguments" sys.exit(1) thread1 = outputThread(command,name="thread1") thread1.start() while True: if not thread1.retval == None: sys.exit(0) #Get current time and when timeout should occur currentTime = datetime.datetime.now() elapsedTime = thread1.Get_Hit() + datetime.timedelta(minutes=timeout) #Check Elapsed time if elapsedTime < currentTime: print "timed out" sys.stdout.flush() break time.sleep(1) ________________________________ From: Taylor, Stuart [mailto:Stuart.Taylor at disney.com] Sent: 13 March 2007 09:50 To: Sick Monkey; Taylor, Stuart Cc: python-list at python.org Subject: RE: Readline() i have a thread class which should read the output from the procedure line by line and finish when the thread is set to kill: class KillableThread(threading.Thread): def __init__(self, name="thread", *args, **kwargs): threading.Thread.__init__(self, *args, **kwargs) self.name = name self.killed = 0 def kill(self): self.killed = 1 def run(self): self.id = threading._get_ident() self.Proc = subprocess.Popen(["python","-tt","output_file.py"], cwd = os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) retval= None while retval == None and not self.killed: line = self.Proc.stdout.readline() retval=self.Proc.poll() to replicate my problem the output_file.py requires a user input. i ask for a user input as my thread will sit waiting on self.Proc.stdout.readline(). This is the point i want to have a timeout or be able to end my thread as there is no output from the output_file. The main approch i cannot implement is to be able to kill the thread as it remains hung on readlines() ________________________________ From: Sick Monkey [mailto:sickcodemonkey at gmail.com] Sent: 13 March 2007 01:51 To: Taylor, Stuart Cc: python-list at python.org Subject: Re: Readline() Maybe if you show us your code we can better assist you. But maybe you can use a global variable or a try-catch method to keep threads from staying alive and help better control your code. On 3/12/07, Taylor, Stuart wrote: I have been working on running an external process using subprocess.popen for a few days. The process is ran over the network to another machine. One thing I have found is that if I perform readline() on the stdout it will hang if the process loses connection. I have tried a few things in a test example: one is to use stdin.write then stdin.flush() which send a string that readline() will read and it ends correctly but doesn't work on the project I need it to work on. Another is to try using threads and ignoar the thread when the process has lost connection but this still leaves the open thread alive even when the main app has finished. I am relatively new to python and I may be making a fundemantal mistake in my implementation, can anyone please inform me of whether sticking with subprocess.popen and readline() is the correct procedure for this sort of task? And if anyone can point me in the correct implementation of this problem I would be gratefull. Thank you Stuart -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From inyeol.lee at siliconimage.com Tue Mar 13 11:43:02 2007 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Tue, 13 Mar 2007 08:43:02 -0700 Subject: Best place for a function? In-Reply-To: <45f435db$0$16855$426a74cc@news.free.fr> References: <45f435db$0$16855$426a74cc@news.free.fr> Message-ID: <20070313154301.GA26206@siliconimage.com> On Sun, Mar 11, 2007 at 06:36:02PM +0100, Bruno Desthuilliers wrote: > Inyeol Lee a ?crit : > > On Wed, Mar 07, 2007 at 05:27:04PM -0500, Sergio Correia wrote: > > > >>I'm writing a class, where one of the methods is kinda complex. The > >>method uses a function which I know for certain will not be used > >>anywhere else. This function does not require anything from self, only > >>the args passed by the method. > >> > >>Where should I put the function? > > > > > > Use staticmethod. It's a normal function with class namespace. > > What do you think the OP will gain from making a simple helper function > a staticmethod ? Apart from extra lookup time ? Namespace. Plz check this old thread. It explains some usage of staticmethod. http://mail.python.org/pipermail/python-list/2003-February/190258.html --Inyeol From jjlee at reportlab.com Thu Mar 8 08:02:43 2007 From: jjlee at reportlab.com (John J. Lee) Date: 08 Mar 2007 13:02:43 +0000 Subject: clientcookie/clientform and checking to see if a website accepted my login details References: <1173085655.703034.10390@v33g2000cwv.googlegroups.com> Message-ID: socialanxiety at gmail.com writes: > alright, i'm coding a program that will log me into yahoo.com (so > far), now, the problem i have is that once i've submitted by login & > password, the program doesn't know whether yahoo.com accepted it. > " > response = ClientCookie.urlopen(form.click()) > " > > now, when i get an error, the contents of 'response' will be > different, ex: the contents of 'example' will be > 'logged in!'. is there any function that can search > through the code for that text to check if i'm logged in or not? There's no general way to find out (regardless of whether you're using Python or something else). So: data = response.read() logged_in = 'logged in!' in data if logged_in: print "logged in OK" John From jan.m.danielsson at gmail.com Sun Mar 4 13:15:30 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sun, 04 Mar 2007 19:15:30 +0100 Subject: doxygen Message-ID: <45eb0cc2$1@griseus.its.uu.se> Hello all, I guess I should really be asking in some doxygen mailing list, but since I believe that I found doxygen through this group, I assume that there are some people here who can answer. When I run doxygen on my python files, it does document classes, but not "standalone" functions. I.e.: ----------------------- ## Foobar class # # This is a test class! class Foobar: ## Init # # This is the init function. def __init__(self): pass ----------------------- ... is included, but: ----------------------- ## Test # # This is a test function def TestFunction(foo=None): pass ----------------------- ..is not. Is this by design? Is it possible to get doxygen to include standalone functions? -- Kind regards, Jan Danielsson From deets at nospam.web.de Fri Mar 9 10:23:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 09 Mar 2007 16:23:07 +0100 Subject: Creat a DLL File from python code, and use that DLL file in other Platform (Labview, Java .NET etc) References: <1173441503.965228.95590@j27g2000cwj.googlegroups.com> Message-ID: <55dcerF24n2e8U1@mid.uni-berlin.de> macedo.silva at gmail.com wrote: > Hi, > > I would like to request your attention for this very specific issue: > > I have several classes in Python, and now I want simply re-use it, in > other language. > > > The closest to solution I think I came was with this site: > http://www.py2exe.org/index.cgi/Py2exeAndCtypesComExeServer?highlight=%28%28Py2exeAndCtypesComDllServer%29%29 > but I not able to solve questions related with TLB files and > __init__.py files. > > So, could anyone give a tip about HOW TO CREAT a dll file from Python? You might have success with http://elmer.sourceforge.net/ Diez From deets at nospam.web.de Fri Mar 9 11:11:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 09 Mar 2007 17:11:21 +0100 Subject: opinion needed References: <1173454035.316124.307620@h3g2000cwc.googlegroups.com> Message-ID: <55df99F24658vU1@mid.uni-berlin.de> azrael wrote: > id like to hear your opinion about something. > I just started using Prolog yesterday and i have my doubts about it, > but it seems to me something like object oriented. so i wanted to ask > you how usefull prolog is. Sure this is no prolog newsgroup so my > question is: because it seems object oriented, how important is it by > understanding python and improving my python skills. because i just > started it, i may bee totaly wrong or i missunderstood. OO? Prolog? Last time I checked it was much more functional if anything else, good for searching solutions in problem-spaces via backtracking. Certainly a concept one should get ones head wrapped around, if only to have a new perspective. No idea how you come to the conclusion it's OO though. Diez From gagsl-py2 at yahoo.com.ar Sun Mar 11 07:50:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 08:50:40 -0300 Subject: Database module & multithreading References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> <54CIh.6545$M65.2077@newssvr21.news.prodigy.net> <2uEIh.14274$bb1.6709@newssvr17.news.prodigy.net> Message-ID: En Sun, 11 Mar 2007 07:55:15 -0300, Jon Ribbens escribi?: > In article , > Gabriel Genellina wrote: >>> I don't know, but stock Python 2.5 seems to stick mysterious '.egg' >>> files in the site-packages directory when you install things. >> >> Which "stock" Python? Not the one from www.python.org... > > Yes, the one from www.python.org. Those .egg must come from other installed packages... -- Gabriel Genellina From inq1ltd at verizon.net Tue Mar 20 20:26:33 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Tue, 20 Mar 2007 20:26:33 -0400 Subject: mysterious unicode In-Reply-To: <1174430100.666040.43970@l77g2000hsb.googlegroups.com> References: <1174430100.666040.43970@l77g2000hsb.googlegroups.com> Message-ID: <200703202026.34160.inq1ltd@verizon.net> On Tuesday 20 March 2007 18:35, Gerry wrote: > I'm using pyExcelerator and xlrd to read and > write data from and to two spreadsheets. > > I created the "read" spreadsheet by importing a > text file - and I had no unicode aspirations. > > When I read a cell, it appears to be unicode > u'Q1", say. > > I can try cleaning it, like this: > > > try: > s.encode("ascii", "replace") > except AttributeError: > pass > > > which seems to work. Here's the mysterious > part (aside from why anything was unicode in > the first place): > > print >> debug, "c=", col, > "r=", row, "v=", value, "qno=", qno > tuple = (qno, family) > try: > data[tuple].append(value) > except: > data[tuple] = [value] > print >> debug, "!!!", col, > row, qno, family, tuple, value, data[tuple] > > which produces: > > c= 1 r= 3 v= 4 qno= Q1 > !!! 1 3 Q1 O (u'Q1', 'O') 4 [1, u' ', 4] > > where qno seems to be a vanilla Q1, but a tuple > using qno is (u'Q1', ...). > > Can somebody help me out? I have been getting the same thing using SQLite3 when extracting data fron an SQLite3 database. I take the database info which is in a list and do name = str.record[0] rather than name = record[0] So far, I havn't had any problems. For some reason the unicode u is removed. I havn't wanted to spend the time to figure out why. jim-on-linux http://www.inqvista.com From steve at REMOVE.THIS.cybersource.com.au Thu Mar 29 01:17:00 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 29 Mar 2007 15:17:00 +1000 Subject: which methods to use? References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> <1175130991.799268.311470@n59g2000hsh.googlegroups.com> Message-ID: On Thu, 29 Mar 2007 04:49:17 +0000, Dennis Lee Bieber wrote: > On 28 Mar 2007 18:16:31 -0700, s99999999s2003 at yahoo.com declaimed the > following in comp.lang.python: > > >> what do you mean by create new object when using list comprehensoin or >> list()? Does using slicing create a new object as well? > > If the destination is a bare name, YES. > > If the destination is a slice of a list, then one is merely > replacing the contents in that slice, but leaving the other parts of the > list in place. Maybe so, but the slice doesn't know where it is being assigned to. It still has to generate a new list object, which is then stored in the appropriate part of the left-hand list object. I suppose a sufficiently clever optimizing compiler might not do it that way, but looking at some code with dis.dis() I'm pretty sure Python does create the new list first. -- Steven From deets at nospam.web.de Thu Mar 8 09:51:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Mar 2007 15:51:15 +0100 Subject: Writing xml file from MS SQL References: <1173364968.605132.252770@s48g2000cws.googlegroups.com> Message-ID: <55am73F248suuU1@mid.uni-berlin.de> Ros wrote: > I am using pymssql for storing data into MS SQL. (I am using pymssql > first time so dont know much about it) > I wish to write/create XML file from database. > There are few examples available for mysql but not much information > about pymssql and MS SQL. > > I have worked with cElementTree with SAX and I guess it can parse data > in the most efficient manner if you compare it with other parsers. How > can I use cElementTree to write xml file with the combination of > pymssql(MS SQL) and pyxml. 1) read data from database 2) create XML-Nodes filled with this data 3) write XML-Nodes to disk 4) .... 5) Profit! Diez From sergio.correia at gmail.com Wed Mar 7 18:20:29 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 7 Mar 2007 18:20:29 -0500 Subject: Best place for a function? In-Reply-To: <1173308274.223424.14950@h3g2000cwc.googlegroups.com> References: <558soiF23polgU1@mid.uni-berlin.de> <1173308274.223424.14950@h3g2000cwc.googlegroups.com> Message-ID: I also found out I can't use `unittest` with nested functions :-( Thank you all for the responses, Best, Sergio On 7 Mar 2007 14:57:54 -0800, bearophileHUGS at lycos.com wrote: > Diez B. Roggisch: > > If it really has no other use as in this class, put it as an > > instancemethod in there. Alternatively, you _could_ nest it like this: > > Using an instancemethod may be the most formally correct solution for > that problem, but often nested function are the simpler solution. A > downside of nested functions is that you can't give them a doctest (in > a simple way). > > Bye, > bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sun Mar 18 05:47:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Mar 2007 06:47:01 -0300 Subject: cannot start IDLE in WinXP References: <1174129756.325715.22280@e1g2000hsg.googlegroups.com> Message-ID: En Sat, 17 Mar 2007 08:09:16 -0300, imx escribi?: > Enviroment: WinXP sp2, python 2.5 > problem: click IDLE using shorcut menu or run phthonw.exe directly, > nothing happen! But running python.exe from the command line is fine. pythonw.exe does not open a window so it's almost invisible. IDLE now uses a socket to connect to the subprocess which runs the python code; perhaps your firewall is blocking that connection. Try starting IDLE with the -n switch. -- Gabriel Genellina From mailmaverick666 at gmail.com Tue Mar 20 06:18:40 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Tue, 20 Mar 2007 15:48:40 +0530 Subject: python & java In-Reply-To: <20070320100600.19457.qmail@webmail92.rediffmail.com> References: <20070320100600.19457.qmail@webmail92.rediffmail.com> Message-ID: <180b672e0703200318m4ad29887q53df64961b206672@mail.gmail.com> Jython is written in pure java. You can use java classes inside python and also can use python classes inside java You can write applets too in python using jython. It converts your python code in java code. On 20 Mar 2007 10:06:00 -0000, sandeep patil wrote: > > what diff betn python & jython > > > On Tue, 20 Mar 2007 rishi pathak wrote : > > >See www.*jython*.org > > > >On 20 Mar 2007 02:23:07 -0700, sandeep patil > >wrote: > >> > >>hi > >> > >>i am fresher i python can any bady tell me who i will use python in > >>web technologies in java base application. > >>what it roll > >> > >>sandeep patil > >> > >>-- > >>http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > > >-- Regards-- > >Rishi Pathak > >National PARAM Supercomputing Facility > >Center for Development of Advanced Computing(C-DAC) > >Pune University Campus,Ganesh Khind Road > >Pune-Maharastra > > > > [image: Diageo] -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From Florian.Lindner at xgm.de Mon Mar 5 15:13:03 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 05 Mar 2007 21:13:03 +0100 Subject: Using string as file Message-ID: Hello, I have a function from a library thast expects a file object as argument. How can I manage to give the function a string resp. have the text it would have written to file object as a string? Thanks, Florian From Emile.Boudreau at cognos.com Fri Mar 30 08:54:08 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Fri, 30 Mar 2007 08:54:08 -0400 Subject: Sending emails to 3 addresses.... Message-ID: <09042D621CD4AA479C678463F3A646D0F08353@sottemail1.ent.ad.cognos.com> Hello all, I'm trying to send a results email to 3 people. For some reason only the first person in the list will receive the email but in the received email it shows the 3 addresses. Here is my code, can someone show me where I'm going wrong?? Thanks sendMail('this is the subject line', 'the results: 71 fails, 229 pass, 300 total.', 'user1 at mycompany.com, user2 at mycompany.com, user3 at mycompany.com') def sendMail(subject, body, TO, FROM="machine at mycompany.com"): print TO HOST = "exchange.mycompany.com" BODY = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % subject, "", body ), "\r\n") server = smtplib.SMTP(HOST) server.sendmail(FROM, [TO], BODY) server.quit() Emile Boudreau This message may contain privileged and/or confidential information. If you have received this e-mail in error or are not the intended recipient, you may not use, copy, disseminate or distribute it; do not open any attachments, delete it immediately from your system and notify the sender promptly by e-mail that you have done so. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nanjundi at gmail.com Mon Mar 26 15:32:46 2007 From: nanjundi at gmail.com (Nanjundi) Date: 26 Mar 2007 12:32:46 -0700 Subject: call to function by text variable In-Reply-To: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: <1174937566.897549.62400@e65g2000hsc.googlegroups.com> On Mar 25, 6:36 pm, "ianar?" wrote: > yeah the subject doesn't really make sense does it? > > anyway want I want to do is this: > if n == 1: > > self.operations.insert(pos, operations.Replace.Panel(self, main)) > > elif n == 2: > > self.operations.insert(pos, operations.ChangeCase.Panel(self, > main)) > > elif n == 3: > > self.operations.insert(pos, operations.Move.Panel(self, main)) > > As you can see all the different functions have the same variables, so > it would be easier if I could just make a list and use that. > > like this: > > list = ["Replace", "ChangeCase", "Move"] > textVariable = list[n] > self.operations.insert(pos, operations.[textVariable].Panel(self, > main)) try this one: textVariable = list[n-1] exec( "self.operations.insert(pos, operations.%s.Panel(self, main))" % textVariable ) Not sure if this is an elegant/right way. -N From arnodel at googlemail.com Fri Mar 9 12:56:14 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 9 Mar 2007 09:56:14 -0800 Subject: Pb with descriptor and super ... In-Reply-To: References: Message-ID: <1173462974.511413.195980@30g2000cwc.googlegroups.com> On Mar 9, 11:22 am, Erwan Adam wrote: [snip] > > [adam at is111902 /home/adam/Work/Python]> python super_from_guido.py > Using built-in super > Desc.__get__ : class_name is A, obj is <__main__.B object at 0xb7bc302c> > and typ is > Using python Super > Desc.__get__ : class_name is A, obj is <__main__.B object at 0xb7bc302c> > and typ is None > Using python MySuper > Desc.__get__ : class_name is A, obj is <__main__.B object at 0xb7bc302c> > and typ is It seems to me that it is the built-in super which has the correct behaviour. When you write obj.attr, python calls attr.__get__(obj, type(obj)) and not attr.__get__(obj) which sets the second arg to None. You can check this by creating a barebone descriptor that simply prints its arguments: class D(object): def __get__(self, obj, objtype): print obj, objtype class A(object): d=D() A().d <__main__.A object at 0x133c5f0> # objtype is not None! Therefore in your case when you do super(B, b).attr then A.__dict__['attr'].__get__(b, type(b)) is called. You can try this, it should give the same output as builtin super. > the Super gives None for typ ... which is quite surprising ! > In MySuper, I just change > > x = x.__get__(self.__obj__) > > by > > x = x.__get__(self.__obj__, cls) > at the -3 :) line of the class ... and it gives the result I expected > at the beginning : obj is b and typ is A !!!! Neither of these are right I think. If my explanation above is right the correct line should be: x = x.__get__(self.__obj__, type(self.__obj__)) HTH -- Arnaud From steve at holdenweb.com Thu Mar 22 21:14:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 21:14:30 -0400 Subject: Idiom for running compiled python scripts? In-Reply-To: References: Message-ID: Mark wrote: > So given the lack of response it seems that there is probably no such > idiom and that I should not be concerned by the inefficiency inherent in > running .py scripts directly? > > I did some time tests and sure, the speed gain is slight, but it is a > gain none the less. Someone already told you - compile the files manually (see the compile built-in function) and then use python file.pyc regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From arkanes at gmail.com Mon Mar 12 22:32:41 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Mar 2007 20:32:41 -0600 Subject: a better solution for GUI in python In-Reply-To: <825ee$45f6018a$54d1d767$4649@news.chello.no> References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> <1173613976.277044.242160@8g2000cwh.googlegroups.com> <55iaceF24d6qgU2@mid.individual.net> <825ee$45f6018a$54d1d767$4649@news.chello.no> Message-ID: <4866bea60703121932w41802a75rec7e70ec338dff9e@mail.gmail.com> On 3/12/07, David Boddie wrote: > On Monday 12 March 2007 16:57, Chris Mellon wrote: > > > Gtk I consider an extremely poor contender as a cross platform > > toolkit. The runtime is enormous and it makes little effort to appear > > native on any non-GNOME platform. > > Given that wxPython more or less relies on GTK+ on Linux, I think > you're probably shooting yourself in the foot here, particularly when > you go on to say this: > > > wxPython is also a perfectly reasonable solution, especially if you > > want a "native" seeming app on all platforms. > > All platforms would ideally include KDE, of course. ;-) > Granted, and something that I normally cover but forgot in this thread. The preferred DE of your users is an important issue as well. KDE users will be best (pretty much only, really) served by pyQt, GNOME users by pyGTK or wxPython. From lbates at websafe.com Thu Mar 15 11:17:06 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 15 Mar 2007 10:17:06 -0500 Subject: Multiline code - trailing slash usage In-Reply-To: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> References: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> Message-ID: <45F96372.1010805@websafe.com> abcd wrote: > When do I need to use a trailing slash to separate code over multiple > lines. > > For example: > > x = "hello world, this is my multiline " + \ > "string!!!!" > > x = {'name' : \ > 'bob'} > > Do I need to use the "\" in the above examples? When do i need to use > it? > You need to use it when your are not inside some context that makes it clear to Python that there's more to the line: You don't need it here because python knows you are inside a list (same is true for tuple). a=[1, 2, 3 ] Same for a dictionary: a={'a1': 1, 'a2': 2, 'a3': 3 } Also when you are inside call list of a function a=foo(a,"this is a very long string", arg3, arg4, kwarg1='one', kwarg2='two') Python knows you aren't done because you haven't provided the closing parenthesis. I do this in list comprehensions also: n=[(variable1, variable2) for variable1, variable2 in something if variable1.startswith('z')] You do need it in your first example, but not in your second. -Larry From michael at jedimindworks.com Sat Mar 24 05:44:12 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 24 Mar 2007 04:44:12 -0500 Subject: execution speed increase after compile py code into exe? In-Reply-To: <4604ebe7$0$28985$da0feed9@news.zen.co.uk> References: <4604ebe7$0$28985$da0feed9@news.zen.co.uk> Message-ID: > > Actualy startup is faster for the apps that I have py2exe'd. I think > this may be because all the modules are in one place and Python > doesn't > have to go searching for them. Thanks, Will! That's good to know. From johnjsal at NOSPAMgmail.com Thu Mar 22 14:48:57 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 22 Mar 2007 14:48:57 -0400 Subject: Been a while... In-Reply-To: References: <4602a1be$0$32400$c3e8da3@news.astraweb.com> Message-ID: <4602cf0c$0$29743$c3e8da3@news.astraweb.com> Michael Bentley wrote: > > On Mar 22, 2007, at 10:34 AM, John Salerno wrote: > >> Hi guys. It's been a while since I've used Python, so I got a little >> rusty, but I really want to start using it again, just out of habit and >> for fun. Can anyone suggest a book or a website with little projects I >> could work on to keep me busy? > > http://www.pythonchallenge.com > > Ugh, I gave up on that site a long time ago! :) From duncan.booth at invalid.invalid Thu Mar 22 12:17:16 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Mar 2007 16:17:16 GMT Subject: Python 3000 idea: reversing the order of chained assignments References: Message-ID: Steve Holden wrote: > In other words, > > assignment_stmt ::= (target_list "=") expression_list | > (target_list "=") assignment_stmt > > and > > assignment_stmt ::= (target_list "=") assignment_stmt | > (target_list "=") expression_list > > are entirely equivalent I'm not quite sure what you are getting at. An assigment_stmt and an expression_list are not ambiguous so those two productions are identical (not just equivalent). Perhaps you are thinking of productions like: m_expr ::= u_expr | m_expr "*" u_expr which will match the same input, but could produce a different parser output than: m_expr ::= u_expr | u_expr "*" m_expr > I'm sure you understand that syntax only specifies what's legal, not how > it should be interpreted. I agree that the syntax does not mandate how it should be interpreted, but it does lead to expectations. If the expression_stmt is hidden from the outer assignment_stmt by an inner one then it is reasonable to expect that the inner production will be completely evaluated before the outer assignment happens. i.e. right to left. From ramdaz at gmail.com Wed Mar 7 14:23:52 2007 From: ramdaz at gmail.com (Ramdas) Date: 7 Mar 2007 11:23:52 -0800 Subject: Any HTML to Latex module available in Python Message-ID: <1173295432.212724.231240@n33g2000cwc.googlegroups.com> Any HTML to Latex module available in Python which I can use to convert HTML text to Latex Ramdas From mc_anjo at tamu.edu Mon Mar 26 23:26:43 2007 From: mc_anjo at tamu.edu (Chris Smith) Date: Mon, 26 Mar 2007 22:26:43 -0500 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174923080.941888.198340@p77g2000hsh.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174918286.213517.100190@l77g2000hsb.googlegroups.com> <1174923080.941888.198340@p77g2000hsh.googlegroups.com> Message-ID: Carl Banks wrote: > On Mar 26, 10:11 am, "Andy Dingley" wrote: > >>On 26 Mar, 14:20, "Noma... at gmail.com" wrote: >> >> >>>what are the advantages of using Python for >>>creating number crunching apps over Fortran?? >> >>If you have to ask, you've not experienced enough Fortran to know its >>sheer horror. >> >>You can write programs in Python that do usefully complicated things, >>and you can get them to work in a reasonable time. Fortran can't do >>this, for anything more than the trivial. "Classic" Fortran tasks of >>the past are now seen as trivial. OK, so they did it to a lot of data, >>but they really didn't do anything very complex to it. > > > You couldn't be more incorrect. I have run some very old (pre-Fortran > 77) programs that are very far from trivial. > > >>You can also write Python that other people can read and maintain. You >>can't do this in Fortran, without a truly insane amount of trouble. > > > This is a lie. I've seen some Fortran code that was hellspawned, and > some that was clear as glass. The latter came about without a "truly > insane amount of trouble". > > >>As >>Fortran programs have historically been authored and hacked on by >>successive generations of grad students, this is the most vital >>feature of all. > > > Perhaps this is your impression because it's the only Fortran code > you've ever been exposed to? > > >>Finally we're no longer so interested in "number crunching". Number >>crunching used to consist of simple operations over vast arrays of >>data, although this was data with remarkably simple structure by >>today's standards. These just aren't the major class of problems of >>interest today. > > > I suspect you're speaking from a narrow perspective, because "number > crunching", as you define it, is still a problem of interest and > heavily researched. Maybe it's not in your field. Anyways, you seem > to be ignorant of the complexities of "simple operations over vast > arrays", as if it you could accomplish these operations with a few > lines of Python and numpy. That might be true for your homework, but > good number-crunching codes often did a lot of stuff under the covers. > > Hear hear. Python and Fortran both have their place. I'm a grad student in Electromagnetics (radio frequency research) and I depend a lot on "number crunching" to help me design the latest and greatest rader array to the coolest cell phone that will connect anywhere. I actually use python to speed up my development of codes for Fortran. I prototype some function that I want in python and then use the final draft of it in my fortran code. What used to take several hours I can do in less than one by leveraging both languages for what they're good for, Python for RAD and Fortran for fast number crunching of my research. Chris From sylvain.thenault at logilab.fr Thu Mar 1 04:01:54 2007 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Thu, 1 Mar 2007 10:01:54 +0100 Subject: [ANN] pylint 0.13 / astng 0.17 Message-ID: <20070301090153.GC12447@crater.logilab.fr> Hi there! I'm very pleased to announce new releases of pylint (0.13) and its underlying library astng (0.17). The PyLint release contains a bunch of bugs fixes, some new checks and command line changes, and a new checker dedicated to Restricted Python checking. If this doesn't sound familiar to you, visit the PyPy_ project web site for more information. The astng release contains a lot of inference fixes and enhancement, so even if pylint should still works with the old version you're strongly encouraged to upgrade. .. _PyPy: http://codespeak.net/pypy/ What is pylint ? ---------------- Pylint is a python tool that checks if a module satisfy a coding standard. Pylint can be seen as another pychecker since nearly all tests you can do with pychecker can also be done with Pylint. But Pylint offers some more features, like checking line-code's length, checking if variable names are well-formed according to your coding standard, or checking if declared interfaces are truly implemented, and much more (see http://www.logilab.org/projects/pylint/ for the complete check list). The big advantage with Pylint is that it is highly configurable, customizable, and you can easily write a small plugin to add a personal feature. The usage it quite simple : $ pylint mypackage.mymodule This command will output all the errors and warnings related to the tested code (here : mypackage.mymodule), will dump a little summary at the end, and will give a mark to the tested code. Pylint is free software distributed under the GNU Public Licence. Home page --------- http://www.logilab.org/project/name/pylint http://www.logilab.org/project/name/logilab-astng Download -------- ftp://ftp.logilab.org/pub/pylint ftp://ftp.logilab.org/pub/astng Mailing list ------------ mailto://python-projects at logilab.org Enjoy ! -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From fd0man at gmail.com Fri Mar 9 20:11:26 2007 From: fd0man at gmail.com (Michael B. Trausch) Date: Fri, 09 Mar 2007 20:11:26 -0500 Subject: UTF-8 output problems Message-ID: <1173489086.5567.6.camel@pepper> I am having a slight problem with UTF-8 output with Python. I have the following program: x = 0 while x < 0x4000: print u"This is Unicode code point %d (0x%x): %s" % (x, x, unichr(x)) x += 1 This program works perfectly when run directly: mbt at pepper:~/tmp$ python test.py This is Unicode code point 0 (0x0): This is Unicode code point 1 (0x1): This is Unicode code point 2 (0x2): This is Unicode code point 3 (0x3): This is Unicode code point 4 (0x4): This is Unicode code point 5 (0x5): This is Unicode code point 6 (0x6): This is Unicode code point 7 (0x7): This is Unicode code point 8 (0x8): This is Unicode code point 9 (0x9): This is Unicode code point 10 (0xa): (... continued) However, when I attempt to redirect the output to a file: mbt at pepper:~/tmp$ python test.py >f Traceback (most recent call last): File "test.py", line 6, in print u"This is Unicode code point %d (0x%x): %s" % (x, x, unichr(x)) UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 39: ordinal not in range(128) This is slightly confusing to me. The output goes all the way to the end of the program when it is not redirected. Why is Python treating the situation differently when the output is redirected? This failure occurs for all redirection, by the way: >, >>, 1>2, pipes, and so forth. Any ideas? ? Mike -- Michael B. Trausch fd0man at gmail.com Phone: (404) 592-5746 Jabber IM: fd0man at gmail.com fd0man at livejournal.com Demand Freedom! Use open and free protocols, standards, and software! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- 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 johnjsal at NOSPAMgmail.com Mon Mar 19 10:13:15 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 19 Mar 2007 10:13:15 -0400 Subject: PythonCard thoughts In-Reply-To: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> References: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> Message-ID: <45fe9b31$0$17946$c3e8da3@news.astraweb.com> king kikapu wrote: > The only "problem" i see with this design is that by that separation > of Gui/Code, you loose the intellisense that (ex. PyDev) some editors/ > plugins can provide because in the .py file nothing is indicating > that , for example, the btnDoWork is a Button object. > This force you to remember many properties and switch back and forth > between your code and the wxPython help file. This is not the case for > wxGlade because all boilerplate code is in the same file (for good and > for bad) I don't know much about PythonCard or wxGlade, but I use wxPython (which wxGlade uses, right?) and you now have the option to separate your GUI and code using an XRC file (xml file that describes layout). So perhaps this is something you can do with wxGlade, but at the same time it might still create the problem you describe above. However, it's very to have your Python files contain just logic. From max at alcyone.com Wed Mar 21 15:30:12 2007 From: max at alcyone.com (Erik Max Francis) Date: Wed, 21 Mar 2007 12:30:12 -0700 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) In-Reply-To: <56d2lrF28q269U1@mid.uni-berlin.de> References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> <56d2lrF28q269U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > dmitrey wrote: > >> I looked to the PEPs & didn't find a proposition to remove brackets & >> commas for to make Python func call syntax caml- or tcl- like: instead >> of >> result = myfun(param1, myfun2(param5, param8), param3) >> just make possible using >> result = myfun param1 (myfun2 param5 param8) param3 >> >> it would reduce length of code lines and make them more readable, + no >> needs to write annoing charecters. > > This is not true, there is no shorter code lines: > > foo bar baz > foo(bar,baz) > > And the "more readable" part certainly depends on the habits of the user - > to me, it's harder to read. I agree. Not to mention, the secondary stated goal of saving typing should be very, very low down on the list of priorities in programming language design. Excessive and needless verbosity is one thing; but saving keystrokes for its own sake is not a priority and never should be. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis I am not afraid / To be a lone Bohemian -- Lamya From openopt at ukr.net Wed Mar 21 10:55:08 2007 From: openopt at ukr.net (dmitrey) Date: 21 Mar 2007 07:55:08 -0700 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) In-Reply-To: <1174488447.404840.112960@n76g2000hsh.googlegroups.com> References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> <1174488447.404840.112960@n76g2000hsh.googlegroups.com> Message-ID: <1174488908.420851.303850@y66g2000hsf.googlegroups.com> I think it should result result = func1(func2, arg) if you want result = func1(func2(arg)) you should use result = func1 (func2 arg) if ... = word1 word2 word3 ... then only word "word1" should be call to func "word1" with parameters word2, word3 etc > If you have > result = func1 func2 arg > is it > result = func1(func2, arg) > or > result = func1(func2(arg)) > > Miki http://pythonwise.blogspot.com From kyosohma at gmail.com Tue Mar 27 10:26:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Mar 2007 07:26:50 -0700 Subject: Use threads or Tkinter event loop? In-Reply-To: <11624$4609251b$4275d90a$15349@FUSE.NET> References: <11624$4609251b$4275d90a$15349@FUSE.NET> Message-ID: <1175005610.438509.37260@r56g2000hsd.googlegroups.com> On Mar 27, 9:07 am, Kevin Walzer wrote: > Kevin Walzer wrote: > > I'm trying to decide whether I need threads in my Tkinter application or > > not. My app is a front end to a command-line tool; it feeds commands to > > the command-line program, then reads its output and displays it in a > > Tkinter text widget. Some of the commands are long-running and/or return > > thousands of lines of output. > > > I initially thought I needed to use threading, because the GUI would > > block when reading the output, even when I configured the blocking to be > > non-blocking. I got threading to work, but it seemed a bit complicated. > > So, I decided to try something simpler, by using the Tkinter event loop > > to force the output to update/display. > > > it seems to work well enough. Here is my threaded code: > > > non-threaded: > > > def insertDump(self): > > self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > > for line in self.finkinstalled: > > self.t.insert(END, line) > > self.update() > > self.t.see(END) > > > And here is my non-threaded code (needs two functions to work) > > > def insertDump(self): > > try: > > data = self.dataQueue.get(block=False) > > for line in data: > > self.t.insert(END, line) > > self.t.see(END) > > self.update() > > > except: > > print "error" > > raise > > > def getDump(self): > > > self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > > self.dataQueue.put(self.file) > > > This brings me to a design, as opposed to coding, question. The > > non-threaded version seems to work just as well as the threaded one, in > > terms of speed. Moreover, it is simpler to code and debug, because I > > don't have to check to make sure the thread queue has data (I sometimes > > get an 'Empty' error message when I first start the thread). Simply > > using the Tk event loop (self.update) is also how I would have coded > > this in Tcl. > > > So my question is this: under what circumstances in Python are threads > > considered "best practice"? Am I wrong to use the Tk event loop instead > > of threads? > > D'oh, I got the code snippets mixed up: > > non-threaded: > > def insertDump(self): > self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > for line in self.finkinstalled: > self.t.insert(END, line) > self.update() > self.t.see(END) > > threaded: > > def insertDump(self): > try: > data = self.dataQueue.get(block=False) > for line in data: > self.t.insert(END, line) > self.t.see(END) > self.update() > > except: > print "error" > raise > > def getDump(self): > > self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > self.dataQueue.put(self.file) > > Sorry! > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com It looks like Tkinter is similar to wxPython in that you're not supposed to use the mainloop for anything except the GUI and GUI commands. The following websites have more info on Tkinter and threads: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 http://www.thescripts.com/forum/thread22536.html http://forums.devshed.com/python-programming-11/tkinter-threads-123001.html I use the Threading module for threading in wxPython. I think that would probably serve you well with Tkinter as well. You can use the join() method to wait for all the threads to exit. Mike From http Sat Mar 3 17:44:25 2007 From: http (Paul Rubin) Date: 03 Mar 2007 14:44:25 -0800 Subject: Questions about app design - OOP with python classes References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <54q5lnF22aafrU1@mid.uni-berlin.de> Message-ID: <7xk5xyt0ae.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > Multi-Level-Specification allows you to > > express physical quantities with their respective unit, and operations > > on them to yield the combined unit at compile-time. There are some > > rather complicated cases where simple unification won't solve the > > type-equations, but then you might annotate things explicitly. > Which is what Apps Hungarian _is_. I think the idea is that the compiler can still check that your annotations are correct, or at least consistent, even if it can't solve the equations itself. Hungarian notation is a variable naming convention which can be followed manually but which the compiler makes no attempt to enforce. Diez, can you suggest any online references about MLS? From edfialk at gmail.com Wed Mar 7 18:05:54 2007 From: edfialk at gmail.com (edfialk) Date: 7 Mar 2007 15:05:54 -0800 Subject: IronPython with Apache Message-ID: <1173308754.051978.62500@v33g2000cwv.googlegroups.com> Hi all, I'm completely new to Python, but fairly experienced in PHP and few other languages. Long story short: The IronPython executable doesn't work for .cgi scripts in my browser. I've been assigned to write a service that pulls in parameters from the URL, accesses a file and serves some data through a CSV. The only problem I foresee myself is accessing and reading this file, which is a 'hyper-cube' in that it has many dimensions of data. Anyway, the code for reading and writing this cube was already written by a coworker in IronPython and .NET. Again, I'm totally new to Python but as I'm stepping through trying to pick out pieces that I need, I can't even import clr. So, I'm told I need IronPython, which I get, and I replace the #!c: \Python25\python.exe with the IronPython executable (#!c: \IronPython-1.0.1\ipy.exe), but I get a 500 Internal Server error and: "[Wed Mar 07 17:02:21 2007] [error] [client 127.0.0.1] malformed header from script. Bad header= File , line 0, in __import__: testing.cgi" in the Error log. Does anyone know how to set up this 'IronPython' through Apache so I can use it to read/write data? Any help would be greatly appreciated. Thanks! -Ed From buzzard at urubu.freeserve.co.uk Wed Mar 14 10:05:35 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 14 Mar 2007 14:05:35 +0000 Subject: number generator In-Reply-To: <45f76346.0@entanet> References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <55fbgjF2492skU1@mid.individual.net> <1173573654.009953.266280@30g2000cwc.googlegroups.com> <7xbqj01u9c.fsf@ruckus.brouhaha.com> <01f501c7653e$1ee8cee0$03000080@hendrik> <55osfiF25uqm7U1@mid.individual.net> <45f76346.0@entanet> Message-ID: <45f807b0.0@entanet> Duncan Smith wrote: > greg wrote: > >>Gabriel Genellina wrote: >> >> >>>The 5th number is not "random". >> >> >>More precisely, the fifth number is not *independent* >>of the others. You can't have five independent random >>numbers that sum to 50; only four independent numbers >>plus a dependent one. >> >>-- >>Greg > > > In the interests of precision, that should probably read "are > constrained to sum to 50"; it's quite possible to generate a sequence of > independent random variates that just happen to sum to 50 (as I'm sure > you know). > > A fairly efficient way of generating random multinomial variates (which > would satisfy the OP's problem) [snip] That is, the OP's original problem (without the positivity constraint added in a later post). Duncan From mahs at telcopartners.com Thu Mar 22 14:35:52 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 22 Mar 2007 11:35:52 -0700 Subject: challenge ? In-Reply-To: <1174581702.968531.82550@y66g2000hsf.googlegroups.com> References: <1174581702.968531.82550@y66g2000hsf.googlegroups.com> Message-ID: alain wrote: > I have a problem I wonder if it has been solved before. > I have a dictionnary and I want the values in the dictionnary to be > annotated with the rank that would be obtained by sorting the values > > def annotate_with_rank(my_dict): > .... > return my_annotated_dict > > In other words, any value a_value would become a 2-tuple > (a_value,rank_of_a_value) > > I seek an elegant solution. > > Alain > >>> d = dict(a=10, b=5, c=8, d=12) >>> dict((k, (v, rank)) for rank, (v, k) in ... enumerate(sorted((v, k) for k, v in d.items()))) {'a': (10, 2), 'c': (8, 1), 'b': (5, 0), 'd': (12, 3)} >>> # sort by value, then by key since (v,k) must be unique Michael From superprad at gmail.com Wed Mar 21 15:18:41 2007 From: superprad at gmail.com (PKKR) Date: 21 Mar 2007 12:18:41 -0700 Subject: parsing combination strings In-Reply-To: References: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> Message-ID: <1174504721.913698.178380@e1g2000hsg.googlegroups.com> On Mar 21, 2:51 pm, "Steven D. Arnold" wrote: > On Mar 21, 2007, at 2:42 PM, PKKR wrote: > > > I need a fast and efficient way to parse a combination string(digits + > > chars) > > > ex: s = "12ABA" or "1ACD" or "123CSD" etc > > > I want to parse the the above string such that i can grab only the > > first digits and ignore the rest of the chacters, > > A regex leaps to mind.....have you investigated the "re" module? > > >>> import re > >>> re.match(r'(\d+)', '123abc').group(1) > '123' > > steven yep thats what i tried as per tommy's advice and came up with: re.split('[^0-9]', str)[0] or is there a better way? From supervau at gmail.com Tue Mar 27 05:26:51 2007 From: supervau at gmail.com (Frank) Date: 27 Mar 2007 02:26:51 -0700 Subject: plot dendrogram with python Message-ID: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> Hi, does anyone know if there is a way to plot a dendrogram with python. Pylab or matplotlib do not provide such a function. Thanks! Frank From nagle at animats.com Fri Mar 30 12:00:17 2007 From: nagle at animats.com (John Nagle) Date: Fri, 30 Mar 2007 16:00:17 GMT Subject: Game programming for kids: looking for open source 2D game development kit In-Reply-To: References: <5741ueF2bgl92U1@mid.uni-berlin.de> Message-ID: Max Kubierschky wrote: > Diez B. Roggisch schrieb: > >> Max Kubierschky schrieb: >> >>> Hello, >>> >>> I'm planning to give a game programming course for kids of mixed age. >>> For this, I am looking for an open source 2D game development kit. >>> I am also willing to participate in the development of the >>> development kit. >>> >>> Features I'd like to see >>> - Possibility to construct simple games via drag and drop without >>> programming >>> - Integration into an IDE >>> - Based on Java or Python >>> Pluses: >>> - Good Tutorial >>> - German documentation The Blender GameKit will do all that. You can do simple games without programming. There's a graphical integrated environment. Programs can be written in Python. There's a published book ("Blender GameKit") German documentation may be hard to come by, though. John Nagle From gagsl-py2 at yahoo.com.ar Mon Mar 19 18:18:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 19:18:50 -0300 Subject: Create TarFile using string buffers References: <1174331199.134156.105430@n59g2000hsh.googlegroups.com> Message-ID: En Mon, 19 Mar 2007 16:06:39 -0300, aurora00 at gmail.com escribi?: > I have a program that generates a number of files that will be > packaged into a tarball. Can I stream the content into TarFile without > first writing them out to the file system? All add(), addfile() and > gettarinfo() seems to assume there is a file in the disk. But for me I > seems inefficient to write all the content to the disk and then have > it read back by the TarFile module. You can create a TarInfo object directly, and use addfile with a StringIO object: import tarfile from cStringIO import StringIO data = "Some text, maybe containing\ntwo or more lines\n" + "The quick brown fox jumps over the lazy dog\n" * 20 fobj = StringIO(data) tar = tarfile.open("sample.tar", "w") tarinfo = tarfile.TarInfo("foo.txt") tarinfo.size = len(data) tar.addfile(tarinfo, fobj) tar.close() tar = tarfile.open("sample.tar", "r") tar.list() foo = tar.extractfile("foo.txt") data_read = foo.read() print "foo.txt:\n%s" % data_read tar.close() assert data == data_read -- Gabriel Genellina From nagle at animats.com Sat Mar 10 12:47:39 2007 From: nagle at animats.com (John Nagle) Date: Sat, 10 Mar 2007 17:47:39 GMT Subject: pylint: don't warn about tabs In-Reply-To: References: <55avniF23jpl2U1@mid.individual.net> Message-ID: <%aCIh.6552$M65.4331@newssvr21.news.prodigy.net> Gabriel Genellina wrote: > En Thu, 08 Mar 2007 14:33:38 -0300, Bjoern Schliessmann > escribi?: > >> Alan Isaac wrote: >> >>> As a tab user, I want the tabs warning turned off. >> >> >> Advice: Don't. IIRC it's planned in future Python versions that TABs >> aren't supported for indentation. > > > AFAIK, using tabs xor spaces will be ok, but not MIXING them. That's what should be enforced. For any module, whitespace at the beginnings of lines should be all spaces or all tabs. Both are unambiguous and can be mechanically converted to each other. But if spaces and tabs are mixed, there's ambiguity. John Nagle From rdiaz02 at gmail.com Mon Mar 26 11:31:51 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Mon, 26 Mar 2007 17:31:51 +0200 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <624934630703260831o404709f3pc77ed3867f616fd3@mail.gmail.com> On 26 Mar 2007 06:20:32 -0700, Nomad.C at gmail.com wrote: > OK... > I've been told that Both Fortran and Python are easy to read, and are > quite useful in creating scientific apps for the number crunching, but > then Python is a tad slower than Fortran because of its a high level > language nature, so what are the advantages of using Python for > creating number crunching apps over Fortran?? > Thanks > Chris > Dear Chris, Why are you focusing on Python vs. Fortran? There might be other choices out there you might want to consider, specifically C, O'Caml, and Ada, since you mention number crunching. When choosing, you should consider what other requirements you'll have; some people have hinted at a few, such as portability (I am not saying fortrain ain't portable) and rapid application development. Will you be doing lots of string manipulation? Processing text-files? Gluing applications? What do people around you use? What type of number crunching will you be doing? Are the libraries available in any of the languages that you are considering that do some/most of what you want to do? Are you concernded about concurrent/distributed programming? Is this your first programming language? Etc, etc, etc. In the end, maybe neither Python nor Fortran might be the best choices for you. HTH, R. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From paul at boddie.org.uk Thu Mar 22 07:31:41 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Mar 2007 04:31:41 -0700 Subject: Python Oracle 10g odbc blob insertion problem In-Reply-To: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> References: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> Message-ID: <1174563101.470315.280940@n59g2000hsh.googlegroups.com> On 22 Mar, 10:21, "Godzilla" wrote: > > I cannot find a solution for my problem with inserting a blob object > (>4000 in length) into an ORACLE database via ODBC. This brings back "happy" memories with Oracle 9i and JDBC. > I have tried the two ways of inserting the blob object (a zip file): > > 1) > fp = open("c:/test/test.zip", "r+b") > data = fp.read() > s = odbc.odbc(cs) > qry = s.cursor() > qry.execute("Insert into tBlob (data) values ('%s')" % > data.encode('hex')) > > return the error: Input String Too Long Limit: 4096 > > 2) > qry.execute("Insert into tBlob (data) values (?)", > data.encode('hex')) > > does not return error, but it does not insert the record correctly. > > Any help will be fully appreciated... If I recall correctly, JDBC provided an API to stream the contents into the column. That is, you needed to provide an instance of one of the mutually incompatible Java stream classes (I don't remember which one) when setting the value, and then the database would suck up the contents. It's quite possible that a similar mechanism involving file- like objects exists in the different Python modules for Oracle, although I haven't checked. Paul From markbpan at mailinator.com Thu Mar 22 21:01:15 2007 From: markbpan at mailinator.com (Mark) Date: 23 Mar 2007 01:01:15 GMT Subject: Idiom for running compiled python scripts? References: Message-ID: So given the lack of response it seems that there is probably no such idiom and that I should not be concerned by the inefficiency inherent in running .py scripts directly? I did some time tests and sure, the speed gain is slight, but it is a gain none the less. From tgrav at mac.com Tue Mar 6 05:57:43 2007 From: tgrav at mac.com (Tommy Grav) Date: Tue, 6 Mar 2007 05:57:43 -0500 Subject: Good handling of input data (was Re: Newbie question) In-Reply-To: <45EC579A.8090602@websafe.com> References: <45EC579A.8090602@websafe.com> Message-ID: On Mar 5, 2007, at 12:47 PM, Larry Bates wrote: > Tommy Grav wrote: >> Hi list, >> >> this is somewhat of a newbie question that has irritated me for >> a while. >> I have a file test.txt: >> >> 0.3434 0.5322 0.3345 >> 1.3435 2.3345 5.3433 >> >> and this script >> lines = open("test.txt","r").readlines() >> for line in lines: >> (xin,yin,zin) = line.split() >> x = float(xin) >> y = float(yin) >> z = float(zin) >> >> Is there a way to go from line.split() to x,y,z as floats without >> converting >> each variable individually? >> >> Cheers >> Tommy > > > Using a list comprehension you would write this as: > > for line in lines: > xin, yin, zin=[float(x) for x in line.split()] > > This if course expects your data to be perfect. If > you want error handling (e.g. less or more than 3 values, > values that cause exception when passed to float, etc.) > you will have to handle that differently. Thanks for the great response. So how would you handle this type of error handling? My main problem is that occasionally there is an entry in the list that is a string: 0.9834 134.4933 78.009 run11 27 Again I would like to avoid having to individually parse the 3 floats, while still easily handling the string, but a list comprehension will not work as far as I can tell. Is there a module that handles this type of flat ascii tables? Something like: (x,y,z,id,n) = ParseFile("float","float","float","string","int") would be great, and I guess (x,y,z,id,n) = PaseFile2("%f %f %f %s %d") would be even better. Cheers Tommy From david at boddie.org.uk Sat Mar 24 19:20:42 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 25 Mar 2007 00:20:42 +0100 Subject: qt ver. 3, linux, windows, and modal forms References: <4605a174$0$5225$4c368faf@roadrunner.com> Message-ID: On Saturday 24 March 2007 23:08, Mike wrote: > I'm having a problem with modal forms on windows. I've written a very > short test program, with a main window and a form called from the main > window. The form is set to modal with form.setModal(1) before calling > form.show(). Is form an instance of a QWidget subclass or a QDialog subclass? Have you tried calling form.exec_loop() instead of form.show()? > All works as expected on Linux. The form is modal, not allowing the main > window to received the focus. If I call the form from within itself, the > topmost form is modal, and not of the previous forms will receive the > focus until the topmost form is closed; then the next topmost is modal, > and so on. This sounds like the desired behaviour. > However, on Windows XP Pro (at work - don't use windows at home), the > form is not modal. The main window will receive the focus with a mouse > click even though the modal form is still on top. But this should show the same behaviour. I suspect that the use of show() rather than exec_loop() leads to the platform-specific behaviour you are seeing. > The source code is identical on both OS's. > > Has anyone run into this before? Is there a fix? I haven't been able to > find anything with google searches, and Trolltech's forums don't seem to > have any entries addressing the problem, either. > > I have a progam that I'm writing for work using Qt and Python, which was > like pulling teeth with our Microsoft oriented IT department, and I very > much do not want to tell them that it's not going to work (modal forms > are essential). Modal forms are quite commonplace, so they should work as you expect. If you above advice doesn't help, you'll need to supply some more information about the versions of Qt, PyQt, SIP and Python you are using. David From rterala at gmail.com Thu Mar 8 16:21:24 2007 From: rterala at gmail.com (Ravi Terala) Date: Thu, 08 Mar 2007 13:21:24 -0800 Subject: implementing SFTP using Python In-Reply-To: <683868.19200.qm@web38806.mail.mud.yahoo.com> References: <683868.19200.qm@web38806.mail.mud.yahoo.com> Message-ID: <45F07E54.1070502@gmail.com> Kiran, You should look into Twisted Python and their Twisted Python Conch package. You might not need to reinvent the wheel. http://twistedmatrix.com/trac/wiki/TwistedConch Ravi kadarla kiran kumar wrote: > Hi Everybody, > > I have to implement SFTP conection from client to the server using > Python script. > Iam very new new to python , and i dont't have much time to complete > this. So I need some pointers from you. > > If anybody has already done this kind of stuff, please let me know. > Please don't think Iam over ambitious, but i need some kind of Pseudo > code ,if possible source code. > > Thanks in Advance, > K.Kiran Kumar > > ------------------------------------------------------------------------ > Never Miss an Email > Stay connected with Yahoo! Mail on your mobile. Get started! > > > From gagsl-py2 at yahoo.com.ar Wed Mar 14 18:27:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Mar 2007 19:27:55 -0300 Subject: question about class methods References: Message-ID: En Wed, 14 Mar 2007 18:04:00 -0300, Darren Dale escribi?: > I've run across some code in a class method that I don't understand: > > def example(self, val=0) > if val and not self: > if self._exp < 0 and self._exp >= -6: 0) "Normal" methods are not class methods, but instance methods. A class method is a method who operates on the class itself; its first argument is the class (maybe a derived one). > I am unfamiliar with some concepts here: > > 1) Under what circumstances would "if not self" be True? "if not self" would be "if self evaluates to False as a boolean": 0, 0.0, 0j, (), [], {}... Other objects usually evaluate always to True, except if they define some special methods: __nonzero__ and __len__. Look those on the Python Reference Manual. > 2) If "not self" is True, how can self have attributes? Perhaps you think of self being None - that should never occur unless you called the method in some convoluted way. The class migh inherit from list, by example, and you want to compute the average: class StatList(list): def avg(self): if self: return sum(self)/len(self) else: raise ValueError("Can't compute average on empty list") > (This is slightly simplified code from the decimal.Decimal.__str__ > method, > line 826 in python-2.4.4) A Decimal number is False when 0. `if not self` is a faster way to say `if self==0` -- Gabriel Genellina From downloadpda at gmail.com Fri Mar 23 06:46:46 2007 From: downloadpda at gmail.com (downloadpda at gmail.com) Date: 23 Mar 2007 03:46:46 -0700 Subject: $1 download the newest pda software Message-ID: <1174646806.028002.65970@d57g2000hsg.googlegroups.com> Want access to 15000+ all the new pda applications? just $1 register for one account to download/buy applications in this site. http://handpedia.vicp.cc/ this is one-time email, thank your reading. From joncle at googlemail.com Fri Mar 16 05:02:06 2007 From: joncle at googlemail.com (Jon Clements) Date: 16 Mar 2007 02:02:06 -0700 Subject: python noob, multiple file i/o In-Reply-To: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> References: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> Message-ID: <1174035726.525608.3340@e1g2000hsg.googlegroups.com> On 16 Mar, 03:56, "hiro" wrote: > Hi there, > > I'm very new to python, the problem I need to solve is whats the "best/ > simplest/cleanest" way to read in multiple files (ascii), do stuff to > them, and write them out(ascii). > > -- > import os > > filePath = ('O:/spam/eggs/') > for file in os.listdir(filePath): #straight from docs > # iterate the function through all the files in the directory > # write results to separate files <- this is where I'm mostly > stuck. > > -- > For clarity's sake, the file naming conventions for the files I'm > reading from are file.1.txt -> file.nth.txt > > It's been a long day, i'm at my wits end, so I apologize in advance if > I'm not making much sense here. > syntax would also be great if you can share some recipes. I'd try the glob module. [code] import glob # Get a list of filenames matching wildcard criteria # (note that path is relative to working directory of program) matching_file_list = glob.glob('O:/spam/eggs/*.txt') # For each file that matches, open it and process it in some way... for filename in matching_file_list: infile = file(filename) outfile = file(filename + '.out','w') # Process the input file line by line... for line in infile: pass # Do something more useful here, change line and write to outfile? # Be explicit with file closures outfile.close() infile.close() [/code] Of course, you can change the wild card criteria in the glob statement, and also then filter further using regular expressions to choose only files matching more specific criteria. This should be enough to get you started though. hth Jon. From jgodoy at gmail.com Sat Mar 10 11:28:42 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 10 Mar 2007 13:28:42 -0300 Subject: Database module & multithreading References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> <1hur0ah.tbqxgzjmqcwmN%aleax@mac.com> <1173542369.216188.223200@p10g2000cwp.googlegroups.com> Message-ID: <87ird9kqpx.fsf@gmail.com> "jupiter" writes: > conn = psycopg2.connect("dbname=test user=test") > > Traceback (most recent call last): > File "", line 1, in > conn = psycopg2.connect("dbname=test user=test") > OperationalError: could not connect to server: Connection refused > (0x0000274D/10061) > Is the server running on host "???" and accepting > TCP/IP connections on port 5432? > > this is the error I am getting with psycopg2 I want to access a local > file PostgreSQL is a server, it access the files. You talk to the RDBMS server. Is it running? Is it accepting connections from your host? -- Jorge Godoy From fabiofz at gmail.com Mon Mar 12 13:27:31 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 12 Mar 2007 14:27:31 -0300 Subject: Pydev 1.3.0 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.0 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Find References: Ctrl+Shift+G can be used to find the references to the selected token in the editor * Fix: Code-analysis: Fixed false positive for statement with no effect Release Highlights in Pydev: ---------------------------------------------- * Code-completion: Deep analysis for discovering arguments in constructs 'from imports' now can be configured given the number of chars of the qualifier * Refactoring for override methods: changed so that it uses the pydev code-completion engine for getting the hierarchy and methods * Fix: Python Nature Restore: begin rule does not match outer scope rule fixed * Fix: Package Explorer: if show-in is in a deep structure, it will show it is the 1st try and not only in the 2nd * Fix: Package Explorer: some intercepts removed elements incorrectly, and ended up messing the navigator and search (which has 'null' elements because of that) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From facundo at taniquetil.com.ar Tue Mar 27 08:39:41 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 27 Mar 2007 12:39:41 +0000 (UTC) Subject: shutil.copy Problem References: <1174970535.061022.141230@l77g2000hsb.googlegroups.com> Message-ID: David Nicolson wrote: > Thanks, but it's definitely not the print. In original the code the > print statements are replaced by a call to a log method. > > Besides, the exception would be different if it was thrown outside of > the try block. The best you can do is take the piece of code that has the problem, show it to us, and then copy the traceback. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From jgodoy at gmail.com Sun Mar 18 07:19:18 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 18 Mar 2007 08:19:18 -0300 Subject: To count number of quadruplets with sum = 0 References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <1174024633.431427.236920@y66g2000hsf.googlegroups.com> <7xslc5k9cc.fsf@ruckus.brouhaha.com> <1174158002.730076.22720@y80g2000hsf.googlegroups.com> <1174166115.263201.51840@d57g2000hsg.googlegroups.com> <1174189566.189546.85510@y80g2000hsf.googlegroups.com> <1174190073.112097.29160@l75g2000hse.googlegroups.com> Message-ID: <877ite3ikp.fsf@gmail.com> "n00m" writes: > my dial-up line's too slow for downloading 4mb of shedskin-0.0.20.exe Don't worry! We can email it to you. :-D -- Jorge Godoy From timr at probo.com Mon Mar 19 23:56:22 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 20 Mar 2007 03:56:22 GMT Subject: fifo queue References: <1174257160.540073.113380@b75g2000hsg.googlegroups.com> Message-ID: "drochom" wrote: > >how would u improve this code? I would add at least one comment... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bdesth.quelquechose at free.quelquepart.fr Thu Mar 8 17:47:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Mar 2007 23:47:22 +0100 Subject: What is the best way to upgrade python? In-Reply-To: <1173388393.052558.69270@s48g2000cws.googlegroups.com> References: <1173388393.052558.69270@s48g2000cws.googlegroups.com> Message-ID: <45f08a69$0$3223$426a74cc@news.free.fr> yinglcs at gmail.com a ?crit : > Hi, > > i am using red hat enterprise 4. It has python 2.3 installed. What is > the best way to upgrade to python 2.4? > > I think one way is to compile python 2.4 from the source, but I can't > remove the old one since when i do 'rpm -e python', i get error like > 'failed dependencies'. Not really a python-related problem by itself, but anyway: you probably have other packages depending on this version of Python, so better to keep it. Now nothing prevents you from having multiple Python versions. Just build from sources (preferably giving /usr/local as prefix to ./configure since it's not the 'system' version), and install in a different location (IIRC there's a make altinstall rule - anyway all this is documented in the source directory). From manstey at csu.edu.au Tue Mar 6 17:45:45 2007 From: manstey at csu.edu.au (manstey) Date: 6 Mar 2007 14:45:45 -0800 Subject: is it possible to give an instance a value? Message-ID: <1173221145.793008.298940@v33g2000cwv.googlegroups.com> Hi, My question probably reflects my misunderstanding of python objects, but I would still like to know the answer. The question is, is it possible for an instnace to have a value (say a string, or integer) that can interact with other datatypes and be passed as an argument? The following code of course gives an error: class Test(object): def __init__(self, val): self.val = val >>> a = Test('hello') >>> a.val + ' happy' 'hello happy' >>> a + 'happy' TypeError: unsupported operand type(s) for +: 'Test' and 'str' Is there a way to make a have the value a.val when it is used as above, or as an argument (eg function(a, 10, 'sdf') etc)? The only fudge I discovered for simple addition was to add to the class def __add__(self, obj): return a.val + obj but this doesn't solve the problem in general. I have tried subclassing the string type, but as it is immutable, this is not flexible the way a.val is (i.e. it can't e reassigned and remain a subclass). Any pointers, or is my question wrong-headed? btw, my motivation is wanting to mimic another oo language which allows this, so it allows: >>>Person.Address 'Sydney' >>>Person.Address.type '%String' >>>Person.Address = 'Canberra' >>>print Person.Address. Person.Address.type Canberra %String etc. We have had to implement Person.Address as Person.Address.val, making Address an instance with .val, .type, etc. From skip at pobox.com Wed Mar 21 12:17:37 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 21 Mar 2007 11:17:37 -0500 Subject: Garbage collection In-Reply-To: References: Message-ID: <17921.23201.912536.584770@montanaro.dyndns.org> Tom> True, but why does Python hang on to the memory at all? As I Tom> understand it, it's keeping a big lump of memory on the int free Tom> list in order to make future allocations of large numbers of Tom> integers faster. If that memory is about to be paged out, then Tom> surely future allocations of integers will be *slower*, as the Tom> system will have to: Tom> 1) page out something to make room for the new integers Tom> 2) page in the relevant chunk of the int free list Tom> 3) zero all of this memory and do any other formatting required by Tom> Python If your program's behavior is: * allocate a list of 1e7 ints * delete that list how does the Python interpreter know your next bit of execution won't be to repeat the allocation? In addition, checking to see that an arena in the free list can be freed is itself not a free operation. From the comments at the top of intobject.c: free_list is a singly-linked list of available PyIntObjects, linked via abuse of their ob_type members. Each time an int is allocated, the free list is checked to see if it's got a spare object lying about sloughin off. If so, it is plucked from the list and reinitialized appropriately. If not, a new block of memory sufficient to hold about 250 ints is grabbed via a call to malloc, which *might* have to grab more memory from the OS. Once that block is allocated, it's strung together into a free list via the above ob_type slot abuse. Then the 250 or so items are handed out one-by-one as needed and stitched back into the free list as they are freed. Now consider how difficult it is to decide if that block of 250 or so objects is all unused so that we can free() it. We have to walk through the list and check to see if that chunk is in the free list. That's complicated by the fact that the ref count fields aren't initialized to zero until a particular chunk is first used as an allocated int object and would have to be to support this block free operation (=> more cost up front). Still, assume we can semi-efficiently determine that a particular block is composed of all freed int-object-sized chunks. We will then unstitch it from the chain of blocks and call free() to free it. Still, we are left with the behavior of the operating system's malloc/free implementation. It probably won't sbrk() the block back to the OS, so after all that work your process still holds the memory. Okay, so malloc/free won't work. We could boost the block size up to the size of a page and use mmap() to map a page into memory. I suspect that would become still more complicated to implement, and the block size being probably about eight times larger than the current block size would incur even more cost to determine if it was full of nothing but freed objects. Tom> If Python freed (most of) the memory when it had finished with it, Tom> then all the system would have to do is: That's the rub. Figuring out when it is truly "finished" with the memory. Tom> Surely Python should free the memory if it's not been used for a Tom> certain amount of time (say a few seconds), as allocation times are Tom> not going to be the limiting factor if it's gone unused for that Tom> long. This is generally the point in such discussions where I respond with something like, "patches cheerfully accepted". ;-) If you're interested in digging into this, have a look at the free list implementation in Objects/intobject.c. It might make for a good Google Summer of Code project: http://code.google.com/soc/psf/open.html http://code.google.com/soc/psf/about.html but I'm not the guy you want mentoring such a project. There are a lot of people who understand the ins and outs of Python's memory allocation code much better than I do. Tom> I've also tested similar situations on Python under Windows XP, and Tom> it shows the same behaviour, so I think this is a Python and/or Tom> GCC/libc issue, rather than an OS issue (assuming Python for linux Tom> and Python for windows are both compiled with GCC). Sure, my apologies. The malloc/free implementation is strictly speaking not part of the operating system. I tend to mentally lump them together because it's uncommon for people to use a malloc/free implementation different than the one delivered with their computer. Skip From researchbase at gmail.com Thu Mar 29 01:55:38 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Thu, 29 Mar 2007 11:25:38 +0530 Subject: newbi question on python rpc server, how it works? In-Reply-To: References: Message-ID: hello all, I have downloaded the entire twisted library. I am also trying to read the documentation but I have a couple of problems right now. firstly, I did not find any thing in twisted documentation that specifically talks about xml rpc. am I missing some thing? secondly, if I am writing an entire application with its logic in an xml rpc server, do I have to create all my classes as instences of xml rpc server (just like I create a java servlet or a php script)? or is it that I just create one xml rpc server class which is like the entri point for all other classes in the package? can you provide a couple of links to howtos or tutorials on creating xml rpc servers and clients with twisted python? I am also confused as to how will I mix the functionality of MySQLDB with twisted python? I am asking this because I felt twisted much cleaner to use than the modules coming with python itself. again I may be wrong and some one might point me to the possible problems with this aproach in the long run. regards. Krishnakant. From tommy.nordgren at comhem.se Thu Mar 8 22:06:06 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 9 Mar 2007 04:06:06 +0100 Subject: Python books? Message-ID: <1CD93DF7-4172-4FF1-B5B4-BF665762C9E7@comhem.se> Could some kind soul please recommend a few text books on Python 2.5 and it's class library? ---- Kine dies, Kinfolk dies, and thus at last yourself This I know that never dies, how a dead mans deeds are deemed. -- Elder edda Tommy Nordgren tommy.nordgren at comhem.se From piet at cs.uu.nl Tue Mar 20 07:10:24 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 20 Mar 2007 12:10:24 +0100 Subject: Displaying EPS in a GUI References: <1174072162.659381.75700@o5g2000hsb.googlegroups.com> Message-ID: >>>>> virtk0s at gmail.com (V) wrote: >V> Does anybody know of a good way to display Encapsulated Postscript >V> images in a GUI? I'm currently using wx, but would be perfectly >V> willing to switch to another binding to keep the program from becoming >V> hackish. You need e Postscript interpreter, e.g. Ghostscript. If you have Ghostscript installed PIL can read EPS images. Then they can be converted to wx images: http://wiki.wxpython.org/index.cgi/WorkingWithImages -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From steve at holdenweb.com Mon Mar 12 23:05:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 12 Mar 2007 23:05:49 -0400 Subject: Interface in IronPython In-Reply-To: <45f5cc7e$0$27190$426a74cc@news.free.fr> References: <1173734174.730471.149680@j27g2000cwj.googlegroups.com> <45f5cc7e$0$27190$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > edfialk a ?crit : >> Hi all, I'm pretty much totally new to IronPython and have come to the >> point that I need an interface to interact with a co-worker's code, >> but I can't seem to find any documents or discussion on syntax for >> writing an interface. >> >> Does anyone know of a link that talks about interfaces in IronPython >> or feel like explaining one too me? :) >> >> Any advice would be greatly appreciated. > > My best advice would be to repost your question here: > http://lists.ironpython.com/listinfo.cgi/users-ironpython.com > That's good advice, but I hope it won't be taken to mean that IronPython questions aren't welcome here too. I would have expected many readers to be familiar with the fuzzyman's techie blog, in which he's recently been describing his experiences building Windows/.NET interfaces with IronPython. Start at http://www.voidspace.org.uk/ironpython/index.shtml regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From memcached at aol.com Mon Mar 12 08:41:50 2007 From: memcached at aol.com (memcached at aol.com) Date: Mon, 12 Mar 2007 08:41:50 -0400 Subject: mod_python's mechanism Message-ID: <8C932BAF0EA83B2-13B8-89F2@WEBMAIL-MB21.sysops.aol.com> Hello, I'm just curious that does mod_python have the same or similiar mechanism comparing to mod_perl? Thanks! ________________________________________________________________________ AOL now offers free email to everyone. Find out more about what's free from AOL at AOL.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Fri Mar 23 12:31:23 2007 From: http (Paul Rubin) Date: 23 Mar 2007 08:31:23 -0800 Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> Message-ID: <7xejnfdiqs.fsf@ruckus.brouhaha.com> Jorgen Grahn writes: > Wikipedia should have some guideline for referencing Usenet postings, > somewhere ... It has one (WP:RS). The guideline is don't do it. The problem is that these guidelines arise out of disputes, i.e. maybe someone tried to use a Usenet post to prove something about a politician, and the result (reasonably) was a guideline that said Usenet posts weren't reliable sources of info. In the cases where it's something ok, the editors use common sense and leave it alone. Until that bot got loose and started removing all Usenet links whether they were ok or not. From jstroud at mbi.ucla.edu Sat Mar 3 03:03:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 03 Mar 2007 08:03:04 GMT Subject: classes and functions In-Reply-To: References: Message-ID: Silver Rock wrote: > Friends, > > I don?t see why using classes.. functions does everything already. I > read the Rossum tutotial and two other already. > > Maybe this is because I am only writing small scripts, or some more > serious misunderstandings of the language. > > Please give me a light. > > thanks guys, > Claire Attempt to code a gui. James From mail at microcorp.co.za Sun Mar 4 03:10:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 4 Mar 2007 10:10:56 +0200 Subject: pop method question References: <1172968335.511875.255750@p10g2000cwp.googlegroups.com> <1huevy2.1431m651a0okjjN%aleax@mac.com> Message-ID: <00bc01c75e34$a343fa40$03000080@hendrik> "Alex Martelli" wrote: > Raymond Hettinger wrote: > ... > > The notion that "pop" is only defined for stack operations is somewhat > > pedantic. > > Worse: it's totally wrong. It's also defined for eyes, as a musical > genre, as a kind of soda, as an avant-garde artistic movement of the > '50s, for baloons, as a parent of the male persuasion, for email > reading, and moreover it's often used to refer to Persistent Organic > Pollutants or Points Of Presence -- not forgetting weasels, either. > One should never forget the pawning of weasels. Then there is the contrary meaning - instead of "take out" it can mean "put in" - Just pop it in the oven, there's a dear... - Hendrik From XX.XmcX at XX.XmclaveauX.com Fri Mar 30 08:14:32 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 30 Mar 2007 14:14:32 +0200 Subject: Object Oriented Database with interface for Pyhton References: <1175245459.867371.92500@n76g2000hsh.googlegroups.com> <1175247009.786698.72390@l77g2000hsb.googlegroups.com> <460ce036$0$1390$426a74cc@news.free.fr> Message-ID: Salut! Heureusement qu'il y a qq fran?ais pour faire un peu de m?nage... -- @-salutations Michel Claveau From bdesth.quelquechose at free.quelquepart.fr Tue Mar 6 13:16:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Mar 2007 19:16:15 +0100 Subject: Project organization and import In-Reply-To: <555jv6F2314bbU1@mid.uni-berlin.de> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <45ec9ba3$0$2333$426a34cc@news.free.fr> <1173167617.207318.22400@h3g2000cwc.googlegroups.com> <45ed41f7$0$21515$426a74cc@news.free.fr> <1173198244.092412.17400@n33g2000cwc.googlegroups.com> <555jv6F2314bbU1@mid.uni-berlin.de> Message-ID: <45eda7ef$0$32279$426a34cc@news.free.fr> Diez B. Roggisch a ?crit : >>I'd like to point out something though. More than one of the people >>who responded have implied that I am bringing my prior-language >>mindset to Python, even suggesting that my brain isn't built for >>Python. ;) In fact I think it's the other way around. I am struggling >>to take full advantage of the fact that Python is an interpreted >>language, to use Python in the most "Pythonic" way. You guys are >>telling me that's broken and I should go back to a workflow that is >>identical in spirit, and not necessarily any faster than I would use >>with a compiled language. While that might be the right answer in >>practice, I don't feel like it's a particularly "good" answer, and it >>confirms my initial impression that Python package management is >>broken. >> >>I think you should be asking yourselves, "Did we all abandon reload() >>because it is actually an inferior workflow, or just because it's >>totally broken in Python?" > > > Sorry, but I fail to see the point of your argumentation. > > Reloading a module means that you obviously have some editor open you code > your module in, and an interactive interpreter running where you somehow > have to make the > > reload(module) > > line (re-)appear, and then most probably (unless the pure reloading itself > triggers some testing code) some other line that e.g. instantiates a class > defined in "module" > > Now how exactly does that differ from having a test.py file containing > > import module > > > and a commandline sitting there with a > > python test.py Actually, make it python -i test.py Then you have test.py executed, and your interactive interpreter up and ready in the desired state. From nagle at animats.com Sat Mar 17 03:12:30 2007 From: nagle at animats.com (John Nagle) Date: Sat, 17 Mar 2007 07:12:30 GMT Subject: Mastering Python In-Reply-To: <1hv3735.f8r5bx3czob7N%aleax@mac.com> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1hv3735.f8r5bx3czob7N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Dennis Lee Bieber wrote: > > >>>need to catch up quickly and master Python programming.How do you >> >>Mastery and quickly are opposing terms Took me 15 years on a job >>using FORTRAN 77 and I still wouldn't have called myself a master. (I'm >>more of a JoAT) > > > My favorite "Stars!" PRT, mind you -- but when some language interests > me enough, I do tend to "master" it... guess it's correlated with what > Brooks saw as the ideal "language lawyer" in his "surgical team" > approach, an intrinsic fascination with bunches of interconnected rules. Python just isn't that complicated. The syntax is straightforward, and the semantics are similar to most other dynamic object-oriented languages. If you know Perl or Smalltalk or LISP or JavaScript, Python does about what you'd expect. Execution model: dynamic stack-type interpreter. Memory model: reference counting with backup garbage collector. Syntax: roughly C-like, with indentation for structure. Typing model: dynamic only Object model: class definitions with multiple inheritance. Object structure: dictionary hash. Exception model: explicit throw/try/catch Theading model: multiprogramming in interpreter. Safe memory model: Yes. Closures: Yes. Design by contract: No. That's Python. Biggest headache is finding out what doesn't work in the libraries. John Nagle From jjl at pobox.com Sat Mar 10 16:20:31 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 10 Mar 2007 21:20:31 GMT Subject: IronPython with Apache References: <1173308754.051978.62500@v33g2000cwv.googlegroups.com> Message-ID: <871wjw7q3f.fsf@pobox.com> "edfialk" writes: [...] > So, I'm told I need IronPython, which I get, and I replace the #!c: > \Python25\python.exe with the IronPython executable (#!c: > \IronPython-1.0.1\ipy.exe), but I get a 500 Internal Server error and: > > "[Wed Mar 07 17:02:21 2007] [error] [client 127.0.0.1] malformed > header from script. Bad header= File , line 0, in __import__: > testing.cgi" in the Error log. [...] Looks odd. Try the IronPython mailing list? Or try this: http://www.microsoft.com/downloads/details.aspx?FamilyId=55932211-0D7E-4C6E-9B18-8F9D2AC1EE43&displaylang=en John From tgrav at mac.com Thu Mar 22 17:00:19 2007 From: tgrav at mac.com (Tommy Grav) Date: Thu, 22 Mar 2007 17:00:19 -0400 Subject: Upgrading python question Message-ID: <3AD132C2-B09B-4FF9-AA86-928DE171B634@mac.com> I am currently using Activepython 2.4.4, but would like to upgrade to 2.5. Am I right in thinking that if I do that I need to reinstall all the packages and modules (like numpy, scipy, pyfits, and so on)? Or is there a way to avoid that? Cheers Tommy From http Wed Mar 21 16:39:11 2007 From: http (Paul Rubin) Date: 21 Mar 2007 12:39:11 -0800 Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> Message-ID: <7xtzwee3gw.fsf@ruckus.brouhaha.com> "Paddy" writes: > I just had a link to Tim peters first post on doctest: > http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > removed from http://en.wikipedia.org/wiki/Doctest as it doesn't fit > their guidelines for external links. Just sit tight for a while. It looks like someone went a bit overboard removing those links with a bot, and is now in the process of putting them back. From siona at chiark.greenend.org.uk Fri Mar 16 07:56:05 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Mar 2007 11:56:05 +0000 (GMT) Subject: Using wildcards with Popen in the Subprocess module References: Message-ID: William Hudspeth wrote: > [ ... ] I need to pass multiple filenames to an >executable. The filenames are similar to one another, but differ only >slightly, hence the use of the wildcard. The executable works well from >the command line if I pass in a wildcard filename, but Popen can't >expand the wildcard. > >>From command line: >% command /path_to_files/filename*.doc > >With Popen: >var1="/path_to_files/filnames*.doc" >result=Popen(["command",var1]).wait() You want: result = Popen(["command", var1], shell=True).wait() See the subprocess docs on using Popen instead of "older functions" (especially os.system): http://docs.python.org/lib/node534.html . You might also want a look at subprocess.call() . -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From mail at microcorp.co.za Mon Mar 12 01:26:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 12 Mar 2007 07:26:45 +0200 Subject: Need help with a string plz! (newbie) References: <1173475520.292989.239200@p10g2000cwp.googlegroups.com><12v3ksihos7uj7a@corp.supernews.com><1173477047.467568.298090@p10g2000cwp.googlegroups.com><2ZqdnZCruccLRWzYnZ2dnUVZ_rqhnZ2d@comcast.com><1173488215.913014.130190@h3g2000cwc.googlegroups.com> <12v8vk7sabb2i84@corp.supernews.com> Message-ID: <011101c76467$074f6000$03000080@hendrik> "Grant Edwards" wrote: > On 2007-03-10, Hendrik van Rooyen wrote: > > wrote: > > > >> Oh, thanks for the advice then. And as for Grant..look forward to > >> seeing more of your posts. > > > > YOW! - some recognition at last! > > :) > > I see somebody pays attention to sigs -- which, BTW, are old quotes > from the Zippy the Pinhead comic strip. www.zippythepinhead.com > Thanks for that - I was wondering where you got hold of the skewed thinking which I enjoy reading so much. - Hendrik From bdesth.quelquechose at free.quelquepart.fr Wed Mar 7 17:41:51 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Mar 2007 23:41:51 +0100 Subject: catching exceptions from an except: block In-Reply-To: References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <45EF260C.6000205@websafe.com> <45ef2e12$0$28891$426a74cc@news.free.fr> Message-ID: <45ef37a6$0$7504$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > En Wed, 07 Mar 2007 19:00:59 -0300, Bruno Desthuilliers > escribi?: > >> this kind of cose is exactly what OO polymorphic dispatch is supposed to > > > this kind of cose? sorry s/cose/code/ > Ce genre de chose? > En quelques sortes, oui, quoique pas tout ? fait !-) From duncan.booth at invalid.invalid Mon Mar 12 05:02:25 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Mar 2007 09:02:25 GMT Subject: Are Lists thread safe? References: <1173467014.510693.60330@30g2000cwc.googlegroups.com> <1173469137.897102.298120@p10g2000cwp.googlegroups.com> <1173469517.797876.262330@t69g2000cwt.googlegroups.com> <1173469804.756713.41700@q40g2000cwq.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > INPLACE_ADD would call MyList.__iadd__ which you have wrapped. But you > have a race condition between that moment and the following > STORE_ATTR, a context switch may happen in the middle. > > It may not be possible to create an absolutely thread-safe list > without some help on the client side. (Comments, someone?) The list itself can be thread safe quite easily, but if the namespace from which you reference it is shared between threads you would have to protect the namespace as well, or avoid using in-place operators. The rebinding is a mutation on the namespace rather than the object, so that is what you have to protect. From wgwigw at gmail.com Wed Mar 28 20:32:23 2007 From: wgwigw at gmail.com (momobear) Date: 28 Mar 2007 17:32:23 -0700 Subject: How can I find out the size of a file In-Reply-To: <1175119748.481117.107910@y80g2000hsf.googlegroups.com> References: <1175119748.481117.107910@y80g2000hsf.googlegroups.com> Message-ID: <1175128343.259515.92230@y80g2000hsf.googlegroups.com> On Mar 29, 6:09 am, Marko.Cain... at gmail.com wrote: > Hi, > > How can I find out the size of a file in a disk in python? > > i try this, but it does not work: > size = open(inputFileNameDir + "/" + file, 'r').size() > > Thank for any help. os.stat(filename), see stat manual for detail.(st_size ) From A.Lloyd.Flanagan at gmail.com Tue Mar 6 14:12:27 2007 From: A.Lloyd.Flanagan at gmail.com (A. Lloyd Flanagan) Date: 6 Mar 2007 11:12:27 -0800 Subject: When will 2.5.1 be released? In-Reply-To: <1173037797.127119.248300@h3g2000cwc.googlegroups.com> References: <1173037797.127119.248300@h3g2000cwc.googlegroups.com> Message-ID: <1173208347.506758.166620@30g2000cwc.googlegroups.com> On Mar 4, 2:49 pm, "Nile" wrote: > This is not a big deal but I would like to use Tix with 2.5. My > understanding is this bug will be fixed in the 2.5.1 release. Does And while we're waiting for 2.5.1, can somebody post a clear (as opposed to the one that comes with Tix ;)) explanation of how to manually install Tix into python 2.5? It should be possible... From Thomas.Ploch at gmx.net Wed Mar 14 14:49:17 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Wed, 14 Mar 2007 19:49:17 +0100 Subject: os.path.basename() - only Windows OR *nix? Message-ID: <45F843AD.6050509@gmx.net> Hello, I have a cgi script that handles fileuploads from windows and *nix machines. i need os.path.basename(filename) to get the pure filename. For *nix, thats not a problem, but for windows, it always returns the full path: #/usr/bin/env python import cgi, os import cgitb; cgitb.enable() form = cgi.FieldStorage() filename = os.path.basename(form['uploadfile'].filename) print 'Content-Type: text/html\n\n' print filename ----------------- For 'C:\text\text.txt', the output is 'C:\text\text.txt', which should be 'text.txt', the same happens for 'C:\\text\\text.txt'. I think its the escapes that makes python not splitting it. All Unix style paths get converted the right way. Is there an easy way around this, or do I really have to write a parser including _all_ Python escapes? Thomas From anil.jupiter9 at gmail.com Sat Mar 10 09:39:13 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 10 Mar 2007 06:39:13 -0800 Subject: Database module & multithreading In-Reply-To: <45f2bfbd$0$5094$ba4acef3@news.orange.fr> References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> Message-ID: <1173537553.064123.13260@t69g2000cwt.googlegroups.com> On Mar 10, 7:29 pm, Laurent Pointal wrote: > jupiter wrote: > > Hi guys!!! > > > Just one quick question... Which database module should I use when I > > want to use multi threading as my application requires lots of data > > from internet ???? I also want this database module to be fast, simple > > n efficient, in any case multi threading capabilities are # 1 > > requirement. > > > Thanx Guys > > > Anil > > See the threadsafety flag of Python DB-API V2 compliant database modules. > 0 = no thread safe > 1 = threads may share module > 2 = + may share connections > 3 = + may share cursors > > A+ > > Laurent. Thanx for this pointer buddy! I have done my homework. Some Database modules are not actively maintained some modules does not work with Python 2.5. At this moment I am using Sqlite3 which is pretty fast but it dosent allow me to use multi threading so which database module is better in terms of multithreading @ From aleax at mac.com Thu Mar 29 11:33:33 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Mar 2007 08:33:33 -0700 Subject: Finding a module's sub modules at runtime References: <460ab913$0$16387$88260bb3@free.teranews.com> <1175112265.427331.93340@o5g2000hsb.googlegroups.com> <460ac66a$0$16290$88260bb3@free.teranews.com> Message-ID: <1hvqae5.1alie2515sbssfN%aleax@mac.com> Joshua J. Kugler wrote: > still be nicely portable. It just seems that since Python is gathering > that information anyway, it should make it available without me having to > walk the directory tree. Sorry, where is Python "gathering that information anyway"? Unless I'm mistaken, Python by default does not walk directory trees of subpackages -- what makes you think it does? Alex From rNOSPAMon at flownet.com Thu Mar 1 13:05:48 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 01 Mar 2007 10:05:48 -0800 Subject: Python on a mac: how to build pythonw? References: Message-ID: In article , Robert Kern wrote: > Ron Garret wrote: > > I'm trying to run the Python examples distributed with XCode and they > > all give me the same error: > > > > Traceback (most recent call last): > > File "checktext.py", line 35, in > > main() > > File "checktext.py", line 8, in main > > pathname = EasyDialogs.AskFileForOpen(message='File to check > > end-of-lines in:') > > File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 650, in > > AskFileForOpen > > _interact() > > File "/usr/local/lib/python2.5/plat-mac/EasyDialogs.py", line 53, in > > _interact > > AE.AEInteractWithUser(50000000) > > MacOS.Error: (-1713, 'no user interaction is allowed') > > > > Googling reveals that the answer is to use pythonw, but there is no such > > thing installed on my system: > > > > [ron at mickey:~]$ pythonw > > -bash: pythonw: command not found > > > > Apparently, pythonw didn't get built when I installed Python 2.5, and I > > can't find any instructions on how to build it. (The installation > > instructions don't seem to mention it.) > > It looks like you built Python yourself. Yep. I'm a do-it-yourself kind of guy :-) > The default build does not allow you to > communicate with the Apple GUI. You need a framework build. I highly > recommend > that you simply use the binary on www.python.org instead of building from > source. If you do want to build from source, please read the file Mac/README > for instructions. Okeydokey. > Note that in recent versions of Python, I believe that the pythonw executable > is no longer necessary as a workaround. How recent? I'm already using 2.5. Thanks! rg From ptmcg at austin.rr.com Sun Mar 18 22:38:52 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Mar 2007 19:38:52 -0700 Subject: Mastering Python In-Reply-To: <1174055241.079644.160750@e1g2000hsg.googlegroups.com> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1174052358.486071.163280@e65g2000hsc.googlegroups.com> <1174055241.079644.160750@e1g2000hsg.googlegroups.com> Message-ID: <1174271932.463826.106290@n59g2000hsh.googlegroups.com> On Mar 16, 9:27 am, "BartlebyScrivener" wrote: > On Mar 16, 8:39 am, "Paul McGuire" wrote: > > > > > Wow, are you still reading? Quit wasting time and go download a > > Python dist and get started already! > > I think you should extract that and spend twenty minutes tidying it up > and then publish it to the Python for Programmers page or make it a > downloadable .pdf. > > http://wiki.python.org/moin/BeginnersGuide/Programmers > > rd > > "The chief contribution of Protestantism to human thought is its > massive proof that God is a bore." > > --H.L. Mencken I've added it to this page, see the last entry. Hope some find it entertaining, if not informative. -- Paul From eglaser at gmail.com Thu Mar 15 08:26:33 2007 From: eglaser at gmail.com (eglaser at gmail.com) Date: 15 Mar 2007 05:26:33 -0700 Subject: spawn process in a new console window In-Reply-To: References: <1173923782.156260.299930@p15g2000hsd.googlegroups.com> <1173931166.767205.220880@l77g2000hsb.googlegroups.com> Message-ID: <1173961593.622422.172720@b75g2000hsg.googlegroups.com> On Mar 15, 5:12 am, Laurent Pointal wrote: > gregpin... at gmail.com a ?crit : > > > > > On Mar 14, 9:56 pm, egla... at gmail.com wrote: > >> Hello, > > >> I have a script that launches a sequence of other programs, some GUI, > >> some console. I'd like the console programs to launch in their own > >> console window, instead of all of them sharing the script's console. > >> How do I do that? > > > Would the subprocess module help here? It's available in Python 2.4 > > onwards. I think it's supposed to be a one stop shop for all your > > external application launching needs (Python group, please correct me > > if I'm wrong here). > > > -Greg > > Try to use "start" > > >>> import os > >>> os.system("start cmd") > > Open a new console with a cmd shell in it. > > See start documentation herehttp://www.ss64.com/nt/start.html > Or typing help start on the command line. It looks like 'start' might be exactly what I need. Thanks. Eli From exarkun at divmod.com Sat Mar 3 00:45:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 3 Mar 2007 00:45:37 -0500 Subject: implementing SFTP using Python In-Reply-To: <683868.19200.qm@web38806.mail.mud.yahoo.com> Message-ID: <20070303054537.17852.1051043701.divmod.quotient.2193@ohm> On Fri, 2 Mar 2007 20:42:55 -0800 (PST), kadarla kiran kumar wrote: >Hi Everybody, > > I have to implement SFTP conection from client to the server using Python script. > Iam very new new to python , and i dont't have much time to complete this. So I need some pointers from you. > > If anybody has already done this kind of stuff, please let me know. Please don't think Iam over ambitious, but i need some kind of Pseudo code ,if possible source code. http://www.google.com/search?hl=en&safe=off&q=%22python+sftp+server%22&btnG=Search might be a place to start. Jean-Paul From dcramer at gmail.com Sat Mar 10 22:23:44 2007 From: dcramer at gmail.com (David Cramer) Date: 10 Mar 2007 19:23:44 -0800 Subject: Python in a desktop environment Message-ID: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> If you had an application that you were about to begin development on which you wanted to be cross platform (at least Mac and Windows), would you suggest using c++ and Python? I'm asking because we were originally thinking about doing c# but after attending PyCon this year I'm reconsidering. We are already using Python for the website and I figure a c++ backend w/ a Python GUI may work really well, and would be pretty easy to port. Any opinions? From http Sun Mar 11 08:05:50 2007 From: http (Paul Rubin) Date: 11 Mar 2007 04:05:50 -0800 Subject: a better solution for GUI in python References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> Message-ID: <7xmz2kq929.fsf@ruckus.brouhaha.com> "ce" writes: > My company is using python currently for our website. We need to > develop a GUI front-end for our ERP that would be portable (Windows > and Linux). Some reason not to use a browser interface instead of a client gui? From laurent.pointal at wanadoo.fr Wed Mar 7 13:10:49 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Wed, 07 Mar 2007 19:10:49 +0100 Subject: Generator expression parenthesis mixed with function call ones References: Message-ID: <45eeff24$0$27370$ba4acef3@news.orange.fr> Dennis Lee Bieber wrote: > On Wed, 07 Mar 2007 17:15:33 +0100, Laurent Pointal > declaimed the following in comp.lang.python: > >> >> How a Python beginner know that he is using a generator and not a >> list-comprehension ? >> > A list comprehension ALWAYS has list brackets [...] around it... Yes, and a generator expression ALWAYS has round brackets... which can be confused with function call ones when it is used in a single argument function call... I still personnaly think function call round brackets and generator expression round brackets should both be present. From lobais at gmail.com Fri Mar 23 10:29:17 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Fri, 23 Mar 2007 15:29:17 +0100 Subject: Exception passing Message-ID: Hi, I have a function, which looks like the following: connecting = False def func (): global connecting connecting = True try: # Do lot of network stuff except Exception, e: connecting = False raise e This works quite good, but it is a hell to debug. Instead of getting a log message to the line which originally raised the exception. Is there anyway to reraise an exception, but preserve the log? From jjl at pobox.com Sat Mar 10 20:24:06 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 11 Mar 2007 01:24:06 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again References: <45eab67a@news.vo.lu> <3hDGh.5963$jx3.2552@newssvr25.news.prodigy.net> <87tzwszmdc.fsf@pobox.com> <_3IIh.9178$jx3.4584@newssvr25.news.prodigy.net> Message-ID: <87d53gzi6c.fsf@pobox.com> John Nagle writes: > John J. Lee wrote: > > John Nagle writes: > > > >>skip at pobox.com wrote: > > Traditionally, in the open source world, one does something about it, > > or shuts up after having made one's point, say, ten or twenty times > > In retail, there's an assumption that for every customer who complains > about a real problem, about a hundred customers noticed it and didn't complain, > and about twenty of them will never come back. ...and, in the gift economy of open source, it's for the giver to recognise that, and the receiver to stop whingeing about it. John From irmen.NOSPAM at xs4all.nl Wed Mar 28 18:09:26 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 29 Mar 2007 00:09:26 +0200 Subject: How can I find out the size of a file In-Reply-To: <1175119748.481117.107910@y80g2000hsf.googlegroups.com> References: <1175119748.481117.107910@y80g2000hsf.googlegroups.com> Message-ID: <460ae7d0$0$338$e4fe514c@news.xs4all.nl> Marko.Cain.23 at gmail.com wrote: > How can I find out the size of a file in a disk in python? os.path.getsize(filename) -Irmen From deets at nospam.web.de Sat Mar 24 14:07:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 24 Mar 2007 19:07:56 +0100 Subject: Join strings - very simple Q. In-Reply-To: <1174758072.851763.80860@e1g2000hsg.googlegroups.com> References: <1174675011.244339@jubilee.claranet.pt> <1174676818.207543.246080@l75g2000hse.googlegroups.com> <1174678166.970277@jubilee.claranet.pt> <1174737587.638835.137070@y80g2000hsf.googlegroups.com> <1174758072.851763.80860@e1g2000hsg.googlegroups.com> Message-ID: <56l7o3F29kgs9U2@mid.uni-berlin.de> 7stud schrieb: > On Mar 24, 8:30 am, Duncan Booth wrote: >> In case you are feeling that the ','.join(l) looks a bit jarring, be aware >> that there are alternative ways to write it. You can call the method on the >> class rather than the instance: >> >> jl = str.join(',', l) >> jl = unicode.join(u'\u00d7', 'l') >> >> ... the catch is you need to know >> the type of the separator in advance. > > When I try the latter example, I get an error: > > lst = ["hello", "world"] > print unicode.join(u"\u00d7", lst) > > Traceback (most recent call last): > File "test1.py", line 2, in ? > print unicode.join(u"\u00d7", lst) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xd7' in > position 5: ordinal not in range(128) You are mixing unicode with bytestrings here. make "hello" u"hello", same for "world". Diez From jordan.taylor2 at gmail.com Fri Mar 16 08:36:13 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 16 Mar 2007 05:36:13 -0700 Subject: python noob, multiple file i/o In-Reply-To: <45fa88e4$0$27372$ba4acef3@news.orange.fr> References: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> <1174035726.525608.3340@e1g2000hsg.googlegroups.com> <1174036100.468116.60780@l77g2000hsb.googlegroups.com> <45fa88e4$0$27372$ba4acef3@news.orange.fr> Message-ID: <1174048573.649381.43360@d57g2000hsg.googlegroups.com> On Mar 16, 7:09 am, Laurent Rahuel wrote: > Maybe the walk method in os module is what you needhttp://docs.python.org/lib/os-file-dir.html > > Regards > > Jon Clements wrote: > > On 16 Mar, 09:02, "Jon Clements" wrote: > >> On 16 Mar, 03:56, "hiro" wrote: > > >> > Hi there, > > >> > I'm very new to python, the problem I need to solve is whats the "best/ > >> > simplest/cleanest" way to read in multiple files (ascii), do stuff to > >> > them, and write them out(ascii). > > >> > -- > >> > import os > > >> > filePath = ('O:/spam/eggs/') > >> > for file in os.listdir(filePath): #straight from docs > >> > # iterate the function through all the files in the directory > >> > # write results to separate files <- this is where I'm mostly > >> > stuck. > > >> > -- > >> > For clarity's sake, the file naming conventions for the files I'm > >> > reading from are file.1.txt -> file.nth.txt > > >> > It's been a long day, i'm at my wits end, so I apologize in advance if > >> > I'm not making much sense here. > >> > syntax would also be great if you can share some recipes. > > >> I'd try the glob module. > > >> [code] > >> import glob > > >> # Get a list of filenames matching wildcard criteria > >> # (note that path is relative to working directory of program) > >> matching_file_list = glob.glob('O:/spam/eggs/*.txt') > > >> # For each file that matches, open it and process it in some way... > >> for filename in matching_file_list: > >> infile = file(filename) > >> outfile = file(filename + '.out','w') > >> # Process the input file line by line... > >> for line in infile: > >> pass # Do something more useful here, change line and write to > >> outfile? > >> # Be explicit with file closures > >> outfile.close() > >> infile.close() > >> [/code] > > >> Of course, you can change the wild card criteria in the glob > >> statement, and also then filter further using regular expressions to > >> choose only files matching more specific criteria. This should be > >> enough to get you started though. > > >> hth > > >> Jon.- Hide quoted text - > > >> - Show quoted text - > > > Okies; postcoding before finishing your early morning coffee is not > > the greatest of ideas! > > > I forgot to mention that glob will return pathnames as well. You'll > > need to check that os.path.isfile(filename) returns True before > > processing it... > > > Jon. Also, leaving the format as .out is not necessarily convenient. You had glob do a search for .txt, so how about doing: Also, Python advises using open() over file() (although I admit to using file() myself more often than not) >>for filename in matching_file_list: >> infile = open(filename,'r') # add 'r' for clarity if nothing else >> outfile = open(filename[:-4] + '.out.txt','w') # assumes file ext of original file is .txt >> # Process the input file line by line... >> for line in infile: >> pass # do thing --> you don't have to iterate line by line, if you specified what you wanted to do to each file we could probably help out here if you need it. >> # Be explicit with file closures >> outfile.close() >> infile.close() Might also add some try/except statements to be safe ;). Cheers, Jordan From jstroud at mbi.ucla.edu Fri Mar 16 20:44:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 16 Mar 2007 17:44:00 -0700 Subject: Executing a list of functions In-Reply-To: <1174081591.638287.152370@y66g2000hsf.googlegroups.com> References: <1174081591.638287.152370@y66g2000hsf.googlegroups.com> Message-ID: HMS Surprise wrote: > Seems to me that one should be able to put the names of several > functions in a list and then have the list executed. But it seems the > output of the functions is hidden, only their return value is visible. > Is this because the list execution is another scope? > > Thanx, > > jh > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > def a(): > print "this is a" > > def b(): > print "this is b" > > lst = [a(), b()] > > lst > The "print" statement does nothing to return a value from the function, so the strings "this is *" will not be stored in your list. They will, however, be printed if you are some how observing your program output (e.g. running it in IDLE, or a command shell). To save the "results" of the functions, you need to produce results, which means actually using "return" to return some value. Here is an example: def a(): print "this is a" return "return value from a" def b(): print "this is b" return "return value from b" functions = [a, b] results = [f() for f in functions] print results Here is the result of this example: py> def a(): ... print "this is a" ... return "return value from a" ... py> def b(): ... print "this is b" ... return "return value from b" ... py> functions = [a, b] py> results = [f() for f in functions] this is a this is b py> print results ['return value from a', 'return value from b'] A fun, but unfortunately deprecated, way to do this is with the "apply" function in conjunction with the "map" function: def a(): print "this is a" return "return value from a" def b(): print "this is b" return "return value from b" functions = [a, b] results = map(apply, functions) print results Here is this example at work: py> def a(): ... print "this is a" ... return "return value from a" ... py> def b(): ... print "this is b" ... return "return value from b" ... py> functions = [a, b] py> results = map(apply, functions) this is a this is b py> print results ['return value from a', 'return value from b'] James From frank-python at benkstein.net Thu Mar 22 13:25:11 2007 From: frank-python at benkstein.net (Frank Benkstein) Date: Thu, 22 Mar 2007 18:25:11 +0100 Subject: challenge ? In-Reply-To: <20070322181146.6ac4999d@localhost> References: <1174581702.968531.82550@y66g2000hsf.googlegroups.com> <20070322181146.6ac4999d@localhost> Message-ID: <20070322182511.07fdf4d4@localhost> Hi, again, On Thu, 22 Mar 2007 18:11:46 +0100 Frank Benkstein wrote: > On 22 Mar 2007 09:41:43 -0700 > "alain" wrote: > > > I have a problem I wonder if it has been solved before. > > I have a dictionnary and I want the values in the dictionnary to be > > annotated with the rank that would be obtained by sorting the values > > > > def annotate_with_rank(my_dict): > > .... > > return my_annotated_dict > > > > In other words, any value a_value would become a 2-tuple > > (a_value,rank_of_a_value) > > > > I seek an elegant solution. > > In your specification of the problem it is unclear what should be done > with duplicate values. My solution assigns every value a different > rank (starting from 0) such that the highest rank is len(my_dict) - 1. The two other possibilities were to still make len(my_dict) ranks but assign equal values an equal rank. That would mean that some ranks are untaken. Or, lastly, to make only as much ranks as there are unique values. > def annotate_with_rank(my_dict): > items = my_dict.items() > items.sort(key = lambda (k, v): v) > return dict((k, (i, v)) for i, (k, v) in enumerate(items)) def annotate_with_rank_2(my_dict): values = my_dict.values() values.sort() return dict((k, (values.index(v), v)) for k, v in my_dict.iteritems()) def annotate_with_rank_3(my_dict): values = list(set(my_dict.itervalues())) values.sort() return dict((k, (values.index(v), v)) for k, v in my_dict.iteritems()) Best regards, Frank Benkstein. -- GPG (Mail): 7093 7A43 CC40 463A 5564 599B 88F6 D625 BE63 866F GPG (XMPP): 2243 DBBA F234 7C5A 6D71 3983 9F28 4D03 7110 6D51 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mail at microcorp.co.za Sun Mar 11 06:27:32 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 11 Mar 2007 12:27:32 +0200 Subject: distributed queue? References: <7xwt1olnlx.fsf_-_@ruckus.brouhaha.com><55h495F250nqbU1@mid.individual.net> <7xhcsssgsm.fsf@ruckus.brouhaha.com> Message-ID: <01ad01c763cc$0218b3c0$03000080@hendrik> "Paul Rubin" wrote: > Bjoern Schliessmann writes: > > (Why does everyone think that "concurrency" equals "usage of > > multiple threads"?) > > Well, it doesn't necessarily, but that's easiest a lot of the time. > > > Try Twisted for your networking needs. > > I should try to understand Twisted better one of these days, but it's > much more confusing than threads. Also, the function I want to > parallelize does blocking operations (database lookups), so in Twisted > I'd have to figure out some way to do them asynchronously. I would think of making 'pullers' in the remote machines in front of whatever it is you are making parallel to get the next thing to do, from a 'queue server' in the originating machine to distribute the stuff. I am not sure if Pyro can help you as I have only read about it and not used it but I think its worth a look. If it were a one on one setup I would not hesitate to recommend it but I can't remember if it is any good for one to many scenarios. - Hendrik From gagsl-py2 at yahoo.com.ar Sun Mar 11 15:48:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 16:48:04 -0300 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> <1173635074.726444.88760@t69g2000cwt.googlegroups.com> <1hut4yc.o9f1kta318hnN%aleax@mac.com> Message-ID: En Sun, 11 Mar 2007 15:26:01 -0300, Alex Martelli escribi?: > Or maybe we should give up ever storing -0.0 in the tables > of constant and ALWAYS have "0.0, unary-minus" wherever it appears (that > would presumably require working on the AST-to-bytecode visitors that > currently work ever-so-slightly-differently for this specific > troublespot in the C-coded version vs the Python-coded one...). I think that way is the less intrusive, doesn't rely on a particular FP implementation, and the more likely to be accepted. Looking at ast.c, the culprit is some optimization in ast_for_factor, line 1506 /* If the unary - operator is applied to a constant, don't generate a UNARY_NEGATIVE opcode. Just store the approriate value as a constant. The peephole optimizer already does something like this but it doesn't handle the case where the constant is (sys.maxint - 1). In that case, we want a PyIntObject, not a PyLongObject. */ After the long "if", I would use parsenumber(STR(pnum)) and check the type and value of the resulting object; if it's a float and 0.0, skip the optimization and continue below as a normal case. Unfortunately I'm not able to compile and test the code right now, so I can't provide an actual patch. (At least, not until tuesday). But I hope this simple comment is useful anyway... (I cannot find peephole.c on the source distribution for Python 2.5, but you menctioned it on a previous message, and the comment above refers to the peephole optimizer... where is it?) -- Gabriel Genellina From anton.vredegoor at gmail.com Fri Mar 30 02:55:48 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 30 Mar 2007 08:55:48 +0200 Subject: Hpw make lists that are easy to sort. In-Reply-To: References: <7xbqidgqy0.fsf@ruckus.brouhaha.com> Message-ID: Terry Reedy wrote: > If I understand correctly, you want to multiiply each of m numbers by each > of n numbers, giving m*n products. That is O(m*n) work. Inserting (and > extracting) each of these is a constant size m priority cue takes, I > believe, O(log(m)) work, for a total of m*n*log(m). That is faster than > O(m*n*log(m*n)) for sorting m*n random numbers. According to this page: http://maven.smith.edu/~orourke/TOPP/P41.html You are very close. The only thing is whether the logarithmic factor can be removed. But there's more: If the input consists of n integers between - M and M, an algorithm of Seidel based on fast Fourier transforms runs in O(n + M log M) time [Eri99a]. The $ \Omega$(n2) lower bounds require exponentially large integers. So maybe there is something at least for this specific case. I hope I'm not irritating someone by posting my thought processes here, since posting things sometimes seems to be the only way to find the links. I wonder if it's the selective attention that makes them turn up after posting or whether your talk about big O's has put me on the right track. Thanks anyway. The problem is still open in general, but some hacks are possible, as Paul Rubin said. A. From esj at harvee.org Fri Mar 23 11:30:42 2007 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 23 Mar 2007 11:30:42 -0400 Subject: fine grain logging cotrol In-Reply-To: References: Message-ID: Peter Otten wrote: > Eric S. Johansson wrote: > > [in private mail -- please don't, Eric] sorry. my preference is for private mail. it's my way of trying to be kind to others by reducing list clutter. > I don't understand. The logging package detects the function name without > user intervention. not in 2.4 afaik. according to the docs for debug/info it the only kwargs which is inspected is exc_info. > Perhaps it's time to step back and explain what you want to achieve rather > than how you proceed. print a log message if a predicate yields true. should be able to have different predicates. the desired predicate is a match on class, method, and level number. class and method should be found automatically by the logging predicate code. apologies again for violating your email protocol and thanks for the help. From antoine at vo.lu Sun Mar 4 14:38:16 2007 From: antoine at vo.lu (Antoine De Groote) Date: Sun, 04 Mar 2007 20:38:16 +0100 Subject: looking for Java final/Ruby freeze functionality in Python Message-ID: <45eb1fdf$1@news.vo.lu> Hello, I've been googling for quite a while now but can't find anything about a function/keyword to make a list (or something else) immutable. Could anybody point me to docs about this matter or give me a reason why this (apparently) doesn't exist in Python? Kind regards, antoine From bdesth.quelquechose at free.quelquepart.fr Tue Mar 20 17:19:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 20 Mar 2007 22:19:26 +0100 Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <1174293300.034362.282460@l75g2000hse.googlegroups.com> <45ffa91e$0$2136$426a74cc@news.free.fr> Message-ID: <4600476b$0$752$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 20 Mar 2007 10:28:10 +0100, Bruno Desthuilliers wrote: > > [deploying weapons of mass snippage] Lol !-) > >>>Otherwise, the choice between old >>>and new is not very important. >> >>Your opinion. Too bad you're missing some of the most powerful parts of >>the language. > > > Yes, it is my opinion, and it seems that in your zeal to defend new-style > classes against an imaginary attack, you've completely misunderstood what > my opinion is. Your opinion, as I understood it, is that it's not worth six extra keystrokes (in the worse case) to get the full power of Python's object model. > I'm not against new-style classes. I do use new-style classes. So why do you use old-style ones too ? Seems like it would be simpler to stick to new-style whatever, no ? > There are a > whole lot of extra features that new-style classes have that old-style > classes don't have, some of which I didn't even think of. (Thanks for > pointing them out, and I'm not being sarcastic.) > > There are plenty of reasons for preferring new style classes. If those > reasons hold for you, then of course you should use new style classes. > > But that's not the same thing as saying that you should use new style > classes *even when you don't care about those features*. Could we see it the other way round ? Everything you can do with old-style classes (except writing code compatible with more than six-years old python interpreters), you can do with new-styles. So why even wasting time asking yourself if you need these features now or will need them later ? Saving six extra keystrokes ? How much time do you need to type 'object' ? Certainly less than 1 second. And how much time will you spend when you'll find out that you finally need some of these 'extra' features ? > I never once suggested that new style classes are unnecessary, or a waste > of time, or bad, or whatever else you seem to think I was saying. My point > was, if you don't _need_ a new style class, there is no reason to avoid > using an old style class. It is a purely personal choice. My point is that there's no reason to keep on using old-style classes (compatibility with six-years old interpreters set aside). > There seems to be a misunderstanding that classic classes have been > depreciated. They certainly have not. Not officially yet, true. But come on, it's been 6 (six) years since type unification, and it has always been obvious (to me at least) that the new object model was to replace the 'classic' one. From kyosohma at gmail.com Fri Mar 23 09:30:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Mar 2007 06:30:50 -0700 Subject: Catching an unknown error In-Reply-To: <1174656547.825228.54240@e65g2000hsc.googlegroups.com> References: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> <1174656547.825228.54240@e65g2000hsc.googlegroups.com> Message-ID: <1174656650.409980.60280@e65g2000hsc.googlegroups.com> On Mar 23, 8:29 am, kyoso... at gmail.com wrote: > On Mar 23, 8:16 am, "Harlin Seritt" wrote: > > > > > Using the code below: > > > ---BEGIN CODE--- > > > value = raw_input("Type a divisor: ") > > try: > > value = int(value) > > print "42 / %d = %d" % (value, 42/value) > > except ValueError: > > print "I can't convert the value to an integer" > > except ZeroDivisionError: > > print "Your value should not be zero" > > except: > > print "Something unexpected happened" > > > ---END CODE--- > > > In the last 'except' block, how can I print out the particular error > > name even though one is not specifically named? > > > Thanks, > > > Harlin > > Make the last 'except' block like this: > > Except Exception, e: > print e > > Mike just don't capitalize the word "except" ... my bad From phd at phd.pp.ru Mon Mar 19 12:39:53 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 19 Mar 2007 19:39:53 +0300 Subject: SQLObject 0.7.4 Message-ID: <20070319163953.GB32328@phd.pp.ru> Hello! I'm pleased to announce the 0.7.4 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.4 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.3 ---------------- * Documentation updates Small Features -------------- * For MySQLdb 1.2.2+ call ping(True) on the connection to allow autoreconnect after a timeout. Bug Fixes --------- * Another round of changes to create/drop the tables in the right order in the command-line client `sqlobject-admin`. * Fixed a bug in UnicodeField - allow comparison with None. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mccredie at gmail.com Mon Mar 5 20:16:21 2007 From: mccredie at gmail.com (Matimus) Date: 5 Mar 2007 17:16:21 -0800 Subject: Is every number in a list in a range? In-Reply-To: <1173130489.377736.312100@30g2000cwc.googlegroups.com> References: <1173130489.377736.312100@30g2000cwc.googlegroups.com> Message-ID: <1173143781.522198.111870@q40g2000cwq.googlegroups.com> On Mar 5, 1:34 pm, "Matimus" wrote: > On Mar 5, 11:03 am, "Steven W. Orr" wrote: > > > I have a list ll of intergers. I want to see if each number in ll is > > within the range of 0..maxnum > > > I can write it but I was wondering if there's a better way to do it? > > > TIA > > > -- > > Time flies like the wind. Fruit flies like a banana. Stranger things have .0. > > happened but none stranger than this. Does your driver's license say Organ ..0 > > Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 > > individuals! What if this weren't a hypothetical question? > > steveo at syslang.net > > I would probably do something using max and min functions like this: > > seq = [...] # your list > > if min(seq) >= 0 && max(seq) <= MAXNUM: > do stuff OOps... I've been writing too much C++ lately (or too little python). That should read: if min(seq) >= 0 and max(seq) <= MAXNUM: do_stuff() From markbpan at mailinator.com Fri Mar 23 03:30:58 2007 From: markbpan at mailinator.com (Mark) Date: 23 Mar 2007 07:30:58 GMT Subject: Idiom for running compiled python scripts? References: Message-ID: On Fri, 23 Mar 2007 14:03:12 +1100, Steven D'Aprano wrote: > Since you've done these tests already, perhaps you can tell us what gain > you actually got? About the same as you, ~20 msecs for my small script samples. > Of course you have to type the "c". You're not deleting the source files > away are you? *wink* Sorry, the wink is lost on me? Of course I am not deleting the sources. In fact, I am also talking about python scripts being called from shell scripts. I guess I'm just surprised that the python installation does not provide a small stub invoker, e.g: A small script called "python_compile_and_run" in "pseudo" code: #!/usr/bin/env python import sys # Following is invalid syntax unfortunately :( from sys.argv[1].rstrip('.py') import main sys.argv = sys.argv[1:] if __name__ == "__main__": main() so I could just do a "python_compile_and_run myscript.py" and it would do what I want, i.e. run myscript.pyc if available and valid, generate and run it if necessary. From john106henry at hotmail.com Mon Mar 19 14:21:20 2007 From: john106henry at hotmail.com (John Henry) Date: 19 Mar 2007 11:21:20 -0700 Subject: PythonCard or Dabo? In-Reply-To: References: Message-ID: <1174328480.776648.250990@b75g2000hsg.googlegroups.com> On Mar 19, 10:24 am, Kevin Walzer wrote: > I'm curious to know what others think of these two frameworks for > building wxPython apps. > > PythonCard has been around longer, but its development seems to have > slowed. The last release, 0.8.2, has been out for quite awhile now. > > Dabo is newer and seems to have gathered a lot of buzz. > > Anyone try both? What's your preference and why? Is one more robust than > the other? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com It all depends on what your needs are. I agree with Steve's comment that the two packages has somewhat of a different application in mind. If you need a working GUI application working *really* quick, I highly recommend Pythoncard - but if you need anything else, you might look at other packages. You might not see lots of development activities with Pythoncard but sometimes not being the breeding edge has its place. From rdm at rcblue.com Sat Mar 17 06:21:41 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 17 Mar 2007 03:21:41 -0700 Subject: Weekly Python Patch/Bug Summary In-Reply-To: References: <200703170454.l2H4skKe003172@bayview.thirdcreek.com> <20070317075121.565D11E4005@bag.python.org> Message-ID: <20070317102146.4440B1E4010@bag.python.org> At 01:32 AM 3/17/2007, Terry Reedy wrote: >"Dick Moores" wrote in message >news:20070317075121.565D11E4005 at bag.python.org... >| May I ask a dumb question here? It isn't clear to me what to do with >these patches. For most of them there is something like, "Committed as >r54386 and r54387". I'm familiar with updating the editor Ulipad to the >latest revision, using software such as TortoiseSVN and RapidSVN. Is that >what is meant? And if so, what's the URL of the trunk? >--------- > >Yes, those are svn revision numbers. Start at svn.python.org. I thought I'd give (the latest release (plus bug fixes) of Python) a try. I first backed up my Python25 folder (I'm using Win XP). Then with Python 25 open I opened the Explorer context menu for the folder and then the TortoiseSVN sub-menu. There doesn't seem to have a menu item that will enable me to update. I tried Export... and entered as "URL of repository", but that choice seems to expect the Python25 folder to be empty. Can you tell me what to do to just update? Dick From miki.tebeka at gmail.com Thu Mar 22 17:04:28 2007 From: miki.tebeka at gmail.com (Miki) Date: 22 Mar 2007 14:04:28 -0700 Subject: Making GIF image twice the size - in memory Message-ID: <1174597468.170020.115340@e65g2000hsc.googlegroups.com> Hello All, I get an image from a web page (via urlopen), and like to make it twice the size. I'm trying (using PIL): ---- code ---- from ImageFile import Parser def double(image_data): image_parser = Parser() image_parser.feed(image_data) im = image_parser.close() new_size = tuple(map(lambda x: 2 * x, im.size)) new = im.resize(new_size) return new.tostring("gif", "P") # This is probably the problem, have no idea image_data = urlopen(url).read() image_data = double(image_data) ---- code ---- However I don't get a valid GIF image. Any ideas? Thanks, Miki http://pythonwise.blogspot.com From lojicdotcomNOSPAM at gmail.com Thu Mar 8 00:35:13 2007 From: lojicdotcomNOSPAM at gmail.com (Brian Adkins) Date: Thu, 08 Mar 2007 00:35:13 -0500 Subject: merits of Lisp vs Python In-Reply-To: <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> Message-ID: John Nagle wrote: > Brian Adkins wrote: >> alex23 wrote: >> >>> John Nagle wrote: >>> >>>> Hosting providers and distro >>>> makers aren't concerned over whether Python works. They >>>> care if C, C++, Java, PHP, and Perl work, but not Python or LISP. >>>> Ask them. >>> >>> >>> Do you have any real experience with recent linux distros? Or with any >>> _real_ hosting providers? > > Do you? You're writing from a gmail account, not your own site. > > I have four hosting accounts with EZpublishing and a dedicated server > at Aplus.net. I spent weeks trying to find a hosting provider that > would provide a Python environment that "just works", like everyone > does for Perl. What you typically get is a basic Python 2.4, > and a refusal to install more packages, because it's so time-consuming. > Or a quote of $50 to $150 per hour to install Python packages. > > There are a very few hosting providers that actually want to provide > Python hosting, such as Hard Hat Hosting. But most don't. >>> >>> Because what you've said is clearly not true. Just because the >>> situation isn't as easy _for you_ as you would like, doesn't mean that >>> Python is being ignored to the extent you're trying to claim. > > I don't see any evidence to back up this unsubstantiated claim. > > John Nagle Ok, since you provided some details you appear less troll-like, so I'll ignore my own advice. With prices of dedicated servers and virtual private servers so cheap, why would anyone get a hosting account without root access? Once you have root, just install whatever you want. It shouldn't take more than a few minutes to install Python or whatever language you desire. If "apt-get install" doesn't give you a recent enough version, just download the source and compile it. Brian P.S. very cool rag doll physics by the way... From AWasilenko at gmail.com Mon Mar 19 01:22:45 2007 From: AWasilenko at gmail.com (AWasilenko at gmail.com) Date: 18 Mar 2007 22:22:45 -0700 Subject: struct.pack returns nothing In-Reply-To: References: Message-ID: <1174281765.884607.113420@p15g2000hsd.googlegroups.com> On Mar 19, 1:12 am, andma... at gmail.com wrote: > If I build a strict with: > > import struct > print struck.pack ('i', 1) > > it returns a '\n'. > What's wrong with it??? > :( > > -- > Andr?s M. > --------------------------------------------- Looks like you spelled struct wrong in the code :) From tiedon_jano at hotmail.com Sun Mar 4 02:55:19 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 04 Mar 2007 07:55:19 GMT Subject: Sorting strings containing special characters (german 'Umlaute') In-Reply-To: References: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> <54r2c4F21fssbU1@mid.individual.net> Message-ID: Robin Becker kirjoitti: > > Bj?rn, in one of our projects we are sorting in javascript in several > languages English, German, Scandinavian languages, Japanese; from > somewhere (I cannot actually remember) we got this sort spelling > function for scandic languages > > a > .replace(/\u00C4/g,'A~') //A umlaut > .replace(/\u00e4/g,'a~') //a umlaut > .replace(/\u00D6/g,'O~') //O umlaut > .replace(/\u00f6/g,'o~') //o umlaut > .replace(/\u00DC/g,'U~') //U umlaut > .replace(/\u00fc/g,'u~') //u umlaut > .replace(/\u00C5/g,'A~~') //A ring > .replace(/\u00e5/g,'a~~'); //a ring > > does this actually make sense? I think this order is not correct for Finnish, which is one of the Scandinavian languages. The Finnish alphabet in alphabetical order is: a-z, ?, ?, ? If I understand correctly your replacements cause the order of the last 3 characters to be ?, ?, ? which is wrong. HTH, Jussi From cjlesh at gmail.com Thu Mar 22 13:42:18 2007 From: cjlesh at gmail.com (cjl) Date: 22 Mar 2007 10:42:18 -0700 Subject: parsing tables with beautiful soup? In-Reply-To: References: <1174499030.042369.312350@n76g2000hsh.googlegroups.com> <1174500627.339029.65590@n76g2000hsh.googlegroups.com> Message-ID: <1174585338.122634.219470@b75g2000hsg.googlegroups.com> DB: Thank you, that worked perfectly. -CJL From magoldfish at gmail.com Tue Mar 6 17:19:21 2007 From: magoldfish at gmail.com (Marcus) Date: 6 Mar 2007 14:19:21 -0800 Subject: calendar (date) iterator? In-Reply-To: References: <1173210910.945107.255850@64g2000cwx.googlegroups.com> Message-ID: <1173219561.475200.42300@h3g2000cwc.googlegroups.com> On Mar 6, 3:19 pm, s... at pobox.com wrote: > Marcus> I'm looking for useful starting points, suggestions, and sample > Marcus> code, to implement a calendar iterator. > > Have you looked at dateutil? > > http://labix.org/python-dateutil > > >>> from dateutil.rrule import rrule, DAILY > >>> from dateutil.parser import parse > >>> rule = rrule(DAILY, count=5, dtstart=parse("2006-03-12")) > >>> for d in rule: > ... print d > ... > 2006-03-12 00:00:00 > 2006-03-13 00:00:00 > 2006-03-14 00:00:00 > 2006-03-15 00:00:00 > 2006-03-16 00:00:00 > > Skip This is exactly what I was looking for! Thanks so much!! From durumdara at gmail.com Mon Mar 26 09:41:10 2007 From: durumdara at gmail.com (durumdara) Date: Mon, 26 Mar 2007 15:41:10 +0200 Subject: Zip file writing progress (callback proc) Message-ID: <4607CD76.2080008@gmail.com> Hi! I want to check my zip file writings. I need some callback procedure to show a progress bar. Can I do that? I don't want to modify the PyLib module to extend it, because if I get another py, the changes are lost. This happening too if I copy the zip module to modify it. Any solution? Thanks for it: dd From bbxx789_05ss at yahoo.com Thu Mar 15 23:25:21 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Mar 2007 20:25:21 -0700 Subject: problem with str() In-Reply-To: References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> <1173990743.998399.82020@b75g2000hsg.googlegroups.com> Message-ID: <1174015521.516078.103240@l77g2000hsb.googlegroups.com> On Mar 15, 5:31 pm, "Gabriel Genellina" wrote: > The fact that a list comprehension "leaks" its variables into the > containing scope is a bit weird. > A generator expression doesn't: > > py> str > > py> w = (str for str in range(10)) > py> w > > py> str > > py> w.next() > 0 > py> str > On Mar 15, 5:34 pm, Paul Rubin wrote: > or: > > methodList = list(str for str in names if callable(getattr(obj, str))) > > genexps, unlike listcomps, make a new scope for their index variable. Thanks. From kyosohma at gmail.com Mon Mar 26 12:04:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 09:04:02 -0700 Subject: wx.grid problem In-Reply-To: <4607e4f1$0$5098$ba4acef3@news.orange.fr> References: <4607e4f1$0$5098$ba4acef3@news.orange.fr> Message-ID: <1174925041.703904.151900@y80g2000hsf.googlegroups.com> On Mar 26, 10:20 am, BH wrote: > Hi ! > > I have a small problem with wx.Grid and scrollbars. > Scrollbars definitively dissapears after resizing the frame. > > Thx for help > > #---------------------------------------------------------------------- > import wx,wx.grid > #---------------------------------------------------------------------- > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title) > #-- > self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > self.grid.CreateGrid(numRows=10,numCols=2) > self.grid.Fit() > self.Fit() > #-- > self.Show(1) > #---------------------------------------------------------------------- > app = wx.PySimpleApp() > frame=MainWindow(None,-1,'Grid sizer') > app.MainLoop() > del app If I understand this correctly, that is normal. Your grid is only two columns by 10 rows, so if you resize your frame so that it shows all rows and columns, the scroll bars will disappear, much like other apps, such as FireFox. If you enlarge the frame enough, the scrollbars go away. Mike From facundo at taniquetil.com.ar Mon Mar 5 10:43:35 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Mon, 5 Mar 2007 15:43:35 +0000 (UTC) Subject: Why does SocketServer default allow_reuse_address = false? References: <45e3668e$0$16385$88260bb3@free.teranews.com> Message-ID: Joshua J. Kugler wrote: > Considering that UNIX Network Programming, Vol 1 (by W. Richard Stevens) > recommends "_All_ TCP servers should specify [SO_REUSEADDR] to allow the > server to be restarted [if there are clients connected]," and that > self.allow_reuse_address = False makes restarting a server a pain if there > were connected clients, why does SocketServer default allow_reuse_address > to False? It's kind of bemusing to subclass ThreadingTCPServer just to > change one variable that arguably should have been True in the first place. > > Is there some history to this of which I'm not aware? Is there a good > reason for it to default to false? If any, don't know. Searched in already reported bugs to check if somebody already noticed. If not, please consider to open a bug. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steve at REMOVE.THIS.cybersource.com.au Wed Mar 21 12:27:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 03:27:37 +1100 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> <1174488447.404840.112960@n76g2000hsh.googlegroups.com> <1174488908.420851.303850@y66g2000hsf.googlegroups.com> Message-ID: On Wed, 21 Mar 2007 07:55:08 -0700, dmitrey top posted: > I think it should result What's "it"? Please don't top post, it makes your answer hard to understand and makes your readers have to do more work to read your posts. We're not being paid to read your posts, so I'd estimate that about 70% of readers have just clicked "Delete" at this point and ignored you. For those remaining: The Original Poster, dmitrey, wants to copy caml syntax, because he doesn't like brackets and commas. The problem is that the expression: name1 name2 is ambiguous. Does it mean name1(name2) or (name1, name2)? Add a third name, and the ambiguity increases: there are now at least four ways to interpret name1 name2 name3: (name1, name2, name3) (name1, name2(name3)) name1(name2, name3) name1(name2(name3)) Dmitrey thinks that the third way is the "right" way to interpret the proposed expression, just because it seems natural to him. But that is illogical: it means that *different* parsing rules are applied to the "name2 name3" part than to the "name1 *" part (where "*" stands in for anything): Dmitry wants "name1 *" to equal name1(*) which is fair enough as it stands. But he wants to expand the * part, not by following the same rule, but by following the different rule "name2 name3" => (name2, name3) and form a tuple. So what should "a b c d" be? (a, b, c, d) a(b, c, d) a(b, (c, d)) a(b(c, d)) a(b(c(d))) Have I missed anything? Which is the "right" way? Who can tell? Who can guess? I don't know how caml resolves these ambiguities, or even if caml resolves them, or if it is a good solution. But I propose that an even better solution is to insist on EXPLICIT function calls and tuple construction, that is to insist on brackets and commas. In other words, to go back to Dmitry's original post where he wrote: "it would reduce length of code lines and make them more readable" I would change that to say "it would reduce length of code lines and make them LESS readable and MORE ambiguous, leading to MORE bugs". -- Steven. From brojohan at hotmail.com Tue Mar 13 16:23:06 2007 From: brojohan at hotmail.com (Bror Johansson) Date: Tue, 13 Mar 2007 21:23:06 +0100 Subject: ActivePython 2.5.0.0 is now available References: Message-ID: <55ofh7F25cn50U1@mid.individual.net> "Trent Mick" skrev i meddelandet news:mailman.5030.1173815941.32031.python-list at python.org... > I'm happy to announce that ActivePython 2.5.0.0 is now available for > download > from: > http://www.activestate.com/products/activepython/ > > This is the first release of ActivePython for Python version 2.5. > Apologies > for the long delay between core Python 2.5 and this release. The good news > is > that part of the reason for this delay was to finally get approval to > include > crypto in ActivePython, hence: I did notice the download earlier today and I have installed it on five Windows-machines (two WinXPPro and three Win2K) and have found one consistent error. Whenever I try Help->Python Manuals from PythonWin I get this errormessage: "Internal error in help file processing :(2, 'ShellExecute', 'Det g?r inte att hitta filen.') The last few words are swedish (the machine I'm using right here is arunning a swedish WinXP) and has this meaning: "It's not possible to find the file". Is there a remedy for this problem? Bror J. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 07:08:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 13:08:01 +0200 Subject: functions, classes, bound, unbound? In-Reply-To: <1174803233.118069.234290@l75g2000hse.googlegroups.com> References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> Message-ID: <4607a991$0$23165$426a74cc@news.free.fr> 7stud a ?crit : >> ...classes don't invoke the function directly, they convert it to >> an 'unbound method' object:: (snip) > >> If you really want to get to the original function, there are a couple >> of options. > > No. Just trying to figure out how some things work. Most of Python's object model is documented here: http://www.python.org/download/releases/2.2.3/descrintro/ http://users.rcn.com/python/download/Descriptor.htm HTH From psdasilvaX at esotericaX.ptX Thu Mar 15 20:02:13 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 16 Mar 2007 00:02:13 +0000 Subject: Subclassing: what is wrong here? Message-ID: <1174003302.156908@jubilee.claranet.pt> Hi! What's wrong with this way of subclassing? from datetime import date class MyDate(date): def __init__(self,year,month=None,day=None): if type(year) is str: # The whole date is here as a string year,month,day=map(int,string.split(year,'-')) if year<100: year+=2000 date.__init__(self,year,month,day) When I do d=MyDate("2007-3-15") I got Traceback (most recent call last): File "", line 1, in ? TypeError: function takes exactly 3 arguments (1 given) Thanks for any help. From http Sat Mar 10 18:26:13 2007 From: http (Paul Rubin) Date: 10 Mar 2007 15:26:13 -0800 Subject: unsigned integer? References: <7xr6rwhpdb.fsf@ruckus.brouhaha.com> Message-ID: <7xhcssllyi.fsf@ruckus.brouhaha.com> "Gabriel Genellina" writes: > Try again with "%u". Passing i or ui makes no difference, both push > the same value on the stack. C relies on the format string to > interpret the arguments. If you use %u you get a very large positive value, not +3. From attn.steven.kuo at gmail.com Wed Mar 21 03:06:34 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 21 Mar 2007 00:06:34 -0700 Subject: Daylight saving time question In-Reply-To: <6ZWLh.307$rd5.176@read3.inet.fi> References: <6ZWLh.307$rd5.176@read3.inet.fi> Message-ID: <1174460794.926689.194640@p15g2000hsd.googlegroups.com> On Mar 20, 12:53 pm, Mr Pekka Niiranen wrote: > Hi, > > is it possible to get the two annual daylight saving times > (day, month and time) from Python by giving location > in some country/location string ("Europe/Finland" for example). > > I need to ask country in program and calculate daylight > saving times for the next few years onwards somehow like this: > > for y in range(2007, 2017): > (m1,d1,t1,m2,d2,t2) = daylight_change_epochs("Finland") > > -pekka- A generator defined via recursion: import dateutil.rrule, dateutil.tz import datetime mytz = dateutil.tz.tzfile("/usr/share/zoneinfo/Europe/Helsinki") start = datetime.datetime(2007,1,1,0,0,0,tzinfo=mytz) end = datetime.datetime(2017,1,1,0,0,0,tzinfo=mytz) successively_finer = { dateutil.rrule.WEEKLY: dateutil.rrule.DAILY, dateutil.rrule.DAILY: dateutil.rrule.HOURLY, dateutil.rrule.HOURLY: dateutil.rrule.MINUTELY, dateutil.rrule.MINUTELY: dateutil.rrule.SECONDLY } # find week, then day, then hour, etc. that spans a change in DST def sieve (start, end, freq): dstflag = start.timetuple()[-1] iter = dateutil.rrule.rrule(freq,dtstart=start,until=end) tprior = start for t in iter: if t.timetuple()[-1] != dstflag: dstflag = t.timetuple()[-1] if freq == dateutil.rrule.SECONDLY: yield tprior, t else: yield sieve(tprior, t, successively_finer[freq]).next() tprior = t raise StopIteration for before, after in sieve(start, end, dateutil.rrule.WEEKLY): print "%s => %s" % ( before.strftime("%Y-%m-%d %H:%M:%S (%a) %Z"), after.strftime("%Y-%m-%d %H:%M:%S (%a) %Z")) I get: 2007-03-25 02:59:59 (Sun) EET => 2007-03-25 03:00:00 (Sun) EEST 2007-10-28 02:59:59 (Sun) EEST => 2007-10-28 03:00:00 (Sun) EET 2008-03-30 02:59:59 (Sun) EET => 2008-03-30 03:00:00 (Sun) EEST 2008-10-26 02:59:59 (Sun) EEST => 2008-10-26 03:00:00 (Sun) EET 2009-03-29 02:59:59 (Sun) EET => 2009-03-29 03:00:00 (Sun) EEST 2009-10-25 02:59:59 (Sun) EEST => 2009-10-25 03:00:00 (Sun) EET 2010-03-28 02:59:59 (Sun) EET => 2010-03-28 03:00:00 (Sun) EEST 2010-10-31 02:59:59 (Sun) EEST => 2010-10-31 03:00:00 (Sun) EET 2011-03-27 02:59:59 (Sun) EET => 2011-03-27 03:00:00 (Sun) EEST 2011-10-30 02:59:59 (Sun) EEST => 2011-10-30 03:00:00 (Sun) EET 2012-03-25 02:59:59 (Sun) EET => 2012-03-25 03:00:00 (Sun) EEST 2012-10-28 02:59:59 (Sun) EEST => 2012-10-28 03:00:00 (Sun) EET 2013-03-31 02:59:59 (Sun) EET => 2013-03-31 03:00:00 (Sun) EEST 2013-10-27 02:59:59 (Sun) EEST => 2013-10-27 03:00:00 (Sun) EET 2014-03-30 02:59:59 (Sun) EET => 2014-03-30 03:00:00 (Sun) EEST 2014-10-26 02:59:59 (Sun) EEST => 2014-10-26 03:00:00 (Sun) EET 2015-03-29 02:59:59 (Sun) EET => 2015-03-29 03:00:00 (Sun) EEST 2015-10-25 02:59:59 (Sun) EEST => 2015-10-25 03:00:00 (Sun) EET 2016-03-27 02:59:59 (Sun) EET => 2016-03-27 03:00:00 (Sun) EEST 2016-10-30 02:59:59 (Sun) EEST => 2016-10-30 03:00:00 (Sun) EET -- Hope this helps, Steven From bdesth.quelquechose at free.quelquepart.fr Wed Mar 21 17:44:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 21 Mar 2007 22:44:08 +0100 Subject: Technical Answer - Protecting code in python In-Reply-To: <1174496172.528613.236730@p15g2000hsd.googlegroups.com> References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> <1174496172.528613.236730@p15g2000hsd.googlegroups.com> Message-ID: <46019eaf$0$30873$426a74cc@news.free.fr> flit a ?crit : > First I wanna thanks the all people who gives good contribution to > this thread, thank you all.. > Now I have something more to say: > > OK, that kind of answer is what I was trying to avoid.. > (snip half-angry answers to Steven) Flit, whether you like the way Steven expresses itself or not, I think you should get over the tone and pay attention to *what* he actually says. As a side note, and from a purely technical POV, the most reliable protection is to *not* distribute the code. IOW, make your app (or the critical parts of it) a web service. This is not an absolute protection, but that's the best you can get AFAICT. From s.mientki at id.umcn.nl Fri Mar 30 07:26:52 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 30 Mar 2007 13:26:52 +0200 Subject: Library for windows ini-files ? Message-ID: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> hello, is there a Python library for easy reading and writing windows ini-files ? thanks, Stef Mientki From collinstocks at gmail.com Wed Mar 7 17:09:04 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Wed, 7 Mar 2007 17:09:04 -0500 Subject: Direct memory access In-Reply-To: <4c0048df0703071404t39a14768p96f57b5e334e97a7@mail.gmail.com> References: <4c0048df0703062040m15e310f2qe3b91f5499fbc07e@mail.gmail.com> <4c0048df0703071404t39a14768p96f57b5e334e97a7@mail.gmail.com> Message-ID: <4c0048df0703071409t1612a90nf9e909061e2830a5@mail.gmail.com> One last thing. Does anyone know how to take a python object and measure how much space it is taking up in memory? I'm thinking probably not, but it's worth asking. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Fri Mar 16 17:59:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Mar 2007 14:59:06 -0700 Subject: Executing a list of functions In-Reply-To: <1174081591.638287.152370@y66g2000hsf.googlegroups.com> References: <1174081591.638287.152370@y66g2000hsf.googlegroups.com> Message-ID: <1174082346.152681.152970@o5g2000hsb.googlegroups.com> lst = [a, b] The () symbol causes the named function to execute, and a function call in the code is always replaced by the function's return value. From jonkersbart at gmail.com Thu Mar 8 05:12:13 2007 From: jonkersbart at gmail.com (jonkersbart at gmail.com) Date: 8 Mar 2007 02:12:13 -0800 Subject: splitting common functions into a sepperate module In-Reply-To: <45efd90d$0$24707$426a74cc@news.free.fr> References: <1173343524.284223.165280@q40g2000cwq.googlegroups.com> <45efd90d$0$24707$426a74cc@news.free.fr> Message-ID: <1173348733.037351.229990@64g2000cwx.googlegroups.com> On 8 mrt, 10:36, Bruno Desthuilliers wrote: > jonkersb... at gmail.com a ?crit : > > > Dear, > > > I have wrote a script and want to group some functions of the script > > in a separate modulo so that I can import the module in other scripts > > and use the same functions there.. > > > The problem is that the common functions need access to some global > > variables defined in the script. > > And now you find out why globals are bad... > > > Python uses different namespaces for > > different modules so I can't access the variables of the script in the > > module. > > > What is the best solution to solve this problem? > > There's no one-size-fits-all answer. Usual solutions include: I was hoping for a one-size-fits-all answer. But it seems to be that it doesn't exists. I already know these solutions, but was hoping for a better one. > - passing the needed values as args to the functions There are to many arguments so this is not a preferred solutions > - wrapping the functions as methods of a class, passing the whole state > as args to the class initializer. I already considerate this one, but I don't like it because it is not correct in terms of the object-oriented concept. Because there are no other solutions I have to bury my bad feelings and use this solution. Thanks, Bart From cpblPublic at gmail.com Wed Mar 7 21:39:21 2007 From: cpblPublic at gmail.com (C Barr Leigh) Date: 7 Mar 2007 18:39:21 -0800 Subject: Bug in python!? persistent value of an optional parameter in function! Message-ID: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> Help! Have I found a serious bug? This seems like highly undesired behaviour to me. From the program below, I get output: call1: ['sdf'] call2: ['Set within test for call2'] call3: ['Set within test for call2'] instead of what I should get, call1: ['sdf'] call2: ['Set within test for call2'] call3: ['Set within test for call3'] I'm using Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02). The code is below. #!/usr/bin/python def testPersistence(anarg,twooption=[]): #print anarg if not twooption: twooption.append('Set within test for '+anarg) print anarg +': '+str(twooption) testPersistence('call1',twooption=['sdf']); testPersistence('call2'); testPersistence('call3'); From gagsl-py2 at yahoo.com.ar Mon Mar 5 20:03:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Mar 2007 22:03:25 -0300 Subject: Dialog with a process via subprocess.Popen blocks forever References: <1172698063.670659.318340@k78g2000cwa.googlegroups.com> <1172770920.052040.33990@h3g2000cwc.googlegroups.com> Message-ID: En Fri, 02 Mar 2007 14:38:59 -0300, Donn Cave escribi?: > In article , > "Gabriel Genellina" wrote: > >> On http://docs.python.org/lib/popen2-flow-control.html there are some >> notes on possible flow control problems you may encounter. > > It's a nice summary of one problem, a deadlock due to full pipe > buffer when reading from two pipes. The proposed simple solution > depends too much on the cooperation of the child process to be > very interesting, though. The good news is that there is a real > solution and it isn't terribly complex, you just have to use select() > and UNIX file descriptor I/O. The bad news is that while this is > a real problem, it isn't the one commonly encountered by first > time users of popen. More bad news: you can't use select() with file handles on Windows. >> If you have no control over the child process, it may be safer to use a >> different thread for reading its output. > > Right - `I used threads to solve my problem, and now I have two > problems.' It can work for some variations on this problem, but > not the majority of them. Any pointers on what kind of problems may happen, and usual solutions for them? On Windows one could use asynchronous I/O, or I/O completion ports, but neither of these are available directly from Python. So using a separate thread for reading may be the only solution, and I can't see why is it so bad. (Apart from buffering on the child process, which you can't control anyway). -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Mar 28 13:50:57 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 28 Mar 2007 10:50:57 -0700 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <1175096255.850014.236570@p15g2000hsd.googlegroups.com> References: <1175083955.167868.88610@n76g2000hsh.googlegroups.com> <1175086435.174354.65640@l77g2000hsb.googlegroups.com> <1175096255.850014.236570@p15g2000hsd.googlegroups.com> Message-ID: <1175104257.418601.100830@y80g2000hsf.googlegroups.com> Kay Schluehr: > RPython is heuristically defined as a subset of Python "static enough > to be translatable to C". So it is actually static analysis that is > done here, not on a local scale but on a simpler sublanguage. It is > not clear to me whether for a sufficiently annotated Py3K program the > inequation RPython != Python still holds? You may also take a very good look at ShedSkin, it's already able to compile a decent part of Python, and that part is slowly growing still. I'd like to see a comparison of SSPython and RPython (width-wise and running speed wise too) :-) Bye, bearophile From Emile.Boudreau at cognos.com Tue Mar 20 14:18:01 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Tue, 20 Mar 2007 14:18:01 -0400 Subject: Subject line with smtplib.sendmail() In-Reply-To: <09042D621CD4AA479C678463F3A646D0E884D5@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0E88404@sottemail1.ent.ad.cognos.com> <09042D621CD4AA479C678463F3A646D0E884D5@sottemail1.ent.ad.cognos.com> Message-ID: <09042D621CD4AA479C678463F3A646D0E884E5@sottemail1.ent.ad.cognos.com> Sorry folks. Scrape the last one that I sent. I noticed that it sends the email perfectly if the code is not in any of my methods but the second I insert it into a method I get the ugly email that I described in my last email. Does anyone know how I can get this code in my method so that I have access to all the variables I have? thanks Emile Boudreau -----Original Message----- From: python-list-bounces+emile.boudreau=cognos.com at python.org [mailto:python-list-bounces+emile.boudreau=cognos.com at python.org] On Behalf Of Boudreau, Emile Sent: Tuesday, March 20, 2007 1:51 PM To: python-list at python.org Subject: RE: Subject line with smtplib.sendmail() Thanks for the reply. When I use the instruction from that list this is the email I receive. I'm using Outlook. Working.on at server.com To: ------------------------------ From: Working.On at server.com To: Emile.Boudreau at server.com Subject: Hello! This Still DOESN't Work!!!!!!!!!!!! It's just adding the "From" "To" "Subject" in the message itself. I want to have each field at the correct place and then just the msg in the body. Any Help?? Thanks Emile Boudreau -----Original Message----- From: python-list-bounces+emile.boudreau=cognos.com at python.org [mailto:python-list-bounces+emile.boudreau=cognos.com at python.org] On Behalf Of Fredrik Lundh Sent: Tuesday, March 20, 2007 11:08 AM To: python-list at python.org Subject: Re: Subject line with smtplib.sendmail() Boudreau, Emile wrote: > I'm trying to send mail from my server to my machine with test > results. I can send the email no problem however, the email doesn't > contain a "recipient list" or a "subject line". I was wondering how > would I go about getting the information on the actual "To" and > "Subject" lines so that I know to whom the email was sent and the > subject line without opening the email? you have to add the headers yourself. see the example in the library reference, or this FAQ entry: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script -- http://mail.python.org/mailman/listinfo/python-list This message may contain privileged and/or confidential information. If you have received this e-mail in error or are not the intended recipient, you may not use, copy, disseminate or distribute it; do not open any attachments, delete it immediately from your system and notify the sender promptly by e-mail that you have done so. Thank you. -- http://mail.python.org/mailman/listinfo/python-list From bbxx789_05ss at yahoo.com Sat Mar 24 16:52:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 Mar 2007 13:52:46 -0700 Subject: Python object overhead? In-Reply-To: References: <1174766882.119041.294020@y66g2000hsf.googlegroups.com> Message-ID: <1174769566.154258.307250@y80g2000hsf.googlegroups.com> On Mar 24, 2:19 pm, Jean-Paul Calderone wrote: > Only one list is created. It is used to define a C array where attributes > will be stored. Each instance still has that C array, but it has much less > overhead than a Python list or dictionary. > It's all C underneath, right? So a dictionary is what? Two parallel C arrays: one array with the names and one with the values? When you do this: __slots__ = ["m", "n"] there still has to be a mapping between the names "m" and "n" and their values. So aren't two parallel C arrays required again? > Whether this reduction in overhead actually results in a useful or measurable > performance improvement is a separate question, of course. > I suppose a dictionary will be required to grow in size, so at periodic intervals new, bigger arrays will need to be created, the contents copied over, and the old arrays destroyed(similar to a in C++). And of course, the C code that accomplishes all that creating, copying and destroying will take up some memory. Is that what you are talking about when you say "overhead"? From dant262 at yahoo.com Thu Mar 22 12:48:17 2007 From: dant262 at yahoo.com (dant262 at yahoo.com) Date: 22 Mar 2007 09:48:17 -0700 Subject: State of the Art Software Development Practices Message-ID: <1174582097.414364.224690@e1g2000hsg.googlegroups.com> Dan Turk Colorado State University 26 Rockwell Hall Fort Collins, CO 80523-1277 USA March 22, 2007 My name is Dan Turk, and I am a faculty member in the Department of Computer Information Systems at Colorado State University. My colleague, Leo Vijayasarathy, and I are conducting a study to better understand the use of agile software development processes, methods, and techniques, and the benefits and limitations associated with their use. About 2 years ago we performed a similar survey. However, while that survey was targeted solely at people who had already been frequent users of agile processes, the current survey looks to draw data from a larger segment of developers and has been updated for that purpose. Please consider participating in this study by completing a brief survey posted at http://www.business.colostate.edu/leov/research/agile/start.cfm . A summary of the results will be posted to this group at the conclusion of this study. Your responses will be entirely anonymous and confidential. The survey does not collect any identifying information and cannot be tracked to the person completing it. General information about your title and years of experience are requested only to build a profile of the survey respondents. Your participation in this study is voluntary. There are no known risks associated with taking part in it. You may stop participating at any time without penalty or loss of benefits to which you are otherwise entitled. If you have questions regarding your rights as a volunteer in this research, please contact Janell Meldrem, Senior Human Research Administrator, (970) 491-1563, Janell.Meldrem at colostate.edu. Thank you in advance for completing the survey and your contribution to this research. If you have any questions about the study or the survey, please call me at 970-491-0467 or email me at Dan.Turk at colostate.edu. Sincerely, Dan Turk, Ph.D. Associate Professor of Computer Information Systems From martinunsal at gmail.com Mon Mar 5 11:18:11 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 5 Mar 2007 08:18:11 -0800 Subject: Project organization and import In-Reply-To: <1173084337.538171.35530@c51g2000cwc.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> Message-ID: <1173111489.163974.89990@30g2000cwc.googlegroups.com> On Mar 5, 12:45 am, "bruno.desthuilli... at gmail.com" wrote: > Remember that you can put code in > the __init__.py of a package, and that this code can import sub- > packages/modules namespaces, making the package internal organisation > transparent to user code Sure, but that doesn't solve the problem. Say you have a package "widgets" with classes ScrollBar, Form, etc. You want the end user to "import widgets" and then invoke "widgets.ScrollBar()". As far as I know there are only two ways to do this, both seriously flawed: 1) Put all your code in one module widgets.py, 2) use "from scrollbar import *" in widgets/__init__.py, which is semi-deprecated and breaks reload(). > Also remember that you can "import as", ie: > > import some_package.some_subpackage.some_module as some_module Sure but that doesn't eliminate the unfortunate interaction between Python class organization and filesystem heirarchy. For example, say you want to organize the widgets package as follows: widgets/scrollbar/*.py widgets/form/*.py widgets/common/util.py Other than messing around with PYTHONPATH, which is horrible, I don't see how to import util.py from the widget code. > Bad form IMHO. Packages and module names should be all_lower, > classnames CamelCased. You're still stuck doing foo.Foo() everywhere in your client code, which is ugly and wastes space, or using "from foo import *" which is broken. > > but I > > believe this is categorically the wrong thing to do in large projects. > > Oh yes ? Why ? For myriad reasons, just one of them being the one I stated -- smaller files with one functional unit each are more amenable to source code management with multiple developers. We could discuss this till we're blue in the face but it's beside the point. For any given project, architecture, and workflow, the developers are going to have a preference for how to organize the code structurally into files, directories, packages, etc. The language itself should not place constraints on them. The mere fact that it is supposedly "Pythonic" to put more functionality in one file indicates to me that the Python package system is obstructing some of its users who have perfectly good reasons to organize their code differently. > > you're going to want files to contain the smallest > > practical functional blocks. I feel pretty confident saying that "put > > more stuff in one file" is the wrong answer, even if it is the > > Pythonic answer. > > Is this actually based on working experience ? It seems that there are > enough not-trivial Python projects around to prove that it works just > fine. Yes. I've worked extensively on several projects in several languages with multi-million lines of code and they invariably have coding styles that recommend one functional unit (such as a class), or at most a few closely related functional units per file. In Python, most of the large projects I've looked at use "from foo import *" liberally. I guess my question boils down to this. Is "from foo import *" really deprecated or not? If everyone has to use "from foo import *" despite the problems it causes, how do they work around those problems (such as reloading)? Martin From bj_666 at gmx.net Thu Mar 1 05:46:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 01 Mar 2007 11:46:58 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> <1172741018.978417.233160@v33g2000cwv.googlegroups.com> <54nlkgF21ft8aU3@mid.individual.net> Message-ID: In <54nlkgF21ft8aU3 at mid.individual.net>, Bjoern Schliessmann wrote: > Michele Simionato wrote: >> On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch >>> In <54msaoF21c6h... at mid.individual.net>, Bjoern Schliessmann > >>>> But what's it (__name__) good for? >>> >>> As objects don't know to which name they are bound, that's a good >>> way to give some information in stack traces or when doing >>> introspection. >> >> Also, the name is used by pickle to find the class of pickled >> instances. > > Mh. I suspect there's also more to it than I see now, but this > __name__ seems quite useless to me. What if I rebind the class' > name after definition? Then it's a way to still get the name of the definition via `__name__`. Together with the name of the module where the definition took place which is also available as attribute on the objects it is very useful to find out where to look for the source code. Just see the default `repr()` of class objects. > Or is it really just for some manual introspection? If it is, it seems a > bit of an overkill to me. > >>>> class Spam(object): > ... pass > ... >>>> Ham = Spam >>>> Spam = 0 >>>> test = Ham() >>>> test.__class__ > What would you expect this to look like if there weren't a __name__ attribute? Ciao, Marc 'BlackJack' Rintsch From csselo at gmail.com Fri Mar 30 04:21:52 2007 From: csselo at gmail.com (csselo at gmail.com) Date: 30 Mar 2007 01:21:52 -0700 Subject: Memory testing in Python Message-ID: <1175242912.103313.99110@n59g2000hsh.googlegroups.com> Hi all I want to test my python code for memory efficiency in gnu/linux.How can I do this? thanks. From aisaac at american.edu Fri Mar 9 18:25:26 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 09 Mar 2007 23:25:26 GMT Subject: pylint: don't warn about tabs References: <55avniF23jpl2U1@mid.individual.net> Message-ID: "Ben Finney" wrote in message news:mailman.4813.1173388535.32031.python-list at python.org... > Sticking to spaces for indentation avoids the ambiguity of > interpretation that ASCII TAB characters are subject to. What ambiguity? Tabs are *less* ambiguous. One tab character is one level of indentation. I have never seen this violated. Users of spaces cannot even count on shared code being 4 rather than 8 spaces. Even though tabs when on this score, face it, in the end it is pure preference. There is no "right" answer (even for emacs users). ;-) And my actual question remains unanswered... Alan Isaac From http Sat Mar 17 03:17:04 2007 From: http (Paul Rubin) Date: 16 Mar 2007 23:17:04 -0800 Subject: Mastering Python References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1hv3735.f8r5bx3czob7N%aleax@mac.com> Message-ID: <7xslc49w5r.fsf@ruckus.brouhaha.com> John Nagle writes: > Execution model: dynamic stack-type interpreter. Erm, the iterator protocol makes the above a little more complicated. > Biggest headache is finding out what doesn't work in the libraries. Good observation. From gagsl-py2 at yahoo.com.ar Fri Mar 23 18:11:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 19:11:23 -0300 Subject: Python object overhead? References: Message-ID: En Fri, 23 Mar 2007 18:27:25 -0300, Mark Nenadov escribi?: > I'd suggest doing the following instead of that while loop: > > for line in open(sys.argv[1]).xreadlines(): Poor xreadlines method had a short life: it was born on Python 2.1 and got deprecated on 2.3 :( A file is now its own line iterator: f = open(...) for line in f: ... -- Gabriel Genellina From khemkaamit at gmail.com Thu Mar 29 08:30:55 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 29 Mar 2007 18:00:55 +0530 Subject: Weird behavior in search in a list In-Reply-To: <6E125C32-13B7-4267-8CA3-6D2BF21D4F81@jedimindworks.com> References: <1175169060.414834.235040@d57g2000hsg.googlegroups.com> <6E125C32-13B7-4267-8CA3-6D2BF21D4F81@jedimindworks.com> Message-ID: <1360b7230703290530x3020980fg3e1b6f3c27a202f7@mail.gmail.com> On 3/29/07, Michael Bentley wrote: > > On Mar 29, 2007, at 6:51 AM, Su Y wrote: > > > > I want find the first number in extend[] which is larger than num, so > def find(num): > # check to make sure there *is* a value greater than num > if max(extend) > num: > # then return the smallest value that is greater than num > return min([x for x in extend if x > num]) > else: > return None I think OP wants the first value in the list greater than 'num' not the smallest greater value in the list. cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From bearophileHUGS at lycos.com Sat Mar 17 17:15:15 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Mar 2007 14:15:15 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174158002.730076.22720@y80g2000hsf.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <1174024633.431427.236920@y66g2000hsf.googlegroups.com> <7xslc5k9cc.fsf@ruckus.brouhaha.com> <1174158002.730076.22720@y80g2000hsf.googlegroups.com> Message-ID: <1174166115.263201.51840@d57g2000hsg.googlegroups.com> Mark Dufour: > FWIW, the original program can also be compiled with Shed Skin (http:// > mark.dufour.googlepages.com), an experimental (static-)Python-to-C++ > compiler, resulting in a speedup of about 8 times for a single test > with 500 tuples. If we want to play, then this is a literal translation to D (I am not much good in D yet, so maybe there are ways to improve this code a bit), as you can see D syntax isn't that bad (I think sometimes D copies some Python syntax): // Compile with: dmd -O -release solver.d import std.stdio, std.stream, std.string; void main() { size_t sch; size_t[size_t] h; size_t[] q,w,e,r; int nrow = -1; auto datafile = new File("m4000.txt", FileMode.In); foreach(char[] row; datafile) { if (nrow == -1) { q.length = row.atoi(); w.length = row.atoi(); e.length = row.atoi(); r.length = row.atoi(); } else { char[][] srow = row.split(); q[nrow] = srow[0].atoi(); w[nrow] = srow[1].atoi(); e[nrow] = srow[2].atoi(); r[nrow] = srow[3].atoi(); } nrow++; } foreach (x; q) foreach (y; w) h[x+y]++; foreach (x; e) foreach (y; r) { size_t* pointer = -x-y in h; if (pointer) sch += *pointer; // simpler but slower: // if (-x-y in h) // sch += h[-x-y]; } writefln(sch); } On my PC with the 1000 lines file this is about 2.2 times faster than my Psyco version and about 4.6 times faster than the same code without Psyco. Bye, bearophile From jantod at gmail.com Sun Mar 4 05:03:23 2007 From: jantod at gmail.com (Janto Dreijer) Date: 4 Mar 2007 02:03:23 -0800 Subject: multiple content-types break cgi.py Message-ID: <1173002603.690853.250090@p10g2000cwp.googlegroups.com> Hi! The Nokia Java SDK allows one to define multiple content-types in a single HTTP header field. I'm not sure if it's standard, but it's happening from some Java-enabled phones. This breaks the FieldStorage class in cgi.py by not causing self.read_urlencoded() to be called at object init. Specifically when one gets a type value like 'text/plain, application/x-www-form- urlencoded'. Hacking one of the lines from: if ctype == 'application/x-www-form-urlencoded': self.read_urlencoded() to if 'application/x-www-form-urlencoded' in [s.strip() for s in ctype.split(",")]: self.read_urlencoded() makes it work as expected. The only reference to this "bug" I can find dates back to 1999: http://tinyurl.com/3ahc3r Regards Janto From svenkat.cm at gmail.com Fri Mar 2 06:18:24 2007 From: svenkat.cm at gmail.com (Venkat) Date: 2 Mar 2007 03:18:24 -0800 Subject: Installation problem: Python 2.5 on solaris 8 Message-ID: <1172834304.930543.261920@h3g2000cwc.googlegroups.com> I am very new to Python. I installed Python in Windows and learning it. But i need to install Python on Solaris 8 to automate few things as my build environment is on Solaris. When i tried to download python 2.5 source code and tried to compile i got the error saying "configure: error: cannot compute sizeof (int), 77". Between i am also getting parse errors for few files including siginfo.h /usr/include/sys/siginfo.h:74: parse error before `pthread_attr_t' /usr/include/sys/siginfo.h:76: parse error before `}' /usr/include/pthread.h:152: parse error before `*' /usr/include/pthread.h:153: parse error before `*' /usr/include/pthread.h:154: parse error before `*' /usr/include/pthread.h:155: parse error before `*' /usr/include/pthread.h:156: parse error before `*' /usr/include/pthread.h:157: parse error before `*' /usr/include/pthread.h:158: parse error before `*' /usr/include/pthread.h:159: parse error before `*' /usr/include/pthread.h:160: parse error before `*' /usr/include/pthread.h:161: parse error before `*' /usr/include/pthread.h:162: parse error before `*' /usr/include/pthread.h:163: parse error before `*' /usr/include/pthread.h:164: parse error before `*' /usr/include/pthread.h:165: parse error before `*' /usr/include/pthread.h:166: parse error before `*' /usr/include/pthread.h:168: parse error before `*' /usr/include/pthread.h:170: parse error before `*' /usr/include/pthread.h:171: parse error before `void' /usr/include/pthread.h:172: parse error before `*' /usr/include/pthread.h:172: parse error before `)' /usr/include/pthread.h:173: parse error before `void' /usr/include/pthread.h:177: parse error before `int' /usr/include/pthread.h:178: parse error before `int' /usr/include/pthread.h:183: parse error before `*' /usr/include/pthread.h:183: parse error before `)' /usr/include/pthread.h:185: parse error before `const' /usr/include/pthread.h:187: parse error before `pthread_self' /usr/include/pthread.h:192: parse error before `*' /usr/include/pthread.h:193: parse error before `*' /usr/include/pthread.h:194: parse error before `*' /usr/include/pthread.h:195: parse error before `*' /usr/include/pthread.h:196: parse error before `*' /usr/include/pthread.h:197: parse error before `*' == uname -m = sun4u uname -r = 5.8 uname -s = SunOS uname -v = Generic_108528-15 /usr/bin/uname -p = sparc /bin/uname -X = System = SunOS Node = sword Release = 5.8 KernelID = Generic_108528-15 Machine = sun4u BusType = Serial = Users = OEM# = 0 == Thanks a lot -Venkat From aleax at mac.com Tue Mar 6 10:37:46 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 6 Mar 2007 07:37:46 -0800 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <45ec933a$0$15549$426a34cc@news.free.fr> <1huivd7.7l18eh1paqp0aN%aleax@mac.com> <87k5xu37vt.fsf@gmail.com> Message-ID: <1hujkzp.11vuf5x1a6yz2aN%aleax@mac.com> Jorge Godoy wrote: ... > > My favorite way of working: add a test (or a limited set of tests) for > > the new or changed feature, run it, check that it fails, change the > > code, rerun the test, check that the test now runs, rerun all tests to > > see that nothing broke, add and run more tests to make sure the new code > > is excellently covered, rinse, repeat. Occasionally, to ensure the code > > stays clean, stop to refactor, rerunning tests as I go. > > I believe this is a distinct case. When we write tests we're worried with the > system itself. Not sure I get what you mean; when I write tests, just as when I write production code, I'm focused (not worried:-) about the application functionality I'm supposed to deliver. The language mostly "gets out of my way" -- that's why I like Python, after all:-). > When using the interactive interpreter we're worried with how > to best use the language. There might be some feature of the system related > to that investigation, but there might be not. For example: "what are the > methods provided by this object?" or "which approach is faster for this loop?" I do generally keep an interactive interpreter running in its own window, and help and dir are probably the functions I call most often there. If I need to microbenchmark for speed, I use timeit (which I find far handier to use from the commandline). I wouldn't frame this as "worried with how to best use the language" though; it's more akin to a handy reference manual (I also keep a copy of the Nutshell handy for exactly the same reason -- some things are best looked up on paper). > I won't write a test case to test loop speed. But I'd poke with the > interpreter and if the environment gets a bit big to setup then I'd go to the > text editor as I said. I don't really see "getting a bit big to setup" as the motivation for writing automated, repeatable tests (including load-tests, if speed is such a hot topic in your case); rather, the key issue is, will you ever want to run this again? For example, say you want to check the relative speeds of approaches A and B -- if you do that in a way that's not automated and repeatable (i.e., not by writing scripts), then you'll have to repeat those manual operations exactly every time you refactor your code, upgrade Python or your OS or some library, switch to another system (HW or SW), etc, etc. Even if it's only three or four steps, who needs the aggravation? Almost anything worth doing (in the realm of testing, measuring and variously characterizing software, at least) is worth automating, to avoid any need for repeated manual labor; that's how you get real productivity, by doing ever less work yourself and pushing ever more work down to your computer. Alex From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 19 09:02:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 14:02:14 +0100 Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: <566vcfF27jlu4U1@mid.uni-berlin.de> References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> Message-ID: <45fe89d4$0$24787$426a34cc@news.free.fr> Diez B. Roggisch a ?crit : > momobear schrieb: >> hi, I am puzzled about how to determine whether an object is >> initilized in one class, anyone could give me any instructions? >> here is an example code: >> >> class coffee: >> def boil(self): >> self.temp = 80 >> >> a = coffer() >> if a.temp > 60: >> print "it's boiled" >> >> in C++ language we must initilized a variable first, so there is no >> such problem, but in python if we don't invoke a.boil(), we will not >> get self.temp to be initilized, any way to determine if it's initilzed >> before self.temp be used. > > You want boil to be called __init__, which is python's constructor name. Actually, __init__ is the initializer. The proper constructor is __new__. From ptmcg at austin.rr.com Thu Mar 29 18:16:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Mar 2007 15:16:17 -0700 Subject: Any "consumer review generators" available? In-Reply-To: <1175200851.955161.169930@n76g2000hsh.googlegroups.com> References: <1175200851.955161.169930@n76g2000hsh.googlegroups.com> Message-ID: <1175206577.476047.139660@r56g2000hsd.googlegroups.com> On Mar 29, 3:40 pm, irs... at gmail.com wrote: > On Mar 29, 9:19 pm, aral... at aol.com wrote: > > > I am looking for a fake consumer review generator that could generate realistic looking reviews for any products, kind of like on amazon.com but generated by Artificial Intelligence. Is there a package available in your favorite programing language... thx alan > > Python's standard module "ai" has a function called > "generateFakeReview". I believe it does what you want, but I haven't > used it myself. You are two days early... :) -- Paul From gagsl-py2 at yahoo.com.ar Wed Mar 7 21:56:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 23:56:37 -0300 Subject: Bug in python!? persistent value of an optional parameter in function! References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> Message-ID: En Wed, 07 Mar 2007 23:39:21 -0300, C Barr Leigh escribi?: > Help! Have I found a serious bug? Not at all! This is by design. > def testPersistence(anarg,twooption=[]): > #print anarg > if not twooption: > twooption.append('Set within test for '+anarg) See http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm -- Gabriel Genellina From grante at visi.com Fri Mar 2 10:29:47 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 02 Mar 2007 15:29:47 -0000 Subject: float64 print digits References: Message-ID: <12uggnbc2aqle77@corp.supernews.com> On 2007-03-02, Ulrich Dorda wrote: > I need a pytho nscript to read numbers(with loads of digits) from a > file, do some basic math on it and write the result out to another file. > > My problem: I don't get python to use more digits: > > In order to try this I type: > > The normal precision one: > >>> from numpy import * > >>> x=1.23456789123456789123456789 > >>> print "%35.25e" %x > 1.2345678912345679000000000e+000 > > > Now I try to use float64 to get more digits You're already using 64 bit floats (which have about 15 significant digits). > >>> z=zeros(3,float64) > >>> z[0] > 0.0 > >>> type(z[0]) > > >>> z[0]=1.23456789123456789123456789 > >>> type(z[0]) > > >>> print "%35.25e" %z[0] > 1.2345678912345679000000000e+000 > > This cuts the digits just like the 32bit case. What 32-bit case? A 32-bit float only has 7-8 significant digits. > Can anyone please help me get more digits? Use the decimal module? -- Grant Edwards grante Yow! What a at COINCIDENCE! I'm an visi.com authorized "SNOOTS OF THE STARS" dealer!! From rpdooling at gmail.com Thu Mar 1 15:39:54 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Mar 2007 12:39:54 -0800 Subject: python equivalent of bash find In-Reply-To: References: <1172780082.961223.222500@s48g2000cws.googlegroups.com> Message-ID: <1172781594.595648.320060@k78g2000cwa.googlegroups.com> > You can probably replicate that using the modules os and shutil. Thank you both for the quick response. rd From steve at REMOVEME.cybersource.com.au Wed Mar 7 21:22:25 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Mar 2007 13:22:25 +1100 Subject: is it possible to give an instance a value? References: <1173221145.793008.298940@v33g2000cwv.googlegroups.com> Message-ID: On Wed, 07 Mar 2007 16:02:05 +0100, egbert wrote: > On Tue, 06 Mar 2007 14:45:45 -0800, manstey wrote: >> >> class Test(object): >> def __init__(self, val): >> self.val = val >> >> a = Test('hello') > >> Is there a way to make a have the value a.val when it is used as >> above, or as an argument (eg function(a, 10, 'sdf') etc)? >> > My impression is that you can do everything you want to > by making your instance callable, and not using a but a(). You can't do this: >>> a() = "some value" SyntaxError: can't assign to function call If you do this: >>> a = "some value" then we're back to the Original Poster's original problem. -- Steven D'Aprano From parsons.nicholas1 at gmail.com Sun Mar 4 07:42:22 2007 From: parsons.nicholas1 at gmail.com (Nicholas Parsons) Date: Sun, 4 Mar 2007 07:42:22 -0500 Subject: pop method question In-Reply-To: References: <1172968335.511875.255750@p10g2000cwp.googlegroups.com> Message-ID: <95D0B0A6-DB30-4D72-9397-881E53A9EDC4@gmail.com> On Mar 4, 2007, at 4:38 AM, Marc 'BlackJack' Rintsch wrote: > In , Nicholas > Parsons wrote: > >> Just from my computer science background when I see pop(), I think >> of a >> stack data structure. > > Then question your presumptions. There are also many people thinking > `list` must be something with nodes and pointers when they see the > interface and usage of Python lists. Good point :). > >> But then again, there are other examples of ambiguity in the python >> language such as allowing operators like '+' to be overloaded. >> Why not >> just have a "add()" method like Java? > > Why does this remove ambiguity? I even would expect different > behaviour > from both. I expect the ``+`` operator to return either an > immutable or > entirely new object, while `add()` can be something on containers that > mutates the object. This is true. As long as the language (be it Java, Python, X) itself remains consistent over time, then this should be fine. > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list From cmfvulcanius at gmail.com Thu Mar 8 11:12:27 2007 From: cmfvulcanius at gmail.com (cmfvulcanius at gmail.com) Date: 8 Mar 2007 08:12:27 -0800 Subject: Reading a portion of a file Message-ID: <1173370347.799134.119100@v33g2000cwv.googlegroups.com> I am using a script with a single file containing all data in multiple sections. Each section begins with "#VS:CMD:command:START" and ends with "#VS:CMD:command:STOP". There is a blank line in between each section. I'm looking for the best way to grab one section at a time. Will I have to read the entire file to a string and parse it further or is it possible to grab the section directly when doing a read? I'm guessing regex is the best possible way. Any help is greatly appreciated. Thanks From waldemar.osuch at gmail.com Tue Mar 6 20:46:12 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: 6 Mar 2007 17:46:12 -0800 Subject: When will 2.5.1 be released? In-Reply-To: <1173208347.506758.166620@30g2000cwc.googlegroups.com> References: <1173037797.127119.248300@h3g2000cwc.googlegroups.com> <1173208347.506758.166620@30g2000cwc.googlegroups.com> Message-ID: <1173231971.972435.186340@h3g2000cwc.googlegroups.com> On Mar 6, 12:12 pm, "A. Lloyd Flanagan" wrote: > On Mar 4, 2:49 pm, "Nile" wrote: > > And while we're waiting for 2.5.1, can somebody post a clear (as > opposed to the one that comes with Tix ;)) explanation of how to > manually install Tix into python 2.5? It should be possible... Copying relevant files from 2.4 installation into corresponding location in 2.5 worked for me. >From what I remember I had to copy: - /tcl/tix8.1/* - /tcl/tix8184.lib - /DLLs/tix8184.dll From joshbloom at gmail.com Thu Mar 8 11:47:58 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Thu, 8 Mar 2007 09:47:58 -0700 Subject: IronPython with Apache In-Reply-To: <1173308754.051978.62500@v33g2000cwv.googlegroups.com> References: <1173308754.051978.62500@v33g2000cwv.googlegroups.com> Message-ID: Hi Ed, Some more info about your environment will be helpful here. What OS version, apache version, etc. -Josh On 7 Mar 2007 15:05:54 -0800, edfialk wrote: > > Hi all, I'm completely new to Python, but fairly experienced in PHP > and few other languages. > > Long story short: The IronPython executable doesn't work for .cgi > scripts in my browser. > > > I've been assigned to write a service that pulls in parameters from > the URL, accesses a file and serves some data through a CSV. The only > problem I foresee myself is accessing and reading this file, which is > a 'hyper-cube' in that it has many dimensions of data. > > Anyway, the code for reading and writing this cube was already written > by a coworker in IronPython and .NET. Again, I'm totally new to > Python but as I'm stepping through trying to pick out pieces that I > need, I can't even import clr. > > So, I'm told I need IronPython, which I get, and I replace the #!c: > \Python25\python.exe with the IronPython executable (#!c: > \IronPython-1.0.1\ipy.exe), but I get a 500 Internal Server error and: > > "[Wed Mar 07 17:02:21 2007] [error] [client 127.0.0.1] malformed > header from script. Bad header= File , line 0, in __import__: > testing.cgi" in the Error log. > > Does anyone know how to set up this 'IronPython' through Apache so I > can use it to read/write data? > > Any help would be greatly appreciated. > Thanks! > -Ed > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Sat Mar 3 15:04:33 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 3 Mar 2007 12:04:33 -0800 Subject: classes and functions In-Reply-To: References: Message-ID: <1172952273.482935.129850@8g2000cwh.googlegroups.com> On Mar 2, 11:01 pm, Nicholas Parsons wrote: > Hi Claire, > > That is the beauty of using Python. You have a choice of using > classes and traditional OOP techniques or sticking to top level > functions. For short, small scripts it would probably be overkill to > use classes. Yet the programmer still has classes in his tool chest > if he/she is writing code that is going to be reused in larger > projects. Exactly the same thing can be said about Lisp, C++, Perl, PHP, and no doubt many other languages that I don't know ;) (Well I guess C++ programs are not called 'scripts') -- Arnaud From bdesth.quelquechose at free.quelquepart.fr Tue Mar 6 08:50:11 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 06 Mar 2007 14:50:11 +0100 Subject: Good handling of input data (was Re: Newbie question) In-Reply-To: References: <45EC579A.8090602@websafe.com> Message-ID: <45ed69af$0$6087$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 06 Mar 2007 05:57:43 -0500, Tommy Grav wrote: > > >>So how would you handle this type of error handling? >>My main problem is that occasionally there is an entry >>in the list that is a string: >> >>0.9834 134.4933 78.009 run11 27 > > > How do you want to deal with such an occasional string? What do you expect > the code to do? > > The way I see it, if you're expecting five floats, and you get four floats > and a string, that's an error. Do you ignore the entire line, or replace > the string with zero, or what? > > > >>Again I would like to avoid having to individually parse the 3 floats, >>while still easily handling the string, but a list comprehension will >>not work as far as I can tell. Is there a module that handles this >>type of flat ascii tables? Something like: >> >>(x,y,z,id,n) = ParseFile("float","float","float","string","int") >> >>would be great, and I guess >> >>(x,y,z,id,n) = PaseFile2("%f %f %f %s %d") >> >>would be even better. > > > How about this? > > def parse_line(line, types): > items = line.split() > return [t(s) for (t, s) in zip(types, items)] > Since the OP mention of last items being here "occasionnaly", I'd go for this instead (nb: ad-hoc implementation - yours is of course better as a general solution): def parse_line(line, *types): items = line.split() return [t(s) for (s, t) in zip(items, types)] My 2 cents From jstroud at mbi.ucla.edu Mon Mar 12 21:14:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 13 Mar 2007 01:14:12 GMT Subject: attaching Tkinter Listbox to python list object In-Reply-To: <1173746051.180729.97350@h3g2000cwc.googlegroups.com> References: <1173746051.180729.97350@h3g2000cwc.googlegroups.com> Message-ID: Steve Potter wrote: > I am trying to find some method of attaching a Listbox object to a > list object so as the contents of the list are changed the contents of > the Listbox will be updated to match. I have found a few references > to something like this in this old post > http://groups.google.com/group/comp.lang.python/browse_thread/thread/3a6fe7534c812f55/43f201ab53cfdbf7 > as well as here http://effbot.org/zone/wck-4.htm . > > It just seems that there should be some way of achieving this. > > The only this I can think of is create a subclass of list that deletes > and then refills the Listbox every time that the list changes, but > this seems very in efficient. > > > Any ideas? > > Steve > If you want the listbox to have the interface of a list, you will probably not want to do it by inheritance because you are going to have to re-write a lot of methods anyway, calling super, etc. Probably better is composition in this case, even though inheritance feels like the right way if you haven't tried it yet and discovered its problems. Inherit from object and fill the class with objects designed for the job. In fact, make sure you want to abstract your data structure to list before you even use that--then create a controller that retrieves appropriate info from the data structure (model) and updates the listbox (view) accordingly. Use callbacks from the listbox to notify the controller if the events in the listbox require modification of the list. Have the controller modify the list and then use the modified list to update the listbox. This is more-or-less MVC. MVC can be as simple as listbox, list, object, or more complicated. But you will be happy you began with an MVC design at some point in the future. You'll really be happy that you didn't inherit from list for this! I've looked into the listbox issue and I have found that you will have to delete and refill the listbox every time the list is changed. I wouldn't worry about speed, though, your computer will keep up with the user, no problem. If you look into other GUI frameworks, you'll find that they all seem to delete and refill at some level. Its just with Tkinter, you have to do this explicitly, which never feels quite right. James From alan.franzoni_invalid at geemail.invalid Wed Mar 7 08:29:29 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 7 Mar 2007 14:29:29 +0100 Subject: Python Source Code Beautifier References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> <1172700549.583792.41660@s48g2000cws.googlegroups.com> <45E8FADB.7000902@cosc.canterbury.ac.nz> <1rgq149m7oern$.1080aifmn5qo8$.dlg@40tude.net> Message-ID: <1fenbu7prg0bm.3q5rj5s6vex4$.dlg@40tude.net> Il Tue, 06 Mar 2007 01:55:54 -0300, Gabriel Genellina ha scritto: > The problem is that other people -not necesarily "smarter and more > experienced" than you- may use those features, and perhaps you have to > read, understand and modify some code written by someone else. > So, you should at least know what "a += b" means, even if you are not > going to use it. That's sure, and I'm in fact glad to know that by now. I still think it's risky, BTW. Python is dynamically typed, after all, and there's no 'a priori' way to know if 'a' is a list or another type, especially another container type. If we rely on duck typing, by the way, we may encounter two types quacking like ducks, flying like ducks, but in fact acting as slightly different ducks. I should remember as well, when designing a container type that I want to use in place of a list, to carefully craft an __iadd__ method which works just like the a list's own __iadd__ method; if I forget, I may introduce a subtle error. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From fsckedagain at gmail.com Wed Mar 28 13:40:59 2007 From: fsckedagain at gmail.com (fscked) Date: 28 Mar 2007 10:40:59 -0700 Subject: XML/encoding/prolog/python hell... Message-ID: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> I am a beginning pythoner and I am having a terrible time trying to figure out how to do something that (it would seeme to me) should be fairly simple. I have a CSV file of unknown encoding and I need to parse that file to get the fields <--- DONE I need to create an xml document that has the proper prolog and namespace information in it. <--- NOT DONE I need it to be encoded properly<--- Looks right in IE, not right in any other app. I should say that I have googled my butt off, tried ElementTree, CSV2XML, and various other things and cannot get any of them to work. A sample of the output I am looking for is as follows: Is there some fundamental thing I am not getting? I cannot get 'tostrings' to work in ElementTree and I cannot figure the prolog out. I posted a similar message back in January, but haven't had much luck. PS No I haven't been trying to do this since January, more important things came up at work and I have just revived this. :) From gagsl-py2 at yahoo.com.ar Sun Mar 18 23:41:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 00:41:53 -0300 Subject: 4 bytes to int References: <969033cd0703181904j2b3e8743m638de5f1bbeef980@mail.gmail.com> Message-ID: En Sun, 18 Mar 2007 23:04:44 -0300, Andres Martinelli escribi?: > My simple question is: > I have an array of 4 bytes, and I want to convert it to the int they > form. You can use the struct module: py> struct.unpack("i", "\x00\x00\x01\x00") (65536,) That's good if you have a string to start from. If your "array of 4 bytes" is actually an array.array object, you can get the string using the tostring method. If your 4 bytes are in another format, maybe this function is more convenient: py> def int_from_bytes(b3, b2, b1, b0): ... "Builds an unsigned int (32bits) from 4 bytes, b3 being the most significa nt byte" ... return (((((b3 << 8) + b2) << 8) + b1) << 8) + b0 ... py> int_from_bytes(0, 0, 0, 0) 0 py> int_from_bytes(0, 0, 0, 10) 10 py> int_from_bytes(0, 0, 1, 0) 256 py> int_from_bytes(0, 0, 255, 255) 65535 py> int_from_bytes(127, 255, 255, 255) 2147483647 py> int_from_bytes(255, 255, 255, 255) 4294967295L -- Gabriel Genellina From J.Fine at open.ac.uk Wed Mar 7 08:52:08 2007 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 7 Mar 2007 13:52:08 -0000 Subject: distutils - how to get more flexible configuration Message-ID: Hello I'm writing a package that has cgi-bin scripts, html files and data files (templates used by cgi scripts). I find that using distutils in the standard way does not give me enough flexibilty, even if I use a setup.cfg. For example, I want certain data files to go to markedly different locations. However, I have come up with a solution, that looks like it will work for me, and I'd welcome comments. Here's the MANIFEST file === setup.py myproj_cfg.py data/wibble.txt data/wobble.txt === And here's the setup.py file I've written === from distutils.core import setup import myproj_cfg data_files = [ (myproj_cfg.wibble, ['data/wibble.txt']), (myproj_cfg.wobble, ['data/wobble.txt']), ] setup(data_files=data_files) === The user is asked to create a myproj_cfg.py file, which might look like === wibble = '/wibble' wobble = '/wobble' === And when a distribution is created and installed we get === $ python setup.py install running install running build running install_data creating /wibble copying data/wibble.txt -> /wibble creating /wobble copying data/wobble.txt -> /wobble === This is an example of what I want. I'd welcome your comments. -- Jonathan Fine The Open University, Milton Keynes, England From ptmcg at austin.rr.com Thu Mar 22 11:51:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 22 Mar 2007 08:51:16 -0700 Subject: Regexp problem with `(' In-Reply-To: <1174551982.865646.38620@y80g2000hsf.googlegroups.com> References: <1174551982.865646.38620@y80g2000hsf.googlegroups.com> Message-ID: <1174578676.330942.62520@e1g2000hsg.googlegroups.com> On Mar 22, 3:26 am, "Johny" wrote: > I have the following text > > Goods Item 146 (174459989) - OurWebSite > > from which I need to extract > `Goods Item 146 ' > > Can anyone help with regexp? > Thank you for help > L. Here's the immediate answer to your question. import re src = "Goods Item 146 (174459989) - OurWebSite" pattern = r"(.*)\(" re.search(pattern,src).groups()[0] I post it this way so that you can relate the re to your specific question, and then maybe apply this to whatever else you are scraping from this web page. Please don't follow up with a post asking how to extract "45","Rubber chicken" from "<tr><td>45</td><td>Rubber chicken</td></tr>". At this point, you should try a little experimentation on your own. -- Paul From aleax at mac.com Sat Mar 3 21:18:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Mar 2007 18:18:50 -0800 Subject: pop method question References: <mailman.4633.1172954118.32031.python-list@python.org> <7xd53qxdb2.fsf@ruckus.brouhaha.com> <mailman.4634.1172955347.32031.python-list@python.org> <pan.2007.03.03.22.55.13.774135@REMOVE.THIS.cybersource.com.au> Message-ID: <1huevw6.dponjy1xld045N%aleax@mac.com> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote: ... > while some_dict: > do_something_with(some_dict.pop()) > > doesn't work. Instead you have to write this: You have to use .popitem for this -- that's what's it's for... Alex From ncalexander at gmail.com Sun Mar 4 19:22:08 2007 From: ncalexander at gmail.com (Nick Alexander) Date: 4 Mar 2007 16:22:08 -0800 Subject: How to set docstrings for extensions supporting PyNumberMethods? In-Reply-To: <1172996063.517322.208220@j27g2000cwj.googlegroups.com> References: <1172948422.661418.312560@8g2000cwh.googlegroups.com> <1172996063.517322.208220@j27g2000cwj.googlegroups.com> Message-ID: <1173054128.726010.203120@h3g2000cwc.googlegroups.com> On Mar 4, 12:14 am, "Ziga Seilnacht" <ziga.seilna... at gmail.com> wrote: > NickAlexanderwrote: > > Hello, > > > I am writing a python extension (compiled C code) that defines an > > extension type with PyNumberMethods. Everything works swimmingly, > > except I can't deduce a clean way to set the docstring for tp_* > > methods. That is, I always have > > > type.__long__.__doc__ == 'x.__long__() <==> long(x)' > > > which a quick glance at the Python 2.5 source shows is the default. > > > I have found that I can use PyObject_GetAttr and PyWrapperDescrObject > > and set the descriptor objects d_base->doc to a char pointer... but I > > can't tell if this is safe. Or the right way to do it. > > > If I'm on the wrong list, please let me know! > > Thanks, > >NickAlexander > > I think that the right way is to add the methods to the tp_methods > slot and use METH_COEXIST in the PyMethodDef flags field. Example: Ziga, thanks for an extremely helpful reply. I'll experiment and post again if there are issues. Cheers! Nick From ckkart at hoc.net Mon Mar 26 22:48:30 2007 From: ckkart at hoc.net (Christian) Date: Tue, 27 Mar 2007 11:48:30 +0900 Subject: build python on Celeron D Message-ID: <eua0l8$po1$1@sea.gmane.org> Hi, I'm having problems with python 2.4.4 built on a Celeron D. I had problems earlier with that processor which I think has understands some 64 bit instructions (whatever that means) but is still 32 bit. Thus when e.g. trying to build numpy with the self built python I get that error: Traceback (most recent call last): File "setup.py", line 89, in ? setup_package() File "setup.py", line 59, in setup_package from numpy.distutils.core import setup File "/mnt/home/ck/prog/scipy/numpy-1.0.1/numpy/__init__.py", line 36, in ? File "numpy/core/__init__.py", line 5, in ? import multiarray ImportError: /media/hda6/home/ck/prog/scipy/numpy-1.0.1/numpy/core/multiarray.so: undefined symbol: Py_InitModule4 which is related to 32<->64 issues, right? So my question is how do I force python to be built with 32bit? Christian From gagsl-py2 at yahoo.com.ar Tue Mar 20 19:29:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 Mar 2007 20:29:35 -0300 Subject: mysterious unicode References: <1174430100.666040.43970@l77g2000hsb.googlegroups.com> Message-ID: <op.tpigvli0x6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 20 Mar 2007 19:35:00 -0300, Gerry <gerard.blais at gmail.com> escribi?: > which seems to work. Here's the mysterious part (aside from why > anything was unicode in the first place): > > print >> debug, "c=", col, "r=", row, "v=", value, > "qno=", qno > tuple = (qno, family) > try: > data[tuple].append(value) > except: > data[tuple] = [value] > print >> debug, "!!!", col, row, qno, family, tuple, > value, data[tuple] > > which produces: > > c= 1 r= 3 v= 4 qno= Q1 > !!! 1 3 Q1 O (u'Q1', 'O') 4 [1, u' ', 4] > > where qno seems to be a vanilla Q1, but a tuple using qno is > (u'Q1', ...). I bet qno was unicode from start. When you print an unicode object, you get the "unadorned" contents. When you print a tuple, it uses repr() on each item. py> qno = u"Q1" py> qno u'Q1' py> print qno Q1 py> print (qno,2) (u'Q1', 2) -- Gabriel Genellina From aahz at pythoncraft.com Sat Mar 3 19:17:40 2007 From: aahz at pythoncraft.com (Aahz) Date: 3 Mar 2007 16:17:40 -0800 Subject: thread safe SMTP module References: <mailman.4616.1172878783.32031.python-list@python.org> Message-ID: <esd374$927$1@panix3.panix.com> In article <mailman.4616.1172878783.32031.python-list at python.org>, Gordon Messmer <gmessmer at u.washington.edu> wrote: > >I believe that I've seen this discussed previously, so maybe there's >some interest in it. I wrote a threaded mail filtering framework >a while ago, and one of the modules does address verification >via SMTP. Since smtplib.SMTP uses blocking IO, it can block the >whole interpreter. Sometimes the whole thing would stop working >indefinitely. That doesn't make any sense. Blocking I/O generally releases the GIL, which is the whole reason Python doesn't totally suck for threading. There may be other thread problems, but I doubt that you have correctly analyzed their source. You can prove this for yourself by trying out my threaded spider at http://www.pythoncraft.com/OSCON2001/ThreadPoolSpider.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From lbates at websafe.com Tue Mar 27 12:35:24 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 27 Mar 2007 11:35:24 -0500 Subject: Zip file writing progress (callback proc) In-Reply-To: <mailman.5627.1174916476.32031.python-list@python.org> References: <mailman.5627.1174916476.32031.python-list@python.org> Message-ID: <8d-dnZKQwMZX2pTbnZ2dnUVZ_ruknZ2d@comcast.com> durumdara wrote: > Hi! > > I want to check my zip file writings. > I need some callback procedure to show a progress bar. > Can I do that? > I don't want to modify the PyLib module to extend it, because if I get > another py, the changes are lost. > This happening too if I copy the zip module to modify it. > Any solution? > > Thanks for it: > dd I did this by extending the write method of my zipfile module. 1) Add a callback= keyword argument to __init__ and saving that in an instance variable (self._callback). def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False, callback=None): """Open the ZIP file with mode read "r", write "w" or append "a".""" self._allowZip64 = allowZip64 self._didModify = False self._callback = callback # new instance variable to be used in write 2) Change write method so that it calls the progress method of the callback function after every block is written (if user passed in one). while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) #-----New lines follow # # Call the progress method of the callback function (if defined) # if self._callback is not None: self._callback.progress(st.st_size, fp.tell()) #-----End of new lines CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) 3) Define a callback class and use it: import zipfile class CB(): def progress(self, total, sofar): zippercentcomplete=100.0*sofar/total print "callback.progress.zippercentcomplete=%.2f" % zippercentcomplete return z=zipfile.ZipFile(r'C:\testzip.zip', mode='w', callback=CB()) z.write(r'c:\Library\TurboDelphi\TurboDelphi.exe') At least by doing it this way you won't break anything if you get a new zipfile module. It just won't show progress any more and then you can patch it. Hope info helps. -Larry Bates From MonkeeSage at gmail.com Mon Mar 5 22:30:07 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 19:30:07 -0800 Subject: Is every number in a list in a range? In-Reply-To: <7xmz2r83ed.fsf@ruckus.brouhaha.com> References: <mailman.4693.1173129006.32031.python-list@python.org> <7xk5xvgo55.fsf@ruckus.brouhaha.com> <1173149481.694255.23350@n33g2000cwc.googlegroups.com> <7x7itvt6nw.fsf@ruckus.brouhaha.com> <1173150785.768534.286700@8g2000cwh.googlegroups.com> <7xmz2r83ed.fsf@ruckus.brouhaha.com> Message-ID: <1173151807.570677.141310@h3g2000cwc.googlegroups.com> On Mar 5, 9:19 pm, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > OK, I didn't read the question that way. I thought the person just > wanted a yes or no answer to whether the list contained any elements > outside the desired range. If the purpose is to select the elements > in the range, then use filter/ifilter or a different listcomp/genexp: > > inrange = [x for x in ll if 0<=x<=maxnum] Well, the OP didn't actually specify what behavior they wanted. I was just trying to go the with broadest case, with arbitrary values. Regards, Jordan From bbxx789_05ss at yahoo.com Mon Mar 19 12:54:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Mar 2007 09:54:55 -0700 Subject: * operator--as in *args? In-Reply-To: <mailman.5260.1174269168.32031.python-list@python.org> References: <1174251225.056602.99810@n59g2000hsh.googlegroups.com> <1174254032.155494.228530@e65g2000hsc.googlegroups.com> <1174266469.127020.186120@l77g2000hsb.googlegroups.com> <1hv6o86.18ve0cc11prsg8N%aleax@mac.com> <mailman.5260.1174269168.32031.python-list@python.org> Message-ID: <1174323295.244565.34740@b75g2000hsg.googlegroups.com> On Mar 18, 7:52 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > def f(*args, **kw): > > ... print "args",args > ... print "kw",kw > ...>>> d = {"a":1, "b":2, "c":3} > >>> f(**d) > Whoa! **? And applied to a function parameter? Back to the drawing board. On Mar 18, 7:21 pm, a... at mac.com (Alex Martelli) wrote: > More generally, with any iterable x, the *x > construct in function call will pass as positional arguments exactly > those items which (e.g.) would be printed by the loop: > for item in x: print x > Thanks. On Mar 18, 7:52 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > def f(*args, **kw): > > ... print "args",args > ... print "kw",kw > ...>>> d = {"a":1, "b":2, "c":3} > >>> f(**d) > Whoa! **? And applied to a function parameter name? Back to the drawing board. The following is what I discovered for anyone else that is interested: More on Defining Functions(GvR tutorial, section 4.7) --Keyword Argument Lists --Arbitrary Argument Lists --Unpacking Argument Lists 1) Applying ** to a function parameter: def g(a, b, **xtraArgs): print xtraArgs g(b=20, c="big", a="hello", d=10) #output: {'c': 'big', 'd': 10} **xtraArgs will be a dictionary of all arguments sent to the function with the syntax "keyword=value" if the keyword does not match any of the function parameter names. 2)Applying * to a function parameter: def g(a, *xtraArgs): print xtraArgs g(10, 20, 30, 40) #output: (20, 30, 40) *xtraArgs will be a tuple containing all arguments sent to the function with the syntax "value" that do not match any function parameter. 3) A function parameter with the syntax *xtraArgs1 must come before a function parameter with the syntax **xtraArgs2: def g(a, b, *xtraArgs1, **xtraArgs2): print xtraArgs1 print xtraArgs2 g(10, 20, 30, 35, d=40, e="hello") #(30, 35) #{'e': 'hello', 'd': 40} 4) Using * to unpack a list, tuple, etc.(any iterable collection--see earlier posts): def g(a, b, c): print a,b,c tpl = (1, 2, 3) g(*tpl) #output: 1 2 3 5) Using ** to unpack dictionaries: def g(a, b, c): print a,b,c dict = {"b":"world", "c":"goodbye", "a":"hello"} g(**dict) #output: hello world goodbye From gregpinero at gmail.com Thu Mar 1 13:36:12 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 1 Mar 2007 10:36:12 -0800 Subject: How to Read Bytes from a file In-Reply-To: <1172771161.015437.50000@n33g2000cwc.googlegroups.com> References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1172757183.819978.219440@v33g2000cwv.googlegroups.com> <1172764725.827624.298180@j27g2000cwj.googlegroups.com> <1172771161.015437.50000@n33g2000cwc.googlegroups.com> Message-ID: <1172774172.389220.124170@j27g2000cwj.googlegroups.com> On Mar 1, 12:46 pm, "Bart Ogryczak" <B.Ogryc... at gmail.com> wrote: > > This solution looks nice, but how does it work? I'm guessing > > struct.unpack will provide me with 8 bit bytes > > unpack with 'B' format gives you int value equivalent to unsigned char > (1 byte). > > > (will this work on any system?) > > Any system with 8-bit bytes, which would mean any system made after > 1965. I'm not aware of any Python implementation for UNIVAC, so I > wouldn't worry ;-) > > > How does count1 work exactly? > > 1,2,4,8,16,32,64,128 in binary are > 1,10,100,1000,10000,100000,1000000,10000000 > x&1 == 1 if x has first bit set to 1 > x&2 == 2, so (x&2>0) == True if x has second bit set to 1 > ... and so on. > In the context of int, True is interpreted as 1, False as 0. Thanks Bart. That's perfect. The other suggestion was to precompute count1 for all possible bytes, I guess that's 0-256, right? Thanks again everyone for the help. -Greg From nick at craig-wood.com Tue Mar 27 04:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 27 Mar 2007 03:30:05 -0500 Subject: with timeout(...): References: <slrnf0f59e.a21.nick@irishsea.home.craig-wood.com> <1174958444.273725.15710@o5g2000hsb.googlegroups.com> Message-ID: <slrnf0hj6p.php.nick@irishsea.home.craig-wood.com> Klaas <mike.klaas at gmail.com> wrote: > On Mar 26, 3:30 am, Nick Craig-Wood <n... at craig-wood.com> wrote: > > Did anyone write a contextmanager implementing a timeout for > > python2.5? > > > > I'd love to be able to write something like > > > > with timeout(5.0) as exceeded: > > some_long_running_stuff() > > if exceeded: > > print "Oops - took too long!" > > > > And have it work reliably and in a cross platform way! > > Doubt it. But you could try: > > class TimeoutException(BaseException): > pass > > class timeout(object): > def __init__(self, limit_t): > self.limit_t = limit > self.timer = None > self.timed_out = False > def __nonzero__(self): > return self.timed_out > def __enter__(self): > self.timer = threading.Timer(self.limit_t, ...) > self.timer.start() > return self > def __exit__(self, exc_c, exc, tb): > if exc_c is TimeoutException: > self.timed_out = True > return True # suppress exception > return False # raise exception (maybe) > > where '...' is a ctypes call to raise the given exception in the > current thread (the capi call PyThreadState_SetAsyncExc) > > Definitely not fool-proof, as it relies on thread switching. Also, > lock acquisition can't be interrupted, anyway. Also, this style of > programming is rather unsafe. > > But I bet it would work frequently. Here is my effort... You'll note from the comments that there are lots of tricky bits. It isn't perfect though as it sometimes leaves behind threads (see the FIXME). I don't think it crashes any more though! ------------------------------------------------------------ """ General purpose timeout mechanism not using alarm(), ie cross platform Eg from timeout import Timeout, TimeoutError def might_infinite_loop(arg): while 1: pass try: Timeout(10, might_infinite_loop, "some arg") except TimeoutError: print "Oops took too long" else: print "Ran just fine" """ import threading import time import sys import ctypes import os class TimeoutError(Exception): """Thrown on a timeout""" PyThreadState_SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc _c_TimeoutError = ctypes.py_object(TimeoutError) class Timeout(threading.Thread): """ A General purpose timeout class timeout is int/float in seconds action is a callable *args, **kwargs are passed to the callable """ def __init__(self, timeout, action, *args, **kwargs): threading.Thread.__init__(self) self.action = action self.args = args self.kwargs = kwargs self.stopped = False self.exc_value = None self.end_lock = threading.Lock() # start subtask self.setDaemon(True) # FIXME this shouldn't be needed but is, indicating sub tasks aren't ending self.start() # Wait for subtask to end naturally self.join(timeout) # Use end_lock to kill the thread in a non-racy # fashion. (Using isAlive is racy). Poking exceptions into # the Thread cleanup code isn't a good idea either if self.end_lock.acquire(False): # gained end_lock => sub thread is still running # sub thread is still running so kill it with a TimeoutError self.exc_value = TimeoutError() PyThreadState_SetAsyncExc(self.id, _c_TimeoutError) # release the lock so it can progress into thread cleanup self.end_lock.release() # shouldn't block since we've killed the thread self.join() # re-raise any exception if self.exc_value: raise self.exc_value def run(self): self.id = threading._get_ident() try: self.action(*self.args, **self.kwargs) except: self.exc_value = sys.exc_value # only end if we can acquire the end_lock self.end_lock.acquire() if __name__ == "__main__": def _spin(t): """Spins for t seconds""" start = time.time() end = start + t while time.time() < end: pass def _test_time_limit(name, expecting_time_out, t_limit, fn, *args, **kwargs): """Test Timeout""" start = time.time() if expecting_time_out: print "Test",name,"should timeout" else: print "Test",name,"shouldn't timeout" try: Timeout(t_limit, fn, *args, **kwargs) except TimeoutError, e: if expecting_time_out: print "Timeout generated OK" else: raise RuntimeError("Wasn't expecting TimeoutError Here") else: if expecting_time_out: raise RuntimeError("Was expecting TimeoutError Here") else: print "No TimeoutError generated OK" elapsed = time.time() - start print "That took",elapsed,"seconds for timeout of",t_limit def test(): """Test code""" # no nesting _test_time_limit("simple #1", True, 5, _spin, 10) _test_time_limit("simple #2", False, 10, _spin, 5) # 1 level of nesting _test_time_limit("nested #1", True, 4, _test_time_limit, "nested #1a", True, 5, _spin, 10) _test_time_limit("nested #2", False, 6, _test_time_limit, "nested #2a", True, 5, _spin, 10) _test_time_limit("nested #4", False, 6, _test_time_limit, "nested #4a", False, 10, _spin, 5) # 2 level of nesting _test_time_limit("nested #5", True, 3, _test_time_limit, "nested #5a", True, 4, _test_time_limit, "nested #5b", True, 5, _spin, 10) _test_time_limit("nested #9", False, 7, _test_time_limit, "nested #9a", True, 4, _test_time_limit, "nested #9b", True, 5, _spin, 10) _test_time_limit("nested #10", False, 7, _test_time_limit, "nested #10a",False, 6, _test_time_limit, "nested #10b",True, 5, _spin, 10) _test_time_limit("nested #12", False, 7, _test_time_limit, "nested #12a",False, 6, _test_time_limit, "nested #12b",False, 10, _spin, 5) print "All tests OK" test() -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From mccredie at gmail.com Fri Mar 16 16:30:19 2007 From: mccredie at gmail.com (Matimus) Date: 16 Mar 2007 13:30:19 -0700 Subject: Finding the insertion point in a list In-Reply-To: <1174069208.088356.289020@d57g2000hsg.googlegroups.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <1174069208.088356.289020@d57g2000hsg.googlegroups.com> Message-ID: <1174077019.462758.289340@d57g2000hsg.googlegroups.com> On Mar 16, 11:20 am, "Matimus" <mccre... at gmail.com> wrote: > You might look at the bisect module (part of the standard > distribution). Here is an example: >>> from bisect import insort >>> x = [0,100,200,1000] >>> insort(x,10) >>> x [0, 10, 100, 200, 1000] From fleitner at REMcnioOVE.es Wed Mar 28 20:25:29 2007 From: fleitner at REMcnioOVE.es (Florian Leitner) Date: Thu, 29 Mar 2007 02:25:29 +0200 Subject: which methods to use? References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> Message-ID: <euf11o$rk6$1@aioe.org> * s99999999s2003 at yahoo.com wrote, On 3/29/07 2:09 AM: > hi > which is the best methods to use for list copying. using list() , [:] > or create list through list comprehension. what are the differences > between these ? > thanks > depends on what you intend to do: -create a new object: use a list comprehension or list() -make a shallow copy: use copy.copy() or the slicing operator ([:]) -make a deep copy (incl. each list element): use copy.deepcopy() Try experimenting around, deleting and adding elements or changing them in the copy of your list and the original and see what happens if you are not sure what these things do. (to use copy, import it first) flo From eurleif at ecritters.biz Thu Mar 29 10:09:29 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 29 Mar 2007 10:09:29 -0400 Subject: YouTube showing repr() of a tuple In-Reply-To: <460b9f48$0$30100$4d3efbfe@news.sover.net> References: <460b9f48$0$30100$4d3efbfe@news.sover.net> Message-ID: <460bc895$0$30091$4d3efbfe@news.sover.net> Leif K-Brooks wrote: > Thought this might amuse some of you: > > <http://youtube.com/results?search_query=korect+my+speling> Better example: <http://youtube.com/results?search_query=korect+my+speling%C2%A1> From steve at REMOVEME.cybersource.com.au Thu Mar 8 03:20:23 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Mar 2007 19:20:23 +1100 Subject: Is numeric keys of Python's dictionary automatically sorted? References: <esn6nu$c8nt$1@netnews.upenn.edu> <1173300100.810023.223130@t69g2000cwt.googlegroups.com> <esn8ir$c8p4$1@netnews.upenn.edu> <1173339260.576508.157010@c51g2000cwc.googlegroups.com> Message-ID: <pan.2007.03.08.08.20.22.586466@REMOVEME.cybersource.com.au> On Wed, 07 Mar 2007 23:34:20 -0800, Nick Vatamaniuc wrote: >> >>From the standard library docs: >> >> > "Keys and values are listed in an arbitrary order which is non-random, >> > varies across Python implementations, and depends on the dictionary's >> > history of insertions and deletions." >> >> > i.e. the behaviour you have discovered is an implementation detail, >> > and could change in future versions. > > I would consider that a bad choice. In the dictionary the keys are a > set i.e. you might as well get a set() when you do d.keys() but the > set() came later so you just get a list. The internal implementation of dictionaries are irrelevant. Whether the keys "inside" a dictionary are "a set of keys" or "a list of keys" or "a bunch of keys" is just semantics. > The problem with a list is > that somehow people want to make sense of it's order, just like in > this case. And the problem with a dictionary is that some people want to make sense of its order, just like in this case, and the fifty thousand previous times people have asked this newsgroup how they can sort a dictionary. > So if instead of asking, he could have just written the > application based on the fact that the keys will always be sorted in > some way. But then one day his application maybe run a different > platform and all of the sudden the keys are not sorted as before and > then disaster strikes. That would be his problem for being a bad coder, not our problem or the language's fault. There is no limit to the "could haves" that lead to disaster. Somebody "could have" assumed that list.sort() returns the sorted list. Somebody "could have" assumed that "is" is merely a synonym for "==". And you know something? We get people making those mistakes all the time. When people make those mistakes, it is *their responsibility*, for being stupid or not reading the docs or not doing sufficient testing, or simply for being inexperienced. > I hope that dictionary.keys() would return a set to emphasize that > keys are unordered. What makes you think that people will magically intuit that sets are unordered when they insist on thinking that dicts are ordered? The below-average coder does this: >>> D = {1: None, 2: None, 3:None} >>> D {1: None, 2: None, 3: None} and concludes that dictionaries are ordered. If they are better-than average, they might try this: >>> D = {1: None, 4: None, 3:None} # keys out of order >>> D {1: None, 3: None, 4: None} Still ordered, right? It's actually quite hard to get a dict with purely integer keys out of order. So they ASS_U_ME that dicts are ordered. What makes you think they won't do the same with sets? >>> set((1, 2, 3)) set([1, 2, 3]) >>> set((1, 4, 3)) set([1, 3, 4]) >>> D = {4: None, 2: None, 1: None, 3: None} >>> set(D.keys()) set([1, 2, 3, 4]) Sure looks ordered to me. The solution is: (1) Don't assume unordered data structures like sets and dicts are ordered, even if they look like it. They aren't. (2) If you want the keys of a dict sorted, get the keys, and sort them when and as you need them. (3) If you think you want a sorted dictionary, chances are you actually want a different algorithm. (4) But if you really do need a sorted dictionary, there are recipes on the web. Google is your friend. But remember, they will be slower than regular dictionaries. -- Steven D'Aprano From steve at holdenweb.com Fri Mar 23 14:25:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 23 Mar 2007 14:25:34 -0400 Subject: Multi-line strings with formatting In-Reply-To: <1174669850.3450.40.camel@dot.uniqsys.com> References: <1174668885.347602.117970@n59g2000hsh.googlegroups.com> <1174669850.3450.40.camel@dot.uniqsys.com> Message-ID: <eu165f$qm2$1@sea.gmane.org> Carsten Haese wrote: > On Fri, 2007-03-23 at 09:54 -0700, gburdell1 at gmail.com wrote: >> When constructing a particularly long and complicated command to be >> sent to the shell, I usually do something like this, to make the >> command as easy as possible to follow: >> >> commands.getoutput( >> 'mycommand -S %d -T %d ' % (s_switch, t_switch) + >> '-f1 %s -f2 %s ' % (filename1, filename2) + >> '> %s' % (log_filename) >> ) >> >> Can anyone suggest a better way to construct the command, especially >> without the "+" sign at the end of each line (except the last) ? If I >> take out the "+", then I need to move all the variables to the end, as >> so: >> >> commands.getoutput( >> 'mycommand -S %d -T %d ' >> '-f1 %s -f2 %s ' >> '> %s' >> % (s_switch, t_switch, filename1, filename2, log_filename) >> ) >> >> or: >> >> commands.getoutput( >> '''mycommand -S %d -T %d \ >> -f1 %s -f2 %s \ >> > %s''' >> % (s_switch, t_switch, filename1, filename2, log_filename) >> ) > > You get the best of both worlds, i.e. one big multiline string with > in-line parameters, by using a mapping: > > commands.getoutput( > '''mycommand -S %(s_switch)d -T %(t_switch)d \ > -f1 %(filename1)s -f2 %(filename2)s \ > > %(log_filename)s''' > % locals() ) > > Of course I'm assuming that s_switch etc. are local variables. If > they're not, well, they ought to be. > > -Carsten > > If that doesn't suit then build a list: l = [ 'mycommand -S %d -T %d ' % (s_switch, t_switch) , '-f1 %s -f2 %s ' % (filename1, filename2) , '> %s' % (log_filename) ] and then return commands.getoutput("".join(l)). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From steve at REMOVEME.cybersource.com.au Thu Mar 1 23:47:38 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 02 Mar 2007 15:47:38 +1100 Subject: Questions about app design - OOP with python classes References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <pan.2007.03.02.04.14.10.655399@REMOVEME.cybersource.com.au> <7xabywnugu.fsf@ruckus.brouhaha.com> Message-ID: <pan.2007.03.02.04.47.37.365032@REMOVEME.cybersource.com.au> On Thu, 01 Mar 2007 20:24:33 -0800, Paul Rubin wrote: > Steven D'Aprano <steve at REMOVEME.cybersource.com.au> writes: >> But if you used Apps Hungarian, and saw this line of code: >> >> if hmmCurrentHeight <= hinCriticalHeight: >> >> then you should instantly recognise that there's a problem. Comparing >> a height in millimetres to a height in inches is not a good thing to do, >> no matter that they're both floats. > > That still sounds like an unreliable manual type system, It's unreliable in the sense that the coder has to follow the naming convention, and must have some bare minimum of sense. If your coders are morons, no naming convention will save you. (For that matter, nothing will save you.) > instead of an > automatic type system that includes dimension analysis. You might > like this: > > http://futureboy.homeip.net/frinkdocs/ > > There are many Python implementations of dimensioned units as well. I > posted one here a few weeks ago. Sure, and I love the Unix utility "units", and my HP calculator. Dimensioned units are useful. But dimensioned units are still only part of the story. Joel describes the situation the early Word developers found: when you're writing a word processor, you are doing a LOT of conversions between screen coordinates and window pane coordinates. Both have the same type (a pair of ints), both have the same dimensional units (length/pixels) but they are semantically different. If you place the character "N" at coordinates 0,0, it makes a big difference if the coordinates are relative to the current window or relative to the screen. Apps Hungarian is a heuristic for dealing with semantic differences, not data types. It deals with more than just dimensional analysis. -- Steven D'Aprano From MonkeeSage at gmail.com Sat Mar 3 17:28:03 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Mar 2007 14:28:03 -0800 Subject: class attrdict In-Reply-To: <1huecz7.1thcn0b1j64biiN%aleax@mac.com> References: <hbf.20070302nsi@bombur.uio.no> <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1172895832.352834.313300@p10g2000cwp.googlegroups.com> <1hud90j.zf49afwqrk0bN%aleax@mac.com> <45e9b753$0$8983$4c368faf@roadrunner.com> <1huecz7.1thcn0b1j64biiN%aleax@mac.com> Message-ID: <1172960883.340892.183850@31g2000cwt.googlegroups.com> On Mar 3, 1:29 pm, a... at mac.com (Alex Martelli) wrote: > It would be nice, yes, weren't it for the inevitable irregularity, one > way or another, caused by the clash between attributes and items. In thinking about it, I think this might fall under 'we're all consenting adults here'. I mean, you can shadow the dict constructor from the toplevel if you're so inclined (or don't know any better). But you could make it harder to accidentally shadow builtin attributes: from warnings import warn class attrdict(dict): __builtins__ = dir(dict) def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) for k, v in self.items(): dict.__setattr__(self, str(k), v) def __setitem__(self, k, v): if k in self.__builtins__: warn('shadowing builtin attribute: %s' % k, RuntimeWarning, 2) dict.__setitem__(self, k, v) dict.__setattr__(self, str(k), v) __setattr__ = __setitem__ a = attrdict([(1,2)], a=3, b=4) a.update = 'test' Regards, Jordan From sjmachin at lexicon.net Fri Mar 2 22:57:03 2007 From: sjmachin at lexicon.net (John Machin) Date: 2 Mar 2007 19:57:03 -0800 Subject: Perl and Python, a practical side-by-side example. In-Reply-To: <45e8c931$0$8646$426a34cc@news.free.fr> References: <mailman.4614.1172875489.32031.python-list@python.org> <45e8c931$0$8646$426a34cc@news.free.fr> Message-ID: <1172894223.669617.79060@31g2000cwt.googlegroups.com> On Mar 3, 12:36 pm, Bruno Desthuilliers > [snip] > DATE = 5 > TARGET = 6 [snip] > Now for the bad news: I'm afraid your algorithm is broken : here are my > test data and results: > > input = [ > #ID STATE ... ... ... TARG DATE > "aaa\tAAA\t...\t...\t...\tBBB\t20071212\n", [snip] Bruno, The worse news is that your test data is broken. According to the OP (and your own code (DATE = 5 etc)), the target state comes last. GIGO. At least you have demonstrated to the OP why naming the field indexes is a good idea :-) Cheers, John From jrpfinch at gmail.com Mon Mar 26 06:29:32 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 26 Mar 2007 03:29:32 -0700 Subject: Calling Queue experts In-Reply-To: <1174899202.355092.209590@l75g2000hse.googlegroups.com> References: <1174899202.355092.209590@l75g2000hse.googlegroups.com> Message-ID: <1174904972.597317.27240@e65g2000hsc.googlegroups.com> Got it. New PickleQueue class should be as follows: import Queue import cPickle class PickleQueue(Queue.Queue): """A multi-producer, multi-consumer, persistent queue.""" def __init__(self, filename, maxsize=0): """Initialize a persistent queue with a filename and maximum size. The filename is used as a persistent data store for the queue. If maxsize <= 0, the queue size is infinite. """ self.filename = filename Queue.Queue.__init__(self, maxsize) print self.queue def _init(self, maxsize): # Implements Queue protocol _init for persistent queue. # Sets up the pickle files. self.maxsize = maxsize try: self.readfile = file(self.filename, 'r') self.queue = cPickle.load(self.readfile) self.readfile.close() except IOError, err: if err.errno == 2: # File doesn't exist, continue ... self.queue = Queue.deque() else: # Some other I/O problem, reraise error raise err except EOFError: # File was null? Continue ... self.queue = Queue.deque() # Rewrite file, so it's created if it doesn't exist, # and raises an exception now if we aren't allowed self.writefile = file(self.filename, 'w') cPickle.dump(self.queue, self.writefile, 1) def __sync(self): # Writes the queue to the pickle file. self.writefile.seek(0) cPickle.dump(self.queue, self.writefile, 1) self.writefile.flush() def _put(self, item): # Implements Queue protocol _put for persistent queue. self.queue.append(item) self.__sync() def _get(self): # Implements Queue protocol _get for persistent queue. item = self.queue.popleft() self.__sync() return item From nobody at invalid.com Thu Mar 22 17:50:59 2007 From: nobody at invalid.com (Erik Johnson) Date: Thu, 22 Mar 2007 15:50:59 -0600 Subject: Been a while... References: <4602a1be$0$32400$c3e8da3@news.astraweb.com> <mailman.5466.1174580521.32031.python-list@python.org> Message-ID: <4602fa3c$1@nntp.zianet.com> "Michael Bentley" <michael at jedimindworks.com> wrote in message news:mailman.5466.1174580521.32031.python-list at python.org... > > On Mar 22, 2007, at 10:34 AM, John Salerno wrote: > > > Hi guys. It's been a while since I've used Python, so I got a little > > rusty, but I really want to start using it again, just out of habit > > and > > for fun. Can anyone suggest a book or a website with little projects I > > could work on to keep me busy? > > http://www.pythonchallenge.com There is also a slew of interesting (and challenging) problems at SPOJ (Sphere Online Judge: https://www.spoj.pl/) which you can solve and submit your Python (or one of about 30 other languages) solution to for automatic and (almost) immediate judging. There is a slew of programming contest problems at http://acm.uva.es/problemset/ , an ACM-sponsored site which does not accept postings in Python, but you can always dig through the problems to find an interesting one to work on. You'll have to decide for yourself if you've solved it correctly / satisfactorily. Good luck, -ej From steve at holdenweb.com Mon Mar 19 13:57:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 13:57:15 -0400 Subject: PythonCard thoughts In-Reply-To: <1174315460.650400.202270@e1g2000hsg.googlegroups.com> References: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> <45fe9b31$0$17946$c3e8da3@news.astraweb.com> <1174315460.650400.202270@e1g2000hsg.googlegroups.com> Message-ID: <etmj0e$29m$1@sea.gmane.org> king kikapu wrote: >> I don't know much about PythonCard or wxGlade, but I use wxPython (which >> wxGlade uses, right?) and you now have the option to separate your GUI >> and code using an XRC file (xml file that describes layout). So perhaps >> this is something you can do with wxGlade, but at the same time it might >> still create the problem you describe above. However, it's very to have >> your Python files contain just logic. > > Yes, both products (PythonCard and wxGlade) uses wxPython. It's just > that PythonCard is sitting on top of wxPython and it intercepts the > events generated. Then it search for an appropriate declared function > on your code and call it (all this happens at runtime). > It shield us from much of the boilerplate code that gui toolkits > require and in the case that you need to address directly wxPython, > you just can! > > I discovered that when you run your designed GUI from PythonCard's > layoutEditor, you have the ability to define a command line option > that is called > "Message Watcher". This, will show you the names of the actual events > that you have to write code for, so you, at least for this, do not > have > to dig the docs for their names. Pretty good! > The only real problem is that PythonCard appears to have run out of development steam. I don't think there's been much^H^H^H^H any work on it in the past year or two. This is a shame, as it showed considerable promise. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From luismgz at gmail.com Mon Mar 19 21:53:57 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 Mar 2007 18:53:57 -0700 Subject: Passing arguments to a command line from a python script In-Reply-To: <1174355342.669635.302960@y80g2000hsf.googlegroups.com> References: <1174348016.873087.179750@d57g2000hsg.googlegroups.com> <mailman.5313.1174350370.32031.python-list@python.org> <1174354958.815878.95020@d57g2000hsg.googlegroups.com> <1174355342.669635.302960@y80g2000hsf.googlegroups.com> Message-ID: <1174355637.450275.148340@l77g2000hsb.googlegroups.com> On Mar 19, 10:49 pm, "zacherates" <zachera... at gmail.com> wrote: > On Mar 19, 9:42 pm, "Luis M. Gonz?lez" <luis... at gmail.com> wrote: > > > > > On Mar 19, 9:25 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > > wrote: > > > > En Mon, 19 Mar 2007 20:46:56 -0300, Luis M. Gonz?lez <luis... at gmail.com> > > > escribi?: > > > > > What I want now is execute the script I just created. > > > > As far as I know, the only way to execute the script is from a command > > > > line and typing "setup.py py2exe". > > > > A few ways: > > > - os.system("commandline"). Simplest way, but you don't have much control, > > > and it blocks until the process finishes. > > > - os.popen[234]? or the functions in the popen2 module > > > - the subprocess module - the most complete way, but simple enough for > > > most cases. > > > > -- > > > Gabriel Genellina > > > I'm sorry, but still I can't figure out this... > > Would you please show me a sample usage of os.system or os.popen for > > passing arguments to the command line? > > In this case, I should pass to the command line "setuppy py2exe". > > > Thanks! > > Luis > > aaron at athena:~$ python > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import os > >>> rt = os.system("ls") > > apps Firefox_wallpaper.png s2 tux_sshot_0.ppm > xorg.conf.diff > Desktop media s3 work > downloads permutation.py squeak workspace > Examples permutation.pyc trackers xorg.conf.aiglx > > >>> rt > 0 > > This implies that `os.system("setuppy py2exe")` should do what you > want. It works! Thank you, this is just what I wanted. Luis From andre.roberge at gmail.com Sat Mar 10 13:24:10 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 10 Mar 2007 10:24:10 -0800 Subject: A Pythonic Way to Measure and Improve Your Programming Skills? In-Reply-To: <mailman.4915.1173549249.32031.python-list@python.org> References: <45F14D7E.3060707@taupro.com> <a06230908c2187f182731@[192.168.1.242]> <1173546636.14230.57.camel@workshop> <mailman.4915.1173549249.32031.python-list@python.org> Message-ID: <1173551049.951482.93620@c51g2000cwc.googlegroups.com> On Mar 10, 1:54 pm, Brad Allen <b... at allendev.com> wrote: > At 9:10 AM -0800 3/10/07, Michael Bernstein wrote: > > >On Sat, 2007-03-10 at 10:01 -0600, Brad Allen wrote: > > >> When I discussed this problem with Michael Bernstein at PyCon he suggested > >> the idea of creating a "chroot jail" for each web session which could run > >> the Python interpreter in a secure sandbox. That might be easier than giving > >> each session a whole virtual server. > > >Note that this wasn't an original idea of mine, I got it from brief > >mentions associated with two existing interactive python-in-a-web-page > >implementations: > > > Try Python:http://www.mired.org/home/mwm/try_python/ > > > TryPy:http://trac.pocoo.org/wiki/TryPy > > Cool! The first link appears to work with Firefox and provides a real example > of using a Python interactive prompt via a non-local web interface. > Interestingly, it doesn't seem to use Crunchy, but instead uses TryPy. try_python was one of the things that inspired me to write Crunchy. > Apparently you can't define classes or functions with TryPy, but I recall you > can using Crunchy. This is important for creating tutorials in which you > ask the student to define a class or function to solve a problem. Yes, Crunchy gives you full access to a regular Python interpreter. In a classroom environment, you can even write some doctests that have to be satisfied by the student's code. One example included in the documentation requires the user to define a class to solve a particular problem. I think that it would be great indeed if Crunchy could be made available from the web in a secure way. Hopefully, by the time we make the 1.0 release, Crunchy will have been found to be useful enough that someone with the appropriate resources will make this happen. Andr? From john.pye at gmail.com Wed Mar 21 00:58:05 2007 From: john.pye at gmail.com (John Pye) Date: 20 Mar 2007 21:58:05 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: <mailman.5372.1174450550.32031.python-list@python.org> References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> <mailman.5372.1174450550.32031.python-list@python.org> Message-ID: <1174453085.748142.48700@y80g2000hsf.googlegroups.com> On Mar 21, 3:15 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Wed, 21 Mar 2007 00:46:03 -0300, John Pye > <john.... at student.unsw.edu.au> escribi?: > > > This is not an option for me, as I want to pass the > > FILE* from Python and all the way into into a existing shared-library > > code. I can't change the latter; it must work ok with standard fprintf > > (etc) functions. > > You can get the file descriptor from the Python file object using its > fileno() method. The file descriptor lives at the OS level, so it's safe > to pass around. You can regenerate a new FILE struct (using the other > runtime library) with fdopen. > > -- > Gabriel Genellina Hmm. Reading this again I think I understand properly now. The 'fileno' is really *not* the same thing as the FILE* pointer cast to an integer. It is a lower-level structure. The question is now, if I don't want to modify my *python* code, how do I get at the 'fileno' property of my PyFileObject? Also, are there consequences for using this approach of regenerating the FILE struct? For example if I have the following: F = os.tmpfile() F.write("some data") F.seek(0) myswigmodule.dosomething(F) F.seek(0) S = F.read() print S I don't know enough about this low-level file handling to really understand the implications of what you are proposing -- perhaps you could explain a little? Cheers JP From steve at holdenweb.com Wed Mar 14 16:54:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Mar 2007 16:54:15 -0400 Subject: string formatting: engineering notation In-Reply-To: <et9l3u$e57$1@ruby.cit.cornell.edu> References: <et9l3u$e57$1@ruby.cit.cornell.edu> Message-ID: <et9nge$5s3$2@sea.gmane.org> Darren Dale wrote: > Does anyone know if it is possible to represent a number as a string with > engineering notation (like scientific notation, but with 10 raised to > multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the > decimal.Decimal class, but repeatedly instantiating Decimals is inefficient > for my application (matplotlib plotting library). If it is not currently > possible, do you think the python devs would be receptive to including > support for engineering notation in future releases? > How close is this: >>> "%.3e" % 3.14159 '3.142e+00' regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From nick at craig-wood.com Mon Mar 26 05:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 26 Mar 2007 04:30:08 -0500 Subject: detect suprocess interaction References: <mailman.5521.1174670106.32031.python-list@python.org> Message-ID: <slrnf0f2mf.7t3.nick@irishsea.home.craig-wood.com> Robin Becker <robin at reportlab.com> wrote: > I'm using subprocess to carry out svn commands (probably should use the svn api > package, but that's a dependency too far). Anyhow my code looks like > > from subprocess import Popen, PIPE > p = Popen((svn,'ls',u),stdout=PIPE,stderr=PIPE) > i = p.wait() > > and this sort of thing works well under most circumstances. However, when this > code is executed for the very first time by a particular user it hangs waiting > on user input. > > This code is being used purely for testing correctness of a particular svn url > so in the normal case we want to throw away both stdout and stderr. In the > exceptional case is it possible to detect that input is required and only in > that case issue the current contents of stdout (presumably a request for a > password)? > > Clearly I need to supply some kind of input filelike object, but is this sort of > thing possible. Yes it is possible, but if you try it you'll find you'll need to implement the fileno() method of file objects which is asked to return an OS file handle. This is obviously a problem! In general subprocess isn't really designed for interactive processes like the above. You'll find it much easier to use pexpect for interactive stuff. Note that svn has its own devious ways of finding a terminal to ask the user for the password, eg... $ svn ls svn+ssh://user at 127.0.0.1/svn </dev/null >/dev/null 2>&1 Password: I don't know exactly how it does that but I suspect it is to do with the controlling terminal... On my system $ setsid svn ls svn+ssh://user at 127.0.0.1/svn </dev/null >/dev/null 2>&1 Pops up a gui box asking for the password! You can simulate the above with Popen(..., stdin=file(os.devnull,"r"), preexec_fn=os.setsid) -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From sjmachin at lexicon.net Mon Mar 5 07:01:31 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Mar 2007 04:01:31 -0800 Subject: list-like behaviour of etree.Element In-Reply-To: <mailman.4668.1173085252.32031.python-list@python.org> References: <mailman.4658.1173041314.32031.python-list@python.org> <1173080656.077853.249520@8g2000cwh.googlegroups.com> <mailman.4668.1173085252.32031.python-list@python.org> Message-ID: <1173096091.815555.28420@30g2000cwc.googlegroups.com> On Mar 5, 8:00 pm, "Fredrik Lundh" <fred... at pythonware.com> wrote: > > extend() will be in the next release: > > http://effbot.org/zone/elementtree-changes-13.htm > Hi Fredrik, "The library requires Python 2.2 or newer." -- Does this apply to cElementTree as well? Reason for asking: my xlrd package works with Python 2.1 or later. I'm using cElementTree in a so-far-so-good prototype of parsing Excel 2007 .XLSX files ... Regards, John Regards, John From DustanGroups at gmail.com Sun Mar 18 09:29:00 2007 From: DustanGroups at gmail.com (Dustan) Date: 18 Mar 2007 06:29:00 -0700 Subject: Private data In-Reply-To: <1174224087.024303.102130@n59g2000hsh.googlegroups.com> References: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> <pan.2007.03.18.12.06.32.760433@REMOVE.THIS.cybersource.com.au> <1174220701.206419.77780@e65g2000hsc.googlegroups.com> <1174224087.024303.102130@n59g2000hsh.googlegroups.com> Message-ID: <1174224540.496180.11440@l75g2000hse.googlegroups.com> On Mar 18, 8:21 am, "Dustan" <DustanGro... at gmail.com> wrote: > On Mar 18, 7:25 am, "Dustan" <DustanGro... at gmail.com> wrote: > > > > > On Mar 18, 7:06 am, Steven D'Aprano > > > First, an example of the code in action. > > > > >>> import PrivateAttributes > > > >>> obj = PrivateAttributes.TestPrivateClassAttributes() > > > >>> obj.getNumInstances() > > > 1 > > > >>> another = PrivateAttributes.TestPrivateClassAttributes() > > > >>> obj.getNumInstances() > > > 2 > > > >>> athird = PrivateAttributes.TestPrivateClassAttributes() > > > >>> athird.getNumInstances() > > > > 3 > > > > The getNumInstances method reports the number of instances of the > > > PrivateAttributes class. There's no obvious class attribute where this > > > count is being kept: > > > > >>> obj.__class__.__dict__.keys() > > > > ['__module__', 'getNumInstances', '__dict__', '__weakref__', '__doc__', > > > '__init__'] > > > > Here's how to hack it, and make it report wrong numbers. > > > > >>> c = obj.getNumInstances.func_closure > > > >>> c[1].cell_contents.numInstances = -300 > > > > >>> athird.getNumInstances() > > > -300 > > > >>> afourth = PrivateAttributes.TestPrivateClassAttributes() > > > >>> athird.getNumInstances() > > > > -299 > > > > So yes, it is absolutely hackable. > > > I did have a feeling that it was hackable, but had no idea how one > > could possibly go about hacking it (I was starting to wonder of there > > was a way to apply locals() and globals() on functions). But now I > > (ehem) sorta know how it's done. > > > > Now, I'm hardly a Python guru, but in about fifteen minutes I followed the > > > trail through the object chain, and found how to hack this. An real guru > > > would probably do it in three minutes. > > > > I was helped a bit by having the source code. But even without the source > > > code, I reckon I could have done it in an hour or so, if I was motivated > > > enough. All the tools you need are a Python interactive session, the dir() > > > function and the dis module. > > > I have used all of those before, but I haven't been able to fully > > understand the output of the dis module; maybe that's my problem. > > Alright, perhaps you can help me out with this learning curve here. I > have seen, but not worked with, some basic assembly code, so I think I > have a vague idea of what it all means, although I have a feeling it's > not all valid assembly (on any widely used machine). > > First I dis.dis'd testPrivateStaticFunctionVariables: > > >>> dis.dis(testPrivateStaticFunctionVariables) > > 21 0 LOAD_DEREF 0 (func) > 3 LOAD_DEREF 1 (internalData) > 6 LOAD_FAST 0 (args) > 9 CALL_FUNCTION_VAR 1 > 12 RETURN_VALUE > > At first I was a little confused by this, because there's no increment > in sight, but then I realized it was dis.dis'ing the wrapper closure > in the internalDataDecorator closure in the PrivateDataEngine function > (and then I hit myself on the head and cried out "doh!"). So that > 'code' is coming from this (taken out of closure): > > def wrapper(*args): > return func(internalData, *args) > > So, based on what you showed me, I found my way after some failed > tries to this: > > >>> dis.dis(testPrivateStaticFunctionVariables.func_closure[0].cell_contents) > > 28 0 LOAD_FAST 0 (internalData) > 3 DUP_TOP > 4 LOAD_ATTR 0 (numCalls) > 7 LOAD_CONST 1 (1) > 10 INPLACE_ADD > 11 ROT_TWO > 12 STORE_ATTR 0 (numCalls) > > 29 15 LOAD_FAST 0 (internalData) > 18 LOAD_ATTR 0 (numCalls) > 21 RETURN_VALUE > > That's coming from this: > > @PrivateDataEngine(numCalls = 0) > def testPrivateStaticFunctionVariables(internalData): > """returns the number of times this function has been called.""" > internalData.numCalls += 1 > return internalData.numCalls > > Here's a few questions on this output, for which I would highly > appreciate some answers: > > What's the difference between 'LOAD_DEREF', 'LOAD_FAST', and > 'LOAD_CONST', and, as seen athttp://docs.python.org/lib/module-dis.html, > 'LOAD_GLOBAL'? I can imagine that 'LOAD_GLOBAL' loads a global, but > seeing as python is such a dynamic language, how exactly is it > supposed to distinguish between them? > > I don't understand the following at all: 'DUP_TOP', 'ROT_TWO'. Any > pointers? > > What does 'INPLACE_ADD' mean, if not in place addition, and if it is > in place addition, why does it need to 'STORE_ATTR' afterward? > > Thanks for any help! If this had been on any other usenet group, someone would have RTFM'd me to hell. http://docs.python.org/lib/bytecodes.html I might still have some more questions later, but for now, I'll look at this. > > > -- > > > Steven From nagle at animats.com Sat Mar 10 19:29:46 2007 From: nagle at animats.com (John Nagle) Date: Sun, 11 Mar 2007 00:29:46 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again In-Reply-To: <87tzwszmdc.fsf@pobox.com> References: <yTtGh.5001$M65.1427@newssvr21.news.prodigy.net> <45eab67a@news.vo.lu> <3hDGh.5963$jx3.2552@newssvr25.news.prodigy.net> <mailman.4653.1173030677.32031.python-list@python.org> <IRDGh.2764$iw4.51@newssvr23.news.prodigy.net> <87tzwszmdc.fsf@pobox.com> Message-ID: <_3IIh.9178$jx3.4584@newssvr25.news.prodigy.net> John J. Lee wrote: > John Nagle <nagle at animats.com> writes: > > >>skip at pobox.com wrote: > Traditionally, in the open source world, one does something about it, > or shuts up after having made one's point, say, ten or twenty times In retail, there's an assumption that for every customer who complains about a real problem, about a hundred customers noticed it and didn't complain, and about twenty of them will never come back. There's a great little book, "A Complaint is a Gift", about this. John Nagle From erwan.adam at cea.fr Fri Mar 9 05:41:45 2007 From: erwan.adam at cea.fr (Erwan Adam) Date: Fri, 09 Mar 2007 11:41:45 +0100 Subject: Pb with descriptor and super ... In-Reply-To: <esr95l$n12$1@ellebore.extra.cea.fr> References: <esr95l$n12$1@ellebore.extra.cea.fr> Message-ID: <esrdl9$oe4$1@ellebore.extra.cea.fr> Erwan Adam a ?crit : > Hi all, > > I have a problem with the use of descriptors > and super. The file is : > > # --------------- > > class Desc(object): > def __init__(self, class_name): > self.class_name = class_name > return > def __get__(self, obj, typ): > print "Desc.__get__ : class_name is %s, obj is %s and typ is > %s"%(self.class_name, obj, typ) > return > pass > > class A(object): > attr = Desc("A") > pass > > class B(A): > attr = Desc("B") > pass > > b = B() > > print "-------" > print "Getting b.attr ..." > print "I hope that : class_name is B, obj is b and typ is B" > b.attr > print "-------" > print "Getting super(B, b).attr ..." > print "I hope that : class_name is A, obj is b and typ is A but it is > not the case !" > super(B, b).attr > print "-------" > > # ----------- > > and the result is : > > ------- > Getting b.attr ... > I hope that : class_name is B, obj is b and typ is B > Desc.__get__ : class_name is B, obj is <__main__.B object at 0xb7b1f8ec> > and typ is <class '__main__.B'> > ------- > Getting super(B, b).attr ... > I hope that : class_name is A, obj is b and typ is A but it is not the > case ! > Desc.__get__ : class_name is A, obj is <__main__.B object at 0xb7b1f8ec> > and typ is <class '__main__.B'> > ------- > > I expected that when getting super(B, b).attr, typ is A, but it is not > the case ... Moreover, on the page : http://users.rcn.com/python/download/Descriptor.htm the author writes : "The call super(B, obj).m() searches obj.__class__.__mro__ for the base class A immediately following B and then returns A.__dict__['m'].__get__(obj, A)." which it seems not the case ... Is it a bug or a mis-understood ? Regards, E.A. > > python used : > > [adam at is111902 /home/adam/Work/Python]> python > Python 2.4.3 (#2, Sep 18 2006, 21:07:35) > [GCC 4.1.1 20060724 (prerelease) (4.1.1-3mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > > Best regards, > > > E.A. From dickinsm at gmail.com Sun Mar 11 13:33:29 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 11 Mar 2007 10:33:29 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: <Xns98F0B0821C330duncanbooth@127.0.0.1> References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <mailman.4944.1173629658.32031.python-list@python.org> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <Xns98F0B0821C330duncanbooth@127.0.0.1> Message-ID: <1173634409.663575.259600@30g2000cwc.googlegroups.com> On Mar 11, 1:21 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > Tim Peters wrote inhttp://blog.gmane.org/gmane.comp.python.devel/day=20050409: > > > All Python behavior in the presence of a NaN, infinity, or signed zero > > is a platform-dependent accident. This is because C89 has no such > > concepts, and Python is written to the C89 standard. It's not easy to > > fix across all platforms (because there is no portable way to do so in > > standard C), although it may be reasonably easy to fix if all anyone > > cares about is gcc and MSVC (every platform C compiler has its own set > > of gimmicks for "dealing with" these things). Understood. Platform dependent is fine. But does this really excuse results like the following? >>> from math import atan2 >>> x = -0.; print atan2(0., -1.) -3.14159265359 >>> print atan2(0., -1.) 3.14159265359 Mark From deets at nospam.web.de Mon Mar 5 06:55:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Mar 2007 12:55:45 +0100 Subject: Return type of operator on inherited class References: <1173093988.715433.205730@t69g2000cwt.googlegroups.com> Message-ID: <552eq1F217b9hU1@mid.uni-berlin.de> looping wrote: > Hi, > my question is on this example: > > class MyStr(str): > def hello(self): > print 'Hello !' > > s1 = MyStr('My string') > s2 = MyStr('My second string') > > s1.hello() > s2.hello() > > s = s1 + s2 > > s.hello() > >>>> > Hello ! > Hello ! > Traceback (most recent call last): > File "<string>", line 204, in run_nodebug > File "<module1>", line 13, in <module> > AttributeError: 'str' object has no attribute 'hello' > > How could I get a type MyStr from the 'plus' (__add__) operation > without overriding it in my class ? You can't. > I need to override *every* operator I like to use ? Yes. Diez From kaushik.ghose at gmail.com Fri Mar 9 20:30:09 2007 From: kaushik.ghose at gmail.com (kghose) Date: 9 Mar 2007 17:30:09 -0800 Subject: Unexpected behavior of list of list Message-ID: <1173490209.398081.200420@h3g2000cwc.googlegroups.com> Hi, The following code listoflists = [[]]*2 listoflists[0].append(1) appends(1) to both listoflists[0] and listoflists[1] (which I did not expect) while listoflists = [[]]*2 listoflists[0] = [1] listoflists[0].append(2) works as expected.i.e. only listoflists[0] gets 2 appended to it and any further operations work as expected. I can't figure out why. Any help with explaining this would be much appreciated thanks! -Kaushik From carsten at uniqsys.com Wed Mar 7 15:55:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 07 Mar 2007 15:55:22 -0500 Subject: Is numeric keys of Python's dictionary automatically sorted? In-Reply-To: <esn6nu$c8nt$1@netnews.upenn.edu> References: <esn6nu$c8nt$1@netnews.upenn.edu> Message-ID: <1173300922.3461.74.camel@dot.uniqsys.com> On Wed, 2007-03-07 at 15:18 -0500, John wrote: > I am coding a radix sort in python and I think that Python's dictionary may > be a choice for bucket. > > The only problem is that dictionary is a mapping without order. But I just > found that if the keys are numeric, the keys themselves are ordered in the > dictionary. No. The sequence of keys in a dictionary is a coincidental side effect of the particular Python implementation, the number of keys, the values of the keys, and the order in which the keys are inserted. You must not rely on the keys appearing in any particular order. Here is a simple counterexample that breaks the ordering, at least for the version I'm running: >>> d = {} >>> for i in range(0,6): d[10**i] = [] ... >>> d {100000: [], 1: [], 100: [], 1000: [], 10: [], 10000: []} -Carsten From superprad at gmail.com Wed Mar 21 15:10:58 2007 From: superprad at gmail.com (PKKR) Date: 21 Mar 2007 12:10:58 -0700 Subject: parsing combination strings In-Reply-To: <mailman.5415.1174503352.32031.python-list@python.org> References: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> <mailman.5415.1174503352.32031.python-list@python.org> Message-ID: <1174504258.691825.16380@e65g2000hsc.googlegroups.com> ah ok, i guess something like this should do it for me then? re.split('[^0-9]', str)[0] From slm_guzel at hotmail.com Sun Mar 25 14:06:57 2007 From: slm_guzel at hotmail.com (gslm) Date: 25 Mar 2007 11:06:57 -0700 Subject: problem at installing phyton on windows Message-ID: <1174846017.637862.284100@l77g2000hsb.googlegroups.com> Hi! I'm too new on phyton.I have installed phyton.But when I write phyton command, unfortunately, i can't run.I suppose that it is bacause of setting path.But i can't solve. Can you help? Another thing is, when i double click the .py file, there are the project form and the command line.How can i provide to view only the project? Thanks... From alain.walter at thalesgroup.com Thu Mar 8 06:22:00 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 8 Mar 2007 03:22:00 -0800 Subject: thread and portability Unix/Linux In-Reply-To: <45ef0f17$0$16318$88260bb3@free.teranews.com> References: <1173264866.645389.268640@v33g2000cwv.googlegroups.com> <45ef0f17$0$16318$88260bb3@free.teranews.com> Message-ID: <1173352920.612543.88830@n33g2000cwc.googlegroups.com> On 7 mar, 21:07, "Joshua J. Kugler" <jos... at eeinternet.com> wrote: > awalter1 wrote: > > Hi, > > I have a Python application that runs under HPUX 11.11 (then unix). It > > uses threads : > > from threading import Thread > > # Class Main > > class RunComponent(Thread): > > > My application should run under Linux (red hat 3 ou 4) and I read that > > differences exist between the implementation of threads : on HPUX > > 11.11 there is CMA (ou DCE) threads and on Linux POSIX thread. Do you > > think that my Python application should be modified or may be such > > differences are hidden by the python interpreter ? > > In other terms, do I get some risks on this particular aspect by > > porting my application ? > > Thanks a lot > > > PS: If you are aware of other risk of porting, I am interested too. > > The Python threading model abstracts from the underlying OS threading, so > there should be no need to change anything (AFAIK). > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmerhttp://www.eeinternet.com > PGP Key:http://pgp.mit.edu/ ID 0xDB26D7CE > > -- > Posted via a free Usenet account fromhttp://www.teranews.com- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - Marvellous ! Thank you From gnewsg at gmail.com Wed Mar 21 05:18:20 2007 From: gnewsg at gmail.com (billiejoex) Date: 21 Mar 2007 02:18:20 -0700 Subject: How many connections can accept a 'binded' socket? In-Reply-To: <ecULh.10215$P47.6848@newssvr22.news.prodigy.net> References: <1174394892.554418.313340@y80g2000hsf.googlegroups.com> <ecULh.10215$P47.6848@newssvr22.news.prodigy.net> Message-ID: <1174468700.689920.187610@y66g2000hsf.googlegroups.com> On 20 Mar, 17:44, John Nagle <n... at animats.com> wrote: > When you ask questions like this, please specify what > operating system you're using. Thanks. That was a Linux Ubuntu 6.10. I submitted a bug report on sourceforge: http://sourceforge.net/tracker/index.php?func=detail&aid=1685000&group_id=5470&atid=105470 Alex Martelli wrote: > A shell command > ulimit -Hn > should report on the hard-limit of the number of open file descriptors; > just ulimit -n should report on the current soft-limit. Thank you, I'll try it. From jstroud at mbi.ucla.edu Fri Mar 2 21:20:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 02 Mar 2007 18:20:06 -0800 Subject: Newbie Test In-Reply-To: <mailman.4617.1172882604.32031.python-list@python.org> References: <mailman.4617.1172882604.32031.python-list@python.org> Message-ID: <esam0m$lvc$1@daisy.noc.ucla.edu> Nicholas Parsons wrote: > Greetings, > > This is just a test to see if I can post to this mailing list. Can > someone from the list please respond to this email so I know it worked? > > Thanks in advance! > --Nick Congratulations, you passed the newbie test! James From qilong_ren at yahoo.com Fri Mar 16 16:39:48 2007 From: qilong_ren at yahoo.com (Qilong Ren) Date: Fri, 16 Mar 2007 13:39:48 -0700 (PDT) Subject: How to get the previous line in a file? Message-ID: <882682.16208.qm@web58912.mail.re1.yahoo.com> Hi,all I am new to this list. And I am glade I am here. I have a question. I need to do some text processing. I need to read from a file line by line. If some line is met with some condition, the previous line needs some modification. How to get the info of the previous line? Thanks! Qilong ____________________________________________________________________________________ 8:00? 8:25? 8:40? Find a flick in no time with the Yahoo! Search movie showtime shortcut. http://tools.search.yahoo.com/shortcuts/#news -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070316/9fef792e/attachment.html> From bj_666 at gmx.net Sun Mar 18 04:24:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 18 Mar 2007 09:24:48 +0100 Subject: Webcams and python References: <1174182674.500068.252550@p15g2000hsd.googlegroups.com> Message-ID: <pan.2007.03.18.08.24.46.950750@gmx.net> In <1174182674.500068.252550 at p15g2000hsd.googlegroups.com>, Synt4x wrote: > from VideoCapture import Device > cam = Device() > > while 1: > img = cam.getImage() > > Now, by doing this, my processor fires up to 100% load, which > obviously makes my pc useless. > > Is there any way or algorithm to lower the cpu load? Just throw a small `time.sleep()` into the loop. Ciao, Marc 'BlackJack' Rintsch From riklaunim at gmail.com Thu Mar 29 09:31:37 2007 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: 29 Mar 2007 06:31:37 -0700 Subject: gettext files manager Message-ID: <1175175097.703995.135640@b75g2000hsg.googlegroups.com> Does anyone know if Python gettext module or something else in Python can "manage" po/mo files - list all strings from po/mo, show untranslated, fuzzy strings ? I need something like that for a "translations manager" :) From sgeiger at ncee.net Tue Mar 20 04:48:08 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 20 Mar 2007 03:48:08 -0500 Subject: Anything available that can read Microsoft .MDB files from Python? In-Reply-To: <569ih4F27o9bdU1@mid.uni-berlin.de> References: <vdBLh.1337$rj1.1043@newssvr23.news.prodigy.net> <56863eF27p5bmU1@mid.uni-berlin.de> <WLBLh.10082$M65.2647@newssvr21.news.prodigy.net> <569ih4F27o9bdU1@mid.uni-berlin.de> Message-ID: <45FF9FC8.6060904@ncee.net> Try installing it from source. Perhaps getting a newer verion is all you would need. If at that point you find there is a bug, report it. Diez B. Roggisch wrote: >> What MDBtools did you install? The RPM, a checkout from CVS, >> or the downloadable distribution? They're all different. >> > > > The one that comes with ubuntu edgy. Just > > > apt-get install mdbtools > > or something, that's it. > > I don't want to start a distro war here - but I always found the > RPM-based distros lacking, to say the least. > > Diez > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20070320/b36979bc/attachment.vcf> From sreisscruz at gmail.com Wed Mar 14 12:22:02 2007 From: sreisscruz at gmail.com (Steve) Date: 14 Mar 2007 09:22:02 -0700 Subject: Setting Up SOAPpy for Python v2.5 on Windows? In-Reply-To: <1173812004.428519.195560@s48g2000cws.googlegroups.com> References: <1173812004.428519.195560@s48g2000cws.googlegroups.com> Message-ID: <1173889322.302145.71680@n59g2000hsh.googlegroups.com> All, Thanks for the suggestions! I think that I will move forward with elementsoap instead of soappy... Steve On Mar 13, 11:53 am, "Steve" <sreissc... at gmail.com> wrote: > Hi All, > > What are the required version of the SOAPpy, PyXML, fpconst that are > needed to run under the Python 2.5 environment on Windows? > > Locations for the downloads? > > Thanks! > > Steve From jackdied at jackdied.com Fri Mar 23 18:04:59 2007 From: jackdied at jackdied.com (Jack Diederich) Date: Fri, 23 Mar 2007 18:04:59 -0400 Subject: Python object overhead? In-Reply-To: <bdd6985b0703231411k7f55835dh5e7b0d2289d33067@mail.gmail.com> References: <bdd6985b0703231411k7f55835dh5e7b0d2289d33067@mail.gmail.com> Message-ID: <20070323220459.GS13084@performancedrivers.com> On Fri, Mar 23, 2007 at 03:11:35PM -0600, Matt Garman wrote: > I'm trying to use Python to work with large pipe ('|') delimited data > files. The files range in size from 25 MB to 200 MB. > > Since each line corresponds to a record, what I'm trying to do is > create an object from each record. However, it seems that doing this > causes the memory overhead to go up two or three times. > > See the two examples below: running each on the same input file > results in 3x the memory usage for Example 2. (Memory usage is > checked using top.) [snip] When you are just appending all the lines in a big list your overhead looks like: records = [] for line in file_ob: records.append(line) But when you wrap each line in a small class the overhead is records = [] for line in file_ob: records.append(line) # the actual string records.append(object()) # allocation for the object instance records.append({}) # dictionary for per instance attributes For small strings like dictionary words the overhead over the second is about 5x the overhead of a plain list. Most of it is the per instance dictionary. If you make the record a new style class (inherit from object) you can specify the __slots__ attribute on the class. This eliminates the per instance dictionary overhead in exchange for less flexibility. Another solution would be to only wrap the lines as they are accessed. Make one class that holds a collection of raw records. Have that return a fancy class wrapping each record right before it is used and discarded. class RecordCollection(object): def __init__(self, raw_records): self.raw_records = raw_records def __getitem__(self, i): return Record(self.raw_records[i]) If you are operating on each of the records in serial you only have the class overhead for one at any given time. Hope that helps, -Jack From steve at holdenweb.com Sat Mar 17 06:29:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 17 Mar 2007 06:29:43 -0400 Subject: File extension In-Reply-To: <cf14220703161559s1d106d03gd02bac4c0d695506@mail.gmail.com> References: <cf14220703161559s1d106d03gd02bac4c0d695506@mail.gmail.com> Message-ID: <45FBC317.2020204@holdenweb.com> Anil Kumar wrote: > Hi, > > Can Python Script can have different extensions like .sh etc.... Or Is > .py is mandatory to be present as the extension for the Python Script. > The interpreter itself doesn't really care. The issues you are hotting are due to operating system. and command shell differences. > We have an application where the script was initially written in shell > script with extension .sh. Now we are migrating this script to be run in > both Unix and Windows, so using Python for migration. > Good for you! > I have created a new Python Script porting all the changes in shell > script and it is working fine in Unix/Linux operating system. Later I > changed the extension of the file from .py to .sh, even then it worked. > The Unix command interpretation mechanism uses PATH as a list of directories to search for the named command file (the first word of the expanded command line). It then looks for the magic string "#!" at the start of the executable file and, if it finds that string, it passes the file to the interpreter named in the rest of the line for execution as a program. Your Python files probably begin with something like #!/usr/bin/python or #!/usr/bin/env python > But when I try a python script with extension .sh in windows, the file > is not getting recognized by the Python interpreter. Is this supported? > Or is there any way we can achieve the same? > In Windows, alas, the mechanism is less versatile. The command interpreter uses an environment variable called PATHEXT to decide which extensions to check when it sees a command that it can't find directly. For example, my PATHEXT variable is currently PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH (you'll observe I have given up on the PATHEXT mechanism - it's too much of a pain in the butt for me, so I just code explicit calls to the python interpreter). It looks on the PATH for a file with the given name and each extension, and when it finds one it then runs the interpreter registered for that type of file. > The reason I am trying to change the extension is, it reduces lot of > porting changes. No need to go to each of our file which were > referencing .sh file before and change it to .py. > > Any Help would be greatly Appreciated. > You could cheat ... if you register the .SH extension as "to be handled by the python interpreter" and then add .SH to PATHEXT this should work under Windows. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 12:04:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 18:04:01 +0200 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174916449.171929.138950@n76g2000hsh.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916449.171929.138950@n76g2000hsh.googlegroups.com> Message-ID: <4607eef2$0$4542$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Mar 26, 8:20 am, "Noma... at gmail.com" <Noma... at gmail.com> wrote: >> OK... >> I've been told that Both Fortran and Python are easy to read, and are >> quite useful in creating scientific apps for the number crunching, but >> then Python is a tad slower than Fortran because of its a high level >> language nature, so what are the advantages of using Python for >> creating number crunching apps over Fortran?? >> Thanks >> Chris > > While I have never personally dealt with Fortran, I looked it up here: > > http://en.wikipedia.org/wiki/Fortran_code_examples > > The code examples speak for themselves. I recommend you look those > over and then look over similar simple program written in Python. > Python is still easier to read. Fortran also appears to be a compiled > language, whereas Python is an interpreted language. Being 'compiled' or 'interpreted' is not a feature of a language, but of a given implementation of a language (and even then, some implementations of some languages supports both). wrt/ CPython (the reference implementation), it is actually compiled to byte-code - just like Java. The main difference being that the VM is smart enough to automagically (re)compile what's needed. From betwys1 at sbcglobal.net Sat Mar 17 14:13:26 2007 From: betwys1 at sbcglobal.net (Brian Whatcott) Date: Sat, 17 Mar 2007 18:13:26 GMT Subject: Phase change material ... References: <1173405474.489111.139350@p10g2000cwp.googlegroups.com> <1173554707.826932.246100@30g2000cwc.googlegroups.com> <3tEIh.4571$B25.683@news01.roc.ny> Message-ID: <tseov2h4mvrg4ov5dl6o7jltv1ocpm7lfv@4ax.com> On Sat, 10 Mar 2007 20:23:27 GMT, Dan Bloomquist <public21 at lakeweb.com> wrote: >thermate at india.com wrote: > >> On Mar 8, 5:57 pm, "martinl" <goo... at mllengineering.ca> wrote: >> >>>Hi All, >>>I'm looking for a substance that does a phase change at between 60 and >>>100 C. >I settled for hurricane wax. (IGI-1260). But that, because I felt it >would suit my application, domestic heating. I have 3 thousand pounds of >the stuff. >http://lakeweb.com/boiler/tubes.jpg >Best, Dan. I don't know how I could have overlooked this note for several days. It sounds like a wonderfully adventurous design. I have not been keeping up with the literature, but phase change media ought to be the way to go. After all, if four tons of ice could hold a house down with a temp differential of 20 degreesC or so, then 1.5 tons of wax might have a good chance of holding the temperature up with a temp differential of 80-20degC = 60 degrees. Wonder what the latent heat is? Less than 340 kJ/kg I imagine. How much did it cost? Brian Whatcott Altus OK From sjdevnull at yahoo.com Tue Mar 6 18:09:50 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 6 Mar 2007 15:09:50 -0800 Subject: Project organization and import In-Reply-To: <1173203395.649560.249930@p10g2000cwp.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <mailman.4685.1173114917.32031.python-list@python.org> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <mailman.4689.1173121575.32031.python-list@python.org> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <mailman.4716.1173190042.32031.python-list@python.org> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> <mailman.4723.1173201596.32031.python-list@python.org> <1173203395.649560.249930@p10g2000cwp.googlegroups.com> Message-ID: <1173222590.548186.229900@j27g2000cwj.googlegroups.com> On Mar 6, 12:49 pm, "Martin Unsal" <martinun... at gmail.com> wrote: > On Mar 6, 9:19 am, "Chris Mellon" <arka... at gmail.com> wrote: > > > You do? Or do you only have trouble because you don't like using "from > > foo import Foo" because you need to do more work to reload such an > > import? > > More work, like rewriting __import__ and reload??? :) > > There's a point where you should blame the language, not the > programmer. Are you saying I'm lazy just because I don't want to mess > with __import__? > > > What makes you think that the exposed namespace has to be isomorphic > > with the filesystem? > > I don't; you do! > > I was clearly talking about files and you assumed I was talking about > namespace. That's Pythonic thinking... and I don't mean that in a good > way! > > > If you want to break a module into multiple packages and then stick > > the files that make up the package in bizarre spots all over the > > filesystem, can you give a reason why? > > Because I have written a project with 50,000 lines of Python and I'm > trying to organize it in such a way that it'll scale up cleanly by > another order of magnitude. Because I've worked on projects with > millions of lines of code and I know about how such things are > organized. It's funny, I'm a newbie to Python but it seems like I'm > one of the only people here thinking about it as a large scale > development language rather than a scripting language. > > Martin I'm still not clear on what your problem is or why you don't like "from foo import bar". FWIW our current project is about 330,000 lines of Python code. I do a ton of work in the interpreter--I'll often edit code and then send a few lines over to the interpreter to be executed. For simple changes, reload() works fine; for more complex cases we have a reset() function to clear out most of the namespace and re-initialize. I don't really see how reload could be expected to guess, in general, what we'd want reloaded and what we'd want kept, so I have a hard time thinking of it as a language problem. From san_2012 at rediffmail.com Tue Mar 20 05:23:07 2007 From: san_2012 at rediffmail.com (sandeep patil) Date: 20 Mar 2007 02:23:07 -0700 Subject: python & java Message-ID: <1174382587.768401.158010@p15g2000hsd.googlegroups.com> hi i am fresher i python can any bady tell me who i will use python in web technologies in java base application. what it roll sandeep patil From aleax at mac.com Fri Mar 23 10:38:47 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 23 Mar 2007 07:38:47 -0700 Subject: Exception passing References: <pan.2007.03.23.14.29.34@gmail.com> Message-ID: <1hvf3ru.1iqe09kju50weN%aleax@mac.com> Thomas Dybdahl Ahle <lobais at gmail.com> wrote: > Hi, I have a function, which looks like the following: > > connecting = False > def func (): > global connecting > connecting = True > try: > # Do lot of network stuff > except Exception, e: > connecting = False > raise e > > This works quite good, but it is a hell to debug. Instead of getting a > log message to the line which originally raised the exception. > > Is there anyway to reraise an exception, but preserve the log? Just use raise without any argument. E.g.: >>> def raiser(): ... print 1/0 ... >>> def reraise1(): ... print 'before' ... try: raiser() ... except Exception, e: ... print 'after' ... raise e ... >>> def reraise2(): ... print 'before' ... try: raiser() ... except Exception, e: ... print 'after' ... raise ... >>> reraise1() before after Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in reraise1 ZeroDivisionError: integer division or modulo by zero >>> reraise2() before after Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in reraise2 File "<stdin>", line 2, in raiser ZeroDivisionError: integer division or modulo by zero >>> As you see, the traceback is "maintained" when you just "raise", though it's altered when you "raise e". Alex From psdasilvaX at esotericaX.ptX Sat Mar 24 15:12:58 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Sat, 24 Mar 2007 19:12:58 +0000 Subject: Join strings - very simple Q. In-Reply-To: <1174754607.773604.85170@l77g2000hsb.googlegroups.com> References: <1174675011.244339@jubilee.claranet.pt> <1174676818.207543.246080@l75g2000hse.googlegroups.com> <1174678166.970277@jubilee.claranet.pt> <1174737587.638835.137070@y80g2000hsf.googlegroups.com> <1174746808.705538@jubilee.claranet.pt> <1174754607.773604.85170@l77g2000hsb.googlegroups.com> Message-ID: <1174843589.996115@jubilee.claranet.pt> Dustan escreveu: > On Mar 24, 7:16 am, Paulo da Silva <psdasil... at esotericaX.ptX> wrote: >> Dustan escreveu: >> >> >> >>> On Mar 23, 1:30 pm, Paulo da Silva <psdasil... at esotericaX.ptX> wrote: >>>> Mike Kent escreveu: >>>> ... >>>>> New way: >>>>> l=['a','b','c'] >>>>> jl=','.join(l) >>>> I thank you all. >>>> Almost there ... >>>> I tried "".join(l,',') but no success ... :-( >>>> Paulo >>> Perhaps you're doing it wrong, despite having an example right in >>> front of you? >> Some misunderstanding here ... >> The post was just to thank. I was refering to what I tried >> before posting the question here. > > Ah. Sorry; I didn't realize that. My fault. The post could well be read the way you did. English is not my 1st language anyway. Regards. Paulo From hq4ever at gmail.com Mon Mar 12 06:33:58 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Mon, 12 Mar 2007 12:33:58 +0200 Subject: programmatically manipulation environment variables of the calling shell Message-ID: <b400c69a0703120333m5565c233laaf1247ed8fb5601@mail.gmail.com> Hello list, I'm trying to write a python script that would allow me to manipulate shell variables of the calling shell. I'm trying to write some logic that would know to add LD_LIBRARY_PATH to the users environment. In bash this is done with "export", can I do this with python? (If at all possible because python is actually a sub process of bash). Thank you, Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From greg at cosc.canterbury.ac.nz Thu Mar 1 18:41:08 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 02 Mar 2007 12:41:08 +1300 Subject: Writing an interpreter for language similar to python!! In-Reply-To: <mailman.4555.1172731037.32031.python-list@python.org> References: <1172684281.057538.224370@h3g2000cwc.googlegroups.com> <mailman.4555.1172731037.32031.python-list@python.org> Message-ID: <54p6ovF21sto3U1@mid.individual.net> Hendrik van Rooyen wrote: > - It is going to be an inferior subset of Python - From what the OP said, it isn't necessarily a subset of Python, just something whose surface syntax is similar. The semantics could be quite different. However, if the semantics *are* to be similar as well, it makes a lot of sense to consider whether Python itself could be used. -- Greg From jantod at gmail.com Sun Mar 4 15:29:20 2007 From: jantod at gmail.com (Janto Dreijer) Date: 4 Mar 2007 12:29:20 -0800 Subject: multiple content-types break cgi.py In-Reply-To: <slrneul7rs.t3l.jon+usenet@snowy.squish.net> References: <1173002603.690853.250090@p10g2000cwp.googlegroups.com> <slrneul7rs.t3l.jon+usenet@snowy.squish.net> Message-ID: <1173040160.844329.48050@s48g2000cws.googlegroups.com> On Mar 4, 12:29 pm, Jon Ribbens <jon+use... at unequivocal.co.uk> wrote: > In article <1173002603.690853.250... at p10g2000cwp.googlegroups.com>, Janto Dreijer wrote: > > The Nokia Java SDK allows one to define multiple content-types in a > > single HTTP header field. I'm not sure if it's standard, but it's > > happening from some Java-enabled phones. > > > The only reference to this "bug" I can find dates back to 1999: > >http://tinyurl.com/3ahc3r > > It's not a bug - sending multiple content-types is just totally broken. > What would such a header even be supposed to mean? It's like saying > "this is an apple orange". Hmmm. Thanks! I suspected as much. Rough inspection suggests that calling connection.setRequestProperty("Content-Type", "application/x-www- form-urlencoded"); on the Nokia 6230 would actually cause the value to be *appended* and not set. Yuck! It looks like I'm going to have to keep a modified copy of cgi.py if I want to support the phone. Or hack something on the Java side. Janto From manstey at csu.edu.au Tue Mar 13 21:23:24 2007 From: manstey at csu.edu.au (manstey) Date: 13 Mar 2007 18:23:24 -0700 Subject: how to detect change of list of instances Message-ID: <1173835404.477078.306410@b75g2000hsg.googlegroups.com> how do I detect a change in a list of class instances? from copy import deepcopy class CaListOfObj(list): """ subclass of list """ def __init__(self, *args, **kwargs): list.__init__(self, *args, **kwargs) class CaClass(object): pass class CaData(object): pass myclass=CaClass() a=CaData() b=CaData() c=CaData() listInstances = CaListOfObj([a,b,c]) setattr(myclass,'initlist',listInstances) setattr(myclass,'newlist',deepcopy(listInstances)) print myclass.initlist == myclass.newlist myclass.newlist.append(c) print myclass.initlist == myclass.newlist gives False False because deep copies of instances are different instances. what I want to do is detect a change between .initlist and .newlist. thanks From AWasilenko at gmail.com Thu Mar 22 20:54:04 2007 From: AWasilenko at gmail.com (AWasilenko at gmail.com) Date: 22 Mar 2007 17:54:04 -0700 Subject: TypeError: 'int' object is not callable Message-ID: <1174611244.465956.104060@n76g2000hsh.googlegroups.com> I'm trying to test a few different approaches to displaying pages via Cherrypy and I'm not having much luck. Here is my code so far: import sys, cherrypy, html class Root: @cherrypy.expose def index(self, pageid = None): selection = html.Page() return selection.input() cherrypy.config.update({'server.socket_port': 2572, 'log.screen': False}) cherrypy.quickstart(Root()) and here is the html.py file that I import: class Page: def input(self,dex=None): if dex == None: return 404(dex) else: return "Something else?" def err404(self,whatitis="N/A"): return """<body bgcolor="#666666"> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br / ><br /><br /><br /><br /> <center>Sorry the page: """ + str(whatitis) + """ does not exist.<br / > <img src="/files/images/404.png" alt="Page cannot be found."></center> </body>""" and here is the error I get when trying to run this: 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. Traceback (most recent call last): File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line 342, in respond cherrypy.response.body = self.handler() File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line 15, in __call__ return self.callable(*self.args, **self.kwargs) File "/home2/awasilenko/webapps/cp/site.py", line 7, in index return selection.input() File "/home2/awasilenko/webapps/cp/html.py", line 4, in input return 404(dex) TypeError: 'int' object is not callable I know this isn't a Cherrypy issue since I have made other pages work, I'm just making a dumb mistake somewhere. My plan is to eventually be able to pass dex to the input def in the page class so it can display the right page. Right now I am just trying to make ANY thing show up, what should happen is since I'm not passing anything everything should be None and the 404 page should pop up. I would also like to make the 404 page print the page that was requested, I have already coded the return but have not "connected" it yet, one step at a time... From mmoum at woh.rr.com Sat Mar 24 18:08:42 2007 From: mmoum at woh.rr.com (Mike) Date: Sat, 24 Mar 2007 18:08:42 -0400 Subject: qt ver. 3, linux, windows, and modal forms Message-ID: <4605a174$0$5225$4c368faf@roadrunner.com> Hi, I'm having a problem with modal forms on windows. I've written a very short test program, with a main window and a form called from the main window. The form is set to modal with form.setModal(1) before calling form.show(). All works as expected on Linux. The form is modal, not allowing the main window to received the focus. If I call the form from within itself, the topmost form is modal, and not of the previous forms will receive the focus until the topmost form is closed; then the next topmost is modal, and so on. However, on Windows XP Pro (at work - don't use windows at home), the form is not modal. The main window will receive the focus with a mouse click even though the modal form is still on top. The source code is identical on both OS's. Has anyone run into this before? Is there a fix? I haven't been able to find anything with google searches, and Trolltech's forums don't seem to have any entries addressing the problem, either. I have a progam that I'm writing for work using Qt and Python, which was like pulling teeth with our Microsoft oriented IT department, and I very much do not want to tell them that it's not going to work (modal forms are essential). Thanks for your help, Mike From deets at nospam.web.de Tue Mar 6 07:40:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 Mar 2007 13:40:00 +0100 Subject: CherryPy + Database questions References: <mailman.4673.1173101612.32031.python-list@python.org> <552l55F22aph6U1@mid.uni-berlin.de> <1173153806.918779.241900@j27g2000cwj.googlegroups.com> Message-ID: <5555p0F21i8s3U1@mid.uni-berlin.de> > SQLite isn't really a DBMS at all, it's just a library. Where is the difference? From the DB-API-side none. And there are plenty of DBs out there that work similar, like MS Access. Show me where it is written that a DBMS has to run as separate server process. > According to > their FAQ (http://www.sqlite.org/faq.html#q8) it is only threadsafe as > long as you aren't changing the same DB in separate threads (so no, > not threadsafe at all). I'm not sure if I share your POV. According to the DB API threadsafty attribtue, it's safe to have multiple threads working on a single DB if each has his own connection. Which is a common idiom anyway. And AFAIK e.g. TurboGears doesn't perform any special measures to synchronize cherrypy worker threads when using sqlite, albeit I'm not 100% sure on this. Diez From http Sat Mar 10 19:04:00 2007 From: http (Paul Rubin) Date: 10 Mar 2007 16:04:00 -0800 Subject: unsigned integer? References: <I9Kdndp49PJLdm_YnZ2dnUVZ_t-mnZ2d@comcast.com> <7xr6rwhpdb.fsf@ruckus.brouhaha.com> <mailman.4922.1173568136.32031.python-list@python.org> <7xhcssllyi.fsf@ruckus.brouhaha.com> <mailman.4923.1173571172.32031.python-list@python.org> Message-ID: <7xslccr6hb.fsf@ruckus.brouhaha.com> "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > > If you use %u you get a very large positive value, not +3. > Exactly, and that's the right value. (unsigned int)(-3) isn't +3. The OP specified that the expected result was 3. From steve at holdenweb.com Wed Mar 21 13:53:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Mar 2007 13:53:00 -0400 Subject: Testing Python updates In-Reply-To: <1174488951.275163.305440@y66g2000hsf.googlegroups.com> References: <1174488951.275163.305440@y66g2000hsf.googlegroups.com> Message-ID: <etrrgf$qte$2@sea.gmane.org> Matthew wrote: > Hello: > > What is the methodology for testing the updates to the Python > language? http://www.pybots.org/ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From http Sun Mar 11 17:28:15 2007 From: http (Paul Rubin) Date: 11 Mar 2007 13:28:15 -0800 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <mailman.4944.1173629658.32031.python-list@python.org> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <no_Ih.8899$PL.2303@newsread4.news.pas.earthlink.net> Message-ID: <7xy7m3tqq8.fsf@ruckus.brouhaha.com> Dennis Lee Bieber <wlfraed at ix.netcom.com> writes: > Pardon? What is "the right thing with signed zeros"... In the last > 30 years I've been on machines that normalize floating zero into a true > zero (all bits are zero: mantissa, exponent, and sign). This is the > first time I've even seen a variable output as a negative 0.0! Most machines these days use IEEE 754 which supports negative zero. http://en.wikipedia.org/wiki/Negative_zero From mailmaverick666 at gmail.com Tue Mar 20 05:34:18 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Tue, 20 Mar 2007 15:04:18 +0530 Subject: python & java In-Reply-To: <1174382587.768401.158010@p15g2000hsd.googlegroups.com> References: <1174382587.768401.158010@p15g2000hsd.googlegroups.com> Message-ID: <180b672e0703200234g3013b0berc599e38a35305da0@mail.gmail.com> See www.*jython*.org On 20 Mar 2007 02:23:07 -0700, sandeep patil <san_2012 at rediffmail.com> wrote: > > hi > > i am fresher i python can any bady tell me who i will use python in > web technologies in java base application. > what it roll > > sandeep patil > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070320/6cb8b441/attachment.html> From bignose+hates-spam at benfinney.id.au Mon Mar 19 04:48:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 19 Mar 2007 19:48:37 +1100 Subject: any ways to judge whether an object is initilized or not in a class References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <1174293300.034362.282460@l75g2000hse.googlegroups.com> Message-ID: <87lkht8vq2.fsf@benfinney.id.au> "momobear" <wgwigw at gmail.com> writes: > class coffee: > def __init__(self): > ''' > do something here > ''' > def boil(self): > self.temp = 80 > > a = coffer() > if a.temp > 60: > print "it's boiled" class Coffee(object): def __init__(self): self.temp = 20 def boil(self): self.temp = 80 a = coffee() if a.temp > 60: print "it's boiled" In Python, it's conventional to name classes in TitleCase, and instances in lower_case. It's also best to inherit every class from another class, leading to a single hierarchy for all classes and types. 'object' is the one to choose if you don't want the behaviour of any other class. As for the original question: the __init__ method of a class is called immediately after the constructor, so that's the place to initialise any instance attributes. -- \ "At my lemonade stand I used to give the first glass away free | `\ and charge five dollars for the second glass. The refill | _o__) contained the antidote." -- Emo Philips | Ben Finney From kyosohma at gmail.com Wed Mar 28 14:14:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 28 Mar 2007 11:14:52 -0700 Subject: Hpw make lists that are easy to sort. In-Reply-To: <eue7lg$3ce$1@news2.zwoll1.ov.home.nl> References: <eue7lg$3ce$1@news2.zwoll1.ov.home.nl> Message-ID: <1175105692.176117.133100@o5g2000hsb.googlegroups.com> On Mar 28, 12:12 pm, Anton Vredegoor <anton.vredeg... at gmail.com> wrote: > Python's sorting algorithm takes advantage of preexisting order in a > sequence: > > #sort_test.py > import random > import time > > def test(): > n = 1000 > k = 2**28 > > L = random.sample(xrange(-k,k),n) > R = random.sample(xrange(-k,k),n) > > t = time.time() > LR = [(i+j) for i in L for j in R] > print time.time()-t > LR.sort() > print time.time()-t > > print > > t = time.time() > #L.sort() > R.sort() > presorted_LR = [(i+j) for i in L for j in R] > print time.time()-t > presorted_LR.sort() > print time.time()-t > > if __name__=='__main__': > test() > > On this -very slow- computer this prints: > > >d:\python25\pythonw -u "sort_test.py" > 1.10000014305 > 8.96000003815 > > 1.10000014305 > 5.49000000954 > >Exit code: 0 > > Presorting the second sequence gains us more than three seconds. I > wonder if there is a way to generate the combined items in such a way > that sorting them is even faster? Is there some other sorting algorithm > that can specifically take advantage of this way -or another way- of > generating this list? > > The final sequence is len(L)*len(R) long but it is produced from only > len(L)+len(R) different items, is it possible to exploit this fact? I'd > also be interested in a more general solution that would work for > summing the items of more than two lists in this way. > > A. I found a website that hopefully will point you in the right direction: http://wiki.python.org/moin/HowTo/Sorting And this one has an interesting profile of various sort methods with Python: http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency Enjoy, Mike From Barkmann at gmail.com Mon Mar 5 13:39:40 2007 From: Barkmann at gmail.com (Chris) Date: 5 Mar 2007 10:39:40 -0800 Subject: FloatCanvas in a wxpython application.... layout problems In-Reply-To: <mailman.4278.1172094038.32031.python-list@python.org> References: <mailman.4278.1172094038.32031.python-list@python.org> Message-ID: <1173119980.413771.25750@8g2000cwh.googlegroups.com> On Feb 21, 1:40 pm, "nelson -" <nelson1... at gmail.com> wrote: > Hi all, > i'm developing an application that uses Floatcanvas to diplay a > cartesian plane. how can i embed it into a "complex" layout? Your best bet is either the floatcanvas list: http://mail.mithis.com/cgi-bin/mailman/listinfo/floatcanvas or the wxPython-users list: http://www.wxpython.org/maillist.php In this case, putting a FloatCanvas in an app is no different than putting any wx.Panel in, so the wxPython list would be fine. -Chris From kyosohma at gmail.com Fri Mar 30 16:23:20 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Mar 2007 13:23:20 -0700 Subject: Tkinter menu question--how to pass arguments In-Reply-To: <85c10$460d65c8$4275d90a$19337@FUSE.NET> References: <85c10$460d65c8$4275d90a$19337@FUSE.NET> Message-ID: <1175285826.971400.321470@y80g2000hsf.googlegroups.com> On Mar 30, 2:32 pm, Kevin Walzer <k... at codebykevin.com> wrote: > I'm having difficulty structuring a Tkinter menu entry. Here is the > command in question: > > self.finkmenu.add_command(label='Update List of Packages', > command=self.authorizeCommand(self.scanPackages)) > > When I start my program, it crashes because it's trying to run the > command self.authorizeCommand. The reason I'm structuring it in this > fashion is that this command takes another command as an argument--in > this case, self.ScanPackages. > > The basic structure of the program is that the self.authorizeCommand > function pops up a dialog box for a password; it then feeds the password > to the function that it takes as an argument, i.e. self.scanPackages. > > I tried setting up the menu entry without the additional parameter, i.e. > command=self.authorizeCommand, but then when I try to run the command > from the menu, it complains there are not enough arguments. > Unsurprising, since self.authorizeCommand takes another function name as > an argument. > > How can I structure the menu item to reflect the correct number of > arguments without it trying to execute the command? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com There are various ways to accomplish this. The 2 most popular that I am aware of are using a helper function or lambda. using a lambda: command=(lambda:self.authorizeCommand(self.scanPackages)) using a handler (i.e. indirection layer): def func(): self.authorizeCommand(self.scanPackages) self.finkmenu.add_command(label='Update List of Packages',command=func) Both of these are talked about in detail in "Programming Python 3rd Ed" by Lutz. I found that helpful for me. Of course, I decided to stop using Tkinter and switched to wxPython. Hope this gets you going though. Mike From nick at craig-wood.com Mon Mar 26 07:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 26 Mar 2007 06:30:04 -0500 Subject: Sending ECHO_REQUEST (pinging) with python References: <pan.2007.03.26.06.30.33@gmail.com> <mailman.5617.1174898513.32031.python-list@python.org> Message-ID: <slrnf0f9tl.ar4.nick@irishsea.home.craig-wood.com> Michael Bentley <michael at jedimindworks.com> wrote: > On Mar 26, 2007, at 1:30 AM, Thomas Dybdahl Ahle wrote: > > It seems however that I have to be root to send those imcp > > packages, but I guess there must be a workaround since I can > > easily use the "ping" command as ordinary user. > > The workaround your ping command is using btw, is probably running > suid root. Under linux the only priviledge you need is CAP_NET_RAW. It is possible to give this to a process - a bit of searching with google will show you how! -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From godzillaismad at gmail.com Fri Mar 23 06:47:14 2007 From: godzillaismad at gmail.com (Godzilla) Date: 23 Mar 2007 03:47:14 -0700 Subject: Create new processes over telnet in XP Message-ID: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> Hello, How do you create/spawn new processes in XP over telnet using python? I.e. I would like to create a new process and have it running in the background... when I terminate the telnet connection, I would what the spawned processes to keep running until I shut it off... I got the os.popen method to spawn a new process running in the backgroun, but not over telnet... tried os.popen[2, 3, 4] and also subprocesses.popen without any luck... Any help will be appreciated... thankyou. From deets at nospam.web.de Thu Mar 8 02:55:33 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Mar 2007 08:55:33 +0100 Subject: persistent fifo queue class In-Reply-To: <4011626.Sbva7xkoP2@teancum> References: <3240528.rhEsMVbDK6@teancum> <554m4vF22dgrpU2@mid.uni-berlin.de> <4011626.Sbva7xkoP2@teancum> Message-ID: <559tslF24a8qrU1@mid.uni-berlin.de> David Bear schrieb: > Diez B. Roggisch wrote: > >> David Bear schrieb: >>> I'm looking to see if there are any examples or prewritting fifo queue >>> classes. I know this is a broad topic. I'm looking to implement a simple >>> application where a web server enqueue and pickle using a local socket on >>> to a 'queue server' -- and then I will have another application dequeue >>> the pickles again using a local socket. >> Why don't you use a DB for that? If you want pickles, use a blob >> column. But all the rest - a defined protocol, stable server, >> transactions - you get for free. >> >> Diez > > Thanks for the suggestion. I did think of this. Indeed the final destination > of the data is in a db. However, the postsgresql server is on a separate > box. It will be connected via a private lan. I was worried that possible > network disruptions would cause either the web application to hang -- or > data to just get lost. I was thinking along the lines is a message queue > architecture, where the web app would push data directly onto a queue -- > and then a worker app would dequeue the data and handle it by sending it to > the db server or otherwise. Well, if your DB connection is flaky, data will be corrupted - or lost. In any case. What good does it do for you to have the messages then? And what if the Harddisk the file sits on is corrupt? And don't forget the added complexity of a home-brewn solution with all its possible errors - much more likely to cause data loss. Diez From domma at procoders.net Fri Mar 2 10:17:55 2007 From: domma at procoders.net (Achim Domma) Date: Fri, 02 Mar 2007 16:17:55 +0100 Subject: Python GUI + OpenGL Message-ID: <45e84025$0$15959$9b4e6d93@newsspool4.arcor-online.net> Hi, I'm developing a GUI app in Python/C++ to visualize numerical results. Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there are no windows binaries for Python 2.5 for quite some time now. I need a OpenGL context without restrictions and some settings dialogs. Is wx + PyOpenGL the way to go? Or could somebody recommend a better set of tools/libs? regards, Achim From aleax at mac.com Sat Mar 3 21:22:09 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Mar 2007 18:22:09 -0800 Subject: class attrdict References: <hbf.20070302nsi@bombur.uio.no> <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1172895832.352834.313300@p10g2000cwp.googlegroups.com> <1hud90j.zf49afwqrk0bN%aleax@mac.com> <45e9b753$0$8983$4c368faf@roadrunner.com> <1huecz7.1thcn0b1j64biiN%aleax@mac.com> <1172960883.340892.183850@31g2000cwt.googlegroups.com> <1hueupp.1dcf9wl17pyf2bN%aleax@mac.com> <1172973970.929910.111000@s48g2000cws.googlegroups.com> Message-ID: <1huew97.129d6nb4qmb42N%aleax@mac.com> MonkeeSage <MonkeeSage at gmail.com> wrote: > On Mar 3, 7:54 pm, a... at mac.com (Alex Martelli) wrote: > > Besides missing the warning in the __init__, this also has pretty weird > > behavior whenever subject to a .pop, .update, .setdefault, del of either > > item or attr, etc, etc: the attributes and items "get out of sync" (and, > > catching each and every mutating-method to keep the separate dicts of > > items and attrs in perfect sync is somewhat of a nightmare). > > Good points. There are many complexities involved, and little actual > gain. Saving three or four chars isn't worth all the trouble. I hadn't > fully thought-out the situation. You make a good point. I do like being able to say foo.bar=baz rather than foo['bar']=baz in certain cases -- not so much to save 3 chars, but to avoid excessive punctuation; however, I don't really need this AND all of dict's power at the same time, so, I don't inherit from dict:-). Alex From exarkun at divmod.com Sat Mar 24 16:19:43 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 24 Mar 2007 15:19:43 -0500 Subject: Python object overhead? In-Reply-To: <1174766882.119041.294020@y66g2000hsf.googlegroups.com> Message-ID: <20070324201943.18920.2076264303.divmod.quotient.5362@ohm> On 24 Mar 2007 13:08:02 -0700, 7stud <bbxx789_05ss at yahoo.com> wrote: >On Mar 23, 4:04 pm, Jack Diederich <jackd... at jackdied.com> wrote: >> >> If you make the record a new style class (inherit from object) you can >> specify the __slots__ attribute on the class. This eliminates the per >> instance dictionary overhead in exchange for less flexibility. >> > >How is efficiency improved with __slots__? Don't you create a list >object that replaces the dictionary object, e.g.: > >class Test(object): > __slots__ = ["m", "n"] > Only one list is created. It is used to define a C array where attributes will be stored. Each instance still has that C array, but it has much less overhead than a Python list or dictionary. Whether this reduction in overhead actually results in a useful or measurable performance improvement is a separate question, of course. Jean-Paul From robert.kern at gmail.com Fri Mar 30 19:32:02 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 30 Mar 2007 18:32:02 -0500 Subject: Indentation for code readability In-Reply-To: <pan.2007.03.30.13.23.40.465374@REMOVE.THIS.cybersource.com.au> References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> <pan.2007.03.30.13.23.40.465374@REMOVE.THIS.cybersource.com.au> Message-ID: <euk6lr$nlb$1@sea.gmane.org> Steven D'Aprano wrote: > On Fri, 30 Mar 2007 02:04:45 -0700, DE wrote: > >> Hello, >> >> Here is what I do in C++ and can not right now in python : >> >> pushMatrix() >> { >> drawStuff(); >> >> pushMatrix(); >> { >> drawSomeOtherStuff() >> } >> popMatrix(); >> } >> popMatrix(); >> >> The curly brackets have no functional meaning >> but increase the readability significantly. > > I don't understand why you are indenting > the function calls. What does the > indentation and spacing signify? pushMatrix() pushes a transformation matrix onto the stack of transformation matrices. The drawing functions draw inside this context of transformations. popMatrix() pops the last transformation matrix. For example, one could push a rotation matrix that rotates the coordinate system 90 degrees from horizontal. drawStuff() might draw some text; usually this would be horizontal, but in the context of the transformation, it will ultimately be drawn vertically. As others have mentioned, this is a perfectly good application of Python 2.5's "with" statement and its context managers. The indentation is meaningful and useful. > Some people > have a strange > idea of > "increase > readability". Please contain the snark. You didn't understand why someone might want this, and that's fine. But please wait until you get a response before assuming that there could be no good reason for wanting this. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From jgodoy at gmail.com Mon Mar 12 08:33:02 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Mon, 12 Mar 2007 09:33:02 -0300 Subject: How to modify the source of a python file inside a python egg file? References: <1173670160.897478.34450@j27g2000cwj.googlegroups.com> Message-ID: <87odmyvdz5.fsf@gmail.com> "yinglcs at gmail.com" <yinglcs at gmail.com> writes: > How to modify the source of a python file inside a python egg file? > I can see the file by unzipping it, but how can I package it back as a > python egg file after my modification. The correct way is to download the source, make your changes and rebuild the egg. Unzipping, changing and zipping it back also works. -- Jorge Godoy <jgodoy at gmail.com> From python-url at phaseit.net Fri Mar 30 20:04:37 2007 From: python-url at phaseit.net (Cameron Laird) Date: Sat, 31 Mar 2007 00:04:37 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Mar 30) Message-ID: <euk8il$29f$1@lairds.us> QOTW: "I have a fake supervisor reference generator for job interviews, a fake house inspection generator for real estate transactions, and a fake parole testimony generator - maybe you could adapt one of them (unfortunately, they are written in dissembler)." - Paul McGuire "... I think that [PyPy] is the most interesting work in CS in many years." - Jacob Hallen PyPy 1.0 is ready--yippee! http://groups.google.com/group/comp.lang.python/browse_thread/thread/5d2675e6895a9daf/ Notice Jacon Hallen's advertisement of the benefits of PyPy. Alex Martelli and Facundo Batista explain the Python perspective on timing-out HTTP requests: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ff84e7340988c168/ Paul McGuire illustrates the intent and use of his valuable pyparsing module: http://groups.google.com/group/comp.lang.python/msg/ee4129aee0f33efc http://groups.google.com/group/comp.lang.python/msg/39337f2c6148e927 More Pythoneers should be familiar with timing and related measurements. Alex Martellii aptly illustrates how rewarding it can be in the hands of a master: http://groups.google.com/group/comp.lang.python/msg/785e1571d3c9b468 Mode of a collection is a sort of reverse-lookup statistic that interestingly models many other useful calculations. Notice how succinctly idiomatic Python solves the problem: http://groups.google.com/group/comp.lang.python/browse_thread/thread/23da16a5fc2ca39d/ ======================================================================== 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. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher 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/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/python/success 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 Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. 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 Many Python conferences around the world are in preparation. Watch this space for links to them. 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://www.python.org/dev/peps/pep-0042/ 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. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *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/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& 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 There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From paul at boddie.org.uk Sun Mar 4 14:28:13 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Mar 2007 11:28:13 -0800 Subject: How use XML parsing tools on this one specific URL? In-Reply-To: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> References: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> Message-ID: <1173036493.121242.290860@64g2000cwx.googlegroups.com> seberino at spawar.navy.mil wrote: > I understand that the web is full of ill-formed XHTML web pages but > this is Microsoft: > > http://moneycentral.msn.com/companyreport?Symbol=BBBY Yes, thank you Microsoft! > I can't validate it and xml.minidom.dom.parseString won't work on it. > > If this was just some teenager's web site I'd move on. Is there any > hope avoiding regular expression hacks to extract the data from this > page? The standards adherence from Microsoft services is clearly at "teenage level", but here's a recipe: import libxml2dom import urllib f = urllib.urlopen("http://moneycentral.msn.com/companyreport? Symbol=BBBY") d = libxml2dom.parse(f, html=1) f.close() You now have a document which contains a DOM providing libxml2's interpretation of the HTML. Sadly, PyXML's HtmlLib doesn't seem to work with the given document. Other tools may give acceptable results, however. Paul From bj_666 at gmx.net Sun Mar 18 12:19:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 18 Mar 2007 17:19:16 +0100 Subject: list comprehension help References: <mailman.5246.1174234283.32031.python-list@python.org> Message-ID: <pan.2007.03.18.16.19.15.533898@gmx.net> In <mailman.5246.1174234283.32031.python-list at python.org>, rkmr.em at gmail.com wrote: > I need to process a really huge text file (4GB) and this is what i > need to do. It takes for ever to complete this. I read some where that > "list comprehension" can fast up things. Can you point out how to do > it in this case? No way I can see here. > f = open('file.txt','r') > for line in f: > db[line.split(' ')[0]] = line.split(' ')[-1] > db.sync() You can get rid of splitting the same line twice, or use `split()` and `rsplit()` with the `maxsplit` argument to avoid splitting the line at *every* space character. And if the names give the right hints `db.sync()` may be a potentially expensive operation. Try to call it at a lower frequency if possible. Ciao, Marc 'BlackJack' Rintsch From mtobis at gmail.com Wed Mar 28 12:22:16 2007 From: mtobis at gmail.com (Michael Tobis) Date: 28 Mar 2007 09:22:16 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <56uk2aF29sotsU1@mid.individual.net> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916838.757839.143310@e65g2000hsc.googlegroups.com> <3f8d9$4607d352$83aef404$23393@news2.tudelft.nl> <1174918424.125068.176920@y80g2000hsf.googlegroups.com> <7o4ld4-qrv.ln1@lairds.us> <1174958090.292094.168150@e65g2000hsc.googlegroups.com> <56uk2aF29sotsU1@mid.individual.net> Message-ID: <1175098936.430665.91580@n76g2000hsh.googlegroups.com> I feel obligated to fan the flames a bit by pointing to http://www.fortranstatement.com/ a site which advocates discontinuing development of Fortran and does a good job of summarizing the problems with the contemporary development of that language. I am not convinced that a new high performance language (Chapel, Fortress, etc.) is necessary. Rather, I feel that FORTRAN 77 is a mature tool, and that it, in combination with a powerful dynamic language (Python being my choice) is entirely sufficient for any foreseeable scientific computing. Fortran 90 and successors (F9* in the following) provide a baroque and elaborate effort to bolt modern computing methods over a finely honed special purpose tool (F77) that manages large numerical arrays spectacularly well. It is as if you decided to add a web search engine (an elaborate, developing set of requirements) to grep (a finely honed special purpose tool). It makes much more sense to add greplike features to your websearch tool than to try to foist "Grep95" (competing with the Google search engine) on everyone who ever needs to find a misplaced text file. F77 interfaces smoothly and neatly with Python. F9* continues to be the single most difficult case for interoperability with any other contemporary algorithmic language. Fortunately there is hope within the new standard, where an "interoperability" flag will force F2003 to deliver arrays that are exportable. In exchange for this balkiness, F9* offers crude and verbose implementations of encapsulation and inheritance. I am sure Dr Beliavsky and some others are productive with F9*, but I would strongly advocate against it for anyone in a position to make a choice in the matter. Some people are competent with hand-powered drills, but I wouldn't set up a furniture production line with them on that basis. The performance and library advantages of Fortran are all available in F77. Higher level abstractions can easily be wrapped around the low level structures using Python and f2py. Making the combination performance-efficient requires some skill, but making a pure Fortran implementation efficient does no less so. I don't think we should or can abandon the excellent infrastructure provided by the Fortran of a generation ago. However, I am totally unconvinced that there is a point to a backward compatible extension to F77 that tries to support OOP and other abstractions unimaginable in the early days of Fortran. F77 and its numerical libraries are mature and complete. I think we should treat it as a remarkable set of packages, and move on. For any purposes I know of not involving an existing F9* legacy, I believe that Python plus F77 is as good as or superior to F9* alone. This includes the total time needed to learn the tools, (I think it is easier to learn Python, F77 and f2py than to learn F9* alone to any comparable skill level.) total time needed to develop the code, whole system performance, testability and maintainability. Once Python gets a first-class array type things will be even smoother as I understand it. mt From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 12:13:22 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 18:13:22 +0200 Subject: Python object overhead? In-Reply-To: <mailman.5633.1174921823.32031.python-list@python.org> References: <mailman.5530.1174684299.32031.python-list@python.org> <56ja46F28lpp9U1@mid.individual.net> <mailman.5633.1174921823.32031.python-list@python.org> Message-ID: <4607f123$0$3225$426a74cc@news.free.fr> Matt Garman a ?crit : (snip) > Also, many folks have suggested operating on only one line at a time > (i.e. not storing the whole data set). Unfortunately, I'm constantly > "looking" forward and backward in the record set while I process the > data (i.e., to process any particular record, I sometimes need to know > the whole contents of the file). (This is purchased proprietary > vendor data that needs to be converted into our own internal format.) Don't know if this could solve your problem, but have considered using an intermediate (preferably embedded) SQL database (something like SQLite) ? From thinker at branda.to Tue Mar 13 01:00:19 2007 From: thinker at branda.to (Thinker) Date: Tue, 13 Mar 2007 13:00:19 +0800 Subject: Starting Python... some questions In-Reply-To: <1173760751.798442.300550@s48g2000cws.googlegroups.com> References: <1173760751.798442.300550@s48g2000cws.googlegroups.com> Message-ID: <45F62FE3.5090408@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 jezonthenet at yahoo.com wrote: > I started using Python a couple of days ago - here are a few > questions: > > * Doesn't the __main__() method automatically execute when I run my > python program? > * Only when I do an import of my test.py file within python and then > run test.__main__() I can see where my bugs are. Is this correct? > (right now this is my only way of running my python program and see > where I have problems) > * Once I've done an import and then I wish to make a change to the > file I've imported I have to quit Python, restart and import that > module again in order for the module to be refreshed. Is there no "re- > import" ? > * Finally, could someone tell me why I'm having problems with the > small module below? > - Python pretends I provide chassis_id() with three parameters, even > though I clearly only provide it with two - why? No, Python is executing a module. You should explicit call __main__() at top scope of your module. For ex. if __name__ == '__main__': __main__() This snippet calls __main__() when the module is executed directly, but not imported as a module. Once a module had been imported, you should invoke reload() function to reload it from filesystem. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFF9i/j1LDUVnWfY8gRAgidAKCxHUWf/XTuT8fRQmeL3hnsO4fohQCgt27R jCNoz4hgp2CxD7H5HPwkfgM= =4g/m -----END PGP SIGNATURE----- From aisaac at american.edu Sat Mar 10 16:04:39 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 10 Mar 2007 21:04:39 GMT Subject: pylint: don't warn about tabs References: <SGXHh.522$mh.330@trnddc05> <55avniF23jpl2U1@mid.individual.net><mailman.4813.1173388535.32031.python-list@python.org><G1mIh.25$qe5.19@trnddc05><mailman.4877.1173484222.32031.python-list@python.org><7LnIh.327$mh7.197@trnddc04> <mailman.4901.1173538554.32031.python-list@python.org> Message-ID: <H3FIh.92$qe5.32@trnddc05> > Alan: >> I really think you should reread the PEP, which is making >> the opposite of your point. Skip: > Quite the opposite, in fact. Laura Creighton wrote that > PEP precisely with the expectation (and hope) that Guido > would reject it, which he did: Note the title and status. Sorry Skip, but this is really just a matter of taking off your blinkers and learning to read. As you say, note the title and status. Or alternatively, read this from the PEP: I figure if I make this PEP, we can then ask Guido to quickly reject it, and then when this argument next starts up again, we can say 'Guido isn't changing things to suit the tab-haters or the only-tabbers, so this conversation is a waste of time.' Alan Isaac From ptmcg at austin.rr.com Sat Mar 24 18:55:23 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Mar 2007 15:55:23 -0700 Subject: Anyone know of a MICR parser algorithm written in Python? In-Reply-To: <1174763132.786644.161500@y66g2000hsf.googlegroups.com> References: <1174763132.786644.161500@y66g2000hsf.googlegroups.com> Message-ID: <1174776923.618895.232630@y80g2000hsf.googlegroups.com> On Mar 24, 2:05 pm, "mkppk" <barnaclej... at gmail.com> wrote: > MICR = The line of digits printed using magnetic ink at the bottom of > a check. > > Does anyone know of a Python function that has been written to parse a > line of MICR data? > Or, some financial package that may contain such a thing? > Or, in general, where I should be looking when looking for a piece of > Python code that may have already been written by someone? > > I'm working on a project that involves a check scanner the produces > the raw MICR line as text. > > Now, that raw MICR needs to be parsed for the various pieces of info. > The problem with MICR is that there is no standard layout. There are > some general rules for item placement, but beyond that it is up to the > individual banks to define how they choose to position the > information. > > I did find an old C program written by someone at IBM... But I've read > it and it is Not code that would nicely convert to Python (maybe its > all the Python I'm used to, be it seems very poorly written). > > Here is the link to that C code:ftp://ftp.software.ibm.com/software/retail/poseng/4610/4610micr.zip > > I've even tried using boost to generate a Python module, but that > didn't go well, and in the end is not going to be a solution for me > anyway.. really need access to the Python source. > > Any help at all would be appreciated, > > -mkp Is there a spec somewhere for this data? Googling for "MICR data format specification" and similar gives links to specifications for the MICR character *fonts*, but not for the data content. And you are right, reverse-engineering this code is more than a 10- minute exercise. (However, the zip file *does* include a nice set of test cases, which might be better than the C code as a starting point for new code.) -- Paul From http Tue Mar 20 01:19:10 2007 From: http (Paul Rubin) Date: 19 Mar 2007 21:19:10 -0800 Subject: How to calculate a file of equations in python References: <1174366116.474507.298010@b75g2000hsg.googlegroups.com> Message-ID: <7x648w331t.fsf@ruckus.brouhaha.com> "John" <Allerdyce.John at gmail.com> writes: > I have a text file which contains math expression, like this > 134 > +234 > +234 Erm, is this a homework assignment? Basicaly you need to identify all the separate operands and operators and decide what to do with them. I'm guessing you don't have to worry about operator precedence, for example the rule that 2+3*5 is treated as 2+(3*5) because * has precedence over +. Anyway the idea is keep a running total and read through the input lines updating the total for each line. From bthom at cs.hmc.edu Fri Mar 23 13:52:09 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Fri, 23 Mar 2007 10:52:09 -0700 Subject: exit to interpreter? Message-ID: <B67ED58E-8982-43E0-8199-694763047BC2@cs.hmc.edu> Hi, I'm writing a function that polls the user for keyboard input, looping until it has determined that the user has entered a valid string of characters, in which case it returns that string so it can be processed up the call stack. My problem is this. I'd also like it to handle a special string (e.g. 'quit'), in which case control should return to the Python command line as opposed to returning the string up the call stack. sys.exit seemed like a good choice, but it exits the python interpreter. I could use an exception for this purpose, but was wondering if there's a better way? --b From robin at reportlab.com Thu Mar 29 06:17:45 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 29 Mar 2007 11:17:45 +0100 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <D78AD813-12F4-49D2-81B3-157681FEC6A4@stackless.com> References: <mailman.5685.1175032114.32031.python-list@python.org> <euenc1$fks$1@nemesis.news.tpi.pl> <D78AD813-12F4-49D2-81B3-157681FEC6A4@stackless.com> Message-ID: <460B9249.5020200@chamonix.reportlab.co.uk> Christian Tismer wrote: ....... >> something >> special, I am unable to dream of? Or is it purely academic project to >> create Python VM in Python? > > It will eventually give you a GIL-free VM, and it already gives you > a lot more than you have dreamt of. > > There is one feature missing that is probably hard to add. > Handling the 'posters who are not willing to read before they post' > syndrome. ....... I come from an academic background (sadly not in computer science) so I understand the need to promote the abstract advances that are being made here. However, I am a bit confused about the applicability of pypy. All the talk of backends, annotation object spaces etc etc may make some sense to really interested parties, but I would like to know what I can do in real terms with the new interpreters? The demo javascript stuff seems a bit fake since others have already done some work in that direction already using ordinary python. RPython may be larger or smaller than those subsets, but that's not clear. I would be interested to know if it's possible to point a tool at an existing python-2.4 module and wrap it into a much faster extension that can be used by my CPython stuff. I know there is preliminary work in that direction. I am hugely encouraged by this C:\Python\devel\pypy-1.0.0>\python24\python \python\lib\test\pystone.py Pystone(1.1) time for 50000 passes = 1.49586 This machine benchmarks at 33425.6 pystones/second C:\Python\devel\pypy-1.0.0>.\pypy-c.exe \python\lib\test\pystone.py Pystone(1.1) time for 50000 passes = 2.16123e-005 This machine benchmarks at 2.3135e+009 pystones/second :) not -- Robin Becker From chris.lasher at gmail.com Tue Mar 27 01:08:11 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 26 Mar 2007 22:08:11 -0700 Subject: build python on Celeron D In-Reply-To: <mailman.5650.1174965907.32031.python-list@python.org> References: <mailman.5650.1174965907.32031.python-list@python.org> Message-ID: <1174972091.173999.9650@n59g2000hsh.googlegroups.com> On Mar 26, 10:48 pm, Christian <ckk... at hoc.net> wrote: > Traceback (most recent call last): > File "setup.py", line 89, in ? > setup_package() > File "setup.py", line 59, in setup_package > from numpy.distutils.core import setup > File "/mnt/home/ck/prog/scipy/numpy-1.0.1/numpy/__init__.py", line 36, in ? > File "numpy/core/__init__.py", line 5, in ? > import multiarray > ImportError: > /media/hda6/home/ck/prog/scipy/numpy-1.0.1/numpy/core/multiarray.so: undefined > symbol: Py_InitModule4 > > which is related to 32<->64 issues, right? <http://www.thescripts.com/forum/thread35987.html> Do you have more than one Python installation on this machine? The link above indicates that if you build NumPy with a different build of Python than you will run it from, you will get this same error. Granted, I'm sure there are many ways to get said error, but that was the most obvious from a five minute search. Alternatively, if you haven't done so already, you may want to mail the numpy-discussion list. From bj_666 at gmx.net Mon Mar 5 03:55:08 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 05 Mar 2007 09:55:08 +0100 Subject: Building a dictionary from a tuple of variable length References: <1173084222.565386.250510@h3g2000cwc.googlegroups.com> Message-ID: <pan.2007.03.05.08.55.08.799038@gmx.net> In <1173084222.565386.250510 at h3g2000cwc.googlegroups.com>, bg_ie wrote: > Therefore, how do I build the tuple of Falses to reflect the length of > my t tuple? In [1]: dict.fromkeys(('one', 'two', 'three'), False) Out[1]: {'three': False, 'two': False, 'one': False} Ciao, Marc 'BlackJack' Rintsch From anton.vredegoor at gmail.com Sat Mar 10 11:04:31 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 10 Mar 2007 17:04:31 +0100 Subject: number generator In-Reply-To: <1173515984.515050.27400@n33g2000cwc.googlegroups.com> References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> <pan.2007.03.09.15.32.01.112493@gmx.net> <1173515984.515050.27400@n33g2000cwc.googlegroups.com> Message-ID: <esukru$1v1$1@news2.zwoll1.ov.home.nl> Raymond Hettinger wrote: > To make the solutions equi-probable, a simple approach is to > recursively enumerate all possibilities and then choose one of them > with random.choice(). Maybe it is possible to generate the possibilities by an indexing function and then use randint to pick one of them. I suppose this is like the bricks and bins problem this thread was about: http://groups.google.nl/group/comp.lang.python/browse_thread/thread/4782b54fa39b3bad Except that the bins now have at least 1 brick in them (if we have positive numbers). I posted a rather simplistic solution (but working I think) after Steven Taschuk made some insightful remarks. I believe it is possible to generate the list of numbers directly instead of permuting a list of '0' and '1' characters and then finding the positions of the '1' elements. A. From shawn.mcgrath at gmail.com Mon Mar 19 12:40:44 2007 From: shawn.mcgrath at gmail.com (Shawn McGrath) Date: 19 Mar 2007 09:40:44 -0700 Subject: Boost Python properties/getter functions for strings In-Reply-To: <1174320047.732767.101930@e65g2000hsc.googlegroups.com> References: <1174312916.127830.303550@o5g2000hsb.googlegroups.com> <1174320047.732767.101930@e65g2000hsc.googlegroups.com> Message-ID: <1174322444.663045.82200@d57g2000hsg.googlegroups.com> On Mar 19, 12:00 pm, "Shawn McGrath" <shawn.mcgr... at gmail.com> wrote: > I forgot to mention, getname is defined as: > const std::string &Entity::getName() const; After more reading I found the copy_const_reference, and replaced: boost::python::return_internal_reference<>()); with: boost::python::return_value_policy<boost::python::copy_const_reference>()); and it fixed my problem. Is there any downside to using copy_const_reference over return_internal_reference? Thanks, Shawn. From gagsl-py2 at yahoo.com.ar Thu Mar 8 04:20:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 06:20:11 -0300 Subject: Descriptor/Decorator challenge References: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> <1173343058.897596.19570@s48g2000cws.googlegroups.com> Message-ID: <op.tou5jxhkx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 08 Mar 2007 05:37:39 -0300, Michele Simionato <michele.simionato at gmail.com> escribi?: > The code to enable recognition of CurrentClass is short enough to be > includede here, but I will qualify it as a five star-level hackery: You forgot the standard disclaimer: "This is extremely dangerous stuff, only highly trained professionals can do that! Kids, never try this at home!" -- Gabriel Genellina From dudaraster at gmail.com Sun Mar 4 05:42:34 2007 From: dudaraster at gmail.com (Aviroce) Date: Sun, 04 Mar 2007 10:42:34 +0000 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST) In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: <repost.92102.1172691920.663009.111260@j27g2000cwj.googlegroups.com> On Feb 24, 11:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. <<<<<<<<<<<"The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. ">>>>>>>>>>>>>>>> THAT IS CALLED PROTECTING CIVIL RIGHTS. IN THE UNITED STATES OF AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE NOT PROTECTED BY THE GENEVA CONVENTION. DR. EVIL, V.P. CHENEY, AND MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION. THIS MEANS ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO. WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER. From scott.daniels at acm.org Fri Mar 9 00:49:50 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 08 Mar 2007 21:49:50 -0800 Subject: TitleCase, camelCase, lowercase In-Reply-To: <mailman.4839.1173415409.32031.python-list@python.org> References: <1173379952.901004@iceman.esoterica.pt> <45f068a2$0$18256$426a74cc@news.free.fr> <1173393063.705376@jubilee.claranet.pt> <45f09905$0$28886$426a34cc@news.free.fr> <1173413376.191416.30990@s48g2000cws.googlegroups.com> <op.towmn6uwx6zn5v@gabriel2.softlabbsas.com.ar> <mailman.4839.1173415409.32031.python-list@python.org> Message-ID: <12v1ta743535efc@corp.supernews.com> Ben Finney wrote: > I prefer to use the term "title case" to refer unambiguously to > "NameWithSeveralWords", leaving the term "camel case" to describe the > case with the humps only in the middle :-) The names "TitleCase" and "camelCase" might suffice here. -- --Scott David Daniels scott.daniels at acm.org From steve at REMOVE.THIS.cybersource.com.au Fri Mar 23 23:43:34 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 24 Mar 2007 14:43:34 +1100 Subject: Multi-line strings with formatting References: <1174668885.347602.117970@n59g2000hsh.googlegroups.com> <1174669850.3450.40.camel@dot.uniqsys.com> <mailman.5524.1174674566.32031.python-list@python.org> <1174703993.715410.173780@e65g2000hsc.googlegroups.com> Message-ID: <pan.2007.03.24.03.43.27.229103@REMOVE.THIS.cybersource.com.au> On Fri, 23 Mar 2007 19:39:53 -0700, Paul McGuire wrote: > (and I'm glad I'm not the only one who uses 'l' for a scratch list > variable...) Yes, and come the revolution, every last one of you will be down the salt mines. I don't mind using capital L as a variable, but l looks too much like I and 1 in most typefaces. Capital O is another nasty one. I also try to avoid using a as a variable name, because a is a definite article in English (like "the") and that makes it difficult to write grammatical sentences about what you're doing. -- Steven. From aleax at mac.com Thu Mar 15 01:38:39 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Mar 2007 22:38:39 -0700 Subject: Python books? References: <1CD93DF7-4172-4FF1-B5B4-BF665762C9E7@comhem.se> <mailman.4942.1173623618.32031.python-list@python.org> <et9n5u$q48$1@panix3.panix.com> <1173906223.048740.18050@b75g2000hsg.googlegroups.com> Message-ID: <1huzl72.z09y4u1xt7lpsN%aleax@mac.com> BartlebyScrivener <rpdooling at gmail.com> wrote: > On Mar 14, 3:50 pm, a... at pythoncraft.com (Aahz) wrote: > > > Some people prefer shorter books -- Python for Dummies (for new > > programmers) and Python in a Nutshell (for experienced programmers) both > > try to give a thorough survey of Python while keeping the book easy to > > carry. Not for me to comment about my own books, but I can second your recommendation for your "for Dummies" for beginners. > And other people like lots of examples and code organized around > practical projects a person might like to accomplish using Python. The > Python Cookbook 2nd edition is great for this, and Martelli et al are > great writers, as well as great programmers. If you like _substantial_ examples, rather than the simple/short ones typically used in manageable-sized books, Hetland's "Practical Python" was also a great buy (I believe it's now been replaced by "Beginning Python" by the same author, but unfortunately I haven't seen that one). In general I dislike books that try to teach a language (or other technology) via "substantial examples", because the issues with the examples may obscure those with the language or technology; e.g., Stroustrup tries that route in "The C++ Programming Language", as Lutz does in "Programming Python", and to my taste the results are inferior. However, at least in "Practical Python" (can't speak for "Beginning Python"), Hetland managed to pull it off -- perhaps by placing the substantial programs he develops as successive examples in a clever sequence, so that at each step he's not dealing with many diverse new issues but just manageably few of them. Alex From m_tayseer82 at yahoo.com Sun Mar 18 14:07:06 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Sun, 18 Mar 2007 11:07:06 -0700 (PDT) Subject: Eureka moments in Python In-Reply-To: <+tk*0oRFr@news.chiark.greenend.org.uk> Message-ID: <548554.50972.qm@web31115.mail.mud.yahoo.com> > I'd be interested in hearing people's stories of Eureka moments > in Python, moments where you suddenly realise that some task > which seemed like it would be hard work was easy with Python. I had a project in the faculty where we were supposed to implement a compiler for a very simple language (no functions, etc). I was responsible for implementing the compiler itself & another colleage was responsible for making an editor for the language - a bonus feature. I was still learning Python & my colleage only heard about it. I implemented the language completely within 4 days. My colleage learnt Python & Tkinter and made a text editor with syntax highlighting & auto-indentation in 3 days. We implemented all the bonus features while other groups was still fighting with lex & yacc just to get it to *run* right. We were the highest ranked group :) The next year, the teaching assistant refused that any project be done in Python because it is so easy :( Part of the productivity boos came from pyggy, a very simple yet powerful parser generator that made writing the compiler clear as exactly as our course note said :) Mohammad Tayseer http://spellcoder.com/blogs/tayseer --------------------------------- Never miss an email again! Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070318/cec29ba4/attachment.html> From steve at holdenweb.com Tue Mar 13 20:13:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 13 Mar 2007 20:13:58 -0400 Subject: help!! *extra* tricky web page to extract data from... In-Reply-To: <7xy7m0eny5.fsf@ruckus.brouhaha.com> References: <1173819262.288501.66350@n76g2000hsh.googlegroups.com> <55ojorF26c25jU1@mid.uni-berlin.de> <55oli1F25u2dmU1@mid.uni-berlin.de> <7xmz2gbx6r.fsf@ruckus.brouhaha.com> <55omooF25ll0vU1@mid.uni-berlin.de> <7x1wjskbs7.fsf@ruckus.brouhaha.com> <55op6uF24n2biU1@mid.uni-berlin.de> <7xy7m0eny5.fsf@ruckus.brouhaha.com> Message-ID: <et7er3$hag$1@sea.gmane.org> Paul Rubin wrote: > "Diez B. Roggisch" <deets at nospam.web.de> writes: >> Obviously this wouldn't really help, as you can't predict what a >> website actually wants which events, in possibly which >> order. Especially if the site does not _want_ to be scrapable- think >> of a simple "click on the images in the order of the numbers shown on >> them" captcha. > > Sure, but most sites don't go to such lengths, and even captchas can > be defeated if you're trying to scrape a specific site and are willing > to spend effort on the particular captcha generator that it uses. > Plus there is always www.captchasolver.com (!). > I especially like the rems and conditions they ask you to acknowledge if you want to sign up as a worker: http://www.captchasolver.com/join/worker# regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From bborcic at gmail.com Wed Mar 21 06:31:06 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 21 Mar 2007 11:31:06 +0100 Subject: How to calculate a file of equations in python In-Reply-To: <1174366116.474507.298010@b75g2000hsg.googlegroups.com> References: <1174366116.474507.298010@b75g2000hsg.googlegroups.com> Message-ID: <etr1ii$o06$1@sea.gmane.org> r='' for line in file : r = str(eval(r+line)) John wrote: > Hi, > I have a text file which contains math expression, like this > 134 > +234 > +234 > > (i.e. an operation (e.g. '+) and then a number and then a new line). > > Can you please tell me what is the easiest way to calculate that file? > for example the above example should be = 134 + 234 + 234 = 602. > > Thank you. > From nospam at nospam.com Wed Mar 28 11:13:38 2007 From: nospam at nospam.com (Mark T) Date: Wed, 28 Mar 2007 08:13:38 -0700 Subject: Python automatic testing: mocking an imported module? References: <1175033934.795913.292030@l77g2000hsb.googlegroups.com> Message-ID: <e_SdnZlWHIaIG5fbnZ2dnUVZ_qidnZ2d@comcast.com> "Silfheed" <silfheed at gmail.com> wrote in message news:1175033934.795913.292030 at l77g2000hsb.googlegroups.com... > Heyas > > So we have the following situation: we have a testee.py that we want > to automatically test out and verifiy that it is worthy of being > deployed. We want our tester.py to test the code for testee.py > without changing the code for testee.py. testee.py has a module in it > that we want to mock in some tests and in others use the real module. > > /foo.py: (real module) > class bar: > def __init__(self): > "I am real" > > /foo_fake/foo.py: (fake module) > class bar: > def ___init__(self): > "I am a banana" > > /testee.py: > import foo > foo.bar() > > /tester.py: > from foo_fake import foo > foo.bar() # prints I am a banana > testee.py # also prints I am a banana > import foo > foo.bar() # prints I am real > testee.py # also prints I am real > > > This isnt working as we would like, does anyone have any tips on how > to get something like this working? > If you add the foo_fake directory to the front of sys.path, "import foo" will import the foo.py in foo_fake directory before the one in the local directory. # unverified code import sys sys.path.append(0,'foo_fake') # add foo_fake to front of path import foo foo.bar() execfile('testee.py') sys.path.pop(0) # remove foo_fake reload(foo) foo.bar() execfile('testee.py') -Mark From aleax at mac.com Thu Mar 29 03:57:03 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Mar 2007 00:57:03 -0700 Subject: gmpy floating point exception References: <eufdde$ekb$1@aioe.org> Message-ID: <1hvpp4y.albgc51fr3fstN%aleax@mac.com> Martin Manns <mmanns at gmx.net> wrote: > Hi, > > I am experiencing some trouble with gmpy v1.01. > Multiplying an mpq with inf results in a floating point exception that > exits python. Has this already been fixed in newer gmpy versions? No, I can reproduce the problem (on a Mac with an Intel CPU) with the current version, 1.02. I will have no time to work for a fix until (I hope) next week, though (spending a long weekend hitch-hiking). > BTW. > 1) What is the best way to test for inf regardless of type? No, 'inf' is in fact not portable among different builds of Python for different CPUs, in general. > 2) Is there any inf type around with > a + inf == inf > inf > a (as long as a != inf) > etc. > that works with any other type? You mean something like: class inf(object): def __radd__(self, other): return self def __gt__(self, other): return self is not other # etc inf = inf() ...? Alex From ptmcg at austin.rr.com Fri Mar 30 17:41:57 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Mar 2007 14:41:57 -0700 Subject: Inserting '-' character in front of all numbers in a string In-Reply-To: <mailman.5793.1175281775.32031.python-list@python.org> References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> <mailman.5793.1175281775.32031.python-list@python.org> Message-ID: <1175290917.509860.224250@o5g2000hsb.googlegroups.com> On Mar 30, 2:09 pm, Michael Bentley <mich... at jedimindworks.com> wrote: > On Mar 30, 2007, at 10:38 AM, kevinliu23 wrote: > > > > > > > I want to be able to insert a '-' character in front of all numeric > > values in a string. I want to insert the '-' character to use in > > conjunction with the getopt.getopt() function. > > > Rigt now, I'm implementing a menu system where users will be able to > > select a set of options like "2a 3ab" which corresponds to menu > > choices. However, with getopt.getopt(), it'll only return what I want > > if I input -2a -3ab as my string. I don't want the user have to insert > > a '-' character in front of all their choices, so I was thinking of > > accepting the string input first, then adding in the '-' character > > myself. > > > So my qusetion is, how do I change: > > > "2a 3ab" into "-2a -3ab". > > Will the first character always be a digit? > > for i in yourstring.split(): > if i[0].isdigit(): > yourstring = yourstring.replace(i, '-%s' % (i,)) > > Or are these hex numbers?- Hide quoted text - > > - Show quoted text - Your replace strategy is risky. If: yourstring = "1ab 2bc 3de 11ab" it will convert to -1ab -2bc -3de 1-1ab -- Paul From xiong.xu.cn at gmail.com Sat Mar 17 07:09:16 2007 From: xiong.xu.cn at gmail.com (imx) Date: 17 Mar 2007 04:09:16 -0700 Subject: cannot start IDLE in WinXP Message-ID: <1174129756.325715.22280@e1g2000hsg.googlegroups.com> Hi, Enviroment: WinXP sp2, python 2.5 problem: click IDLE using shorcut menu or run phthonw.exe directly, nothing happen! But running python.exe from the command line is fine. I searched this issue on the net and this forum and tried some suggestions but with no luck. Any ideas? Thanks in advance, Xiong From knipknap at gmail.com Wed Mar 14 16:43:36 2007 From: knipknap at gmail.com (Samuel) Date: 14 Mar 2007 13:43:36 -0700 Subject: Converting a list to a dictionary In-Reply-To: <1173904326.037621.10390@n76g2000hsh.googlegroups.com> References: <1173902878.561018.244310@y80g2000hsf.googlegroups.com> <45f8583d$0$10407$426a34cc@news.free.fr> <1173904326.037621.10390@n76g2000hsh.googlegroups.com> Message-ID: <1173905016.752156.248140@n59g2000hsh.googlegroups.com> On Mar 14, 9:32 pm, "Drew" <olso... at gmail.com> wrote: > I'm using Python2.5 and it seems that this only gives me a hash with > the first id and first record. Am I doing something wrong? Try this instead: >>> class Person(): ... def __init__(self): ... self.id = 5 ... >>> mylist = [] >>> for i in range(100): ... p = Person() ... p.id = i ... mylist.append(p) ... >>> mydict = dict((r.id,r) for r in mylist) >>> mydict What this does is it maps the id to the object. In your case, you only have one id. -Samuel From steve at holdenweb.com Sat Mar 17 06:29:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 17 Mar 2007 06:29:43 -0400 Subject: File extension In-Reply-To: <cf14220703161559s1d106d03gd02bac4c0d695506@mail.gmail.com> References: <cf14220703161559s1d106d03gd02bac4c0d695506@mail.gmail.com> Message-ID: <45FBC317.2020204@holdenweb.com> Anil Kumar wrote: > Hi, > > Can Python Script can have different extensions like .sh etc.... Or Is > .py is mandatory to be present as the extension for the Python Script. > The interpreter itself doesn't really care. The issues you are hotting are due to operating system. and command shell differences. > We have an application where the script was initially written in shell > script with extension .sh. Now we are migrating this script to be run in > both Unix and Windows, so using Python for migration. > Good for you! > I have created a new Python Script porting all the changes in shell > script and it is working fine in Unix/Linux operating system. Later I > changed the extension of the file from .py to .sh, even then it worked. > The Unix command interpretation mechanism uses PATH as a list of directories to search for the named command file (the first word of the expanded command line). It then looks for the magic string "#!" at the start of the executable file and, if it finds that string, it passes the file to the interpreter named in the rest of the line for execution as a program. Your Python files probably begin with something like #!/usr/bin/python or #!/usr/bin/env python > But when I try a python script with extension .sh in windows, the file > is not getting recognized by the Python interpreter. Is this supported? > Or is there any way we can achieve the same? > In Windows, alas, the mechanism is less versatile. The command interpreter uses an environment variable called PATHEXT to decide which extensions to check when it sees a command that it can't find directly. For example, my PATHEXT variable is currently PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH (you'll observe I have given up on the PATHEXT mechanism - it's too much of a pain in the butt for me, so I just code explicit calls to the python interpreter). It looks on the PATH for a file with the given name and each extension, and when it finds one it then runs the interpreter registered for that type of file. > The reason I am trying to change the extension is, it reduces lot of > porting changes. No need to go to each of our file which were > referencing .sh file before and change it to .py. > > Any Help would be greatly Appreciated. > You could cheat ... if you register the .SH extension as "to be handled by the python interpreter" and then add .SH to PATHEXT this should work under Windows. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From stevena at neosynapse.net Wed Mar 21 14:51:58 2007 From: stevena at neosynapse.net (Steven D. Arnold) Date: Wed, 21 Mar 2007 14:51:58 -0400 Subject: parsing combination strings In-Reply-To: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> References: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> Message-ID: <C802B3C6-FF0D-4AFE-B0B5-4CC431FDB353@neosynapse.net> On Mar 21, 2007, at 2:42 PM, PKKR wrote: > I need a fast and efficient way to parse a combination string(digits + > chars) > > ex: s = "12ABA" or "1ACD" or "123CSD" etc > > I want to parse the the above string such that i can grab only the > first digits and ignore the rest of the chacters, A regex leaps to mind.....have you investigated the "re" module? >>> import re >>> re.match(r'(\d+)', '123abc').group(1) '123' steven From fredrik at pythonware.com Mon Mar 5 03:55:01 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Mar 2007 09:55:01 +0100 Subject: How use XML parsing tools on this one specific URL? References: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> <17899.1902.949251.452086@montanaro.dyndns.org> Message-ID: <esglt5$2lp$1@sea.gmane.org> skip at pobox.com wrote: > > Chris> http://moneycentral.msn.com/companyreport?Symbol=BBBY > > Chris> I can't validate it and xml.minidom.dom.parseString won't work on > Chris> it. > > Chris> If this was just some teenager's web site I'd move on. Is there > Chris> any hope avoiding regular expression hacks to extract the data > Chris> from this page? > > Tidy it perhaps or use BeautifulSoup? ElementTree can use tidy if it's > available. ElementTree can also use BeautifulSoup: http://effbot.org/zone/element-soup.htm as noted on that page, tidy is a bit too picky for this kind of use; it's better suited for "normalizing" HTML that you're producing yourself than for parsing arbitrary HTML. </F> From gregor at hostgis.com Wed Mar 7 05:25:56 2007 From: gregor at hostgis.com (Gregor Mosheh) Date: Wed, 7 Mar 2007 03:25:56 -0700 (MST) Subject: How to build a Windows service using win32? Message-ID: <3486.168.103.93.50.1173263156.squirrel@maps.hostgis.com> I'm trying to write a Win32 service. The following is straight from Python Programming on Win32 and it doesn't work. Is that book out of date; is there a new way to do services? I searched Google for hours trying to find any other method, and have been beating on this one for 5 more hours. The present error is: C:\Tester>python tester.py debug Debugging service Tester - press Ctrl+C to stop. Error 0xC0000004 - Python could not import the service's module <type 'exceptions.ImportError'>: No module named service The code is: import win32serviceutil, win32service, win32event class Service(win32serviceutil.ServiceFramework): _svc_name_ = "EDMS-to-CG" _svc_display_name_ = "EDMS-to-CG Syncer" _svc_description_ = "Uploaded the EDMS database to Cartograph" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): pausetime = 60 * 1000 while True: stopsignal = win32event.WaitForSingleObject(self.hWaitStop, pausetime) if stopsignal == win32event.WAIT_OBJECT_0: break self.runOneLoop() def runOneLoop(self): import servicemanager servicemanager.LogInfoMsg('Running') win32serviceutil.HandleCommandLine(Service) From goodTweetieBird at hotmail.com Wed Mar 21 16:52:56 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 21 Mar 2007 13:52:56 -0700 Subject: Printing __doc__ In-Reply-To: <ets4qe$i0i$00$1@news.t-online.com> References: <1174506426.108098.243940@d57g2000hsg.googlegroups.com> <ets4qe$i0i$00$1@news.t-online.com> Message-ID: <1174510376.417966.110370@e1g2000hsg.googlegroups.com> On Mar 21, 3:35 pm, Peter Otten <__pete... at web.de> wrote: > gtb wrote: > > In a function I can use the statement n = > > sys._getframe().f_code.co_name to get the name of the current > > function. Given that I can get the name how can I print the __doc__ > > string? I cant use the following, it will tell me to bugger off as the > > string has no such attribute. > > > def spam(self): > > n = sys._getframe().f_code.co_name > > print n.__doc__ #Wrong > > print __doc__ #No good either > > #.... > >>> import sys > >>> def docstring(): > > ... return sys._getframe(1).f_code.co_consts[0] > ...>>> def foo(): > > ... print "My docstring is %r" % docstring() > ...>>> def bar(): > > ... "bar's docstring" > ... print "My docstring is %r" % docstring() > ...>>> foo() > > My docstring is None>>> bar() > > My docstring is "bar's docstring" > > No idea how brittle that might be, though. > > Peter Thanks. Pardon my ignorance, but brittle? From claird at lairds.us Mon Mar 26 11:16:55 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 26 Mar 2007 15:16:55 +0000 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916838.757839.143310@e65g2000hsc.googlegroups.com> <3f8d9$4607d352$83aef404$23393@news2.tudelft.nl> <1174918424.125068.176920@y80g2000hsf.googlegroups.com> Message-ID: <7o4ld4-qrv.ln1@lairds.us> In article <1174918424.125068.176920 at y80g2000hsf.googlegroups.com>, Nomad.C at gmail.com <Nomad.C at gmail.com> wrote: . . . >Is there a mac version?? >Thanks >Chris > Yes. Several, in fact--all available at no charge. The Python world is different from what experience with Fortran might lead you to expect. I'll be more clear: Fortran itself is a distinguished language with many meritorious implementations. It can be costly, though, finding the implementation you want/need for any specific environment. Python, in contrast, is blessed with a plethora of implementations and variations, all of which are available without licensing fee. In particular, recent Mac OS X installations INCLUDE Python--it's already in there! From mail at timgolden.me.uk Thu Mar 22 08:30:24 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 22 Mar 2007 12:30:24 +0000 Subject: Python-URL! - weekly Python news and links (Mar 22) In-Reply-To: <46027530$0$10420$426a74cc@news.free.fr> References: <etsq3d$jcg$1@lairds.us> <46027530$0$10420$426a74cc@news.free.fr> Message-ID: <460276E0.8020409@timgolden.me.uk> Bruno Desthuilliers wrote: > Cameron Laird a ?crit : >> This is the first time you've received "Python-URL!" in 2007. No, >> that's not the fault of your mail server; we've just been on sabbatical. >> Now we're back. > > Great ! I was a bit worried... > Seconded; I've always looked forward to the Python-URL and I was a bit afeared that it had run out of steam. Good to see it back... and thanks for keeping it up! TJG From stephan.diehl at gmx.net Fri Mar 30 10:46:23 2007 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Fri, 30 Mar 2007 16:46:23 +0200 Subject: next python berlin user group meeting / naechstes berliner python treffen Message-ID: <euj7rs$pj7$00$1@news.t-online.com> time: 3.4., 7pm place: c-base info: http://groups.google.de/group/python-berlin From quentel.pierre at wanadoo.fr Sun Mar 25 03:03:52 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 25 Mar 2007 00:03:52 -0700 Subject: List comprehension returning subclassed list type? In-Reply-To: <1174804990.037158.22790@l77g2000hsb.googlegroups.com> References: <1174804990.037158.22790@l77g2000hsb.googlegroups.com> Message-ID: <1174806232.810906.219660@n59g2000hsh.googlegroups.com> On 25 mar, 08:43, "bullockbefriending bard" <kinch1... at gmail.com> wrote: > Given: > > class Z(object): > various defs, etc. > > class ZList(list): > various defs, etc. > > i would like to be able to replace > > z_list = ZList() > for y in list_of_objects_of_class_Y: > z_list.append(y) > > with something like this: > > z_list = [Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y] > > Of course this just gives me a plain list and no access to the > methodsof z_list. I could, of course go and write a static method in > ZList which takes a plain list of Z objects and returns a ZList. > > Anyway, my question is whether or not this can be done more elegantly > via list comprehension? Hello, A list comprehension will give you a list. But you can use a generator expression : z_list = ZList(Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y) Regards, Pierre From aahz at pythoncraft.com Sun Mar 18 19:33:56 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Mar 2007 16:33:56 -0700 Subject: Grep Equivalent for Python References: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> <1huzlrm.1scmekr1val8sbN%aleax@mac.com> <1174255846.721961.108370@e1g2000hsg.googlegroups.com> Message-ID: <etki94$7qq$1@panix3.panix.com> In article <1174255846.721961.108370 at e1g2000hsg.googlegroups.com>, tereglow <tom.rectenwald at eglow.net> wrote: >On Mar 15, 1:47 am, a... at mac.com (Alex Martelli) wrote: >> tereglow <tom.rectenw... at eglow.net> wrote: >>> >>>grep^MemTotal /proc/meminfo | awk '{print $2}' >> >> If you would indeed do that, maybe it's also worth learning something >> more about the capabilities of your "existing" tools, since >> >> awk '/^MemTotal/ {print $2}' /proc/meminfo >> >> is a more compact and faster way to perform exactly the same task. >> >> (You already received a ton of good responses about doing this in >> Python, but the "pipegrepinto awk instead of USING awk properly in the >> first place!" issue has been a pet peeve of mine for almost 30 years >> now, and you know what they say about old dogs + new tricks!-). > >I had no idea you could do that. Thanks for the tip, I need to start >reading that awk/sed book collecting dust on my shelf! Your other option is to completely abandon awk/sed. I started writing stuff like this in Turbo Pascal back in the early 80s because there simply wasn't anything like awk/sed available for CP/M. In the 90s, when I needed to do similar things, I used Perl. Now I use Python. >From my POV, there is really no reason to learn the advanced shell utilities. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From rowen at cesmail.net Fri Mar 2 16:09:09 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 02 Mar 2007 13:09:09 -0800 Subject: Converting a c array to python list References: <es66m4$cnr$1@inews.gazeta.pl> Message-ID: <rowen-9DEBB0.13090902032007@gnus01.u.washington.edu> In article <es66m4$cnr$1 at inews.gazeta.pl>, zefciu <zefirek at Speacock.Pau.Apoznan.Mpl> wrote: > Hi! > > I want to embed a function in my python application, that creates a > two-dimensional array of integers and passes it as a list (preferably a > list of lists, but that is not necessary, as the python function knows > the dimensions of this array). As I read the reference, I see, that I > must first initialize a list object and then item-by-item put the values > to the list. Is there any faster way to do it? And is it worth to > implement? The same problem is resolved in the current version by > calling a smaller c function (that counts just one element of the array) > many times. Will it add much performance to the process? My first thought is to use the numpy library since it is good at quickly creating large arrays (of any dimension) and you can easily get the data out as a list if you really need that (but are you sure you need that? You may be able to just use the numpy array directly). It might help to have a clearer idea of why you want to do this. -- Russell P.S. numarray or Numeric would also do the job. They are older, deprecated numeric libraries. numpy is recommended for new code. From bignose+hates-spam at benfinney.id.au Thu Mar 8 16:03:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 Mar 2007 08:03:51 +1100 Subject: pylint: don't warn about tabs References: <SGXHh.522$mh.330@trnddc05> <55avniF23jpl2U1@mid.individual.net> Message-ID: <874povzbuw.fsf@benfinney.id.au> Bjoern Schliessmann <usenet-mail-0306.20.chr0n0ss at spamgourmet.com> writes: > Alan Isaac wrote: > > As a tab user, I want the tabs warning turned off. > > Advice: Don't. Agreed. Sticking to spaces for indentation avoids the ambiguity of interpretation that ASCII TAB characters are subject to. In addition, PEP 8 (which many people consider a strong suggestion for a style guide for all Python code) recommends four space characters for indentation. > IIRC it's planned in future Python versions that TABs aren't > supported for indentation. I've not seen such plans, can you support that? If you're thinking of this post from Guido, please note the date it was made: <URL:http://www.artima.com/weblogs/viewpost.jsp?thread=101968> -- \ "Dvorak users of the world flgkd!" -- Kirsten Chevalier, | `\ rec.humor.oracle.d | _o__) | Ben Finney From ebgssth at gmail.com Sat Mar 3 04:45:28 2007 From: ebgssth at gmail.com (js ) Date: Sat, 3 Mar 2007 18:45:28 +0900 Subject: print a ... z, A ... Z, "\n"' in Python In-Reply-To: <a23effaf0703030142t42d5bb51jc0fe761e51294f25@mail.gmail.com> References: <mailman.4623.1172909667.32031.python-list@python.org> <1172913109.184004.132680@30g2000cwc.googlegroups.com> <a23effaf0703030142t42d5bb51jc0fe761e51294f25@mail.gmail.com> Message-ID: <a23effaf0703030145p7943faabv7560cdfb0fb7cb24@mail.gmail.com> > But note that you return the last item of the range too, and that goes > against the semantic of the usual Python range/xrange, so you may want > to call this function with another name. That makes sense. 100% agree with you. > Maybe there are better ways to solve this problem. Maybe a way to > generate (closed?) char ranges can be added to the Python standard > lib. Maybe we don't want char range If string constants would be rich enough. From rhc28 at cornell.edu Mon Mar 19 17:11:15 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Mon, 19 Mar 2007 17:11:15 -0400 Subject: urgent - Matplolib with IDLE! In-Reply-To: <26f4c9e60703191308j55287087ydc12c24656b4df6b@mail.gmail.com> References: <26f4c9e60703191308j55287087ydc12c24656b4df6b@mail.gmail.com> Message-ID: <a749952d0703191411u1ce36ca4lbb4ad50d705ab074@mail.gmail.com> Dear Ana, I have the same problem with a similar setup (except Python 2.4.3) and have tried the same solutions (BTW those steps really did used to work on my machine using Python 2.3.5). In the short term you could either try IPython (a proper solution to this problem, which returns me to the prompt just fine after closing the figure) or try the following "quick and dirty fix" with IDLE: 1) If your script does stuff other than define classes and functions, put in a command that prevents it getting to the calculations (e.g. insert a "1/0" line) or, for instance, turn all your calculations into function calls that you can easily comment out (temporarily). Run your script using F5 so that you just get the prompt. 3) Create an empty figure using pylab.figure() or whatever. 2) Close the figure and the IDLE console (command prompt window) that opened when you ran the script (you have to say Yes when it asks about killing a python process). 3) This leaves an orphaned python process which you have to clean up later using your Task Manager, but ... 4) you can now continue to interact with any new IDLE console created in the current session when you bring up new figures. i.e. uncomment the parts of your script that actually do stuff and run it again. At least that's a quick fix that's working for me while I await a better answer too... Perhaps this hack will outrage someone's sensibilities sufficiently that we'll hear of a better IDLE solution. HTH, Rob From mikelem at iastate.edu Fri Mar 2 20:27:15 2007 From: mikelem at iastate.edu (Jeff Groves) Date: Fri, 2 Mar 2007 19:27:15 -0600 (CST) Subject: "unknown encoding: string-escape" in frozen Python Message-ID: <152719221075600@webmail.iastate.edu> I'm using FreezePython on a Python program that uses wxPython and subprocess. The result almost works, but it always hits this bug: File "velauncher.py", line 847, in Launch File "python/velLaunchCode.py", line 61, in __init__ File "python/velLaunchCode.py", line 143, in Unix File "python/subprocess.py", line 599, in __init__ File "python/subprocess.py", line 1031, in _execute_child File "/usr/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 985, in load_string self.append(rep.decode("string-escape")) LookupError: unknown encoding: string-escape I tried adding --include-modules=encodings to the arguments, but I'm still getting the string-escape error. How can I include the encoding in the freeze? I'm using Python2.3 and the downloadable version of subprocess.py for Python2.3 on Redhat. -Jeff Groves From laurent.pointal at limsi.fr Mon Mar 19 08:52:56 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 19 Mar 2007 13:52:56 +0100 Subject: XML based programming language In-Reply-To: <1174307748.936567.191440@e1g2000hsg.googlegroups.com> References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> <56786fF2743atU2@mid.uni-berlin.de> <1174307748.936567.191440@e1g2000hsg.googlegroups.com> Message-ID: <etm12l$qlh$1@news2.u-psud.fr> stefaan a ?crit : >> Elementtree isn't lex. You are comparing apples and oranges here. Lex >> tokenizes, yacc creates trees. Both of is covered in XML itself - it's >> defined the tokenization and parsing, built into elementtree. So, >> elemnttree is lex _and_ yacc for XML. And if your language is written in >> XML, that's all there is to it. > > I see your point. But yacc does more: I specify a grammar, and yacc > will > reject input files that do not conform to the grammar. > Elementtree OTOH will happily accept any valid XML file, all checking > has to > implememented manually by me. > > Best regards, > Stefaan. > For an XML represented programming language, isn't the DTD (or other XML definition format) your grammar? IE. Just use an XML validator tool and you dont need to write checking. DTDs may be not enough, see other definitions tools. From cfbolz at gmx.de Wed Mar 28 12:04:30 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 28 Mar 2007 18:04:30 +0200 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <6AFD137D-BE66-4BD6-84C5-0D473FCC3377@stackless.com> References: <mailman.5685.1175032114.32031.python-list@python.org> <1175041489.368797.281750@d57g2000hsg.googlegroups.com> <460A297A.5030605@gmx.de> <6AFD137D-BE66-4BD6-84C5-0D473FCC3377@stackless.com> Message-ID: <460A920E.504@gmx.de> Hi Christian! Christian Tismer wrote: > On 28.03.2007, at 10:38, Carl Friedrich Bolz wrote: > >> Brain error on our side: the gc_pypy.dll is the dll of the Boehm >> garbage >> collector, which you would need to compile yourself (which makes >> precompiled binaries a bit useless :-) ). We updated the zip file, >> would >> you mind checking whether it works better now? > > Why can't we provide a pre-compiled binary? > Is this a license issue? We can. That's exactly what we did. Cheers, Carl Friedrich Bolz From usenet at elehack.net Thu Mar 22 20:53:34 2007 From: usenet at elehack.net (Michael Ekstrand) Date: Fri, 23 Mar 2007 01:53:34 +0100 (CET) Subject: how can I invoke a Java code? References: <1174610940.971724.206900@l75g2000hse.googlegroups.com> Message-ID: <etv8ee$6vd$1@aioe.org> On Thu, 22 Mar 2007 17:49:01 -0700, momobear wrote: > A friend of my write a Java program, and I want use it in my python > program as a module. I searched the topic in Google and find maybe the > better way is use GCJ to compile it. Is there any other way for me? the > simple and speediness choice the better. thanks. If you want to run the Java program as a separate process, you can run "java -jar TheProgram.jar". If you're wanting to interact with the code, your best option may be Jython, an implementation of Python in Java. - Michael From nobody at invalid.com Tue Mar 27 14:11:01 2007 From: nobody at invalid.com (Erik Johnson) Date: Tue, 27 Mar 2007 12:11:01 -0600 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916449.171929.138950@n76g2000hsh.googlegroups.com> <pan.2007.03.26.22.17.16.194451@REMOVE.THIS.cybersource.com.au> Message-ID: <46095e24$1@nntp.zianet.com> "Steven D'Aprano" <steve at REMOVE.THIS.cybersource.com.au> wrote in message news:pan.2007.03.26.22.17.16.194451 at REMOVE.THIS.cybersource.com.au... > Sheesh. Do Java developers go around telling everybody that Java is an > interpreted language? I don't think so. > > What do you think the "c" in ".pyc" files stands for? "Cheese"? On the contrary... Sun is very careful to make sure you understand that Java is *COMPILED*! Remember, remember, always remember: Java is COMPILED! See that: the java "compiler": javac. You have to call it explicitly when you build your Java software so that it compiles Java source code (that way Java executes really fast)!! (And don't forget, Java source is *compiled*, just like C++.) What's a JVM? Why would you need one since Java is *compiled*, remember? But seriously... I'm not a language or architecture guru. Is there any real difference between a JVM and an interpreter? I mean, I have some general feel that bytecode is a lower-level, more direct and more efficient thing to be interpreting that Java or Python source, but at the bottom level, you are still running an interpreter which is going to be (significantly?) more inefficient than executing native machine instructions directly on the CPU, right? Why is Python able to automatically compile source into bytecode on the fly (when needed) but Java still forces you to do so explicitly? I don't mean to bash Java - I think it has it's place as well, but I mean to note that Java is very carefully marketed whereas Python's image is not managed by a major, international corporation. From wgwigw at gmail.com Mon Mar 19 04:35:00 2007 From: wgwigw at gmail.com (momobear) Date: 19 Mar 2007 01:35:00 -0700 Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: <566vcfF27jlu4U1@mid.uni-berlin.de> References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> Message-ID: <1174293300.034362.282460@l75g2000hse.googlegroups.com> On Mar 19, 4:19 pm, "Diez B. Roggisch" <d... at nospam.web.de> wrote: > momobear schrieb: > > > > > hi, I am puzzled about how to determine whether an object is > > initilized in one class, anyone could give me any instructions? > > here is an example code: > > > class coffee: > > def boil(self): > > self.temp = 80 > > > a = coffer() > > if a.temp > 60: > > print "it's boiled" > > > in C++ language we must initilized a variable first, so there is no > > such problem, but in python if we don't invoke a.boil(), we will not > > get self.temp to be initilized, any way to determine if it's initilzed > > before self.temp be used. > > You want boil to be called __init__, which is python's constructor name. > Then it will be called in a statement like > > a = coffee() > > automatically. > > Diez sorry, I should add more code to implement my ideas. class coffee: def __init__(self): ''' do something here ''' def boil(self): self.temp = 80 a = coffer() if a.temp > 60: print "it's boiled" From aahz at pythoncraft.com Thu Mar 8 11:29:41 2007 From: aahz at pythoncraft.com (Aahz) Date: 8 Mar 2007 08:29:41 -0800 Subject: thread safe SMTP module References: <mailman.4616.1172878783.32031.python-list@python.org> <mailman.4644.1172997256.32031.python-list@python.org> <esf50h$9n6$1@panix3.panix.com> <mailman.4657.1173039582.32031.python-list@python.org> Message-ID: <espdll$fa9$1@panix3.panix.com> In article <mailman.4657.1173039582.32031.python-list at python.org>, Gordon Messmer <yinyang at eburg.com> wrote: >Aahz wrote: >> >> Assuming you have correctly tracked down the problem area, I would call >> that a thread bug in Python. But my experience is that you simply have >> run into a problem with the socket. I would suggest that using >> socket.setdefaulttimeout() would work just as well. > >I believe that solution, also would not work. This note is included in >the socket documentation, regarding "timeout mode": > >http://docs.python.org/lib/socket-objects.html >"A consequence of this is that file objects returned by the makefile() >method must only be used when the socket is in blocking mode; in timeout >or non-blocking mode file operations that cannot be completed >immediately will fail." > >smtplib.SMTP uses file objects when reading SMTP responses. If I used >setdefaulttimeout(), then the socket would be in timeout mode and the >above note would be applicable. Hrm. At this point, I would suggest taking discussion to python-dev; it has been too long since I looked closely at thread/socket behavior. >I am not at all above calling python's behavior a bug, except that it >seemed like a known behavior given the note in the thread documentation >regarding built-in functions that block on I/O. No, at this point I think this is neither bug nor about thread blocking on I/O. I think it's about sockets dying and the inability of sockets in blocking mode to recover. I have seen this kind of behavior in single-threaded systems. But it really needs someone who knows more than I do, and I think the first step here is to go ahead and file a bug report for tracking purposes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From bdesth.quelquechose at free.quelquepart.fr Sun Mar 11 13:36:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 11 Mar 2007 18:36:02 +0100 Subject: Best place for a function? In-Reply-To: <mailman.4868.1173469085.32031.python-list@python.org> References: <f1aa6d810703071427g4735f009m579b807aa261fe49@mail.gmail.com> <mailman.4868.1173469085.32031.python-list@python.org> Message-ID: <45f435db$0$16855$426a74cc@news.free.fr> Inyeol Lee a ?crit : > On Wed, Mar 07, 2007 at 05:27:04PM -0500, Sergio Correia wrote: > >>I'm writing a class, where one of the methods is kinda complex. The >>method uses a function which I know for certain will not be used >>anywhere else. This function does not require anything from self, only >>the args passed by the method. >> >>Where should I put the function? > > > Use staticmethod. It's a normal function with class namespace. What do you think the OP will gain from making a simple helper function a staticmethod ? Apart from extra lookup time ? From stargaming at gmail.com Sun Mar 11 15:04:50 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 11 Mar 2007 20:04:50 +0100 Subject: any better code to initalize a list of lists? In-Reply-To: <LkYIh.2513$Qw.314@newssvr29.news.prodigy.net> References: <esqc9r$cn09$1@netnews.upenn.edu> <LkYIh.2513$Qw.314@newssvr29.news.prodigy.net> Message-ID: <et1jsj$16er$1@ulysses.news.tiscali.de> Donald Fredkin schrieb: > John wrote: > > >>For my code of radix sort, I need to initialize 256 buckets. My code >>looks a little clumsy: >> >>radix=[[]] >>for i in range(255): >> radix.append([]) >> >>any better code to initalize this list? > > > radix = [[[]]*256][0] > >>> x = [[[]]*256][0] >>> x [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ... >>> x[0].append(1) >>> x [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], ... Nice one. From facundo at taniquetil.com.ar Wed Mar 7 11:08:44 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 7 Mar 2007 16:08:44 +0000 (UTC) Subject: Generator expression parenthesis mixed with function call ones References: <esmn5q$5ni$1@news2.u-psud.fr> Message-ID: <esmo28$l6a$1@sea.gmane.org> Laurent Pointal wrote: >>>> f(4,i for i in range(10)) > File "<stdin>", line 1 > SyntaxError: invalid syntax > > > Why does Python allow generator expression parenthesis to be mixed with > function call parenthesis when there is only one parameter ? For simplicity and elegant coding, so you can do something like you did at first: sum(i for i in range(10)) > IMHO this should be forbidden, usage must not be different when there is > only one parameter and when there are more parameters. The problem in your last test is that if you use more than one argument, you *must* use the parenthesis. In Py2.5 there's a better message error: >>> f(4,i for i in range(10)) File "<stdin>", line 1 SyntaxError: Generator expression must be parenthesized if not sole argument The correct way to do that is: >>> f(4,(i for i in range(10))) 4 (<generator object at 0xb7dab56c>,) Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From mail at microcorp.co.za Wed Mar 14 03:44:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 14 Mar 2007 09:44:24 +0200 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com><pan.2007.03.09.16.34.18.818584@REMOVE.THIS.cybersource.com.au><55fbgjF2492skU1@mid.individual.net><1173573654.009953.266280@30g2000cwc.googlegroups.com><7xbqj01u9c.fsf@ruckus.brouhaha.com><slrnevae8j.dr9.nick@irishsea.home.craig-wood.com><01f501c7653e$1ee8cee0$03000080@hendrik> <op.to437igfx6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <020901c7660c$b478ba00$03000080@hendrik> "Gabriel Genellina" <ga...l-py2 at yahoo.com.ar> wrote: >You can't have two different sets with four equal numbers - it's not a >very difficult thing, it's impossible to distinguish because they're >identical! >Given 4 numbers in the set, the 5th is uniquely determined. By example: >12, 3, 10, 18 *must* end with 7. The 5th number is not "random". Any >randomness analysis should include only the first 4 numbers (or any other >set of 4). >In other words, there are only 4 degrees of freedom. In the fence analogy, >you only have to choose where to place 4 poles; the 5th is fixed at the >end. Yes - the requirement of "5 random numbers" is in a sense in conflict with the requirement of "that add up to 50" - because for the fifth number, given that you have chosen the other 4, you have to "get lucky" and choose the "right one" if you are doing it randomly... What my question was about was whether some sort of cluster analysis applied to the results of repeated application of two algorithms would reveal the way in which the numbers were chosen - the first one being choose five numbers, see if they add up to 50, repeat if not, repeat till say 1000 samples generated, and the second being choose four numbers, see if they add to less than 50, repeat if not, else make the fifth the difference between the sum and 50, repeat till 1000 instances generated... Intuitively, the second one will run a LOT faster, all other things being equal, and I was simply wondering if one could tell the difference afterwards - in the first case all the numbers clearly come from the same population, while in the second case four of them do, and the fifth could possibly be from a different population, as it was "forced" to make up the difference. So I am not so very sure that the set of fifth numbers of the second run would actually be indistinguishable from that of the first. - Hendrik From lbates at websafe.com Wed Mar 14 15:27:10 2007 From: lbates at websafe.com (Larry Bates) Date: Wed, 14 Mar 2007 14:27:10 -0500 Subject: os.path.basename() - only Windows OR *nix? In-Reply-To: <mailman.5106.1173899956.32031.python-list@python.org> References: <45F843AD.6050509@gmx.net> <et9h7k$ehr$1@sea.gmane.org> <mailman.5106.1173899956.32031.python-list@python.org> Message-ID: <45F84C8E.3020106@websafe.com> Thomas Ploch wrote: > Steve Holden schrieb: >> Clearly if form['uploadfile'] is returning the client's path information >> you do have to remove that somehow before further processing, which also >> means you need to deduce what the client architecture is to correctly >> remove path data. Of course this also leaves open the question "what >> does a Mac client return?", and you might want to cater for that also. > > I tested from linux and Mac OS, and on both os.path.basename() works as > expected (since the server it runs on is a UNIX one). That brings me to > the question, how Do I a) get the cients architecture and b) send the > architecture of the client through cgi.FieldStorage()? > >> I suspect you will also find that there are at least some circumstances >> under which a Unix browser will also include path information. > > Which ones should that be? Since os.path.basename() _is_ doing the right > thing on *nix style paths (Mac OS is not different there), I cant think > of other circumstances. > > >> I presume you are looking to use the same filename that the user >> provided on the client? Does this mean that each user's files are >> stored in different directories? Otherwise it's not always a good idea >> to use filenames provided by the user for files on the server anyway. > > Yes, each User has his own directory. Files get timestamped and then put > into the corresponding directory. It is just that having > 'C:\a\very\long\path\file.ext' as a filename on the server is not nice. > > Thomas > You will need to write some Javascript and assign something to a hidden field that gets posted. Here is some Javascript to get you started: http://www.javascripter.net/faq/operatin.htm -Larry From danilo.horta at gmail.com Mon Mar 19 09:50:48 2007 From: danilo.horta at gmail.com (Horta) Date: 19 Mar 2007 06:50:48 -0700 Subject: Timeout to readline()/readlines() Message-ID: <1174312248.404607.212110@b75g2000hsg.googlegroups.com> Hi folks, Sometimes, when I do an os.popen*(), the process executed by the command hangs, and the script stops forever on the readline()/ readlines() calls. I found that I can use select, but I'm thinking... if, after a sellect() call returns, the stdout (for example) has more than one line? or if it has just some characters, no newline, and the process just hangs? I just want a readline(timeout) and readlines(timeout) like functions. Do I need to create my owns or there're already implemented? Thanks. From jantod at gmail.com Sun Mar 11 08:47:34 2007 From: jantod at gmail.com (Janto Dreijer) Date: 11 Mar 2007 05:47:34 -0700 Subject: threading and iterator crashing interpreter In-Reply-To: <mailman.4935.1173613653.32031.python-list@python.org> References: <1173609124.089611.242080@h3g2000cwc.googlegroups.com> <mailman.4935.1173613653.32031.python-list@python.org> Message-ID: <1173617253.901671.136910@q40g2000cwq.googlegroups.com> On Mar 11, 1:46 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Sun, 11 Mar 2007 07:32:04 -0300, Janto Dreijer <jan... at gmail.com> > escribi?: > > > > > I have been having problems with the Python 2.4 and 2.5 interpreters > > on both Linux and Windows crashing on me. Unfortunately it's rather > > complex code and difficult to pin down the source. > > > So I've been trying to reduce the code. In the process it's started to > > crash in different ways. I'm not sure if any of it is related. The > > following is only crashing Python 2.5 (r25:51908, Sep 19 2006, > > 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 in two different(?) > > ways. > > > ==================== > > > Using the login1() function will throw a bunch of exceptions the most > > interesting of which is: > > > Exception in thread Thread-34: > > Traceback (most recent call last): > > File "C:\Python25\lib\threading.py", line 460, in __bootstrap > > self.run() > > File "C:\Python25\lib\threading.py", line 440, in run > > self.__target(*self.__args, **self.__kwargs) > > File "Copy of scratchpad.py", line 20, in login1 > > random.choice(System.sessions).session_iter.next() > > RuntimeError: instance.__dict__ not accessible in restricted mode > > From the error message, you appear to be using some form of restricted > execution - RExec or similar. I didn't try that way, but using the normal > mode, I got this different exception instead (using login1): > > Exception in thread Thread-85: > Traceback (most recent call last): > File "c:\apps\python\lib\threading.py", line 460, in __bootstrap > self.run() > File "c:\apps\python\lib\threading.py", line 440, in run > self.__target(*self.__args, **self.__kwargs) > File "crash.py", line 20, in login1 > random.choice(System.sessions).session_iter.next() > ValueError: generator already executing > > It appears to indicate that you must syncronize the generators. > Adding a Lock object to Session appears to work OK: > > class Session: > def __init__(self): > self.lock = Lock() > self.session_iter = session_iter(self) > > def login1(): > # first interpreter > System.sessions.append(Session()) > while 1: > session = random.choice(System.sessions) > session.lock.acquire() > session.session_iter.next() > session.lock.release() > > Your login2 version does not generate any error on my PC. > > -- > Gabriel Genellina As far as I can tell I'm not running it from restricted mode explicitly. The reason I'm doing the random.choice() is so I don't have a handle ("session" in this case) that would prevent it from being garbage collected. I am not bothered by the Python-level Exceptions. I am bothered by the interpreter throwing a segfault. What I suspect is happening is the Session object is deallocated, while it still has a reference from within the iterator. It's quite difficult to reproduce these bugs consistently. You might need to run it a few times. From robert.kern at gmail.com Thu Mar 15 03:25:03 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 15 Mar 2007 02:25:03 -0500 Subject: Python eggs and openSuse 10.2 errors In-Reply-To: <1173942600.262524.196550@n59g2000hsh.googlegroups.com> References: <1173942600.262524.196550@n59g2000hsh.googlegroups.com> Message-ID: <etascj$7s1$1@sea.gmane.org> Turd Flop Down M'leg wrote: > Heyas > > So I got all hooked on python eggs at pycon, but then I got all hooked > on openSuse 10.2 (with the xgl cube and the beryl fanciness, and some > other misc debris). Unfortunately, it doesnt appear that openSuse > 10.2, which is using python 2.5, wants to play nicely with python > eggs. When I try to run `sudo python ez_setup.py`, I simply get an > error: > Downloading http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c5-py2.5.egg > error: invalid Python installation: unable to open /usr/lib/ > python2.5/config/Makefile (No such file or directory) > > The /usr/lib/python2.5/config directory didnt exist, so I tried > creating it but with no change in results. You need to install the development package for python. It should be called python2.5-devel or something similar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From z80vsvic20 at hotmail.com Wed Mar 28 02:56:36 2007 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: 27 Mar 2007 23:56:36 -0700 Subject: wxPython, Syntax highlighting Message-ID: <1175064996.150578.300170@l77g2000hsb.googlegroups.com> Hi, I am looking for wx widget that has the ability to show text, edit the text (like a TextCtrl) but also does syntax highlighting (if the text is e.g. XML or HTML). I have been looking in the latest wxPython version but I could not really find anything. Any suggestions? (I need this because my collegue who is very Java-minded can apparently do that without any problems) Kd From thinker at branda.to Wed Mar 21 09:41:44 2007 From: thinker at branda.to (Thinker) Date: Wed, 21 Mar 2007 21:41:44 +0800 Subject: encoding characters In-Reply-To: <b35f5c730703210352v3d01b10bs40ff213a3f862e9d@mail.gmail.com> References: <b35f5c730703210352v3d01b10bs40ff213a3f862e9d@mail.gmail.com> Message-ID: <46013618.4050207@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Valentina Marotto wrote: > > > The problem is about the insertion data into database. > > one of errors is: > > exceptions.UnicodeEncodeError: 'ascii' codec can't encode > characters in position 25-26: ordinal not in range(128) > > <http://baghera.crs4.it:8080/sources#tbend> help me! Thanks More information, please. For example, what DBMS are used. Snippet run into error! - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGATYX1LDUVnWfY8gRAtkgAKC9VV4GrraeL9+f3WcHuoUIvZQsLwCg4vPq qTMx1Rbr5vUGGwmO5hGn/hU= =zWkT -----END PGP SIGNATURE----- From steve at holdenweb.com Tue Mar 27 09:48:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 27 Mar 2007 09:48:25 -0400 Subject: socket read timeout In-Reply-To: <eub6un$k3d$3@nemesis.news.tpi.pl> References: <U39Oh.178798$BK1.144837@newsfe13.lga> <eub6un$k3d$3@nemesis.news.tpi.pl> Message-ID: <eub7be$3qd$1@sea.gmane.org> Jarek Zgoda wrote: > hg napisa?(a): > >> I am looking for the most efficient / cleanest way to implement a socket >> read with timeout (Windows mainly but would be great if the same code >> worked under *nix) > > Did you see http://www.timo-tasi.org/python/timeoutsocket.py ? > Note that since 2.4, I believe, sockets in the standard library allow you to specify a timeout parameter. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From pengning at kingsoft.net Sun Mar 18 00:40:06 2007 From: pengning at kingsoft.net (bruce peng) Date: Sun, 18 Mar 2007 12:40:06 +0800 Subject: How to parse the os.system() output in python References: <1174177736.241481.115150@d57g2000hsg.googlegroups.com> <mailman.5237.1174189740.32031.python-list@python.org> Message-ID: <etifo0$vj7$1@news.yaako.com> how to redirect the putput of the program to a file? thanks. "Sebastian Bassi" <sbassi at clubdelarazon.org> wrote in message news:mailman.5237.1174189740.32031.python-list at python.org... > On 17 Mar 2007 17:28:56 -0700, yinglcs at gmail.com <yinglcs at gmail.com> > wrote: >> I use os.system() to execute a system command in python. >> Can you please tell me how can I parse (in python) the output of the >> os.system() ? > > Maybe you mean to parse the output of the program you run using > os.system. If this is the case, you should redirect the putput of the > program to a file (with ">") and then parse that file. > > Best, > SB. From riko at despammed.com Thu Mar 22 17:35:53 2007 From: riko at despammed.com (Enrico 'Mc Osten' Franchi) Date: Thu, 22 Mar 2007 22:35:53 +0100 Subject: why brackets & commas in func calls can't be ommited? (maybe it couldbe PEP?) References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> <mailman.5413.1174502330.32031.python-list@python.org> <1174502836.912713.294390@y80g2000hsf.googlegroups.com> Message-ID: <1hvede4.h5flxy1cl04lkN%riko@despammed.com> <bearophileHUGS at lycos.com> wrote: > But I think in some situations Ruby allows to omit them, solving some > of the "impossibile" problems shown in this thread. This makes Ruby a > bit better than Python to create application-specific mini languages, > that are quite useful in some situations. Yes. However, Ruby parser has to resort to heuristic in many cases: <http://www.rubycentral.com/book/language.html> "When Ruby sees a name such as ``a'' in an expression, it needs to determine if it is a local variable reference or a call to a method with no parameters. To decide which is the case, Ruby uses a heuristic." In fact it is something I don't really like about Ruby (even though I find it useful in some cases). This is a 'pathological example' def a print "Function 'a' called\n" 99 end for i in 1..2 if i == 2 print "a=", a, "\n" else a = 1 print "a=", a, "\n" end end But I have to say that omitting brackets in a language such as Python or Ruby can make the code very hardly readable. The interpreter isn't the only one who has to resort to heuristic: everytime you read a name with no parenthesis you may have to go back and see whether it is a bound variable, a method (so you may have to check documentation for various modules) or an 'invalid' variable you forgot to initialize. In fact, when I'm reading code from a project I'm not familiar with, it can be quite hard in the first place. In fact most Rubyists advice to use parentheses (unless you want to achieve a DSL like effect, or in very simple cases like puts s ) The third problem I found out is related to blocks ({} and do have different precedence order). They are only syntax errors, but I find them annoying. -- blog: http://www.akropolix.net/rik0/blogs | Uccidete i filosofi, site: http://www.akropolix.net/rik0/ | tenetevi riso e forum: http://www.akropolix.net/forum/ | bacchette per voi. From daftspaniel at gmail.com Wed Mar 14 10:19:24 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: 14 Mar 2007 07:19:24 -0700 Subject: using python to visit web sites and print the web sites image to files In-Reply-To: <1173862973.001501.200090@o5g2000hsb.googlegroups.com> References: <1173684778.539755.236130@t69g2000cwt.googlegroups.com> <mailman.4978.1173719342.32031.python-list@python.org> <1173728423.775330.164470@t69g2000cwt.googlegroups.com> <1173731204.621260.192000@30g2000cwc.googlegroups.com> <1173747288.760536.60020@j27g2000cwj.googlegroups.com> <1173822266.306935.199410@o5g2000hsb.googlegroups.com> <1173862973.001501.200090@o5g2000hsb.googlegroups.com> Message-ID: <1173881964.062448.245390@y80g2000hsf.googlegroups.com> On Mar 14, 9:02 am, "imx" <xiong.xu... at gmail.com> wrote: > Cool, but does it mean that I will need .net to run the code? Yep - runtime is free though as is IronPython. For my program the license is BSD. Cheers, Davy From lucastorri at gmail.com Mon Mar 12 11:00:19 2007 From: lucastorri at gmail.com (Lucas Torri) Date: Mon, 12 Mar 2007 12:00:19 -0300 Subject: backslashes in lists In-Reply-To: <BAY126-W1035B549162BA0DFB02563D37D0@phx.gbl> References: <BAY126-W1035B549162BA0DFB02563D37D0@phx.gbl> Message-ID: <b58273130703120800x50cb7268m328ebc1459c77271@mail.gmail.com> The backslash is a key to enter especial characters, like breakline: '\n' There is two backslashes cause of this especial condition of this char, but if you try print the specific string you will see that only one backslash remain: print alist[2] On 3/12/07, Fabio Gomes <flgoms at hotmail.com> wrote: > > Hi list, > > I'm trying to use a string with backslashes in a list. But Python parses > strings in lists with repr(). > > > >>> alist = ['a', 'b', 'c:\some\path'] > >>> alist > ['a', 'b', 'c:\\some\\path'] > >>> print alist > ['a', 'b', 'c:\\some\\path'] > > > I already tried str() and raw (r) but it didn't work. All I want is to > keep a single backslash in the string since it is a path information. > > Can anyone help me, please? > > Thank you. > > ------------------------------ > O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na > Web e sua rede amigos. Confira! <http://spaces.live.com/signup.aspx> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070312/cf606f54/attachment.html> From harlinseritt at yahoo.com Fri Mar 23 09:48:20 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 Mar 2007 06:48:20 -0700 Subject: Catching an unknown error In-Reply-To: <1174657346.379483.72200@e1g2000hsg.googlegroups.com> References: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> <1174657346.379483.72200@e1g2000hsg.googlegroups.com> Message-ID: <1174657700.265254.292590@n59g2000hsh.googlegroups.com> On Mar 23, 9:42 am, kyoso... at gmail.com wrote: > On Mar 23, 8:16 am, "Harlin Seritt" <harlinser... at yahoo.com> wrote: > > > > > Using the code below: > > > ---BEGIN CODE--- > > > value = raw_input("Type a divisor: ") > > try: > > value = int(value) > > print "42 / %d = %d" % (value, 42/value) > > except ValueError: > > print "I can't convert the value to an integer" > > except ZeroDivisionError: > > print "Your value should not be zero" > > except: > > print "Something unexpected happened" > > > ---END CODE--- > > > In the last 'except' block, how can I print out the particular error > > name even though one is not specifically named? > > > Thanks, > > > Harlin > > Thanks for pointing that out. I was following logic I was taught in > Hetland's book, which supposedly was up-to-date for Python 2.4. > Typical textbook error. > > Mike Thanks guys... that gets 'er done. Harlin Seritt From steve at holdenweb.com Thu Mar 22 22:24:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 22:24:44 -0400 Subject: Idiom for running compiled python scripts? In-Reply-To: <pan.2007.03.23.01.01.15@mailinator.com> References: <pan.2007.03.21.00.37.14@mailinator.com> <pan.2007.03.23.01.01.15@mailinator.com> Message-ID: <etvds6$hpv$1@sea.gmane.org> Mark wrote: > So given the lack of response it seems that there is probably no such > idiom and that I should not be concerned by the inefficiency inherent in > running .py scripts directly? > > I did some time tests and sure, the speed gain is slight, but it is a > gain none the less. Sorry, what you really need is the compileFile() function from the compiler module. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From alainpoint at yahoo.fr Tue Mar 27 04:39:35 2007 From: alainpoint at yahoo.fr (alain) Date: 27 Mar 2007 01:39:35 -0700 Subject: SPE question Message-ID: <1174984775.810988.145060@p77g2000hsh.googlegroups.com> Hi, Could someone tell me how to uninstall SPE under windows? Alain From nick at craig-wood.com Fri Mar 9 08:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 09 Mar 2007 07:30:08 -0600 Subject: 2 new comment-like characters in Python to aid development? References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <slrnev2cl1.vc0.nick@irishsea.home.craig-wood.com> <45f138ee$0$23918$426a74cc@news.free.fr> <m11wjyy7p5.fsf@chezmarshall.freeserve.co.uk> Message-ID: <slrnev2m9v.179.nick@irishsea.home.craig-wood.com> Robert Marshall <spam at chezmarshall.freeserve.co.uk> wrote: > On Fri, 09 Mar 2007, Bruno Desthuilliers wrote: > > > > > Nick Craig-Wood a ?crit : > >> dbhbarton at googlemail.com <dbhbarton at googlemail.com> wrote: > >>> What if 2 new 'special' comment-like characters were added to > >>> Python?: > >>> > >>> > >>> 1. The WIP (Work In Progress) comment: > >> > >> I use # FIXME for this purpose or /* FIXME */ in C etc. > >> > >> I have an emacs macro which shows it up in bright red / yellow text > >> so it is easy to see > > > > <ot> > > Care to share this macro ? > > </ot> > > I have this > > (cond (window-system > (progn > (font-lock-add-keywords > 'python-mode '(("\\<FIXME: .*$" 0 font-lock-warning-face prepend)))))) This is what I use which is very similar (font-lock-add-keywords 'python-mode '( ("\\<\\(FIXME\\):?" 1 font-lock-warning-face prepend) ) ) -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From mboldin_2000 at yahoo.com Sun Mar 4 09:26:42 2007 From: mboldin_2000 at yahoo.com (Michael Boldin via alt email) Date: Sun, 4 Mar 2007 06:26:42 -0800 (PST) Subject: IDLE & MySQLdb import error Message-ID: <158410.47599.qm@web30812.mail.mud.yahoo.com> I installed python 2.5 and used the win package for installing MySQLdb. (I am running Windows XP) Everything works as expected using python directly (Windows command shell) but using IDLE gives the import error below. Same error with PythonWin as my IDE and everything works using python 2.4-- with IDLE and without, mySQLdb is loaded with out error. Below is the IDLE screen capture Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2 >>> import MySQLdb Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import MySQLdb File "C:\Python25\lib\site-packages\MySQLdb\__init__.py", line 19, in <module> import _mysql ImportError: DLL load failed: The specified procedure could not be found. >>> It seems that when using IDLE the _mysql package can not be found although the path is the same as non-IDLE python and help('modules') shows _mysql is an available. Is this an IDLE or MySQLdb bug or some incorrect settign on my side ____________________________________________________________________________________ Looking for earth-friendly autos? Browse Top Cars by "Green Rating" at Yahoo! Autos' Green Center. http://autos.yahoo.com/green_center/ From olsonas at gmail.com Wed Mar 14 11:30:27 2007 From: olsonas at gmail.com (Drew) Date: 14 Mar 2007 08:30:27 -0700 Subject: dict.items() vs dict.iteritems and similar questions Message-ID: <1173886227.609832.170540@l75g2000hse.googlegroups.com> When is it appropriate to use dict.items() vs dict.iteritems. Both seem to work for something like: for key,val in mydict.items(): print key,val for key,val in mydict.iteritems(): print key,val Also, when is it appropriate to use range() vs xrange(). From my understanding, xrange() essentially gives you an iterator across a range, so it should be used when iterating. Should you only use range() when want to physically store the range as a list? Thanks, Drew From mail at microcorp.co.za Fri Mar 2 01:29:00 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 2 Mar 2007 08:29:00 +0200 Subject: How to Read Bytes from a file References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com><1172757183.819978.219440@v33g2000cwv.googlegroups.com><1172764725.827624.298180@j27g2000cwj.googlegroups.com><1172771161.015437.50000@n33g2000cwc.googlegroups.com> <1172774172.389220.124170@j27g2000cwj.googlegroups.com> Message-ID: <015601c75c94$10af7d40$03000080@hendrik> <gregpinero at gmail.com> wrote: > Thanks Bart. That's perfect. The other suggestion was to precompute > count1 for all possible bytes, I guess that's 0-256, right? 0 to 255 inclusive, actually - that is 256 numbers... The largest number representable in a byte is 255 eight bits, of value 128,64,32,16,8,4,2,1 Their sum is 255... And then there is zero. - Hendrik From luismgz at gmail.com Fri Mar 2 18:48:03 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 2 Mar 2007 15:48:03 -0800 Subject: class declaration shortcut In-Reply-To: <1172878142.169464.161690@31g2000cwt.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172878142.169464.161690@31g2000cwt.googlegroups.com> Message-ID: <1172879283.545209.100480@j27g2000cwj.googlegroups.com> On Mar 2, 8:29 pm, "MonkeeSage" <MonkeeS... at gmail.com> wrote: > On Feb 28, 1:26 pm, "Luis M. Gonz?lez" <luis... at gmail.com> wrote: > > > I've come across a code snippet inwww.rubyclr.comwhere they show how > > easy it is to declare a class compared to equivalent code in c#. > > I wonder if there is any way to emulate this in Python. > > I posted like 10 minutes ago, but it looks like it didn't go through. > The ruby code is not an easy way to declare a class, it is a ruby > class for creating c-like struct objects. > > This is the basic idea behind the ruby Struct class (but this is quick > and dirty, the real implementation is different and done in c, but you > should get the basic idea): > > class Struct2 > def initialize(*args) > @@attrs = [] > args.each { |arg| > eval("class << self; attr_accessor :#{arg} end") > @@attrs.push(arg) > } > end > def new(*args) > args.each_index { |i| > eval("self.#{@@attrs[i]}=args[i]") > return self > } > end > end > > Person = Struct2.new(:name) > bob = Person.new('bob') > puts bob.name > > A python equiv. would be something like: > > class Struct(): > def __init__(self, *args): > self.attrs = [] > for arg in args: > setattr(self, arg, None) > self.attrs.append(arg) > def __call__(self, *args): > for i in range(len(args)): > setattr(self, self.attrs[i], args[i]) > return self > > Person = Struct('name') > bob = Person('bob') > print bob.name > > Regards, > Jordan Thanks for your detailed reply! So after all, the www.rubyclr.com code is not a fair comparison. Because the c# code shows a class definition, and the ruby code shows a struct definition, which is not equivalent to a class. Is that right? From stefaan.himpe at gmail.com Mon Mar 19 15:32:47 2007 From: stefaan.himpe at gmail.com (stefaan) Date: 19 Mar 2007 12:32:47 -0700 Subject: XML based programming language In-Reply-To: <567h7sF287idqU1@mid.uni-berlin.de> References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> <56786fF2743atU2@mid.uni-berlin.de> <1174307748.936567.191440@e1g2000hsg.googlegroups.com> <567h7sF287idqU1@mid.uni-berlin.de> Message-ID: <1174332767.221788.252460@l77g2000hsb.googlegroups.com> > All of these are grammar-specifications that allow you to define the > structure of your XML-documents with more constraints. Ok, I should have foreseen the schema checker answer...my point really is that yacc can do even more than just checking the conformance to a grammar. It also allows me to specify semantic actions, e.g. to help in building an abstract syntax tree from the concrete syntax tree, or to implement a very basic interpreter... mock example: <input><definevar name="a" value="10"/><definevar name="b" value="12" / ></input> <output><sum arg1="a" arg2="b"/></output> No schema checker can take this specification and simply output "22". XSLT might be able to implement it, but it is complex for anything real-life. Elementtree can immediately give me the concrete syntax tree, but any semantic actions have to be implemented during a manually programmed tree traversal. Anyway, it is not urgent for me, I have something which works, it just seems like something's missing still from the existing XML tool collection. Or I am being thick-headed ;) From hq4ever at gmail.com Mon Mar 12 07:29:03 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Mon, 12 Mar 2007 13:29:03 +0200 Subject: programmatically manipulation environment variables of the calling shell In-Reply-To: <F217FCE7-18E0-495D-A2E9-87D28F15224C@comhem.se> References: <b400c69a0703120333m5565c233laaf1247ed8fb5601@mail.gmail.com> <F217FCE7-18E0-495D-A2E9-87D28F15224C@comhem.se> Message-ID: <b400c69a0703120429o6bb5612fmf56a8a034fbb1b32@mail.gmail.com> On 3/12/07, Tommy Nordgren <tommy.nordgren at comhem.se> wrote: > > On 12 mar 2007, at 11.33, Maxim Veksler wrote: > > > Hello list, > > > > I'm trying to write a python script that would allow me to manipulate > > shell variables of the calling shell. I'm trying to write some logic > > that would know to add LD_LIBRARY_PATH to the users environment. > > > > In bash this is done with "export", can I do this with python? (If at > > all possible because python is actually a sub process of bash). > > > > Thank you, > > Maxim. > This is not possible to do directly. > There is however a possibility to solve this problem under special > circumstances. > 1. Your python (/perl/shell/etc) script must write the wanted > environment > variables to standard out, as key-value pairs with a suitable separator. > 2. The invoking shell must agree with your script as to what > separator is used. > 3. In the calling shell do myshellvars=`your_python_script`; > 4. Now the calling shell can parse the variable myshellvars to set > up the environment. Yes, thats exactly what I was set to do. <<< bash for export_val in $(python env_variables_maxim.py); do export $export_val; done >>> <<< python (env_variables_maxim.py) print 'FOO=123 BAR=/home/src:$BAR PATH=/nfs/bin' >>> Thank you. > ------ > What is a woman that you forsake her, and the hearth fire and the > home acre, > to go with the old grey Widow Maker. --Kipling, harp song of the > Dane women > Tommy Nordgren > tommy.nordgren at comhem.se > > > > -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From reply at group.invalid Sat Mar 31 04:13:05 2007 From: reply at group.invalid (Pom) Date: Sat, 31 Mar 2007 08:13:05 GMT Subject: wx textctrl font style Message-ID: <lKoPh.95364$Kd.480300@phobos.telenet-ops.be> Hello I have a tuple of strings which I must show in a textctrl, each item in the tuple representing one line of text. The first three lines of text should each have another style (fontsize and color) i'm using this code to achieve this: tmppos = self.txtInfo.GetInsertionPoint() # get the cursor pos self.txtInfo.write(str(csr[0])+'\n') tmppos2 = self.txtInfo.GetInsertionPoint() # get the new cursor pos self.txtInfo.SetStyle(tmppos, tmppos2, wx.TextAttr("BLUE", wx.NullColour, tmpnewfont)) self.txtInfo.write(str(csr[1])+'\n') tmppos3 = self.txtInfo.GetInsertionPoint() # get the new cursor pos self.txtInfo.SetStyle(tmppos2, tmppos3, wx.TextAttr("BLUE", wx.NullColour, tmpnewfont2)) self.txtInfo.write(str(csr[2])+'\n') tmppos4 = self.txtInfo.GetInsertionPoint() # get the new cursor pos self.txtInfo.SetStyle(tmppos3, tmppos4, wx.TextAttr(wx.Nullcolour, wx.NullColour, tmpnewfont3)) Now, I was wondering if this is the right way of doing this, because I have the feeling this code sucks. Anybody has a better way of doing this? Thx !!! From nagle at animats.com Wed Mar 21 20:17:07 2007 From: nagle at animats.com (John Nagle) Date: Thu, 22 Mar 2007 00:17:07 GMT Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: <etscd5$g0g$1@news.onet.pl> References: <ets9hc$74f$1@news.onet.pl> <pan.2007.03.21.22.28.43.880478@REMOVE.THIS.cybersource.com.au> <etscd5$g0g$1@news.onet.pl> Message-ID: <7WjMh.318$YL5.80@newssvr29.news.prodigy.net> Marcin Ciura wrote: > Neither would I. I must have expressed myself not clearly enough. > Currently > x = y = z > is roughly equivalent to > x = z > y = z > I propose to change it to > y = z > x = z Actually, it is equivalent to y = z x = y > Python performs chained assignments backwards compared to other languages... C and C++ are both right-to-left, like Python. In Pascal, Modula I/II/III, and Ada, assignments are not expressions, so it's not a meaningful question there. John Nagle From jstroud at mbi.ucla.edu Thu Mar 22 23:05:41 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Mar 2007 20:05:41 -0700 Subject: Been a while... In-Reply-To: <4602a1be$0$32400$c3e8da3@news.astraweb.com> References: <4602a1be$0$32400$c3e8da3@news.astraweb.com> Message-ID: <etvg65$bdp$3@daisy.noc.ucla.edu> John Salerno wrote: > Hi guys. It's been a while since I've used Python, so I got a little > rusty, but I really want to start using it again, just out of habit and > for fun. Can anyone suggest a book or a website with little projects I > could work on to keep me busy? > > (I do have Beginning Python with the 10 projects in the back, but those > might be a little too involved for me right now.) > > Thanks! > John Hawk this list and try to pick off easy answers before anyone else. That's what I do. The pressure is to be right, because if you're not, you hear about it in a hurry. James From malaclypse2 at gmail.com Thu Mar 1 08:56:40 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 1 Mar 2007 08:56:40 -0500 Subject: Python Tutorial In-Reply-To: <19269e540703010533u329b2ac2sa82e5e219d7c98f5@mail.gmail.com> References: <19269e540703010533u329b2ac2sa82e5e219d7c98f5@mail.gmail.com> Message-ID: <16651e80703010556w1e110c77l7c4a4f4e8a9b9aa9@mail.gmail.com> On 3/1/07, Timm Florian Gloger <timm.gloger at gmail.com> wrote: > is Guido van Rossum's "Python Tutorial" in non-HTML formats (e.g. PDF > or PS) avaiable for free? Yes. Download one of the PDF documentation zips from here: http://docs.python.org/download and extract the tut.pdf file. AFAIK it's not available as a seperate download. -- Jerry From nospam at nospam.com Thu Mar 22 00:36:10 2007 From: nospam at nospam.com (Mark T) Date: Wed, 21 Mar 2007 21:36:10 -0700 Subject: Python 3000 idea: reversing the order of chained assignments References: <ets9hc$74f$1@news.onet.pl> <pan.2007.03.21.22.28.43.880478@REMOVE.THIS.cybersource.com.au> <etscd5$g0g$1@news.onet.pl> <7WjMh.318$YL5.80@newssvr29.news.prodigy.net> <1hvcadb.134pbvp1y39wi3N%aleax@mac.com> Message-ID: <DvGdnQacTuMlmp_bnZ2dnUVZ_uWdnZ2d@comcast.com> "Alex Martelli" <aleax at mac.com> wrote in message news:1hvcadb.134pbvp1y39wi3N%aleax at mac.com... > John Nagle <nagle at animats.com> wrote: > >> Marcin Ciura wrote: >> >> > Neither would I. I must have expressed myself not clearly enough. >> > Currently >> > x = y = z >> > is roughly equivalent to >> > x = z >> > y = z >> > I propose to change it to >> > y = z >> > x = z >> >> Actually, it is equivalent to >> >> y = z >> x = y > > Not really: > >>>> class chatty(object): > ... def __init__(self): self.__dict__['__hide'] = {} > ... def __setattr__(self, name, value): > ... print 'sa', name, value > ... self.__dict__['__hide'][name] = value > ... def __getattr__(self, name): > ... print 'ga', name > ... return self.__dict__['__hide'].get(name) > ... >>>> c = chatty() >>>> x = c.zop = 23 > sa zop 23 >>>> > > As you can see, there is no read-access to c.zop, which plays the role > of y there. > > > Alex This is interesting: >>> class Test(object): ... def __getattribute__(self,n): ... print 'reading',n ... return object.__getattribute__(self,n) ... def __setattr__(self,n,v): ... print 'writing',n,v ... return object.__setattr__(self,n,v) ... >>> x=Test() >>> x.a=1; x.b=2; x.c=3 writing a 1 writing b 2 writing c 3 >>> x.a=x.b=x.c reading c writing a 3 writing b 3 >>> I wouldn't have expected "a" to be assigned first in a right-to-left parsing order. The result is the same in any case. -Mark T. From http Wed Mar 7 20:41:26 2007 From: http (Paul Rubin) Date: 07 Mar 2007 17:41:26 -0800 Subject: Flatten a two-level list --> one liner? References: <mailman.4778.1173312889.32031.python-list@python.org> Message-ID: <7xk5xs341l.fsf@ruckus.brouhaha.com> "Sergio Correia" <sergio.correia at gmail.com> writes: > 2) Reduce > eggs = reduce(lambda x, y: x+y, spam) > > I feel the 1st way is too cumbersome (three lines), and although I > like the 2nd way (except for the lambda part), I understand reduce is > discouraged by Guido so I want to know if there is a "Better Way"(TM) > ? I thought map/reduce were considered ok again, but the above runs in quadratic time, not good. I'd use: eggs = list(itertools.chain(*spam)) From tjreedy at udel.edu Sun Mar 4 02:20:33 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Mar 2007 02:20:33 -0500 Subject: are there any "Piecewise Cubic Hermite Interpolating Polynomial" inpython References: <1172960724.090104.187690@z35g2000cwz.googlegroups.com> Message-ID: <esdrvv$l3$1@sea.gmane.org> "jitasi" <steven.ge at gmail.com> wrote in message news:1172960724.090104.187690 at z35g2000cwz.googlegroups.com... | Hi all | | I want to use the matlab function "pchip" in python. | I have checked the scipy, but there is only spline Interpolating. | Are there any pchip Interpolating in python? Putting p.. c.. h.. i.. p... Python into Google gives 165 results. Have you checked any? From admin at loial.co.uk Sat Mar 31 08:59:20 2007 From: admin at loial.co.uk (loial) Date: 31 Mar 2007 05:59:20 -0700 Subject: Need help with python and pyxml on AIX Message-ID: <1175345960.078897.167410@e65g2000hsc.googlegroups.com> I have been asked to install a python application on AIX 5.3 that runs OK on Windows I have installed Python 4.2.2 from python.org and pyXML form sourceforge. However when I run the application I get the following error : class xml.sax._exceptions.SAXReaderNotAvailable Do I need to set some Python environment variables? Can I test the availibility of this from the python command line. e.g import something? I am new to Python From rmcore at gmail.com Mon Mar 12 13:08:51 2007 From: rmcore at gmail.com (Michael Bentley) Date: Mon, 12 Mar 2007 12:08:51 -0500 Subject: using python to visit web sites and print the web sites image to files In-Reply-To: <1173684778.539755.236130@t69g2000cwt.googlegroups.com> References: <1173684778.539755.236130@t69g2000cwt.googlegroups.com> Message-ID: <4E8BEE8F-6D5B-44A4-B2D6-A771AD7BDB21@gmail.com> > > I wonder whether python can be used to simulate a real user to do the > following: > 1) open a web site in a browser; > 2) printscreen, so to copy the current active window image to > clipboard; > 3) save the image file to a real file > > Any pointer will be apprieciated! Which OS? From paul at boddie.org.uk Thu Mar 1 08:40:43 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Mar 2007 05:40:43 -0800 Subject: installing "pysqlite" In-Reply-To: <1172749563.834987.197840@z35g2000cwz.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> <1172663495.011225.76410@v33g2000cwv.googlegroups.com> <1172741654.589821.255220@v33g2000cwv.googlegroups.com> <1172745997.863121.96940@8g2000cwh.googlegroups.com> <1172749563.834987.197840@z35g2000cwz.googlegroups.com> Message-ID: <1172756443.839448.327280@h3g2000cwc.googlegroups.com> On 1 Mar, 12:46, "Nader" <n.em... at gmail.com> wrote: > > ldd returens the next result: > ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so > linux-gate.so.1 => (0xffffe000) > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x40040000) > libc.so.6 => /lib/tls/libc.so.6 (0x40050000) I think you pasted the nm result in here, but you seem to be missing libsqlite3.so.0 (from what I see myself). From what I've just read about linux-gate.so, the linker can't seem to find the SQLite libraries. More on linux-gate.so here: http://www.trilithium.com/johan/2005/08/linux-gate/ > and the 'nm' gives this: > > nm usr/people/emami/lib/libsqlite3.so | grep sqlite3_set_authorize > 0000ce40 T sqlite3_set_authorizer That looks alright. > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) I guess this was the end of the ldd result. I'm out of ideas, unfortunately. I think you should experiment with LD_LIBRARY_PATH and run ldd again to see if you can get it to show libsqlite3.so.0. The pysqlite mailing list might be the best place to ask for help if that doesn't work. Sorry! Paul From g.brandl at gmx.net Wed Mar 28 16:27:38 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Wed, 28 Mar 2007 22:27:38 +0200 Subject: Question about extending tuple In-Reply-To: <1175112084.430548.275000@b75g2000hsg.googlegroups.com> References: <1175110340.415385.58340@e65g2000hsc.googlegroups.com> <mailman.5721.1175111042.32031.python-list@python.org> <1175112084.430548.275000@b75g2000hsg.googlegroups.com> Message-ID: <euej3r$upt$1@sea.gmane.org> abcd schrieb: >> As an immutable type, tuple makes use of __new__. >> >> class MyTuple(tuple): >> def __new__(cls, *args): >> return tuple.__new__(cls, args) >> >> should work. >> >> Georg > > strange. not very consistent. On the contrary -- __new__ *and* __init__ exist for all types. The only difference is where a specific object is initialized, and therefore which method you have to override. __new__ is a static method (it doesn't need to be declared as one, this is done automatically as it predates the introduction of staticmethod()) which is called to *construct* an instance. This can only be done once for a specific object since each call to __new__ will result in a *new* object. In other words, this is perfect for immutable objects -- once created, never changed. __init__, OTOH, is called on the *instance* to initialize it. Of course, this process can be repeated, and is therefore apt for mutable objects like lists. I hope you see now why it is consistent. Georg From simon at brunningonline.net Wed Mar 14 06:45:05 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 14 Mar 2007 10:45:05 +0000 Subject: Attribute monitoring in a class In-Reply-To: <45F7CF5F.7090005@gmail.com> References: <45F7CF5F.7090005@gmail.com> Message-ID: <8c7f10c60703140345t66d37738q99aa705a54df44db@mail.gmail.com> On 3/14/07, Joel Andres Granados <joel.granados at gmail.com> wrote: > I have googled quite a bit on this matter and I can't seem to find what > I need (I think Im just looking where I'm not suppose to :). I'm > working with code that is not of my authorship and there is a class > attribute that is changes by directly referencing it (object.attr = > value) instead of using a getter/setter (object.setAttr(Value) ) > function. The thing is that I have no idea when the change occurs and I > would REALLY like to find out. > So here comes my question ..... > Is there a function construct inside a python class that is > automatically called when an attr is changed???? You want __setttr__(). See <http://docs.python.org/ref/attribute-access.html>. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning MSN: small_values From israphelr at googlemail.com Tue Mar 13 18:54:24 2007 From: israphelr at googlemail.com (israphelr at googlemail.com) Date: 13 Mar 2007 15:54:24 -0700 Subject: Problem I have with a while loop/boolean/or In-Reply-To: <NIWdnbz1EMIkt2rYnZ2dnUVZ_o6gnZ2d@comcast.com> References: <1173825244.368771.273720@e1g2000hsg.googlegroups.com> <NIWdnbz1EMIkt2rYnZ2dnUVZ_o6gnZ2d@comcast.com> Message-ID: <1173826464.713183.47530@y66g2000hsf.googlegroups.com> On Mar 13, 10:50 pm, Larry Bates <lba... at websafe.com> wrote: > israph... at googlemail.com wrote: > > Hi all. > > > I have a problem with some code :( > > > ----------- > > > hint = raw_input("\nAre you stuck? y/n: ") > > hint = hint.lower() > > > while (hint != 'n') or (hint != 'y'): > > hint = raw_input("Please specify a valid choice: ") > > > --------------------------------------------- > > > so everytime I run the program, and enter my choice as y or n, I'm > > told to 'Please Specify a valid Choice Again' and can't get out of the > > loop. > > > ----------- > > > hint = raw_input("\nAre you stuck? y/n: ") > > hint = hint.lower() > > > while (hint != 'n'): > > hint = raw_input("Please specify a valid choice: ") > > > --------------------------------------------- > > > As for here when I enter n, I can leave the while loop. > > > Anyway I can't put my finger on this, so I'd be real grateful if > > someone could tell me what I've done wrong. Thanks. > > (I have a guy feeling it's something really silly I'm overlooking...) > > Your if test is wrong. > > If hint='n' > > hint !='n' is False > hint !='y' is True > > False or True equals True > > I think you want something like: > > hint = raw_input("\nAre you stuck? y/n: ") > hint = hint.lower() > > while hint not in ['y', 'n']: > hint = raw_input("Please specify a valid choice: ") > > -Larry Thanks Larry. From duncan.booth at invalid.invalid Fri Mar 30 10:19:06 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Mar 2007 14:19:06 GMT Subject: Indentation for code readability References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> Message-ID: <Xns99039BD4762EFduncanbooth@127.0.0.1> "DE" <devrim.erdem at gmail.com> wrote: > Here is what I do in C++ and can not right now in python : > > pushMatrix() > { > drawStuff(); > > pushMatrix(); > { > drawSomeOtherStuff() > } > popMatrix(); > } > popMatrix(); > If I understand this contortion is because you have some sort of stack and you want the code to follow the depth as you push and pop things from the stack. If you write this in Python then when drawSomeOtherStuff() throws an exception your 'stack' will get messed up, so you'll need to add some more code to handle this. Using Python 2.5 this is the sort of thing you should end up with (and you'll notice that your indentation appears naturally when you do this): from __future__ import with_statement from contextlib import contextmanager # Dummy functions so this executes def pushMatrix(arg): print "pushMatrix", arg def popMatrix(arg): print "popMatrix", arg def drawStuff(): print "drawStuff" def drawSomeOtherStuff(): print "drawSomeOtherStuff" # The matrix stack implemented as a context handler. @contextmanager def NewMatrixContext(arg): pushMatrix(arg) try: yield finally: popMatrix(arg) # and finally the function to actually draw stuff in appropriate # contexts. def fn(): with NewMatrixContext(1): drawStuff() with NewMatrixContext(2): drawSomeOtherStuff() fn() From aleax at mac.com Thu Mar 15 10:50:44 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 15 Mar 2007 07:50:44 -0700 Subject: Returning other instance from __init__ References: <1173933158.948806@jubilee.claranet.pt> <1huzkla.i6dshw1grnysmN%aleax@mac.com> <1173958589.875188.203900@y80g2000hsf.googlegroups.com> Message-ID: <1hv0amj.14r0m02if7iblN%aleax@mac.com> Paul Boddie <paul at boddie.org.uk> wrote: ... > > > class C1: > > > def __init__(self,xxx): ... > > Use __new__ for such purposes, not __init__. (You need to make C1 > > newstyle, e.g. inherit from object, to make special method __new__ > > work). > > Call me a traditionalist, but why wouldn't a factory function be good > enough? That depends on whether you need name C1 to refer to a class, or not. If you want name C1 to be usable outside this module as a class (to subclass it, use with isinstance or issubclass, be available to an IDE's classbrowser or other means of introspection including pydoc, etc), then making name C1 refer to a function instead would not work. > Or perhaps seeing more special methods and decorators just puts me in > a grumpy mood. ;-) For me, the power of Python is derived from being > able to do things like making callables "constructors" whilst > providing some illusion that C1 (in this case) is a class. For me, OTOH, it's not just smoke and mirrors (or as you say "illusion"), there's also plenty of real power, and __new__ is part of that. (Decorators however are just handy syntax -- they let you avoid repeating one name three times, and avoiding repetition is a good thing, but their real power is essentially that of higher-order-functions that could of course be used with other syntax if need be). Alex From danb_83 at yahoo.com Sun Mar 11 12:04:51 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Mar 2007 09:04:51 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> Message-ID: <1173629090.993914.55570@30g2000cwc.googlegroups.com> On Mar 11, 9:31 am, "Mark Dickinson" <dicki... at gmail.com> wrote: > I get the following behaviour on Python 2.5 (OS X 10.4.8 on PowerPC, > in case it's relevant.) > > >>> x, y = 0.0, -0.0 > >>> x, y > (0.0, 0.0) > >>> x, y = -0.0, 0.0 > >>> x, y > > (-0.0, -0.0) > > I would have expected y to be -0.0 in the first case, and 0.0 in the > second. Should the above be considered a bug, or is Python not > expected to honour signs of zeros? I'm working in a situation > involving complex arithmetic where branch cuts, and hence signed > zeros, are important, and it would be handy if the above code could be > relied upon to do the right thing. IIRC, float.__repr__ just does whatever libc does. Have you tried using printf("%g, %g", 0.0, -0.0) in a C program? From mark at mailinator.com Sun Mar 25 03:10:23 2007 From: mark at mailinator.com (Mark) Date: 25 Mar 2007 07:10:23 GMT Subject: Idiom for running compiled python scripts? References: <pan.2007.03.21.00.37.14@mailinator.com> <pan.2007.03.23.01.01.15@mailinator.com> <pan.2007.03.23.03.03.11.268638@REMOVEME.cybersource.com.au> <pan.2007.03.23.07.30.56@mailinator.com> <1174746081.436526.64360@l75g2000hse.googlegroups.com> <pan.2007.03.24.22.59.05@mailinator.com> <pan.2007.03.25.03.40.32.158357@REMOVE.THIS.cybersource.com.au> Message-ID: <pan.2007.03.25.07.10.22@mailinator.com> On Sun, 25 Mar 2007 13:40:33 +1000, Steven D'Aprano wrote: > Because this is entirely a trivial saving. Who cares? Sheesh. > ... > Saving 18ms on a script that takes 50ms to execute *might* be > worthwhile, ... I don't understand your attitude. Sure, we are talking slight savings in machine efficiency but I am sure the python developers have laboured many long hours on subtle optimisations of the virtual machine, many of which probably dwarf the issue discussed here. Tell them their work is trivial and unnecessary. Every little bit helps. Why do I concern myself with this inefficiency - because it is there. Of course I realise the modern mantra that "premature optimisation is the root of all evil" but I don't subscribe to it. Programmers have been "encouraged" to not give a toss about efficiency and the outcome is all too apparent - most software today looks and runs like a pile of crap. From nagle at animats.com Sun Mar 4 12:24:15 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Mar 2007 17:24:15 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again In-Reply-To: <45eab67a@news.vo.lu> References: <yTtGh.5001$M65.1427@newssvr21.news.prodigy.net> <45eab67a@news.vo.lu> Message-ID: <3hDGh.5963$jx3.2552@newssvr25.news.prodigy.net> Patrick Useldinger wrote: > http://www.serpentine.com/blog/2006/12/22/how-to-build-safe-clean-python-25-rpms-for-fedora-core-6/ I've read that. It's very funny. "Now you?ll need to go into the SOURCES directory and frob a single file..." It does have something very useful in it - Python's 2.5's dependency list: sudo yum install autoconf bzip2-devel db4-devel \ expat-devel findutils gcc-c++ gdbm-devel glibc-devel gmp-devel \ libGL-devel libX11-devel libtermcap-devel ncurses-devel \ openssl-devel pkgconfig readline-devel sqlite-devel tar \ tix-devel tk-devel zlib-devel If a Python build needs all that, something in ./configure should be checking for each of those. After all, that's what ./configure is supposed to be for. It looks like a Python install will plow ahead without ncurses-devel, and install a dud version. (Why is "make install" doing compiles, anyway? It should just be copying. "make" is supposed to do all the compiles.) This, though, illustrates exactly what I was talking about - there is no off the shelf way to install Python 2.5 on Fedora Core 6. Others have worked through this and documented their pain and how to do it manually, but that's not the same as fixing the packaging problem. Debian tries to deal with this problem. See http://www.debian.org/doc/packaging-manuals/python-policy/index.html But Fedora Core does not. Perl, PHP, C, C++, and Java don't have this particular problem. Python stands alone, out in the cold. John Nagle From bj_666 at gmx.net Thu Mar 29 14:02:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 29 Mar 2007 20:02:32 +0200 Subject: encoding confusions References: <eugrkh$7n7$1@foggy.unx.sas.com> Message-ID: <pan.2007.03.29.18.02.31.821534@gmx.net> In <eugrkh$7n7$1 at foggy.unx.sas.com>, Tim Arnold wrote: > I have the contents of a file that contains French documentation. > I've iterated over it and now I want to write it out to a file. > > I'm running into problems and I don't understand why--I don't get how the > encoding works. > My first attempt was just this: > < snipped code for classes, etc; fname is string, codecs module loaded.> > < self.contents is the French file's contents as a single string > What is the type of `self.contents`, `str` or `unicode`? You *decode* strings to unicode objects and you *encode* unicode objects to strings. It doesn't make sense to encode a string in 'latin-1' because it must be decoded first and the "automatic" decoding assumes ASCII and barfs if there's something non-ascii in the string. Ciao, Marc 'BlackJack' Rintsch From rbutler at mtsu.edu Sat Mar 24 19:51:34 2007 From: rbutler at mtsu.edu (Ralph Butler) Date: Sat, 24 Mar 2007 18:51:34 -0500 Subject: question about C extensions Message-ID: <B4WdnWF575o3JJjbnZ2dnUVZ_vOlnZ2d@comcast.com> Hi: I have a question about extending python with C. I have read the docs and done some googling, but come up short on this particular (small) problem. I want to write a c extension to int. In particular, I want to grab the memory for the int from an alternative heap. I am confused about 2 things: (1) Do I need to call the __init__ function for int itself, and if so, how do I do that? (2) Do I supply my own tp_alloc function to retrieve the memory for my new elements, and if so, what should it look like? (Assume for the moment that I simply plan to do a malloc.) I have attached code that does most of the work and has my initials (RMB) at a couple of the pieces of code I think I may need. Any pointers to fairly specific examples would be appreciated. I have found non-specific examples a bit confusing. Thanks. --ralph -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: setup.py URL: <http://mail.python.org/pipermail/python-list/attachments/20070324/ccdbf59e/attachment.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: t1.py URL: <http://mail.python.org/pipermail/python-list/attachments/20070324/ccdbf59e/attachment-0001.ksh> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: intext.c URL: <http://mail.python.org/pipermail/python-list/attachments/20070324/ccdbf59e/attachment.c> From maxerickson at gmail.com Tue Mar 13 17:41:33 2007 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 13 Mar 2007 21:41:33 +0000 (UTC) Subject: help!! *extra* tricky web page to extract data from... References: <1173819262.288501.66350@n76g2000hsh.googlegroups.com> Message-ID: <Xns98F2B3F4E3A7maxericksongmailcom@80.91.229.5> "seberino at spawar.navy.mil" <seberino at spawar.navy.mil> wrote: > How extract the visible numerical data from this Microsoft > financial web site? > > http://tinyurl.com/yw2w4h > > If you simply download the HTML file you'll see the data is *not* > embedded in it but loaded from some other file. > > Surely if I can see the data in my browser I can grab it somehow > right in a Python script? > > Any help greatly appreciated. > > Sincerely, > > Chris > The url for the data is in an iframe. If you need to scrape the original page for some reason(instead of iframe url directly), you can use urlparse.urljoin to resolve the relative url. max From bearophileHUGS at lycos.com Thu Mar 8 06:04:38 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Mar 2007 03:04:38 -0800 Subject: property syntax In-Reply-To: <mailman.4797.1173349253.32031.python-list@python.org> References: <1173346452.096798.215970@t69g2000cwt.googlegroups.com> <mailman.4797.1173349253.32031.python-list@python.org> Message-ID: <1173351878.314596.252030@30g2000cwc.googlegroups.com> Gabriel Genellina: > You miss this common way, that does not depend on metaclasses, > nor base classes, nor custom decorators... My purpose was to discuss a new syntax. The other stuff is mostly for reference, to show that lot of (some) people has tried to find alternative solutions to a problem they feel. > The only drawback is the "deprecated" I can see other drawbacks: you have to use an explicit doc = "..." instead of a normal docstring, and you have to remember to put return property(**locals()) at its end. I don't know if your version is compatible with Psyco (I presume it's compatible). And I think all those solutions can't be subclassed like I have shown in the altenative syntax (but maybe you can find a way to modify the metaclass version to allow this too). Bye and thank you, bearophile From cjlesh at gmail.com Wed Mar 21 11:16:39 2007 From: cjlesh at gmail.com (cjl) Date: 21 Mar 2007 08:16:39 -0700 Subject: difference between urllib2.urlopen and firefox view 'page source'? In-Reply-To: <mailman.5377.1174459814.32031.python-list@python.org> References: <mailman.5377.1174459814.32031.python-list@python.org> Message-ID: <1174490199.317770.168760@l77g2000hsb.googlegroups.com> Group: Thank you for all the informative replies, they have helped me figure things out. Next up is learning beautiful soup. Thank you for the code example, but I am trying to learn how to 'screen scrape', because Yahoo does make historical stock data available using the CSV format, but they do not do this for stock options, which is what I am ultimately attempting to scrap. Here is what I have so far, I know how broken and ugly it is: import urllib2, sys from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://finance.yahoo.com/q/op?s=" + sys.argv[1]) soup = BeautifulSoup(page) print soup.find("table",{"id" :"yfncsubtit"}).big.b.contents[0] This actually works, and will print out the current stock price for whatever ticker symbol you supply as the command line argument when you launch this script. Later I will add error checking, etc. Any advice on how I am using beautiful soup in the above code? thanks again, cjl From steven.bethard at gmail.com Thu Mar 1 14:37:42 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Mar 2007 12:37:42 -0700 Subject: class declaration shortcut In-Reply-To: <1172772214.569734.95990@n33g2000cwc.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172748388.475530.57570@k78g2000cwa.googlegroups.com> <YJudnezV_r1DZXvYnZ2dnUVZ_hGdnZ2d@comcast.com> <1172772214.569734.95990@n33g2000cwc.googlegroups.com> Message-ID: <xemdnYBwM6UetnrYnZ2dnUVZ_qarnZ2d@comcast.com> Arnaud Delobelle wrote: > On Mar 1, 4:01 pm, Steven Bethard <steven.beth... at gmail.com> wrote: >> Arnaud Delobelle wrote: > [...] >> This does pretty much the same thing as the recipe I posted: > > Not at all. My new_struct create returns a new class which is similar > to a C struct (notice the __slots__). The recipe you refer to is > nothing more a class which can be initialised with some attributes. It > does not address the OP's question at all. > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 Huh? It uses __slots__ in almost exactly the same way. If you just s/Struct/Record in your ``new_struct`` function, you'll get essentially the same behavior, except that if you use the recipe, you'll get an __init__ that handles positional arguments, and displays better help:: >>> def new_struct(name, *slots): ... return type(name, (Struct,), {'__slots__': slots}) ... >>> Person = new_struct('Person', 'name') >>> Person('Bob') Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: __init__() takes exactly 1 argument (2 given) >>> Person(name='Bob') Person(name='Bob') >>> help(Person.__init__) Help on method __init__ in module __main__: __init__(self, **vals) unbound __main__.Person method >>> def new_struct(name, *slots): ... return type(name, (Record,), {'__slots__': slots}) ... >>> Person = new_struct('Person', 'name') >>> Person('Bob') Person(name='Bob') >>> help(Person.__init__) Help on method __init__: __init__(self, name) unbound records.Person method Maybe I'm not understanding you? Steve From martin.laloux at gmail.com Tue Mar 27 07:37:31 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 27 Mar 2007 04:37:31 -0700 Subject: plot dendrogram with python In-Reply-To: <1174995101.750777.117860@b75g2000hsg.googlegroups.com> References: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> <1174995101.750777.117860@b75g2000hsg.googlegroups.com> Message-ID: <1174995450.988349.106810@y80g2000hsf.googlegroups.com> I use pycluster http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/cluster/software.htm#pycluster From http Wed Mar 7 23:28:45 2007 From: http (Paul Rubin) Date: 07 Mar 2007 20:28:45 -0800 Subject: Bug in python!? persistent value of an optional parameter in function! References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> <7xfy8gqwof.fsf@ruckus.brouhaha.com> <NcLHh.5653$M65.1389@newssvr21.news.prodigy.net> <pan.2007.03.08.04.07.49.661894@REMOVEME.cybersource.com.au> Message-ID: <7xejo0bbpe.fsf@ruckus.brouhaha.com> Steven D'Aprano <steve at REMOVEME.cybersource.com.au> writes: > def factorial(n, _cache={}): > try: > return _cache[n] > except KeyError: > There are other ways of implementing caches, but this is quick and easy > and works well for many functions. I like this better (examples are untested): def factorial(n): try: return factorial.cache[n] except KeyError: pass ... factorial.cache = {} you could even use a decorator: def memoize(f): # memoize a 1-arg function f.cache = {} def g(f,x): if x in f.cache: return f.cache[x] return f.cache.setdefault(x, f(x)) return functools.partial(g,f) ... @memoize def factorial(n): return 1 if n==0 else n*factorial(n-1) From steve at REMOVE.THIS.cybersource.com.au Thu Mar 29 01:08:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 29 Mar 2007 15:08:56 +1000 Subject: Modal value of an array References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> Message-ID: <pan.2007.03.29.05.08.55.936109@REMOVE.THIS.cybersource.com.au> On Wed, 28 Mar 2007 20:40:22 -0700, datta.abhirup at gmail.com wrote: > Hi > > How can I find out the modal value in an array. That is the value > which occurs maximum time in the sequence .. > > e.g. if my array has values like [2,3,2,2,2,4,2,2] definitely the > maximum time 2 occurs in the array. so this function should be able to > return 2 as a result .. > > So is there any function in built in python which can do that ? No. You need to create a frequency table, then do a reverse-lookup on the frequency table. Assuming your data is small, this should be plenty fast enough. def mode(data): # create a frequency table freq = {} for x in data: freq[x] = freq.get(x, 0) + 1 # find the maximum frequency F = max(freq.values()) # return the items (one or more) with that frequency modes = [] for x, f in freq.items(): if f == F: modes.append(x) return modes >>> mode([2,3,2,2,2,4,2,2]) [2] >>> mode([2,3,2,3,2,3,4,1]) [2, 3] -- Steven. From luismgz at gmail.com Thu Mar 1 15:21:53 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Mar 2007 12:21:53 -0800 Subject: class declaration shortcut In-Reply-To: <1172772214.569734.95990@n33g2000cwc.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172748388.475530.57570@k78g2000cwa.googlegroups.com> <YJudnezV_r1DZXvYnZ2dnUVZ_hGdnZ2d@comcast.com> <1172772214.569734.95990@n33g2000cwc.googlegroups.com> Message-ID: <1172780513.838701.136340@j27g2000cwj.googlegroups.com> On Mar 1, 3:03 pm, "Arnaud Delobelle" <arno... at googlemail.com> wrote: > On Mar 1, 4:01 pm, Steven Bethard <steven.beth... at gmail.com> wrote: > > > Arnaud Delobelle wrote: > [...] > > This does pretty much the same thing as the recipe I posted: > > Not at all. My new_struct create returns a new class which is similar > to a C struct (notice the __slots__). The recipe you refer to is > nothing more a class which can be initialised with some attributes. It > does not address the OP's question at all. > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > > > Note that your approach requires repetition of the 'Person' and quotes > > around each attribute name, which the OP complained about. The recipe at > > least gets rid of the repetition of 'Person'. > > The 'name' argument is not necessary. It is just here to give a user- > friendly name to the newly created class. > One could just as well write the new_struct function so that > > >>> Person = new_struct('name', 'tel', ...) > > Of course it would be impossible for the function written as above to > name the class in a user-meaningful way. The recipe you refer to does > not face this problem because it is not a method to quickly create a > new class, it is merely a class whose __init__ method allows you to > initialise some attribute at instance-creation time. > > As for the quotes around the attribute names, well... Let's say that > if it was possible to do without, I don't think I would be using > python... > > -- > Arnaud This is the closest we got so far to the intended result. If there was a way to enter attributes without quotes, it would be almost identical. Anyway, I wonder if the code comparison in www.rubuclr.com between the c# and ruby code is fair... As far as I know, classes and structs are not the same thing. In the case of that ruby example, can someone add methods later? Luis From __peter__ at web.de Fri Mar 2 06:15:10 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Mar 2007 12:15:10 +0100 Subject: float64 print digits References: <mailman.4601.1172832473.32031.python-list@python.org> Message-ID: <es90t3$1u7$03$1@news.t-online.com> Ulrich Dorda wrote: [Warning: I'm no expert and don't have numpy installed] > I need a pytho nscript to read numbers(with loads of digits) from a > file, do some basic math on it and write the result out to another file. > > My problem: I don't get python to use more digits: > > In order to try this I type: > > The normal precision one: > >>> from numpy import * > >>> x=1.23456789123456789123456789 > >>> print "%35.25e" %x > 1.2345678912345679000000000e+000 > > > Now I try to use float64 to get more digits > > >>> z=zeros(3,float64) > >>> z[0] > 0.0 > >>> type(z[0]) > <type 'numpy.float64'> > >>> z[0]=1.23456789123456789123456789 The right side of the assignment is a float, so the extra digits would already be lost before you get a chance to convert to float64. But then Python's float is a C double and should already use 64 bits... > >>> type(z[0]) > <type 'numpy.float64'> > >>> print "%35.25e" %z[0] > 1.2345678912345679000000000e+000 > > This cuts the digits just like the 32bit case. > > Can anyone please help me get more digits? gmpy? Peter From pibizza at gmail.com Wed Mar 14 10:14:11 2007 From: pibizza at gmail.com (PaoloB) Date: 14 Mar 2007 07:14:11 -0700 Subject: Mocking OpenOffice in python? In-Reply-To: <mailman.5083.1173881058.32031.python-list@python.org> References: <1173861553.036985.74670@p15g2000hsd.googlegroups.com> <1173880102.3459.26.camel@dot.uniqsys.com> <mailman.5083.1173881058.32031.python-list@python.org> Message-ID: <1173881651.879253.206580@p15g2000hsd.googlegroups.com> On 14 Mar, 14:52, Shane Geiger <sgei... at ncee.net> wrote: > My take was that this is an effort to manipulate these files without the > need for Open Office, so I replied as follows: > > Open Office files (.ods and perhaps .odt) are just zipped or gzipped. > Unpack that and then you are dealing with manipulating regular text > files--probably HTML. No. What I was trying was to build a fake OpenOffice server, so that we could interact with a fake OpenOffice during our unit test. As OpenOffice is quite slow, this could improve the performance of our unit tests. However, your suggestion is interesting. Ciao PaoloB From bblais at bryant.edu Mon Mar 5 08:33:27 2007 From: bblais at bryant.edu (Brian Blais) Date: Mon, 05 Mar 2007 08:33:27 -0500 Subject: CherryPy + Database questions Message-ID: <45EC1C27.3090106@bryant.edu> Hello, I have more of a conceptual question about the way databases work, in a web framework, but I will be implementing things with CherryPy and SQLAlchemy. If you make a web form that adds rows to a database, and use sqlite as the engine, is there a danger of a race condition if several users at the same time try to submit the form? I want a unique row id, and make a unique identifier for the submissions. Am I in danger of having multiple submissions given the same identifier? I know that if I implemented things without a database, but used a flat file or something like it, I would have that possibility, when two processes try to read and update the file at the same time. If you want something more specific, I can throw some code together, but I wanted to get an answer before that because it will change the way I develop the code. thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From exarkun at divmod.com Thu Mar 1 09:20:05 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Mar 2007 09:20:05 -0500 Subject: How to update DNS record In-Reply-To: <1172751262.972242.215990@p10g2000cwp.googlegroups.com> Message-ID: <20070301142005.17852.868262670.divmod.quotient.1386@ohm> On 1 Mar 2007 04:14:23 -0800, andi.clemens at gmx.net wrote: >On Mar 1, 10:33 am, Bjoern Schliessmann <usenet- >mail-0306.20.chr0n... at spamgourmet.com> wrote: >> Read RFC 2136 (Dynamic updates in the DNS) and see if your server >> can be configured to do this. If not, you'll have to change the >> zone files manually and reload the DNS config. > >It worked before with a perl script, but now I'm using django for all >our web services so I want to implement this update function in Python >as well. >I don't know how to do this in Python, right now I'm trying it with >twisted, but I don't what to do exactly. It would be nice if somebody >has an example for doing this. > You need to provide more details. There is no one way to change the configuration of a DNS server. Different servers have different features and different interfaces. A start would be to specify which DNS server software needs to be reconfigured. You might also want to include an example of what kind of change you want to make. For example, do you want to add and delete records? Do you want to change the address of associated with an existing A record? Are all your changes in a single zone? etc. Jean-Paul From sreisscruz at gmail.com Tue Mar 13 14:53:24 2007 From: sreisscruz at gmail.com (Steve) Date: 13 Mar 2007 11:53:24 -0700 Subject: Setting Up SOAPpy for Python v2.5 on Windows? Message-ID: <1173812004.428519.195560@s48g2000cws.googlegroups.com> Hi All, What are the required version of the SOAPpy, PyXML, fpconst that are needed to run under the Python 2.5 environment on Windows? Locations for the downloads? Thanks! Steve From kyosohma at gmail.com Mon Mar 26 13:37:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 10:37:21 -0700 Subject: how to abort on syntax errors In-Reply-To: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> References: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <1174930640.724685.72160@y80g2000hsf.googlegroups.com> On Mar 26, 12:21 pm, "Josh" <n... at nowhere.com> wrote: > I have a lot of except Exception, e statements in my code, which poses some > problems. One of the biggest is whenever I refactor even the triviallest > thing in my code. > > I would like python to abort, almost as if it were a compile-time error, > whenever it cannot find a function, or if I introduced a syntax error. But, > instead, it merrily proceeds on its way. > > Is there some idiom that you use in situations like these? > thanks, > josh Try sticking in an try: #do something except SyntaxError, e: print e sys.exit(0) except Exception, e: print e # You put in as many exceptions as you like. Mike From NunezD at gmail.com Thu Mar 15 23:56:02 2007 From: NunezD at gmail.com (hiro) Date: 15 Mar 2007 20:56:02 -0700 Subject: python noob, multiple file i/o Message-ID: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> Hi there, I'm very new to python, the problem I need to solve is whats the "best/ simplest/cleanest" way to read in multiple files (ascii), do stuff to them, and write them out(ascii). -- import os filePath = ('O:/spam/eggs/') for file in os.listdir(filePath): #straight from docs # iterate the function through all the files in the directory # write results to separate files <- this is where I'm mostly stuck. -- For clarity's sake, the file naming conventions for the files I'm reading from are file.1.txt -> file.nth.txt It's been a long day, i'm at my wits end, so I apologize in advance if I'm not making much sense here. syntax would also be great if you can share some recipes. Thanks in advance. h. From codecraig at gmail.com Fri Mar 2 13:01:51 2007 From: codecraig at gmail.com (abcd) Date: 2 Mar 2007 10:01:51 -0800 Subject: pyHook or SetWindowsHookEx In-Reply-To: <1172684780.613003.30350@z35g2000cwz.googlegroups.com> References: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> <1172684780.613003.30350@z35g2000cwz.googlegroups.com> Message-ID: <1172858511.262384.121670@j27g2000cwj.googlegroups.com> :( From soyrush at gmail.com Sat Mar 24 19:42:50 2007 From: soyrush at gmail.com (Rodrigo Lopez-Negrete) Date: 24 Mar 2007 16:42:50 -0700 Subject: "persistent" plot windows Message-ID: <1174779770.134013.256280@b75g2000hsg.googlegroups.com> Hi all, I'm trying to write a python script using plotting form pylab. Unfortunatelly I've encountered a problem. When I run the script via 'python myscript.py' the plot windows open and close very quickly, or when I added the show() command the shell window was locked until I closed the figures. My question is: is there a way to open those windows in the background without blocking the shell and without running it interactively?? something like gnuplot -persist? Thanks all, Rodrigo Lopez-Negrete From hg at nospam.org Tue Mar 27 10:45:11 2007 From: hg at nospam.org (hg) Date: Tue, 27 Mar 2007 16:45:11 +0200 Subject: socket read timeout References: <U39Oh.178798$BK1.144837@newsfe13.lga> <eub6un$k3d$3@nemesis.news.tpi.pl> <mailman.5668.1175003334.32031.python-list@python.org> Message-ID: <VegOh.15507$nh4.13055@newsfe20.lga> Steve Holden wrote: > Jarek Zgoda wrote: >> hg napisa?(a): >> >>> I am looking for the most efficient / cleanest way to implement a socket >>> read with timeout (Windows mainly but would be great if the same code >>> worked under *nix) >> >> Did you see http://www.timo-tasi.org/python/timeoutsocket.py ? >> > Note that since 2.4, I believe, sockets in the standard library allow > you to specify a timeout parameter. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Recent Ramblings http://holdenweb.blogspot.com Hi and thanks to all. Do you mean use select ? Thanks, hg From gagsl-py2 at yahoo.com.ar Wed Mar 7 18:21:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 20:21:44 -0300 Subject: Calling a function with unknown arguments? References: <1173308108.239943.174560@j27g2000cwj.googlegroups.com> Message-ID: <op.touduik0x6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 07 Mar 2007 19:55:08 -0300, Rob <crowell at mit.edu> escribi?: > I can get a list of a function's arguments. >>>> def bob(a, b): > ... return a+b > ... >>>> bob.func_code.co_varnames > ('a', 'b') > > Let's say that I also have a dictionary of possible arguments for this > function. >>>> possible = {'a':10, 'b':5, 'c':-3} > > How do I proceed to call bob(a=10, b=5) with this information? You're almost done. Notice that co_varnames includes local variables too; only the first co_argcount are positional arguments. If you only want to deal with positional arguments (no *args, no **kw): py> def bob(a,b): ... c = a+b ... return c ... py> bob.func_code.co_varnames ('a', 'b', 'c') py> bob.func_code.co_argcount 2 py> args = dict((name, possible[name]) for name in bob.func_code.co_varnames[:bo b.func_code.co_argcount] if name in possible) py> args {'a': 10, 'b': 5} py> bob(**args) 15 It can handle missing arguments (if they have a default value, of course): py> def bob(a, k=3): ... return a+k ... py> args = dict((name, possible[name]) for name in bob.func_code.co_varnames[:bo b.func_code.co_argcount] if name in possible) py> args {'a': 10} py> bob(**args) 13 -- Gabriel Genellina From anton.vredegoor at gmail.com Wed Mar 14 12:24:16 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 14 Mar 2007 17:24:16 +0100 Subject: number generator In-Reply-To: <7xps7bbz8g.fsf@ruckus.brouhaha.com> References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> <pan.2007.03.09.15.32.01.112493@gmx.net> <1173515984.515050.27400@n33g2000cwc.googlegroups.com> <1173861843.878008.83090@p15g2000hsd.googlegroups.com> <7xps7bbz8g.fsf@ruckus.brouhaha.com> Message-ID: <et9cji$bfs$2@news4.zwoll1.ov.home.nl> Paul Rubin wrote: >> def genpool(n, m): >> if n == 1: >> yield [m] >> else: >> for i in xrange(1, m): >> for rest in genpool(n-1, m-i): >> yield rest + [i] >> >> import random >> print random.choice(list(genpool(n=4, m=20))) > > This generates a lot of the partitions more than once, with > possibly unequal probability. Well, I just noticed that with my memoization function it produces too little :-( But I hope you notice that this function doesn't create only partitions but all possible outcomes? A. From mccredie at gmail.com Thu Mar 15 19:22:32 2007 From: mccredie at gmail.com (Matimus) Date: 15 Mar 2007 16:22:32 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> Message-ID: <1174000951.999433.149760@n59g2000hsh.googlegroups.com> > Any ideas to speed it up say 10 times? Or the problem only for C-like > langs? I dout this will speed it up by a factor of 10, but in your solution you are mapping the values in the input file to longs. The problem statement states that the maximum value for any of the numbers is 2**28. I assume the reason for this is precisely to allow you to use 32-bit integers. So, you can safely use int instead, and it _might_ speed up a little. From bdesth.quelquechose at free.quelquepart.fr Thu Mar 8 15:23:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Mar 2007 21:23:15 +0100 Subject: Where to "import"? In-Reply-To: <1173379952.901004@iceman.esoterica.pt> References: <1173379952.901004@iceman.esoterica.pt> Message-ID: <45f068a2$0$18256$426a74cc@news.free.fr> Paulo da Silva a ?crit : > Hi! > > If I have two files .py such as > > m.py > from c import * avoid this kind of import except in an interactive interpreter and eventually in a package __init__.py. Better to use either: from c import c or import c ... x = c.c() > ... > x=c() > ... > os.any_method ... Then you need to import os > ... > > c.py > class c: class C(object): 1/ better to stick to naming conventions (class names in CamelCase) 2/ do yourself a favor: use new-style classes > def __init__(self, ...): > ... > os.any_method ... > ... > ... > > both using os module where should I put the "import os"? In both files? Yes. In your above example, it worked because of the "from c import *" - and this is exactly why it's bad form to use this in a module (well: that's one of the reasons why). Each module should *explicitly* import all it's direct dependencies. From johnpenk7 at yahoo.com Mon Mar 26 12:35:51 2007 From: johnpenk7 at yahoo.com (jp) Date: 26 Mar 2007 09:35:51 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: <1174926471.899631.228810@e65g2000hsc.googlegroups.com> References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> <1174925855.552135.228190@n59g2000hsh.googlegroups.com> <1174926471.899631.228810@e65g2000hsc.googlegroups.com> Message-ID: <1174926951.133085.294900@l75g2000hse.googlegroups.com> On Mar 26, 11:27 am, kyoso... at gmail.com wrote: > On Mar 26, 11:17 am, kyoso... at gmail.com wrote: > > > On Mar 26, 10:51 am, "jp" <johnpe... at yahoo.com> wrote: > > > > I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > > > I skip over these widgets when using the tab key? > > > > Thank you, > > > John > > > I would probably write some custom event handling. Something that > > could tell it was a key-press event and not just an on-focus event. > > Then it would be a simple, if key-press == tab, put focus on next #> > widget of interest. Something like that should work. > > > Mike > > I looked in my Tkinter book, and it says that if the widget has the > "takefocus" option set to true, the widget is placed in the tab group > and will get focus when they are tabbed to. I assume that this means > if you set the PMW widgets' "takefocus" option to false, they will be > skipped over since they won't be in the tab group. > > Mike I've tried using the takefocus option set to 0 and 1 but either way, the tab key still stops at my EntryField. Below is my snippet of code. What am I doing wrong? entry=Pmw.EntryField(frame, labelpos = 'w', value = "", label_text = 'Name:') entry.grid(row=1) #entry.component('entry').takefocus = 1 entry.component('entry').takefocus = 0 From bbxx789_05ss at yahoo.com Fri Mar 16 15:15:33 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Mar 2007 12:15:33 -0700 Subject: TypeError: 'module' object is not callable In-Reply-To: <1174066969.563803.216040@p15g2000hsd.googlegroups.com> References: <1174066969.563803.216040@p15g2000hsd.googlegroups.com> Message-ID: <1174072533.834956.46310@b75g2000hsg.googlegroups.com> Hi, I can't find any documentation on the profile() function. But it might take a function reference as an argument and not the string you are feeding it. For instance: profile(t.printworld) Note the difference between: t.printworld t.printworld() The latter executes the function and then replaces the function call with the return value of the function. From skip at pobox.com Sun Mar 4 16:38:57 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Mar 2007 15:38:57 -0600 Subject: identifying modules to be built and not Message-ID: <17899.15473.620236.302603@montanaro.dyndns.org> The thread John Nagle started about building Python 2.5 on Fedora Core 6 led me to implement a slight change to Python's setup.py. You clearly can't have the build stop if the bits needed to build a particular module aren't found or if compiling a module fails, but it's fairly straightforward to note which modules could be built and which can't be. There's a patch for setup.py on SourceForge you can try if you want: http://python.org/sf/1673619 When setup.py is run it emits output like this after checking for modules it knows how to build (this is from my Mac): Located the necessary bits to build these modules: _AE _AH _App _bisect _bsddb _CarbonEvt _CF _CG _Cm _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _Ctl _ctypes _ctypes_test _curses _curses_panel _Dlg _Drag _elementtree _Evt _File _Fm _Folder _functools _hashlib _heapq _Help _hotshot _IBCarbon _Icn _Launch _List _locale _lsprof _Menu _Mlte _multibytecodec _OSA _Qd _Qdoffs _Qt _random _Res _Scrap _Snd _socket _sqlite3 _ssl _struct _TE _testcapi _tkinter _weakref _Win array audioop autoGIL binascii bsddb185 bz2 cmath ColorPicker cPickle crypt cStringIO datetime dbm dl fcntl gestalt grp icglue imageop itertools MacOS math mmap Nav nis operator OSATerminology parser pwd pyexpat readline resource rgbimg select strop syslog termios time unicodedata Failed to find the necessary bits to build these modules: _elementtree _md5 _sha _sha256 _sha512 gdbm linuxaudiodev ossaudiodev spwd Feel free to add comments to the above patch page. It will help the development team decide whether or not it's a worthwhile addition. Skip From yinglcs at gmail.com Thu Mar 22 14:43:36 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 22 Mar 2007 11:43:36 -0700 Subject: How can I tar each sub-directories inside a directory Message-ID: <1174589016.152380.161990@n76g2000hsh.googlegroups.com> Hi, how can I do * for each sub-directory of the current directory * tar that to a tar file * remove that sub-directory From gigs at hi.t-com.hr Tue Mar 20 12:46:05 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 20 Mar 2007 17:46:05 +0100 Subject: P: maticna graficka monitor In-Reply-To: <etp33d$gcf$1@ss408.t-com.hr> References: <etp33d$gcf$1@ss408.t-com.hr> Message-ID: <etp34f$gcf$2@ss408.t-com.hr> Gigs_ wrote: > prodajem: > > maticnu sapphire am2rd580adv, pola god stara, pod garancijom -> 700kn > > graficku sapphire x1650 pro 256 mb pola god start pod garancijom -> 600kn > > monitor philips 190p6es brilliance (kostao 4.100), star 1.5 godinu > garancija vrijedi jos 1.5 godinu -> 2000kn sorry wrong group From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 19 10:39:49 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 15:39:49 +0100 Subject: Still the __new__ hell ... In-Reply-To: <mailman.5278.1174308102.32031.python-list@python.org> References: <mailman.5278.1174308102.32031.python-list@python.org> Message-ID: <45fea0b3$0$15544$426a74cc@news.free.fr> Jean-Paul Calderone a ?crit : > On Mon, 19 Mar 2007 13:17:11 +0100, Bruno Desthuilliers >> >> [snip] >> >> And what if it's a unicode string ? >> The correct idiom here is: >> if isinstance(year, basestring): >> >>> year,month,day=map(int,string.split(year,'-')) >> year, month, day = map(int, year.split('-')) > > And what if it's another kind of string? One that doesn't inherit from basestring ? > The correct idiom is: > > try: > parts = year.split('-') > except AttributeError: > # Handle int case > else: > year, month, day = map(int, parts) > >> >>> if year < 100: >>> year += 2000 >>> return date.__new__(cls,year,month,day) >>> And what if it's an object that has nothing to do with a string but happens to have a split() method ?-) >> (snip) Jean-Paul, you're of course right from a theoretical POV. Practically speaking, chances that such a method will ever be fed with a string-like object not deriving from basestring are IMVHO *very* low. While I usually raise a big warning flag when I spot a test against isinstance(), I'd say this is an example of the few cases where it's ok. YMMV of course... From bj_666 at gmx.net Thu Mar 1 17:11:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 01 Mar 2007 23:11:26 +0100 Subject: Unpacking problem References: <1172783865.479377.42790@h3g2000cwc.googlegroups.com> Message-ID: <pan.2007.03.01.22.11.25.463928@gmx.net> In <1172783865.479377.42790 at h3g2000cwc.googlegroups.com>, Chris Garland wrote: > But an unsigned char & a short give me this >>>> unpack('Bh','\x90\x06\x00') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > struct.error: unpack str size does not match format Let's pack this: In [90]: pack('Bh', 0x90, 0x6) Out[90]: '\x90\x00\x06\x00' Per default the values are (un)packed with the preferred alignment of the C compiler, so here is an extra byte to place the short at an even address. If you give the endianess in the format string there's no padding: In [91]: pack('<Bh', 0x90, 0x6) Out[91]: '\x90\x06\x00' Ciao, Marc 'BlackJack' Rintsch From mikael at isy.liu.se Thu Mar 8 11:27:19 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 08 Mar 2007 17:27:19 +0100 Subject: Tell me the truth In-Reply-To: <OFA0A2DBF6.794F6BB0-ONC1257298.00415F42-C1257298.0053864B@bureauveritas.com> References: <OFA0A2DBF6.794F6BB0-ONC1257298.00415F42-C1257298.0053864B@bureauveritas.com> Message-ID: <45F03967.9020309@isy.liu.se> francois.petitjean at bureauveritas.com wrote: > If I take into account the fact that 'True' and 'False' are singletons > (guaranteed ?) : > (not not x) is bool(x) # should be always True. > [snip code and results of code] > Consider the following: >>> def ok1(x): return (not not x) is bool(x) >>> def ok2(x): return (not not x) is bool(x) is True >>> def ok3(x): return ok1(x) is True >>> def ok4(x): return ((not not x) is bool(x)) is True >>> def ok5(x): return ((not not x) is bool(x)) and (bool(x) is True) >>> for x in [False, True]: print x,ok1(x), ok2(x), ok3(x), ok4(x), ok5(x) False True False True True False True True True True True True Note that ok2(x) and ok5(x) exhibit the same behaviour. HTH /MiO From chimalus at gmail.com Fri Mar 30 21:17:19 2007 From: chimalus at gmail.com (jd) Date: 30 Mar 2007 18:17:19 -0700 Subject: clean up html document created by Word In-Reply-To: <1175275249.200620.76590@o5g2000hsb.googlegroups.com> References: <1175275249.200620.76590@o5g2000hsb.googlegroups.com> Message-ID: <1175303839.299837.260780@e65g2000hsc.googlegroups.com> Wow, thanks for all the great responses! Here's my summary: - demoronizer (from John Walker) is designed to solve some very particular problems that could be considered bugs. However, it doesn't remove the unnecessary html generated by Word. http://www.fourmilab.ch/webtools/demoroniser/ - The tool from Microsoft can be used in two ways: you can copy html to the clipboard or export to "compact html". The former results in slightly cleaner html but doesn't include the style sheet and so the rendering isn't as nice; the latter does include the style sheet but it's got slightly more junk in it. Both approaches preserve the "blank" paragraphs (basically, <p> </p>) for spacing, which is unnecessary and clutters up the html. This tool did properly preserve the footnotes in my test document. http://www.microsoft.com/downloads/details.aspx?FamilyID=209ADBEE-3FBD-482C-83B0-96FB79B74DED&displaylang=EN BTW, I didn't know this, but much of the extra html was added by Microsoft to allow round-tripping between html and Word. - Tidy with Win2000 configuration: It's already bundled in with my editor (PSPad) so this was a nice surprise (I guess I never explored that submenu -- that's the "problem" with modern editors and their zillions of features). The tidy output could use a more whitespace to improve html readability, but I assume I can change the config file to do this. No "blank paragraphs" (better than the Microsoft tool) but footnotes were messed up. http://www.w3.org/People/Raggett/tidy/ -- jeff From rdm at rcblue.com Sat Mar 17 03:51:13 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 17 Mar 2007 00:51:13 -0700 Subject: Weekly Python Patch/Bug Summary In-Reply-To: <200703170454.l2H4skKe003172@bayview.thirdcreek.com> References: <200703170454.l2H4skKe003172@bayview.thirdcreek.com> Message-ID: <20070317075121.565D11E4005@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070317/2609bf9a/attachment.html> From gagsl-py2 at yahoo.com.ar Tue Mar 6 01:38:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Mar 2007 03:38:56 -0300 Subject: This web site creates a *popup window* => how fetch contents in a script? References: <1173161903.046347.192300@j27g2000cwj.googlegroups.com> Message-ID: <op.toq8q6gsx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 06 Mar 2007 03:18:23 -0300, seberino at spawar.navy.mil <seberino at spawar.navy.mil> escribi?: > The following web page puts a report in a *popup window* by clicking > the "Generate Report" button.... > > http://moneycentral.msn.com/investor/research/printrep.asp?Symbol=BBBY > > How can I grab this pop window page in a python script? (It doesn't > seem to have a URL!?!) Of course it has: http://moneycentral.msn.com/investor/research/sreport.asp?Symbol=BBBY&Y1=1&CR=1&Type=Equity If your browser don't let you know the actual URL... try a better browser :) -- Gabriel Genellina From paul.rudin at ntlworld.com Sat Mar 24 05:12:12 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Sat, 24 Mar 2007 09:12:12 +0000 Subject: execution speed increase after compile py code into exe? References: <mailman.5544.1174724418.32031.python-list@python.org> Message-ID: <871wjfyphv.fsf@rudin.co.uk> Kelie <kf9150 at gmail.com> writes: > hello, > > would there be any speed increase in code execution after python code being > compiled into exe file with py2exe? AIUI that's not what p2yexe is about - it's essentially about packaging up your python program for ease of distribution and installation on windows boxes. However, you might find that you can get significant speed-ups by using psyco <http://psyco.sourceforge.net/>, on x386 type hardware at least. From attn.steven.kuo at gmail.com Fri Mar 2 10:22:05 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 2 Mar 2007 07:22:05 -0800 Subject: Matplotlib axes label In-Reply-To: <1172847759.727020.281300@p10g2000cwp.googlegroups.com> References: <1172790626.088267.303150@j27g2000cwj.googlegroups.com> <1172814815.385543.180040@j27g2000cwj.googlegroups.com> <1172815638.950663.198040@t69g2000cwt.googlegroups.com> <1172847759.727020.281300@p10g2000cwp.googlegroups.com> Message-ID: <1172848925.223085.277440@n33g2000cwc.googlegroups.com> On Mar 2, 7:02 am, "John Henry" <john106he... at hotmail.com> wrote: > On Mar 1, 10:07 pm, "John Henry" <john106he... at hotmail.com> wrote: > > > > > On Mar 1, 9:53 pm, attn.steven.... at gmail.com wrote: > (snipped) > > > You can try adjusting the labels and ticks > > > using matplotlib.ticker. > > > > To the example you cited, one can add > > > > from matplotlib.ticker import MultipleLocator, FormatStrFormatter > > > > # ... > > > > minorLocator = MultipleLocator(0.1) > > > minorFormattor = FormatStrFormatter('%0.1f') > > > ax.yaxis.set_minor_locator(minorLocator) > > > ax.yaxis.set_minor_formatter(minorFormattor) > > > > show() > > > > Thank you for the response. Yes, adding those lines did work. > > > But what exactly is going on here? Why would adding these two lines > > works? > > > Thanks, > > Okay, I played with the ticker formater and locator routines. > Unfortunately, it doesn't help. The locator sets the major value and > the formatter determines how the axes label is formatted. It doesn't > gurantee that the first label starts at the origin. Half of my plots > works, and half of them doesn't. As default, matplotlib places labels and tick marks at major ticks. Minor ticks are invisible as a default. The lines that I added turned on *minor* ticks and their labels; I set them to appear at integer multiples of 0.1 and I formatted them as floating point numbers. There's nothing to prevent you from having minor ticks appear at intervals that exceed those of major ticks. E.g., minorLocator = MultipleLocator(1.1) # etc. -- Hope this helps, Steven From grflanagan at yahoo.co.uk Tue Mar 13 10:30:01 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 13 Mar 2007 07:30:01 -0700 Subject: most complete xml package for Python? In-Reply-To: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> Message-ID: <1173796201.779457.202610@h3g2000cwc.googlegroups.com> On Mar 13, 1:43 pm, "metaperl" <metap... at gmail.com> wrote: > Without even checking them all out, I'm thinking the Amara XML Toolkit > must be the most feature-packed. The developers are readily available > on IRC for support and they seem to make regular releases. > > As a meld3 user, I have been using ElementTree under the hood, but was > dismayed to find out that you can't find elements by attribute and I > am finding it difficult to remove elements. Hardly in competition with Amara or lxml, but I wrote this extension to ElementTree which handles attributes to a limited extent: http://gflanagan.net/site/python/utils/elementfilter/ (Be aware that parts of the filter string are 'eval-ed') Gerard From fd.calabrese at gmail.com Fri Mar 9 10:17:13 2007 From: fd.calabrese at gmail.com (cesco) Date: 9 Mar 2007 07:17:13 -0800 Subject: number generator In-Reply-To: <7x7itqqxlh.fsf@ruckus.brouhaha.com> References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> Message-ID: <1173453432.893222.308610@j27g2000cwj.googlegroups.com> On Mar 9, 3:51 pm, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > "cesco" <fd.calabr... at gmail.com> writes: > > I have to generate a list of N random numbers (integer) whose sum is > > equal to M. If, for example, I have to generate 5 random numbers whose > > sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a > > simple pattern or function in Python to accomplish that? > > Erm, yes, lots of ways, there are probably further constraints on the > problem, such as the size of the integers, how the lists are supposed > to be distributed, etc. Can you be more specific? Is this for an > application? If it's a homework problem, that's fine, but it's better > in that case for respondents to suggest hints rather than full solutions. Given two positive integers, N and M with N < M, I have to generate N positive integers such that sum(N)=M. No more constraints. Thanks again Francesco From lligo at icm.edu.pl Tue Mar 13 18:25:03 2007 From: lligo at icm.edu.pl (=?utf-8?q?=C5=81ukasz_Ligowski?=) Date: Tue, 13 Mar 2007 23:25:03 +0100 Subject: Iterating across a filtered list In-Reply-To: <1173820592.220605.64040@l77g2000hsb.googlegroups.com> References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <mailman.5035.1173819607.32031.python-list@python.org> <1173820592.220605.64040@l77g2000hsb.googlegroups.com> Message-ID: <200703132325.04130.lligo@icm.edu.pl> Hi, On Tuesday 13 of March 2007 22:16:32 Arnaud Delobelle wrote: > for x in L: > if g(x): > do stuff with f(x) for x in itertools.ifilterfalse(g, L): do stuff Maybe this would be even better? L From duncan.booth at invalid.invalid Mon Mar 5 10:33:25 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Mar 2007 15:33:25 GMT Subject: Dictionary of Dictionaries References: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> <1173104962.782667.50760@j27g2000cwj.googlegroups.com> Message-ID: <Xns98EA9D0E73460duncanbooth@127.0.0.1> "Bart Ogryczak" <B.Ogryczak at gmail.com> wrote: > On Mar 5, 11:22 am, b... at yahoo.com wrote: >> messagesReceived = dict.fromkeys(("one","two"), {}) > > This creates two references to just *one* instance of empty > dictionary. > I'd do it like: > messagesReceived = dict([(key, {}) for key in ("one","two")]) > Alternatively use a defaultdict (Python 2.5) and you don't need to know the keys in advance: >>> from collections import defaultdict >>> messagesReceived = defaultdict(dict) >>> messagesReceived['one']['123'] = 11111 >>> messagesReceived['two']['121'] = 22222 >>> messagesReceived['two']['124'] = 43333 >>> messagesReceived defaultdict(<type 'dict'>, {'two': {'121': 22222, '124': 43333}, 'one': {'123': 11111}}) From steven.bethard at gmail.com Fri Mar 16 11:37:28 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Mar 2007 09:37:28 -0600 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <pan.2007.03.16.08.18.32.205449@gmx.net> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <7x6491k9t3.fsf@ruckus.brouhaha.com> <pan.2007.03.16.08.18.32.205449@gmx.net> Message-ID: <xoednQr6GoIkJGfYnZ2dnUVZ_o7inZ2d@comcast.com> Marc 'BlackJack' Rintsch wrote: > In <7x6491k9t3.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >> "n00m" <n00m at narod.ru> writes: >>> h = collections.defaultdict(itertools.repeat(0).next) >> Something wrong with >> h = collections.defaultdict(int) >> ????? > > According to a post by Raymond Hettinger it's faster to use that iterator > instead of `int`. Yep. It's because the .next() method takes no arguments, while int() takes varargs because you can do:: int('2') int('2', 8) Calling a no-args function is substantially faster than calling a varargs function. STeVe From lew at nospam.lewscanon.com Wed Mar 21 15:11:30 2007 From: lew at nospam.lewscanon.com (Lew) Date: Wed, 21 Mar 2007 15:11:30 -0400 Subject: On Java's Interface (the meaning of interface in computer programing) In-Reply-To: <1174484076.994815.89820@y66g2000hsf.googlegroups.com> References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <BMmdneR6mfcvt5zbnZ2dnUVZ_rCsnZ2d@comcast.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> Message-ID: <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> Dr. Who wrote: > Don't Feed The Trolls :-) But, but - you fed me!? Oh, wait, I'm only a half-troll, on my father's side. Thanks for the attention. Kidding aside, a post like the OP's is useful as an exercise in finding the errors, grammatical and factual. It's like a math book I had in my first year at university. Its theorems were riddled with typographical errors, mixing the us, vs and ws all around. I'd be up for hours figuring out if I was wrong or the book was wrong. In the end it gave me a lot more exercise than the homework problems did. Also, I wanted to protect the innocent. We could put up a contest - whoever finds and corrects the most errors in the post wins. Ties broken by the quality of the correct explanations. Incorrect explanations count against the entry. -- Lew From supervau at gmail.com Tue Mar 13 02:33:43 2007 From: supervau at gmail.com (Frank) Date: 12 Mar 2007 23:33:43 -0700 Subject: Calling cpp from python/SWIG Message-ID: <1173767623.632550.148000@64g2000cwx.googlegroups.com> Hi, I have the following problem: I want to parse an array M1 from python to a cpp function fct which returns an array M2. How can I do this best? Is SWIG appropriate or is there something else? If someone could give some code example or a link to a page with examples, that would be great! Thanks to all! Frank From fredrik at pythonware.com Fri Mar 23 09:34:07 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Mar 2007 14:34:07 +0100 Subject: Catching an unknown error References: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> <1174656547.825228.54240@e65g2000hsc.googlegroups.com> Message-ID: <eu0l0f$b13$1@sea.gmane.org> kyosohma at gmail.com wrote: > Make the last 'except' block like this: > > Except Exception, e: > print e while that's good enough for the given example, it's not good enough for the general case (in contemporary Python, exceptions don't have to inherit from the Exception class). </F> From jstroud at mbi.ucla.edu Thu Mar 8 06:42:41 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 08 Mar 2007 11:42:41 GMT Subject: Howto find dict members from a list of keys In-Reply-To: <mailman.4794.1173345912.32031.python-list@python.org> References: <esogs0$41a$1@online.de> <mailman.4790.1173342408.32031.python-list@python.org> <pan.2007.03.08.08.37.48.318909@REMOVEME.cybersource.com.au> <mailman.4794.1173345912.32031.python-list@python.org> Message-ID: <RESHh.1235$FG1.333@newssvr27.news.prodigy.net> Gabriel Genellina wrote: > En Thu, 08 Mar 2007 05:37:48 -0300, Steven D'Aprano > <steve at REMOVEME.cybersource.com.au> escribi?: > >> On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote: >> >>> found_dic_members = [d[key] for key in l] >> >> *self stares at the line of code* >> >> *self thinks about what he just posted* >> >> *self realises with acute embarrassment that he's jumped to conclusions >> and completely misunderstood the Original Poster's question* >> >> Oops! I'll just be slinking away now... > > LOL! :) > > (...now! But when I saw your previous post, I had to check whether it > was *me* who misunderstood the OP answering with a silly one-liner...) > > > --Gabriel Genellina > I think it was a silly one-liner. If you look closely at the example, the only mapping of [7, 8] ==> [8, 9] is [key, key] ==> [value, value] Look again at the example and consider the positional relationships. The answer, then, is trivial if not silly: [d[k] for k in l] It doesn't appear he as asking for the interesting case: [value, value] ==> [key, key] Its easy to see how Gabriel was thrown for a loop on this one. James From steve at holdenweb.com Mon Mar 19 13:19:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 13:19:50 -0400 Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: <45fe89d4$0$24787$426a34cc@news.free.fr> References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <45fe89d4$0$24787$426a34cc@news.free.fr> Message-ID: <etmgq9$mep$1@sea.gmane.org> Bruno Desthuilliers wrote: > Diez B. Roggisch a ?crit : >> momobear schrieb: >>> hi, I am puzzled about how to determine whether an object is >>> initilized in one class, anyone could give me any instructions? >>> here is an example code: >>> >>> class coffee: >>> def boil(self): >>> self.temp = 80 >>> >>> a = coffer() >>> if a.temp > 60: >>> print "it's boiled" >>> >>> in C++ language we must initilized a variable first, so there is no >>> such problem, but in python if we don't invoke a.boil(), we will not >>> get self.temp to be initilized, any way to determine if it's initilzed >>> before self.temp be used. >> You want boil to be called __init__, which is python's constructor name. > > <nitpicking> > Actually, __init__ is the initializer. The proper constructor is __new__. > </nitpicking> > <nitpicking severity="be-kind-to-novices"> Actually you would have to ensure that the class's metaclass was <type "type"> for that to be true. Classic classes don't *have* a __new__ method. </nitpicking> And of course the real answer is that the __init__ method should set a default value (modulo the sneaky use of class attributes) for any attributes that might be accessed before other methods get a chance to set them. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From ptmcg at austin.rr.com Fri Mar 16 17:34:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Mar 2007 14:34:31 -0700 Subject: How to get the previous line in a file? In-Reply-To: <mailman.5194.1174078319.32031.python-list@python.org> References: <882682.16208.qm@web58912.mail.re1.yahoo.com> <mailman.5194.1174078319.32031.python-list@python.org> Message-ID: <1174080870.969335.59100@b75g2000hsg.googlegroups.com> On Mar 16, 3:51 pm, Shane Geiger <sgei... at ncee.net> wrote: > lines = open('/tmp/foo.py', > "r").read().splitlines() > > previous_line = > '' > > for line in > lines: > > if "foo" in > line: > > print "found foo in the current line. The previous line is: " > + > previous_line > > previous_line = > line > > > > > > Qilong Ren wrote: > > Hi,all > > > I am new to this list. And I am glade I am here. > > I have a question. I need to do some text processing. I need to read > > from a file line by line. If some line is met with some condition, the > > previous line needs some modification. How to get the info of the > > previous line? > > > Thanks! > > Qilong > > > ------------------------------------------------------------------------ > > Never miss an email again! > > Yahoo! Toolbar > > <http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolb...> > > alerts you the instant new Mail arrives. Check it out. > > <http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolb...> > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgei... at ncee.net | 402-438-8958 | http://www.ncee.net > > Leading the Campaign for Economic and Financial Literacy > > sgeiger.vcf > 1KDownload- Hide quoted text - > > - Show quoted text - If the list is not long, zip the lines together in pairs: lines = """ test1 test2 foo test3 test4 """.split("\n") for prev,curr in zip(lines[:-1],lines[1:]): if "foo" in curr: break else: prev = "<not found>" print "line before foo is:", prev prints: line before foo is: test2 -- Paul From aspineux at gmail.com Sat Mar 17 19:59:36 2007 From: aspineux at gmail.com (aspineux) Date: 17 Mar 2007 16:59:36 -0700 Subject: Automagically log changes in table In-Reply-To: <1174164187.257094.236020@l75g2000hse.googlegroups.com> References: <1174164187.257094.236020@l75g2000hse.googlegroups.com> Message-ID: <1174175976.156270.65830@e1g2000hsg.googlegroups.com> Hi You can get this using "triggers" and "stored procedures". These are SQL engine dependent! This is available for long time with postgress and only from version 5 with mysql. This let you write SQL code (Procedure) that will be called when "trigged" by an event like inserting new row, updating rows, deleting .... BR On 17 mar, 21:43, "George Sakkis" <george.sak... at gmail.com> wrote: > This is more in the context of Turbogears/SQLAlchemy, but if anyone > has implemented something similar with other packages it might be > useful to know. > > I'd like to have a way to make a table "loggable", meaning it would > get, say, two fields "last_modified" and "modified_by", and every > write operation on it would automatically record the time and the id > of the user who did the addition or change (I'm not sure how to deal > with deletions let's leave this for now). Has anyone done something > like that or knows where to start from ? > > George From aleax at mac.com Tue Mar 20 22:58:49 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 20 Mar 2007 19:58:49 -0700 Subject: Documentation for "str()" could use some adjustment - Unicode issue References: <XnqLh.10046$M65.6527@newssvr21.news.prodigy.net> <mailman.5276.1174294980.32031.python-list@python.org> <DlzLh.14853$uo3.6108@newssvr14.news.prodigy.net> <1hv8tz5.l61xmz1mtprhiN%aleax@mac.com> <fRWLh.46$rO7.22@newssvr25.news.prodigy.net> Message-ID: <1hvahxv.1pih2eo19v33reN%aleax@mac.com> John Nagle <nagle at animats.com> wrote: ... > > Are you looking at p. 109 of the 2nd edition of the Nutshell? > > No, I'm looking at the original edition from 2003. That > was what Borders had in stock late last year. Eeek -- the 2nd edition came out in July 2006, and several months later Borders were STILL stocking the older, long-out-of-print one?! I occasionally checked this summer and the Palo Alto and Sunnyvale locations of Borders did seem to upgrade reasonably fast -- but maybe that's just a Silicon Valley thing...? Alex From bbxx789_05ss at yahoo.com Mon Mar 19 13:21:42 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Mar 2007 10:21:42 -0700 Subject: class objects, method objects, function objects In-Reply-To: <mailman.5281.1174315662.32031.python-list@python.org> References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> <mailman.5281.1174315662.32031.python-list@python.org> Message-ID: <1174324902.778062.104610@b75g2000hsg.googlegroups.com> Hi, Thanks for the responses. I understand that python automatically sends 'self' to a member function, i.e. self gets prepended to the argument list. I guess I am having trouble with this statement: ---- When the method object is called with an argument list, it is unpacked again, a new argument list is constructed from the instance object and the original argument list, and the function object is called with this new argument list. --- because I don't quite understand the timing. The "unpacked again" part confuses me. If I have this code: class MyClass: def g(self, name): print "Hello " + name x = MyClass() x.g("GvR") here is what happens when I try to follow the sequence of events GvR describes: ---------------- When an instance attribute is referenced that isn't a data attribute, its class is searched. x.g("GvR") ==> 'g' is not a data attribute, so class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. ==>method object is created When the method object is called with an argument list, x.g("GvR") ==> I think I'm both "referencing an instance attribute" and calling the method object with an argument list it(the method object) is unpacked again, a new argument list is constructed from the instance object and the original argument list, and the function object is called with this new argument list. ?? From gagsl-py2 at yahoo.com.ar Tue Mar 13 16:16:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Mar 2007 17:16:34 -0300 Subject: httplib/socket problems reading 404 Not Found response References: <1173755273.697153.97270@64g2000cwx.googlegroups.com> <mailman.4994.1173757609.32031.python-list@python.org> <1173793104.358361.137130@30g2000cwc.googlegroups.com> Message-ID: <op.to489wamx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 13 Mar 2007 10:38:24 -0300, Patrick Altman <paltman at gmail.com> escribi?: >> Yes, it's a known problem. See this message with a >> self-response:http://mail.python.org/pipermail/python-list/2006-March/375087.html > Are there plans to include this fix in the standard Python libraries > or must I make the modifications myself (I'm running Python 2.5)? Submit a bug report, if not already done. http://sourceforge.net/tracker/?group_id=5470 -- Gabriel Genellina From jstroud at mbi.ucla.edu Thu Mar 22 23:00:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Mar 2007 20:00:34 -0700 Subject: My MVC critique In-Reply-To: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> References: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> Message-ID: <etvfsi$bdp$1@daisy.noc.ucla.edu> scott.w.white at gmail.com wrote: > Looking at different MVC frameworks from many langauges from PHP to > Python, I've concluded that the explosion of MVC frameworks is mainly > due to undisciplined & unexperienced programmers. > > Nobody would argue about the separation of the layers because this is > not the problem I have with it, if anything most implementations > emphasis separation at the wrong places. The end solutions end up > looking very mickey mouse. > > It's been long asserted starting with Smalltalk there there be a > separation of layers with an application starting with the view (what > the user sees), the controller (which controls the flow of the > application) and the model (the representation of the data). > > What MVC does not emphasis is the separation of the data access layer, > one of the most important pieces of an application. So what is done > with this? For many the DAL is either encapsulated within the model > or some toolkit that generates the SQL for them, this may lead to > decreased overall security of a database and inefficient queries. > > The catalyst for MVC frameworks on the web has been the slew of poorly > written applications mostly in PHP & Perl , this has driven many > programmers looking for control & consistency. However this need is > short sighted when people find a magical bullet MVC Framework, and do > not place emphasis on minimization & reusability of code. Therefore > you end up with the same paradigm as before, just crappy applications > separated out into pieces. > > No doubt there should be separation of layers, but there also has to > be a real dialogue about programming as a discipline & science, not as > a craft of gluing popsicle sticks together. > > There should be more discussion of architecture before a project > starts and more code reviews and discussions in project teams. Also > one off projects (putting one programming on an island giving them a > compiler/interpreter) is a great way to get a crappy application. > > That being said, I presently don't use one, but I'm still holding out > for an MVC framework that works for me and provides me power, > flexibility and is well documented. > Xah, is that you? From timr at probo.com Thu Mar 8 02:08:53 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 08 Mar 2007 07:08:53 GMT Subject: how can I find out the value of an environment variable? References: <1173147734.603718.179870@8g2000cwh.googlegroups.com> Message-ID: <sidvu291fj27bj5cild7l1jo2gpasbt88o@4ax.com> "ken" <ken.carlino at gmail.com> wrote: > >how can I find out the value of an environment variable in my pythong >script? C:\Apps\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ['PATH'] 'C:\\WINDOWS\\system32;c:\\WINDOWS;c:\\WINDOWS\\System32\\Wbem;c:\\bin;e:\\bin' >>> -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From newsuser at stacom-software.de Fri Mar 16 09:20:31 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Fri, 16 Mar 2007 14:20:31 +0100 Subject: String formatting with fixed width Message-ID: <ete5ec$juo$2@online.de> Hello alltogether, is it possible to format stings with fixed width of let's say 7 character. T need a floating point with 3 chars before dot, padded with ' ' and 3 chars after dot, padded with '0'. Followingh is my approach >>> f = 21.1 >>> s = "%.03f" % f >>> s '21.100' But there are missing ' '. How can I get that? (For bigger numbers than 999 they might be cut: 1021 -> 021) Thanks, Alexander From bruno.desthuilliers at gmail.com Thu Mar 1 03:14:43 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 1 Mar 2007 00:14:43 -0800 Subject: Question about raise and exceptions. In-Reply-To: <o0jcu2hhqs13gu04vnmd8tmp3849u1pg54@4ax.com> References: <mailman.4523.1172688540.32031.python-list@python.org> <snkbu25ft2hn3hrchg888afkapgrjutonn@4ax.com> <45e5e640$0$18215$426a74cc@news.free.fr> <o0jcu2hhqs13gu04vnmd8tmp3849u1pg54@4ax.com> Message-ID: <1172736883.332020.299830@a75g2000cwd.googlegroups.com> On 1 mar, 04:46, Daniel Klein <danielklei... at gmail.com> wrote: > On Wed, 28 Feb 2007 22:03:13 +0100, Bruno Desthuilliers > > > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > >Daniel Klein a ?crit : > >> The arguments for TransitionError must be a tuple, > > >Err... > > >> eg: > > >> msg = "Going to error state %d from state %d" % (self.curr_state, > >> newstate) > >> raise TransitionError(self, curr_state, newstate, msg) > > >Where did you see a tuple here ? You're code is *calling* > >TransitionError, passing it the needed arguments. > > >Note that it's the correct syntax - but not the correct explanation !-) > > My bad :-( > > Thanks for setting me straight. I had (wrongly) thought that the stuff > inside of () was a tuple. For the record, it's the ',' that makes the tuple. The () are (in this context) the call operator. >>> t = 1, 2, 3 >>> t (1, 2, 3) >>> type(t) <type 'tuple'> >>> t2 = 1, >>> t2 (1,) >>> def toto(): >>> return "it's me" ... >>> toto <function toto at 0xb7d18c34> >>> toto() "it's me" >>> From psdasilvaX at esotericaX.ptX Fri Mar 23 15:30:24 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 23 Mar 2007 19:30:24 +0000 Subject: Join strings - very simple Q. In-Reply-To: <1174676818.207543.246080@l75g2000hse.googlegroups.com> References: <1174675011.244339@jubilee.claranet.pt> <1174676818.207543.246080@l75g2000hse.googlegroups.com> Message-ID: <1174678166.970277@jubilee.claranet.pt> Mike Kent escreveu: ... > New way: > l=['a','b','c'] > jl=','.join(l) > I thank you all. Almost there ... I tried "".join(l,',') but no success ... :-( Paulo From jstroud at mbi.ucla.edu Sat Mar 10 20:54:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 11 Mar 2007 01:54:23 GMT Subject: minimum age to learn python (a.k.a graphical vs text languages) In-Reply-To: <mailman.4905.1173540820.32031.python-list@python.org> References: <mailman.4905.1173540820.32031.python-list@python.org> Message-ID: <jjJIh.5107$FG1.2494@newssvr27.news.prodigy.net> Brian Blais wrote: > Hello, > > I was wondering what the approximate minimum age to learn python is. > Has anyone had experience teaching middle school students, or elementary > school students Python? What brought this up for me is thinking about > starting a Lego robots group in a local middle school. I only teach > college, and have little experience with middle school students, so I > find it hard to guess what they could actually do. I started > programming when I was about 5th grade, on a Commodore VIC 20 (3.5k > RAM!) in basic, but I don't think I am typical. (Of course, now, you > can probably infer my age to within 2 years! :) ). > > > I've written something so that students can program in Python syntax to > run the Lego Mindstorms robots. The most commonly used language for > these robotos, in the middle school, is Robolab which is entirely > graphical. Although a good program, I find there are some drawbacks: > 1) Robolab is commercial, and not all schools can afford this above and > beyond the price of the lego mindstorms > 2) Robolab only runs on Mac/Windows, and not Linux, so those schools > that have tried to save money on the operating system get whacked there too > 3) Robolab can *only* do Lego robots. > > Although you learn the basic language structures (loops, branching, > etc...), because it is graphical, Robolab doesn't translate directly. > Perhaps this is enough for kids to start, but perhaps one can do better. > > On the other hand, my pynqc tool (which uses the freely available nqc > language for the Lego Mindstorms) is: > 1) free (in both senses) > 2) runs on Mac/Linux/Windows > 3) because you use python syntax, it is easier to go and do other python > projects not involving robots > > In my mind, this opens up more doors, but it is not graphical. > > I wanted to hear responses from people who have experience teaching > programming in elementary/middle (or even high) school. Do graphical > languages make a big difference? Do text-based languages put up > barriers to young learners? Is it no big deal either way? > > > thanks, > > Brian Blais > Probably, its not so much that graphical is easy to learn, but, for kids, I'm guessing that its less boring than text-based. They already understand a lot about programming by customizing their video games on the Wii, or whatever Sony playbox X. Really, What you need is a "first person shooter" programming language. Perhaps, make them program their own guns or "power moves". Have competitions at the end of the week using the guns they create. There's nothing like learning to program by programming a bullet to follow a quadratic spline through a maze of corridors, nailing an opponent whose position was calculated by triangulation. You'll see who the good programmers are then. Probably, you'll see some of the best programming of your life. James From aleax at mac.com Fri Mar 30 10:41:33 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 30 Mar 2007 07:41:33 -0700 Subject: Indentation for code readability References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> <euikp8$2dgn$1@ariadne.rz.tu-clausthal.de> Message-ID: <1hvs2eo.po0daya4nuegN%aleax@mac.com> Thomas Kr?ger <newsgroups at nospam.nowire.org> wrote: > BTW: having one way to do it is one of the main ideas of Python's > philosophy. Yes, just like C's -- see point 4 in the "Spirit of C" summary taken from the ISO Standard for C and quoted e.g. at <http://www.artima.com/cppsource/spiritofc.html> . Of course, it's an ideal, a design principle, not an actual description of how things turn out (in either language). Alex From laurent.pointal at limsi.fr Fri Mar 9 10:05:03 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 09 Mar 2007 16:05:03 +0100 Subject: Creating a DLL file from Python Code In-Reply-To: <1173442086.281115.95300@q40g2000cwq.googlegroups.com> References: <1173442086.281115.95300@q40g2000cwq.googlegroups.com> Message-ID: <esrt2i$47n$1@news2.u-psud.fr> macedo.silva at gmail.com a ?crit : > Hi, > > I would like to request your attention for this very specific issue: > > I have several classes in Python, and now I want simply re-use it, in > other language. > > The closest to solution I think I came was with this site: > http://www.py2exe.org/index.cgi/Py2exeAndCtypesComDllServer > but I not able to solve questions related with TLB files and > __init__.py files. > > So, could anyone give a tip about how to creat a dll file from Python? > It is possible under any conditions? For inter-languages intagration maybe you can use some distributed objects protocol like CORBA (see OmniORBpy), or - as you wrote about a DLL - COM/DCOM (see pywin32). Or write a simple TCP or UDP layer to communicate with your existing classes. Note: all that need some work in the Python side to be able to work using a client/server model. Note2: as long as your interface dont change, you can make modifications in both sides without problem. A+ Laurent. From steve at holdenweb.com Mon Mar 19 23:04:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 23:04:09 -0400 Subject: Still the __new__ hell ... In-Reply-To: <568s5gF287c68U2@mid.individual.net> References: <1174167360.522350@jubilee.claranet.pt> <45fe7f46$0$2138$426a74cc@news.free.fr> <1174337519.926611@jubilee.claranet.pt> <568s5gF287c68U2@mid.individual.net> Message-ID: <etnj29$lpu$1@sea.gmane.org> greg wrote: > Paulo da Silva wrote: >> As a relatively inexperient >> in python, how could I know that a 'string' is an instance of >> basestring? > > isinstance(x, basestring) > > This works because basestring is defined as the > tuple (str, unicode) and isinstance accepts a > tuple of types as well as just a single type. > The idea is right, but the detail is completely wrong. basestring is a *type*. >>> basestring <type 'basestring'> It's the base class of which both str and unicode are subclasses. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From no at spam.it Thu Mar 1 13:44:25 2007 From: no at spam.it (Pablo was Paolo) Date: Thu, 01 Mar 2007 19:44:25 +0100 Subject: Reading csv files using SQL In-Reply-To: <mailman.4581.1172769998.32031.python-list@python.org> References: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> <WItFh.7822$Jl.2517@newsread3.news.pas.earthlink.net> <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> <mailman.4568.1172751025.32031.python-list@python.org> <45e70a14$0$37202$4fafbaef@reader3.news.tin.it> <mailman.4581.1172769998.32031.python-list@python.org> Message-ID: <45e71f07$0$819$4fafbaef@reader5.news.tin.it> Tim Golden ha scritto: > I vaguely remember that you can get an ODBC driver for CSV. There is a standard ODBC driver for use text file or csv, in windows. But I use Linux on production servers. I'd like to find a Python library or tool. Thanks! Paolo From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 28 07:15:17 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 28 Mar 2007 13:15:17 +0200 Subject: XML Parsing In-Reply-To: <1175067518.919256.243090@n59g2000hsh.googlegroups.com> References: <1175067518.919256.243090@n59g2000hsh.googlegroups.com> Message-ID: <460a4e2f$0$14532$426a74cc@news.free.fr> pyapplico at gmail.com a ?crit : > I want to parse this XML file: > > <?xml version="1.0" ?> > > <text> > > <text:one> > <file>filename</file> > <contents> > Hello > </contents> > </text:one> > > <text:two> > <file>filename2</file> > <contents> > Hello2 > </contents> > </text:two> > > </text> > > This XML will be in a file called filecreate.xml > > As you might have guessed, I want to create files from this XML file > contents, so how can I do this? Using a sax parser might be the best solution here. From deets at nospam.web.de Wed Mar 21 10:03:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 Mar 2007 15:03:57 +0100 Subject: Technical Answer - Protecting code in python References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> Message-ID: <56csadF28irilU1@mid.uni-berlin.de> flit wrote: > Hello All, > > I have a hard question, every time I look for this answer its get out > from the technical domain and goes on in the moral/social domain. > First, I live in third world with bad gov., bad education, bad police > and a lot of taxes and bills to pay, and yes I live in a democratic > "state" (corrupt, but democratic). > So please, don't try to convince me about the social / economical / > open source / give to all / be open / all people are honest until > prove contrary / dance with the rabbits... > Remember I need to pay bills and security. > Now the technical question: Most of these discussions aren't about open source or moral, but exactly about what you ask - technicalities. A friend of mine is so f**ing fluent with a disassembler, he immediately has whatever amount of credits he wants in your usual simulation style game. It's just a question of if the hurdles you put up are high enough for you intended audience - and for some reason people feel that compiled code would be much more safe. It's not. Unless very special measures are taken (e.g. skype), but that then is also beyond the common C-compiler run. And what almost always is not a point is that you've programmed something that would be interesting for outher to rip apart and use in pieces. Sorry, but 99% of all code is just a bit of glue logic - and the reluctance of developers to even use explicitly bought and well-documented libraries instead of rolling out their own, customized solution illustrates that adjusting your mindset to that of somebody else is much more of a problem than actually writing amounts of - mostly trivial - code. The only _real_ interesting thing is copy-protection. But that's a problem for all, also the compiler-camp-buddies. > 1 - There is a way to make some program in python and protects it? I > am not talking about ultra hard-core protection, just a simple one > that will stop 90% script kiddies. If you can, just deliver the pyc-files. Should be hard enough for most people. > 2 - If I put the code in web like a web service, how can I protect my > code from being ripped? There is a way to avoid someone using my site > and ripping the .py files? A service doesn't expose those files, unless you somehow instruct it to do so. Diez From aleax at mac.com Thu Mar 29 03:46:40 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Mar 2007 00:46:40 -0700 Subject: which methods to use? References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> <euf11o$rk6$1@aioe.org> <1175130991.799268.311470@n59g2000hsh.googlegroups.com> <pan.2007.03.29.04.56.14.874710@REMOVE.THIS.cybersource.com.au> <1175154020.467194.40000@b75g2000hsg.googlegroups.com> Message-ID: <1hvpoqf.1jl697wvbomidN%aleax@mac.com> <s99999999s2003 at yahoo.com> wrote: ... > under what circumstances do we need to create a copy of a tuple :-> > "btuple = atuple[:]". tuples are immutable, so wouldn't it be "wasting > memory"? Nah -- btuple is atuple. The "copy" is a no-op, in this case. > another query, in the docs, list(a) and a[:] does the same thing (a = > [1,2,3] for example), but besides the speed of slicing is faster than > list(), what advantage is there for using list(a) in this case ? Readability (a word is more readable than idiomatic punctuation), and conceptual uniformity with making shallow copies of other containers of known types such as sets and dicts. Alex From cjw at sympatico.ca Sat Mar 17 16:26:55 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 17 Mar 2007 16:26:55 -0400 Subject: distributing python software in jar like fashion In-Reply-To: <1173926243.640611.107130@o5g2000hsb.googlegroups.com> References: <Vs6dnZOY8sSDM2XYnZ2dnUVZ_rqhnZ2d@comcast.com> <1173926243.640611.107130@o5g2000hsb.googlegroups.com> Message-ID: <ethiug$u71$1@sea.gmane.org> ce wrote: > On Mar 15, 10:23 am, alf <ask at me> wrote: >> Hi, >> >> I have a small app which consist of a few .py files. Is there any way to >> distribute it in jar like fashion as a single file I can just run python >> on. I obviously look for platform independent solution. >> >> Thx in advance, A. > > You can import from zip achieves as PEP 273, but to execute in the > same mechanism as the jar files, recently there is no way afaik. You could treat the collection of files as a Python package. You would then add an __init__.py file to your collection and, in that __init__.py arrange to initiate main.py (or whatever you call your initiator program). Colin W. > > ce (pain n d'ass) > From cyberco at gmail.com Sun Mar 11 12:07:23 2007 From: cyberco at gmail.com (cyberco) Date: 11 Mar 2007 09:07:23 -0700 Subject: PIL: reading bytes from Image In-Reply-To: <mailman.4925.1173573914.32031.python-list@python.org> References: <1173568560.648691.61760@64g2000cwx.googlegroups.com> <mailman.4925.1173573914.32031.python-list@python.org> Message-ID: <1173629243.214806.220070@s48g2000cws.googlegroups.com> Thanks, I've tried the StringIO option as follows: ================================= img = Image.open('/some/path/img.jpg') img.thumbnail((640,480)) file = StringIO, StringIO() img.save(file, 'JPEG') ================================= But it gives me: ================================= exceptions.TypeError Traceback (most recent call last) C:\Python24\lib\site-packages\PIL\Image.py in save(self, fp, format, **params) 1303 1304 try: -> 1305 save_handler(self, fp, filename) 1306 finally: 1307 # do what we can to clean up C:\Python24\lib\site-packages\PIL\JpegImagePlugin.py in _save(im, fp, filename) 407 ) 408 --> 409 ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)]) 410 411 def _save_cjpeg(im, fp, filename): C:\Python24\lib\site-packages\PIL\ImageFile.py in _save(im, fp, tile) 464 bufsize = max(MAXBLOCK, im.size[0] * 4) # see RawEncode.c 465 try: --> 466 fh = fp.fileno() 467 fp.flush() 468 except AttributeError: TypeError: descriptor 'fileno' of 'file' object needs an argument ================================= It looks similar to the code in Sparklines except for the fact that the latter creates an Image from scratch. 2B > Saving the image, in a > format your client understands, to a file like object like > StringIO.StringIO is an easy path to take. > > Sparklines shows this in action: > > http://bitworking.org/projects/sparklines/ > > max From timothy.kellogg at gmail.com Mon Mar 5 23:03:27 2007 From: timothy.kellogg at gmail.com (timothy.kellogg at gmail.com) Date: 5 Mar 2007 20:03:27 -0800 Subject: CherryPy + Database questions In-Reply-To: <552l55F22aph6U1@mid.uni-berlin.de> References: <mailman.4673.1173101612.32031.python-list@python.org> <552l55F22aph6U1@mid.uni-berlin.de> Message-ID: <1173153806.918779.241900@j27g2000cwj.googlegroups.com> On Mar 5, 8:44 am, "Diez B. Roggisch" <d... at nospam.web.de> wrote: > Brian Blais wrote: > > Hello, > > > I have more of a conceptual question about the way databases work, in a > > web > > framework, but I will be implementing things with CherryPy and SQLAlchemy. > > If you make a web form that adds rows to a database, and use sqlite as > > the engine, is there a danger of a race condition if several users at the > > same time try to submit the > > form? I want a unique row id, and make a unique identifier for the > > submissions. Am I in danger of having multiple submissions given the same > > identifier? > > > I know that if I implemented things without a database, but used a flat > > file or something like it, I would have that possibility, when two > > processes try to read and update the file at the same time. > > > If you want something more specific, I can throw some code together, but I > > wanted to get an answer before that because it will change the way I > > develop the code. > > Usually, that is exactly what a RDBMS gives you. See the database connector > module's threadsaftey property to see what exactly you can expect. > > Diez SQLite isn't really a DBMS at all, it's just a library. According to their FAQ (http://www.sqlite.org/faq.html#q8) it is only threadsafe as long as you aren't changing the same DB in separate threads (so no, not threadsafe at all). Hope this helps. --Tim From tjreedy at udel.edu Wed Mar 21 19:45:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Mar 2007 19:45:14 -0400 Subject: Python 3000 idea: reversing the order of chained assignments References: <ets9hc$74f$1@news.onet.pl><pan.2007.03.21.22.28.43.880478@REMOVE.THIS.cybersource.com.au> <etscd5$g0g$1@news.onet.pl> Message-ID: <etsg2a$9gv$1@sea.gmane.org> "Marcin Ciura" <marcin.ciura at poczta.NOSPAMonet.pl> wrote in message news:etscd5$g0g$1 at news.onet.pl... | Neither would I. I must have expressed myself not clearly enough. | Currently | x = y = z | is roughly equivalent to | x = z | y = z except that z is only evaluated once. | I propose to change it to | y = z | x = z Unless target expression expressions interact, there is no difference. When there are such side effects, I think it best to be explicit about what you want to happen first, as in your original code, instead of trying to mash them together in one line. Terry Jan Reedy From newsuser at stacom-software.de Mon Mar 5 04:36:41 2007 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Mon, 05 Mar 2007 10:36:41 +0100 Subject: Howto pass exceptions between threads Message-ID: <esgo77$t6e$1@online.de> Hallo Alltogether, I've searched in this mailing list, but it seems to me that there is no general approach to pass exceptions from one thread to another. I think most application do a unique way of handling "unhandled exceptions", at least they (should) try to log them. The following discussion seems to me most valuable (Sorry for the long URL, I don't know a way of shorter) http://groups.google.de/group/comp.lang.python/browse_frm/thread/a2ebb2a2f611779b/4b820c20ff3fcea8?lnk=gst&q=%2Bexception+%2Bthread&rnum=6&hl=de#4b820c20ff3fcea8 http://groups.google.de/group/comp.lang.python/browse_frm/thread/2c61c06795f525f3/348a8d9e85883fe3?lnk=gst&q=pass+%2Bexception+%2Bthread&rnum=1&hl=de#348a8d9e85883fe3 I've the feeling that if you're using the python class threading.Thread you've a unique interface of handling it. (thread synchronizing + exception raising) But' when you've a C++ extension, that uses it's own thread implementation and your exceptions happens in python code (but from a thread that is controlled by your extension) you have another problem. Maybe I've overseen something in the python docu, so I ask for the solutions, concepts, hints ... you solved the problem. Regards Alexander From pecora at anvil.nrl.navy.mil Fri Mar 9 11:20:38 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Fri, 09 Mar 2007 11:20:38 -0500 Subject: Is this right? Multiple imports of same module. References: <pecora-B92BB8.09304609032007@ra.nrl.navy.mil> <1173455185.225036.167700@64g2000cwx.googlegroups.com> Message-ID: <pecora-A2B96D.11203809032007@ra.nrl.navy.mil> In article <1173455185.225036.167700 at 64g2000cwx.googlegroups.com>, "Bart Ogryczak" <B.Ogryczak at gmail.com> wrote: > On Mar 9, 3:30 pm, Lou Pecora <pec... at anvil.nrl.navy.mil> wrote: > > Then mymodule is imported only once, but each module has access to it > > through the module name (mod1 and mod2) and the alias MM (mod3). Is > > that right? > > Yes, it is. Praise the Lord. :-) I got one right in the namespaces puzzles. (But see my followup on using 'from XXX import *' in this thread. I'm still not a namespace guru. > > I was concerned about multiple imports and efficiency. > > If the module is already loaded, it won't be loaded again. Dictionary > of loaded modules is avaliable as sys.modules. Good to know. Thank you. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From steven.potter at gmail.com Sat Mar 17 15:44:45 2007 From: steven.potter at gmail.com (Steve Potter) Date: 17 Mar 2007 12:44:45 -0700 Subject: Pickle and Instance Methods Message-ID: <1174160685.098122.29780@l77g2000hsb.googlegroups.com> I have a class that I am trying to pickle. One of the attributes is used to set a callback e.g. self.attribute.setCallback(self.callbackfunction). I understand that this cannot be saved by pickle. My question is, is there another way of setting a callback that would agree with pickle? If not is there some way to make pickle ignore the problem attribute? Thanks, Steve From ocollioud at gmail.com Thu Mar 15 03:02:11 2007 From: ocollioud at gmail.com (olive) Date: 15 Mar 2007 00:02:11 -0700 Subject: Mocking OpenOffice in python? In-Reply-To: <1173861553.036985.74670@p15g2000hsd.googlegroups.com> References: <1173861553.036985.74670@p15g2000hsd.googlegroups.com> Message-ID: <1173942131.661806.293780@y80g2000hsf.googlegroups.com> On Mar 14, 9:39 am, "PaoloB" <pibi... at gmail.com> wrote: > Hi everyone, Since OO is shipped with Py 2.3 only, I use Jython to drive OO through its Java API. Our app is a mix of: - ODT XML scrapping/templating based on Dom4j which, surprisingly, when use with Jython, is the most pythonic XML API I have tried so far (I find better than minidom, ElementTree or even lxml which is my choice under CPython). - OObean integrated in Java Gui and driven by Jython. I don't like Java much though, but this is what our management wants us to use. By chance, Jython is tolerated so far. Olive. From edurand.com at gmail.com Thu Mar 8 02:52:31 2007 From: edurand.com at gmail.com (edurand) Date: 7 Mar 2007 23:52:31 -0800 Subject: image processing In-Reply-To: <mailman.4735.1173243292.32031.python-list@python.org> References: <1173171010.239215.130580@n33g2000cwc.googlegroups.com> <7xirdekauw.fsf@ruckus.brouhaha.com> <1173186981.056242.152120@64g2000cwx.googlegroups.com> <mailman.4735.1173243292.32031.python-list@python.org> Message-ID: <1173340351.471170.52050@q40g2000cwq.googlegroups.com> On Mar 7, 5:54 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 06 Mar 2007 10:16:21 -0300, edurand <edurand.... at gmail.com> > escribi?: > > > On Mar 6, 9:57 am, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > >> "edurand" <edurand.... at gmail.com> writes: > >> > Have a look at :http://filters.sourceforge.net/ > > It's a DLL, so yes, it run on Windows. > > If someone would like to port it on other OS, why not. > > Could you please update the project attributes then? Operating System, > Language... They appear not to have the right values. > > -- > Gabriel Genellina You are right. I have changed "Operating System" to "All 32-bit MS Windows (95/98/NT/2000/XP)". For the "Programming Language", we don't have to change anything, because Filters can be used in C, C++, C#, Delphi, Java, Python, .NET Thanks for your comment Emmanuel Durand From bdesth.quelquechose at free.quelquepart.fr Wed Mar 7 16:55:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Mar 2007 22:55:54 +0100 Subject: catching exceptions from an except: block In-Reply-To: <1173295587.143018.102220@p10g2000cwp.googlegroups.com> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173295587.143018.102220@p10g2000cwp.googlegroups.com> Message-ID: <45ef2ce6$0$6088$426a74cc@news.free.fr> Miki a ?crit : > Hello Arnaud, > > >>Imagine I have three functions a(x), b(x), c(x) that each return >>something or raise an exception. Imagine I want to define a function >>that returns a(x) if possible, otherwise b(x), otherwise c(x), >>otherwise raise CantDoIt. > > Exceptions are for error handling, not flow control. def until(iterable,sentinel): for item in iterable: if item == sentinel: raise StopIteration yield item >>> for item in until(range(10), 5): ... print item ... 0 1 2 3 4 >>> Exceptions *are* a form of flow control. From http Fri Mar 9 11:00:48 2007 From: http (Paul Rubin) Date: 09 Mar 2007 08:00:48 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> <mailman.4858.1173454941.32031.python-list@python.org> Message-ID: <7xps7ipftb.fsf@ruckus.brouhaha.com> Carsten Haese <carsten at uniqsys.com> writes: > > Given two positive integers, N and M with N < M, I have to generate N > > positive integers such that sum(N)=M. No more constraints. > Paul still had a point, since the word "positive" is a vital piece of > information that never appeared in your original description. It's maybe even more complicated that way. Does the OP want to generate each possible partition with equal probability? See http://en.wikipedia.org/wiki/Partition_number for more info. From aleax at mac.com Thu Mar 22 00:47:05 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 21 Mar 2007 21:47:05 -0700 Subject: Garbage collection References: <etrb1q$t01$1@gemini.csx.cam.ac.uk> <mailman.5394.1174484981.32031.python-list@python.org> <etrhfo$bv3$1@gemini.csx.cam.ac.uk> <mailman.5398.1174490143.32031.python-list@python.org> <etrj61$euc$1@gemini.csx.cam.ac.uk> <mailman.5403.1174493865.32031.python-list@python.org> <etrpqf$t8g$3@gemini.csx.cam.ac.uk> Message-ID: <1hvchlx.13gg6ie17naf4oN%aleax@mac.com> Tom Wright <tew24 at spam.ac.uk> wrote: > real programs. I can't help thinking that there are some situations where > you need a lot of memory for a short time though, and it would be nice to > be able to use it briefly and then hand most of it back. Still, I see the > practical difficulties with doing this. What I do in those cases: a. fork b. do the memory-hogging work in the child process c. meanwhile the parent just waits d. the child sends back to the parent the small results e. the child terminates f. the parent proceeds merrily I learned this architectural-pattern a long, long time ago, around the time when fork first got implemented via copy-on-write pages... Alex From kavithapython at yahoo.co.in Thu Mar 8 14:40:57 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Thu, 8 Mar 2007 19:40:57 +0000 (GMT) Subject: writing dictionary to file In-Reply-To: <8c7f10c60703081024t5bddb16ne98cf5ba5b4db670@mail.gmail.com> Message-ID: <677146.76946.qm@web7811.mail.in.yahoo.com> Hi Simon, iam till here: dorc=some['DorC'] amount=some['amount'] f=open("logfile.txt", "w") if dorc =='C': a = -(amount) if dorc == 'D': b = amount sum=a + b if sum == 0: f.writelines("name:") f.writelines("%s" %some['name']) f.writelines("credit:") f.writelines("%s" % amount) but i see an empty file opened,,, kavitha Simon Brunning <simon at brunningonline.net> wrote: On 3/8/07, kavitha thankaian wrote: > can anyone help me??? I'm sure we can. How far have you got so far? -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning MSN: small_values --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070308/cd132228/attachment.html> From ashwin.kashyap at thomson.net Fri Mar 9 16:45:29 2007 From: ashwin.kashyap at thomson.net (Ashwin Kashyap) Date: Fri, 09 Mar 2007 16:45:29 -0500 Subject: Adding Lib/site-packages Message-ID: <1173476729.9800.3.camel@kashyapa2.prin.am.thmulti.com> Hello, I am trying to create a python distribution using the Python-2.5 sources. What I would like to do is to add a bunch of Python packages to the Lib/site-packages directory and have them compiled and installed when I do a ./configure && make install For example, I checked in M2Crypto, python-cjson into Lib/site-packages directory. Will it be compiled in automatically or do I need to do a manual "python setup.py" for each? Which files do I need to edit and how do I accomplish this? Thanks, Ashwin From gagsl-py2 at yahoo.com.ar Sat Mar 17 05:53:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Mar 2007 06:53:18 -0300 Subject: Returning other instance from __init__ - I need help References: <1173933158.948806@jubilee.claranet.pt> <1huzkla.i6dshw1grnysmN%aleax@mac.com> <1173970438.864747@jubilee.claranet.pt> <1174076229.671240@jubilee.claranet.pt> <1174093476.6937@jubilee.claranet.pt> Message-ID: <op.tpbfbxk2x6zn5v@gabriel2> En Fri, 16 Mar 2007 22:05:05 -0300, Paulo da Silva <psdasilvaX at esotericaX.ptX> escribi?: > When debugging, I found this is wrong!!! > Would someone please clarify what do I have to return from > __new__? Try this. I used a classmethod for load, it may be easier to subclass. class C(object): def __new__(cls, filename=None, foo=None, bar=None): if filename is not None: return cls.load(filename) inst = super(C, cls).__new__(cls) inst.foo = foo inst.bar = bar return inst @classmethod def load(cls, filename): inst = super(C, cls).__new__(cls) inst.foo = "some foo loaded from "+filename inst.bar = "some bar loaded from "+filename return inst class D(C): @classmethod def load(cls, filename): inst = super(D, cls).__new__(cls) inst.foo = "D foo loaded from "+filename inst.bar = "D bar loaded from "+filename return inst c1 = C(foo=1, bar=2) print "c1=", c1 print "c1.foo=", c1.foo print "c1.bar=", c1.bar c2 = C(filename="xxx.txt") print "c2=", c2 print "c2.foo=", c2.foo print "c2.bar=", c2.bar d1 = D(foo=10, bar=20) print "d1=", d1 print "d1.foo=", d1.foo print "d1.bar=", d1.bar d2 = D(filename="yyy.txt") print "d2=", d2 print "d2.foo=", d2.foo print "d2.bar=", d2.bar -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Thu Mar 8 04:57:17 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 08 Mar 2007 09:57:17 GMT Subject: VIM: Python type indented-block command equivalent to % for C? In-Reply-To: <1173330126.098105.275160@n33g2000cwc.googlegroups.com> References: <1173330126.098105.275160@n33g2000cwc.googlegroups.com> Message-ID: <16RHh.49465$%k1.388231@phobos.telenet-ops.be> Paddy3118 schreef: > Assuming that only space characters are allowed > for indenting, is their a way to yank a Python > block like y% works for C , or a way to move to > the end of a block defined by indentation? > > I have tried help indent but could not find > anything. I don't know either, but if you find anything, please post it to this list: I'm looking for such functionality too. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From grahn+nntp at snipabacken.dyndns.org Fri Mar 23 10:14:51 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 23 Mar 2007 14:14:51 GMT Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> Message-ID: <slrnf07k5r.3nr.grahn+nntp@frailea.sa.invalid> On 21 Mar 2007 12:18:50 -0700, Paddy <paddy3118 at googlemail.com> wrote: > I just had a link to Tim peters first post on doctest: > http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > removed from http://en.wikipedia.org/wiki/Doctest as it doesn't fit > their guidelines for external links. > I wonder, could maybe the official website be persuaded to host a copy > so that it could be linked to? Wikipedia should have some guideline for referencing Usenet postings, somewhere ... Anyway, it's a good thing to provide at least the Message-ID of the posting. As an example, your your posting here was uniquely identified by the Message-ID <1174504730.728688.52380 at y80g2000hsf.googlegroups.com> /Jorgen -- // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From joshua at eeinternet.com Wed Mar 7 15:07:58 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 07 Mar 2007 11:07:58 -0900 Subject: thread and portability Unix/Linux References: <1173264866.645389.268640@v33g2000cwv.googlegroups.com> Message-ID: <45ef0f17$0$16318$88260bb3@free.teranews.com> awalter1 wrote: > Hi, > I have a Python application that runs under HPUX 11.11 (then unix). It > uses threads : > from threading import Thread > # Class Main > class RunComponent(Thread): > > My application should run under Linux (red hat 3 ou 4) and I read that > differences exist between the implementation of threads : on HPUX > 11.11 there is CMA (ou DCE) threads and on Linux POSIX thread. Do you > think that my Python application should be modified or may be such > differences are hidden by the python interpreter ? > In other terms, do I get some risks on this particular aspect by > porting my application ? > Thanks a lot > > PS: If you are aware of other risk of porting, I am interested too. The Python threading model abstracts from the underlying OS threading, so there should be no need to change anything (AFAIK). j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From jstroud at mbi.ucla.edu Thu Mar 22 23:01:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 22 Mar 2007 20:01:47 -0700 Subject: My MVC critique In-Reply-To: <etvfsi$bdp$1@daisy.noc.ucla.edu> References: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> <etvfsi$bdp$1@daisy.noc.ucla.edu> Message-ID: <etvfur$bdp$2@daisy.noc.ucla.edu> James Stroud wrote: > scott.w.white at gmail.com wrote: > >> Looking at different MVC frameworks from many langauges from PHP to >> Python, I've concluded that the explosion of MVC frameworks is mainly >> due to undisciplined & unexperienced programmers. >> >> Nobody would argue about the separation of the layers because this is >> not the problem I have with it, if anything most implementations >> emphasis separation at the wrong places. The end solutions end up >> looking very mickey mouse. >> >> It's been long asserted starting with Smalltalk there there be a >> separation of layers with an application starting with the view (what >> the user sees), the controller (which controls the flow of the >> application) and the model (the representation of the data). >> >> What MVC does not emphasis is the separation of the data access layer, >> one of the most important pieces of an application. So what is done >> with this? For many the DAL is either encapsulated within the model >> or some toolkit that generates the SQL for them, this may lead to >> decreased overall security of a database and inefficient queries. >> >> The catalyst for MVC frameworks on the web has been the slew of poorly >> written applications mostly in PHP & Perl , this has driven many >> programmers looking for control & consistency. However this need is >> short sighted when people find a magical bullet MVC Framework, and do >> not place emphasis on minimization & reusability of code. Therefore >> you end up with the same paradigm as before, just crappy applications >> separated out into pieces. >> >> No doubt there should be separation of layers, but there also has to >> be a real dialogue about programming as a discipline & science, not as >> a craft of gluing popsicle sticks together. >> >> There should be more discussion of architecture before a project >> starts and more code reviews and discussions in project teams. Also >> one off projects (putting one programming on an island giving them a >> compiler/interpreter) is a great way to get a crappy application. >> >> That being said, I presently don't use one, but I'm still holding out >> for an MVC framework that works for me and provides me power, >> flexibility and is well documented. >> > > Xah, is that you? Oh, wait...No. Not crossposted. Must be someone else. From no at spam.it Thu Mar 1 01:30:54 2007 From: no at spam.it (Pablo was Paolo) Date: Thu, 01 Mar 2007 07:30:54 +0100 Subject: Reading csv files using SQL In-Reply-To: <WItFh.7822$Jl.2517@newsread3.news.pas.earthlink.net> References: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> <WItFh.7822$Jl.2517@newsread3.news.pas.earthlink.net> Message-ID: <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> Hi, Dennis Lee Bieber ha scritto: > You could maybe use SQLite to load the CSV file and process in an > actual DBMS... Ok, this is the solution I'm using actually (with PostGres). My hope is to find a way to do the same thing without using a DBMS but working directly with the files. Thanks a lot, Paolo From laurent.pointal at limsi.fr Wed Mar 7 04:44:44 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 07 Mar 2007 10:44:44 +0100 Subject: Device Drivers in python(kernel modules) In-Reply-To: <0KgHh.7433$re4.5435@newssvr12.news.prodigy.net> References: <180b672e0703060409i7eca1b65se10923c79a8f5b23@mail.gmail.com> <mailman.4713.1173185473.32031.python-list@python.org> <0KgHh.7433$re4.5435@newssvr12.news.prodigy.net> Message-ID: <esm1i1$p9l$1@news2.u-psud.fr> John Nagle a ?crit : > Thomas Ploch wrote: >> rishi pathak schrieb: >> >>> I am not much of a kernel programmer , I have a requirement to shift a >>> python code to work as a kernel module. >>> So I was just wondering whether we can write a kernel module in python. >>> A thought is that if we can somehow convert python code into a C object >>> code then it can be done. >>> Can some one suggest something..anything > > 3. This is probably a bad idea. If it doesn't have to go in the > operating system kernel, it shouldn't go in the kernel. > > John Nagle I agree. If (under Linux) this is just to provide a driver-like interface (ie. using file-system objects manipulation), OP may take a look at FUSE (Filesystem in Userspace - http://fuse.sourceforge.net/) and its Python binding (http://www.google.fr/search?q=FUSE+%2B+Python). From deets at nospam.web.de Fri Mar 30 07:59:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 Mar 2007 13:59:23 +0200 Subject: Library for windows ini-files ? In-Reply-To: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> References: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> Message-ID: <574cd7F2bhegkU1@mid.uni-berlin.de> stef schrieb: > hello, > > is there a Python library for easy reading and writing windows ini-files ? Isn't ConfigParser ini-style? I'm not totally sure though. Diez From steve at holdenweb.com Wed Mar 21 08:49:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Mar 2007 08:49:39 -0400 Subject: flattening/rolling up/aggregating a large sorted text file In-Reply-To: <1174479568.427193.132740@n59g2000hsh.googlegroups.com> References: <1174479568.427193.132740@n59g2000hsh.googlegroups.com> Message-ID: <etr9nl$1o4$1@sea.gmane.org> adtvff at yahoo.com wrote: > Hi, > > Given a large ascii file (delimited or fixed width) with one ID field > and dimensions/measures fields, sorted by dimensions, I'd like to > "flatten" or "rollup" the file by creating new columns: one for each > combination of dimension level, and summing up measures over all > records for a given ID. > > If the wheel has already been invented, great, please point me in the > right direction. If not, please share some pointers on how to think > about this problem in order to write efficient code. > > Is a hash with dimension level combinations a good approach, with > values reset at each new ID level? > > I know mysql, Oracle etc will do this , but they all have a cap on # > of columns allowed. SAS will allow unlimited columns, but I don't own > SAS. > > Thanks. > > > ID,color,shape,msr1 > ------------------------------ > 001, blue, square, 4 > 001, red , circle, 5 > 001, red, circle, 6 > > > ID, blue_circle, blue_square, red_circle, red_square > -------------------------------------------------------------------------- > 001,0,4,11,0 > 002 ... > It seems a bit wrong-headed to force this problem to fit a solution where you define relations with a variable number of columns when the natural way to solve it would seem to be to sum the msr1 values for each unique combination of ID, color and shape. That's a pretty straightforward relational problem. So, is there some reason the result *has* to have that variable number of columns? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From eric.brunel at pragmadev.com Tue Mar 27 08:03:55 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 27 Mar 2007 14:03:55 +0200 Subject: tkinter popup References: <euaq8n$1l9$1@ss408.t-com.hr> Message-ID: <op.tpujstcdyvwwzh@ericb.pragmadev> On Tue, 27 Mar 2007 12:05:07 +0200, Gigs_ <gigs at hi.t-com.hr> wrote: > Hi all > > I cant figure out how to disable resizing of my popup window? myPopupWindow.wm_resizable(0, 0) It may or may not make resize controls disappear depending on your platform and/or window manager. But the resizing will be impossible in any case. > How to put this popup window to show in the middle of my text editor? > It is writen with Toplevel. A bit trickier. For example (untested): myPopupWindow.after_idle(centerPopupWindow) with: def centerPopupWindow(): x, y = editorWindow.winfo_rootx(), editorWindow.winfo_rooty() w, h = editorWindow.winfo_width(), editorWindow.winfo_height() ww, hh = myPopupWindow.winfo_width(), myPopupWindow.winfo_height() myPopupWindow.geometry('%sx%s+%s+%s', ww, hh, x + w/2 - ww/2, y + h/2 - hh/2) The after_idle trick is needed since the dimensions for the popup window will only be known when the window is actually displayed. In theory, myPopupWindow.update_idletasks() should update the display so that the window dimensions are known, but there are cases where it doesn't work. So the after_idle trick is surer. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mccredie at gmail.com Thu Mar 15 17:09:53 2007 From: mccredie at gmail.com (Matimus) Date: 15 Mar 2007 14:09:53 -0700 Subject: Tkinter menu toplevel or frame In-Reply-To: <etc2tj$1d3$1@ss408.t-com.hr> References: <etc2tj$1d3$1@ss408.t-com.hr> Message-ID: <1173992993.267825.197990@y66g2000hsf.googlegroups.com> > Please tell me is here anything that I should change. The way you have written it, master _must_ be a Toplevel object. So, maybe parent is the correct name, but it doesn't really matter. As a side note, there is no reason for this class to inherit Frame. Aside from packing and sizing the frame, you appear to do nothing else with it. You could just as easily inherit from object. You should never make a custom widget that packs itself anyway. A frame object should act like a frame. What you have made looks more like what I would call an application class. If you are trying to make a Menu, I would inherit from that instead. As an application class (you will still need the new,save... methods to be defined): class MyApp(object): def __init__(self, master=None): if master: self.master = master else: self.master = Tk() frame = Frame(master, width=200, height=200) frame.pack(fill=BOTH, expand=YES) self.makeMenuBar() def makeMenuBar(self): self.menubar = Menu(self.master) self.master.config(menu=self.menubar) pulldown = Menu(self.menubar, tearoff=0) pulldown.add_command(label='New', command=self.new) pulldown.add_command(label='Open', command=self.onOpen) pulldown.add_command(label='Save', command=self.save) pulldown.add_command(label='Save As', command=self.saveas) pulldown.add_separator() pulldown.add_command(label='Exit', command=self.onExit) self.menubar.add_cascade(label='File', underline=0, menu=pulldown) A menu class (this is untested, but it is close to how I would do it): class MyMenu(Menu): def __init__(self, master=None, **kwargs): Menu.__init__(self, master, **kwargs): self.master = master # This is equivalent to self packing, do it outiside of the widget # self.master.config(menu=self.menubar) pulldown = Menu(self, tearoff=0) pulldown.add_command(label='New', command=self.new) pulldown.add_command(label='Open', command=self.onOpen) pulldown.add_command(label='Save', command=self.save) pulldown.add_command(label='Save As', command=self.saveas) pulldown.add_separator() pulldown.add_command(label='Exit', command=self.onExit) self.add_cascade(label='File', underline=0, menu=pulldown) You can use this in the application class: class MyApp(object): def __init__(self, master=None): if master: self.master = master else: self.master = Tk() self.menubar = MyMenu(self.master) self.master.config(menu=self.menubar) frame = Frame(master, width=200, height=200) frame.pack(fill=BOTH, expand=YES) From luismgz at gmail.com Mon Mar 19 11:11:01 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 Mar 2007 08:11:01 -0700 Subject: PythonCard thoughts In-Reply-To: <1174315460.650400.202270@e1g2000hsg.googlegroups.com> References: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> <45fe9b31$0$17946$c3e8da3@news.astraweb.com> <1174315460.650400.202270@e1g2000hsg.googlegroups.com> Message-ID: <1174317061.619314.215200@l77g2000hsb.googlegroups.com> On Mar 19, 11:44 am, "king kikapu" <aboudou... at panafonet.gr> wrote: > > I don't know much about PythonCard or wxGlade, but I use wxPython (which > > wxGlade uses, right?) and you now have the option to separate your GUI > > and code using an XRC file (xml file that describes layout). So perhaps > > this is something you can do with wxGlade, but at the same time it might > > still create the problem you describe above. However, it's very to have > > your Python files contain just logic. > > Yes, both products (PythonCard and wxGlade) uses wxPython. It's just > that PythonCard is sitting on top of wxPython and it intercepts the > events generated. Then it search for an appropriate declared function > on your code and call it (all this happens at runtime). > It shield us from much of the boilerplate code that gui toolkits > require and in the case that you need to address directly wxPython, > you just can! > > I discovered that when you run your designed GUI from PythonCard's > layoutEditor, you have the ability to define a command line option > that is called > "Message Watcher". This, will show you the names of the actual events > that you have to write code for, so you, at least for this, do not > have > to dig the docs for their names. Pretty good! Would you please explain more in detail this "Message Watcher" option? I use PythonCard from time to time, and I find it very easy to use and practical, even considering the small shortcomings you mentioned above, but I have no idea of this feature you're talking about.. Regards, Luis From steve at REMOVE.THIS.cybersource.com.au Thu Mar 29 00:56:15 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 29 Mar 2007 14:56:15 +1000 Subject: which methods to use? References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> <euf11o$rk6$1@aioe.org> <1175130991.799268.311470@n59g2000hsh.googlegroups.com> Message-ID: <pan.2007.03.29.04.56.14.874710@REMOVE.THIS.cybersource.com.au> On Wed, 28 Mar 2007 18:16:31 -0700, s99999999s2003 wrote: > what do you mean by create new object when using list comprehensoin or > list()? Does using slicing create a new object as well? Yes it does. >>> alist = [1, 2, 4, 8, 16] >>> blist = alist # not a copy >>> id(alist) == id(blist) True >>> blist = alist[:] # a copy >>> id(alist) == id(blist) False By the way, "id(obj) == id(another_object)" is just a long way of writing "obj is another_object". In general: - use a list comprehension when you need to calculate the list items - use slicing when you are copying an actual list, or if you don't care what type of object you get - use the list() function when your existing object might not be an actual list, and you want the copy to be a list. E.g. atuple = (1, 2, 3) alist = [2*n+3 for n in atuple] btuple = atuple[:] blist = list(atuple) -- Steven. From jason at tishler.net Fri Mar 16 08:36:51 2007 From: jason at tishler.net (Jason Tishler) Date: Fri, 16 Mar 2007 08:36:51 -0400 Subject: Python Eggs on Cygwin In-Reply-To: <1174005208.972118.104860@l77g2000hsb.googlegroups.com> References: <1174005208.972118.104860@l77g2000hsb.googlegroups.com> Message-ID: <20070316123651.GA3508@tishler.net> Kazu, On Thu, Mar 15, 2007 at 05:33:29PM -0700, Kazu Nisimura wrote: > >>> import MySQLdb > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/MySQLdb/__init__.py", line > 19, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 7, in ? > File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 6, in > __bootstrap__ > ImportError: Permission denied > > This seems to be Eggs/Cygwin problem. Is there any solution? The following is a WAG... Does the MySQL Python module contain shared extension modules (i.e., DLLs)? If so, are they executable? If not, then make them so (i.e., chmod +x). 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 mikeschinkel at gmail.com Sun Mar 11 10:01:13 2007 From: mikeschinkel at gmail.com (Mike Schinkel) Date: Sun, 11 Mar 2007 10:01:13 -0400 Subject: Parsing Indented Text (like parsing Python) In-Reply-To: <op.to01f4bvx6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar> References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com><1173595945.530722.273030@30g2000cwc.googlegroups.com><000a01c763c0$6863a560$2102fea9@Guides.local><op.to0tfybfx6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar><008f01c763de$9a1a4190$0702a8c0@Guides.local> <op.to01f4bvx6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar> Message-ID: <00a701c763e5$bac45c80$0702a8c0@Guides.local> Gabriel Genellina wrote: > > The problem is, how do I figure out how > > many spaces represent a tab? > > You can't, unless you have more context. How does Python do it? > > one case, someone could have their editor configured to > > allow tabs to use 3 spaces and the user could > > intermingle tabs and spaces. In other cases, a user > > might have their editor configured to have a tab equal > > 8 spaces yet also intermingle tabs and spaces. When a > > human looks at the document it is obvious the setting > > but how can I make it obvious to my program? > > > "it is obvious the setting?" How do you infer that? From > other properties of the document, semantics? Just from > the content, and the number of tabs and spaces, you can't > get anything. >From looking at it. It might require changing tab widths in the editor, but one setting will make it clear. > > I could force the user to specify tabwidth at the top > > of the file, but I'd rather not. And since Python > > doesn't either, I know it is possible to write a parser > > to do this. I just don't know how. > > > Python simply assumes 8 spaces per tab. If your Python > source ONLY uses tabs, or ONLY spaces, it doesn't matter. > If you mix tabs+spaces, Python simple replaces each tab > by 8 spaces. If you edited that using 4 spaces, Python > will get it wrong. That's why all people always say > "never mix tabs and spaces" Ah. I didn't know that. Like I said at first, I am new to Python (but I've been reading a lot about it! 3 books thus far. Nutshell, Cookbook, wxPython) Okay, I'll just use a directive at the top of the file and let the user specify. Not perfect, but such is life. Thanks again. -- -Mike Schinkel http://www.mikeschinkel.com/blogs/ http://www.welldesignedurls.org http://atlanta-web.org - http://t.oolicio.us From martinunsal at gmail.com Tue Mar 6 12:24:32 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 6 Mar 2007 09:24:32 -0800 Subject: Project organization and import In-Reply-To: <mailman.4722.1173200207.32031.python-list@python.org> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> <45ec8f2c$0$29110$426a34cc@news.free.fr> <1173199320.094675.58350@p10g2000cwp.googlegroups.com> <mailman.4722.1173200207.32031.python-list@python.org> Message-ID: <1173201871.742845.84040@t69g2000cwt.googlegroups.com> On Mar 6, 8:56 am, "Chris Mellon" <arka... at gmail.com> wrote: > Scrollbar *can't* assume that util will be present in its namespace, > because it won't be unless it imports it. Scrollbar needs to import > its own dependencies. But why do you think thats a problem? OK, maybe I'm totally missing something here, but you can't do "import ../util/common" in Python can you? Look at the directory structure in my original post. How does Scrollbar.py import its dependencies from common.py, without relying on PYTHONPATH? Martin From skip at pobox.com Wed Mar 14 15:21:11 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 14 Mar 2007 14:21:11 -0500 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: <1173899640.547531.99260@l75g2000hse.googlegroups.com> References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <et958a$o9c$1@news2.u-psud.fr> <mailman.5103.1173898419.32031.python-list@python.org> <1173899640.547531.99260@l75g2000hse.googlegroups.com> Message-ID: <17912.19239.431596.566325@montanaro.dyndns.org> >> I find "iter<anything>" to be extremely ugly and hope to avoid using >> them altogether until they are gone in Py3k. Drew> Ugly, maybe, but don't you take a decent performance hit when Drew> loading the entire dict into memory at once? Especially if the Drew> dict is large? Sure, but I try hard to keep my dicts small. ;-) Skip From arkanes at gmail.com Tue Mar 6 12:34:25 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 11:34:25 -0600 Subject: Project organization and import In-Reply-To: <1173201871.742845.84040@t69g2000cwt.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> <45ec8f2c$0$29110$426a34cc@news.free.fr> <1173199320.094675.58350@p10g2000cwp.googlegroups.com> <mailman.4722.1173200207.32031.python-list@python.org> <1173201871.742845.84040@t69g2000cwt.googlegroups.com> Message-ID: <4866bea60703060934g4a20d8bat8a030172c75c2f9@mail.gmail.com> On 6 Mar 2007 09:24:32 -0800, Martin Unsal <martinunsal at gmail.com> wrote: > On Mar 6, 8:56 am, "Chris Mellon" <arka... at gmail.com> wrote: > > Scrollbar *can't* assume that util will be present in its namespace, > > because it won't be unless it imports it. Scrollbar needs to import > > its own dependencies. But why do you think thats a problem? > > OK, maybe I'm totally missing something here, but you can't do > "import ../util/common" in Python can you? > > Look at the directory structure in my original post. How does > Scrollbar.py import its dependencies from common.py, without relying > on PYTHONPATH? > It assumes that util.common is a module thats on the PYTHONPATH. The common way to ensure that this is the case is either to handle util as a separate project, and install it into the system site-packages just as you would any third party package, or to have it (and all your other application packages and modules) off a single root which is where your your application "base" scripts live. This, and other intra-package import issues are affected by the relative/absolute import changes that were begun in Python 2.5, you can read about them here: http://www.python.org/dev/peps/pep-0328/ Note that using relative imports to import a package that "happens" to be share a common higher level directory would be frowned upon. The "blessed" mechanism would still be to use an absolute import, and to install the other package on the PYTHONPATH in one of any number of ways. From lialie at gmail.com Thu Mar 1 03:03:01 2007 From: lialie at gmail.com (lialie) Date: Thu, 01 Mar 2007 16:03:01 +0800 Subject: quickly read a formated file? Message-ID: <45E688B5.1050405@gmail.com> Hi, Is there a fine way to read a formated file like: %HEADER title = "Untilted" username = "User" %DATA ...... ...... The formated file may be very popularly, but the module ConfigPaser doesn't handle it. Is there a way to process it freely? From gigs at hi.t-com.hr Thu Mar 8 10:32:26 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 08 Mar 2007 16:32:26 +0100 Subject: Tkinter menu Message-ID: <esmluc$4bv$1@ss408.t-com.hr> hi i have create widget with menu bar and menus on it. when i resize my widget to less than menubar is than from right to left menus on menubar goes to second row. who to disable that? all I want is that when i resize my widget to less size, that menus on menubar stays on default position . thanks i advance From tinaweb at bestemselv.com Fri Mar 23 09:46:30 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 23 Mar 2007 14:46:30 +0100 Subject: Need help to learn Python In-Reply-To: <1174626206.083519.294730@y66g2000hsf.googlegroups.com> References: <1174626206.083519.294730@y66g2000hsf.googlegroups.com> Message-ID: <IsWdnYjB_MarR57bRVnzvQ@telenor.com> PythonBiter wrote: > Hi everyone, > > I'm very new in this Group as well Python language. I want to learn > Python. So could you please advice me, and guide me how can i become > master in Python ! > > > Thanks, > Partha > Lots of great resources for beginners: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers From gagsl-py2 at yahoo.com.ar Wed Mar 7 02:06:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 04:06:23 -0300 Subject: Wrong exist status for os.system, os.poepen, etc. References: <83e8215e0703060739j3cd924c4o8dc19423e8f49055@mail.gmail.com> <020401c76083$b4072d60$03000080@hendrik> Message-ID: <op.tos4oxl1x6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 07 Mar 2007 02:50:59 -0300, Hendrik van Rooyen <mail at microcorp.co.za> escribi?: > "Paolo Pantaleo" <paolopantaleo at gmail.com> wrote: >> >>> import os >> >>> os.system("/tmp/x") >> 5120 >> > 256 times 20 is 5120 > this is a big/little endian little bug No, it's the old "RTFM" one. -- Gabriel Genellina From rrs at researchut.com Fri Mar 16 03:40:27 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Fri, 16 Mar 2007 13:10:27 +0530 Subject: lock problem References: <mailman.5153.1173996320.32031.python-list@python.org> <1174026699.143415.69940@n59g2000hsh.googlegroups.com> Message-ID: <b8upc4-cq2.ln1@www.researchut.com> Leo Kislov wrote: > You're changing environmental variable __kabc_ldap that is shared > between your threads. Environment is not designed for that kind of > usage, it was designed for settings. Either use an option to set > output file or just redirect stdout. If the interface of ldapsearch is > so lame that it requires environmental variable use env to set the > variable: "env __kabc_ldap=/tmp/wrjhdsf ldapsearch ..." The environment variable is set with temp_file_name which gets the name from tempfile.mkstemp(), which is run in every thread. So I don't think the environment variable is going to be the same. Ritesh -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" From rene at korteklippe.de Thu Mar 1 09:04:55 2007 From: rene at korteklippe.de (=?ISO-8859-1?Q?Ren=E9_Fleschenberg?=) Date: Thu, 01 Mar 2007 15:04:55 +0100 Subject: django learn In-Reply-To: <es6kt4$i9b$1@ss408.t-com.hr> References: <es6kt4$i9b$1@ss408.t-com.hr> Message-ID: <45e6dd7d$0$23137$9b4e6d93@newsspool1.arcor-online.net> Hi Gigs_ schrieb: > I want to learn to make web pages with django. > I dont know nothing about HTML. > > How much of HTML I need to know to be able to learn django well? You need to get a profound knowledge of it, unless you have someone else who does the HTML/Templating for your project. In that case, you could probably get away with learning just the basics. -- Ren? From kyosohma at gmail.com Thu Mar 29 09:45:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 Mar 2007 06:45:04 -0700 Subject: Finding User Profile path In-Reply-To: <mailman.5755.1175174512.32031.python-list@python.org> References: <1175116080.934888.171450@n76g2000hsh.googlegroups.com> <mailman.5745.1175154506.32031.python-list@python.org> <1175173141.277735.192020@o5g2000hsb.googlegroups.com> <mailman.5755.1175174512.32031.python-list@python.org> Message-ID: <1175175904.199745.81460@y80g2000hsf.googlegroups.com> On Mar 29, 8:23 am, Tim Golden <m... at timgolden.me.uk> wrote: > kyoso... at gmail.com wrote: > > One of my co-workers thought I could do > > something like this: > > > c = wmi.WMI() > > for i in c.Win32_UserAccount(Name=user): > > # Get user paths somehow. > > > I messed around with that, but I think he was mistaken. It has lots of > > good info, but not what I need. > > > I apologize for not being specific. I will look at those win32net > > functions. > > > Mike > > Might depend on what you mean by "profile" but would the > users' homeDirectory/homeDrive active directory attributes > or the profilePath be of use here? If so, they're fairly > easy to get hold of. > > TJG Yes. It's the homeDirectory as you say. Once again the IT community's use of multiple terms for the same thing has bitten me. Mike From s99999999s2003 at yahoo.com Wed Mar 28 21:16:31 2007 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 28 Mar 2007 18:16:31 -0700 Subject: which methods to use? In-Reply-To: <euf11o$rk6$1@aioe.org> References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> <euf11o$rk6$1@aioe.org> Message-ID: <1175130991.799268.311470@n59g2000hsh.googlegroups.com> On Mar 29, 8:25 am, Florian Leitner <fleit... at REMcnioOVE.es> wrote: > * s99999999s2... at yahoo.com wrote, On 3/29/07 2:09 AM: > > > hi > > which is the best methods to use for list copying. using list() , [:] > > or create list through list comprehension. what are the differences > > between these ? > > thanks > > depends on what you intend to do: > > -create a new object: > use a list comprehension or list() > > -make a shallow copy: > use copy.copy() or the slicing operator ([:]) > > -make a deep copy (incl. each list element): > use copy.deepcopy() > > Try experimenting around, deleting and adding elements or changing them > in the copy of your list and the original and see what happens if you > are not sure what these things do. (to use copy, import it first) > > flo thanks. what do you mean by create new object when using list comprehensoin or list()? Does using slicing create a new object as well? From fsckedagain at gmail.com Thu Mar 29 10:51:22 2007 From: fsckedagain at gmail.com (fscked) Date: 29 Mar 2007 07:51:22 -0700 Subject: XML/encoding/prolog/python hell... In-Reply-To: <570b3oF2b2uk9U1@mid.uni-berlin.de> References: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> <570b3oF2b2uk9U1@mid.uni-berlin.de> Message-ID: <1175179882.563945.199760@n59g2000hsh.googlegroups.com> Here is what I currently have. Still missing prolog information and namespace info. Encoding is irritating me also. :) import os,sys import csv from elementtree.ElementTree import Element, SubElement, ElementTree, tostring def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i root = Element("boxes") myfile = open('ClientsXMLUpdate.csv') csvreader = csv.reader(myfile) for row in csvreader: mainbox = SubElement(root, "box") r2 = csv.reader(myfile) b = r2.next() mainbox.attrib["city"] = b[10] mainbox.attrib["country"] = b[9] mainbox.attrib["phone"] = b[8] mainbox.attrib["address"] = b[7] mainbox.attrib["name"] = b[6] mainbox.attrib["pl_heartbeat"] = b[5] mainbox.attrib["sw_ver"] = b[4] mainbox.attrib["hw_ver"] = b[3] mainbox.attrib["date_activated"] = b[2] mainbox.attrib["mac_address"] = b[1] mainbox.attrib["boxid"] = b[0] indent(root) ElementTree(root).write('test.xml', "UTF-8") From gagsl-py2 at yahoo.com.ar Tue Mar 20 07:01:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 Mar 2007 08:01:26 -0300 Subject: Load three different modules which have the same name References: <1174329389.488531.270010@p15g2000hsd.googlegroups.com> <1174329764.310542.298430@b75g2000hsg.googlegroups.com> <mailman.5300.1174338208.32031.python-list@python.org> <1174387253.412138.124830@d57g2000hsg.googlegroups.com> Message-ID: <op.tphh8otvx6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar> En Tue, 20 Mar 2007 07:40:53 -0300, abcd <codecraig at gmail.com> escribi?: >> Blerch! Why not just call the modules by the right names in the first >> place? Then each will have its own sys.modules entry for a start ... > > what do i need to do? also, is there a way I can load each one as I > have but each one have its own unique entry in sys.modules? For > example i could load Person from Person (in alpha) as, "Person_Alpha" > or something like that in sys.modules? not sure how I might do that. Use the "as" clause when importing; it's almost the same phrase you wrote above: from alpha.Person import Person as Person_Alpha or something like that. alpha should be a package, as someone already said. -- Gabriel Genellina From eric.brunel at pragmadev.com Mon Mar 12 04:38:58 2007 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 12 Mar 2007 09:38:58 +0100 Subject: UTF-8 References: <mailman.4899.1173535209.32031.python-list@python.org> Message-ID: <op.to2ia8ldyvwwzh@ericb.pragmadev> On Sat, 10 Mar 2007 15:00:04 +0100, Olivier Verdier <chtito at gmail.com> wrote: [snip] > The default encoding i wish to set is UTF-8 since it encodes unicode and > is nowadays the standard encoding. I can't agree with that: there are still many tools completely ignoring the encoding problem, and just saving sequences of bytes for any text. This results in letting the current OS deciding what encoding is used, and this is still not always UTF-8. Just consider how many web pages are still encoded in a local encoding without even any specification of what it may be in the HTML header, or how many times you see a [?] or a black square replacing a character in newsgroups or mailing lists. UTF-8 *should* be the standard encoding, but certainly isn't... > Having ascii as a default encoding is a pretty strange choice since > ascii encodes only 127 characters (suitable only for English, without > fancy symbols like ?) whereas utf-8 encodes virtually infinitely many > characters (suitable for all languages). Besides, utf-8 is a superset of > ascii so having it by default won't harm anything. On the contrary, it's IMHO a very sensible thing to do: any character with a code > 127 could be in any encoding. So supposing an encoding would be guessing, and part of the Python Zen is: "in the face of ambiguity, refuse the temptation to guess". The problem is here that if the encoding is not UTF-8, things can seem to work, but give completely wrong results. So the decision was apparently to use the minimal common set for everything, which is ASCII; this seems quite logical to me. (BTW, one could even argue that the default encoding should be non-existent, as I think there are some non-latin encodings that do not even include ASCII [I think I saw a Chinese encoding like that one day...]. So even supposing that ASCII will work is sometimes wrong...) > At the very least there should be a configuration file that allows to > set a default encoding (although setting anything else than utf-8 should > be advised against). Such a feature would be greatly appreciated by all > of us non native English speakers around the world. Well, I *am* a non-native English speaker, and after the first "why should I bother about all this encoding stuff?" period, which seems to happen to everybody, I finally understood the logic behind Python choices, and why I *should* bother about encodings. Whatever the default encoding is, and whatever you do, encodings will still be a problem for some time. The transition phase from local encodings to universal ones is likely to last a few years more, if not a few decades... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From Thomas.Ploch at gmx.net Wed Mar 14 15:19:20 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Wed, 14 Mar 2007 20:19:20 +0100 Subject: os.path.basename() - only Windows OR *nix? In-Reply-To: <et9h7k$ehr$1@sea.gmane.org> References: <45F843AD.6050509@gmx.net> <et9h7k$ehr$1@sea.gmane.org> Message-ID: <45F84AB8.2010504@gmx.net> Steve Holden schrieb: > Clearly if form['uploadfile'] is returning the client's path information > you do have to remove that somehow before further processing, which also > means you need to deduce what the client architecture is to correctly > remove path data. Of course this also leaves open the question "what > does a Mac client return?", and you might want to cater for that also. I tested from linux and Mac OS, and on both os.path.basename() works as expected (since the server it runs on is a UNIX one). That brings me to the question, how Do I a) get the cients architecture and b) send the architecture of the client through cgi.FieldStorage()? > I suspect you will also find that there are at least some circumstances > under which a Unix browser will also include path information. Which ones should that be? Since os.path.basename() _is_ doing the right thing on *nix style paths (Mac OS is not different there), I cant think of other circumstances. > I presume you are looking to use the same filename that the user > provided on the client? Does this mean that each user's files are > stored in different directories? Otherwise it's not always a good idea > to use filenames provided by the user for files on the server anyway. Yes, each User has his own directory. Files get timestamped and then put into the corresponding directory. It is just that having 'C:\a\very\long\path\file.ext' as a filename on the server is not nice. Thomas From cga2000 at optonline.net Fri Mar 16 22:04:18 2007 From: cga2000 at optonline.net (cga2000) Date: Fri, 16 Mar 2007 21:04:18 -0500 Subject: Mastering Python In-Reply-To: <1174055241.079644.160750@e1g2000hsg.googlegroups.com> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1174052358.486071.163280@e65g2000hsc.googlegroups.com> <1174055241.079644.160750@e1g2000hsg.googlegroups.com> Message-ID: <20070317020418.GA3542@turki.gavron.org> On Fri, Mar 16, 2007 at 09:27:21AM EST, BartlebyScrivener wrote: > On Mar 16, 8:39 am, "Paul McGuire" <p... at austin.rr.com> wrote: > > > > Wow, are you still reading? Quit wasting time and go download a > > Python dist and get started already! > > > > I think you should extract that and spend twenty minutes tidying it up > and then publish it to the Python for Programmers page or make it a > downloadable .pdf. Not sure where it should go. Perhaps add a little nook and cranny link named "facts & advocacy". I'm only an occasional user of Python and admittedly not as well-read as many on this list .. but I must say that this is the first time I run into something that so clearly states what makes Python stand apart from those other .. er .. "difficult" .. should I say .. languages. Make it a wiki so everyone can add his two cents? Start a DocBook, LaTex, CSS.. competition and turn it into some kind of marketing tool with all the trimmings? In any event it would be a shame to waste it. Thanks, cga From steve at REMOVE.THIS.cybersource.com.au Sat Mar 17 19:45:18 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 18 Mar 2007 10:45:18 +1100 Subject: formatting strings to have the same width References: <1174172864.205137.193740@y66g2000hsf.googlegroups.com> Message-ID: <pan.2007.03.17.23.45.16.968087@REMOVE.THIS.cybersource.com.au> On Sat, 17 Mar 2007 16:07:44 -0700, spohle wrote: > hi, > > i got random strings and wanna attach a " | " at the end. now if i > print them i want the | to always be underneath each other. example > code: > > foo = ["aaa", "1232"] > for each in foo: > > print foo[0].center(10, " ") + " | " > foo2 = "1232" > print foo2.center(10, " ") + " | " > > even though i define a constant width on the strings the | don't show > up underneath each other. > any ideas ? Three possibilities: (1) Your code is fine, but whatever you are using to display the strings is wrong because it is using the wrong sort of font. What font are you using? If it is a proportional font, e.g. Times New Roman, then each different character is a different width, and counting characters is not likely to result in equal widths. e.g. compare these two lines: mw mw mw mw mw | il il il il il | If the vertical bars line up, you're (probably) using a fixed-width font like Courier. If they're not, you're (probably) using a proportional font like Ariel or Times. (2) Your code is fine, but your data is bad. You are centering your strings with a width of ten. Is it possible that some of the strings you are passing into the are longer than ten characters? If so, you'll get funny results, because str.center() will never shorten the string you pass it. (3) You code in Python like you write in English: poorly with lots of errors. "Wanna" isn't a word (unless you're trying to be funny), and capitalization is the difference between: I helped my Uncle Jack off a horse and I helped my uncle jack off a horse. After fixing your indentation error, your example code works perfectly for me. Perhaps your real code is different, and part of the difference causes the problem? For instance, your example code seems to do something unlikely to be useful: foo = ["aaa", "1232"] for each in foo: print foo[0].center(10, " ") + " | " That prints the FIRST item each time around the loop, instead of each item. Also, you don't need the second argument to center. By default, space is used as a fill character. -- Steven. From paul at boddie.org.uk Wed Mar 28 08:54:56 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 28 Mar 2007 05:54:56 -0700 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <1175083955.167868.88610@n76g2000hsh.googlegroups.com> References: <mailman.5685.1175032114.32031.python-list@python.org> <1175083955.167868.88610@n76g2000hsh.googlegroups.com> Message-ID: <1175086435.174354.65640@l77g2000hsb.googlegroups.com> On 28 Mar, 14:12, "Kay Schluehr" <kay.schlu... at gmx.net> wrote: > > A somewhat unrelated question. With Py3K Python gets optional type > annotations. No, I believe the consensus is that Python 3000 gets optional annotations which aren't specifically for type information... nudge nudge, wink wink! That last part is important, because that's also how many other people have interpreted this particular feature. I seem to recall that some of the PyPy people weren't interested in static analysis [1], so I'm skeptical about whether type annotations are their kind of thing, either. That said, I imagine that the handling of metadata (including type details) is an element in the way RPython works, but I also imagine that things get more complicated as such metadata diverges from plain type information and into arbitrary "observations" about other aspects of program behaviour. Still, I'd like to see the PyPy people stick their necks out and answer your questions. ;-) Paul [1] http://codespeak.net/pipermail/pypy-dev/2007q1/003607.html From devrim.erdem at gmail.com Fri Mar 30 10:25:03 2007 From: devrim.erdem at gmail.com (DE) Date: 30 Mar 2007 07:25:03 -0700 Subject: Indentation for code readability In-Reply-To: <Xns99039BD4762EFduncanbooth@127.0.0.1> References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> <Xns99039BD4762EFduncanbooth@127.0.0.1> Message-ID: <1175264703.412795.123550@r56g2000hsd.googlegroups.com> Thanks Duncan. I guess you and Peter have been typing in the same minute :) It really looks like a good solution, I wasn't aware this with statement in Python. I can imagine the context handler coming handy in other cases too. Devrim From likwoka at gmail.com Tue Mar 6 11:58:43 2007 From: likwoka at gmail.com (Alex Li) Date: 6 Mar 2007 08:58:43 -0800 Subject: Graphviz Python Binding for Python 2.5 on Windows? In-Reply-To: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> References: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> Message-ID: <1173200323.696497.139590@c51g2000cwc.googlegroups.com> Thanks all for your suggestions. Nick: I am trying to avoid generate the dot file manually so that I can minimize bugs coz by me ;) SPE: Unfortunately that may be too radical ;) I work in a corporate environment (read: MS shop) and my group wants to generate a dependency graph of our system. I was trying to take this opportunity to introduce some python to the group. They were amazed when I came up with the script in a few hours and were willing to try it out by installing python, yapgvb, and graphviz. But it won't work on python 2.5! It's kind of a bummer to tell them to install an older version of python. On second look, I will try pydot again. Despite no release for a long time, it seems to be reasonably complete. Now, I am sure we will redo it in C# after my "prototype"; but that will just prove the advantages of python in terms of code size and productivity :) From bearophileHUGS at lycos.com Wed Mar 21 16:50:29 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Mar 2007 13:50:29 -0700 Subject: parsing combination strings In-Reply-To: <46019843$0$15530$426a74cc@news.free.fr> References: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> <mailman.5416.1174504434.32031.python-list@python.org> <1174504721.913698.178380@e1g2000hsg.googlegroups.com> <46019843$0$15530$426a74cc@news.free.fr> Message-ID: <1174510229.357049.240660@y66g2000hsf.googlegroups.com> Bruno Desthuilliers: > exp = re.compile(r'^([0-9]+)') > for s in ["12ABA", "1ACD", "123CSD"]: > print exp.match(line).group(0) This may be enough too: exp = re.compile(r'\d+') for s in ["12ABA", "1ACD", "123CSD"]: print exp.match(line).group(0) With it: exp.match("a123CSD") = None Bye, bearophile From facundo at taniquetil.com.ar Tue Mar 20 13:00:39 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 20 Mar 2007 17:00:39 +0000 (UTC) Subject: if __name__ == 'main': References: <1174409383.842776.264350@b75g2000hsg.googlegroups.com> Message-ID: <etp3vl$i0b$1@sea.gmane.org> gtb wrote: > I often see the following 'if' construct in python code. What does > this idiom accomplish? What happens if this is not main? How did I get > here if it is not main? > ... > if __name__ == 'main': > myQuest('myQuest').Run() This idiom is for executing the code if you're running the .py directly, or doing nothing if you're just "import"ing the module. Take note, that when you import a module, __name__ gets the module name. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From theller at ctypes.org Thu Mar 22 13:10:00 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 22 Mar 2007 18:10:00 +0100 Subject: Technical Answer - Protecting code in python In-Reply-To: <VAyMh.35$ek6.24@newsfe12.lga> References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> <pan.2007.03.21.16.23.54.575318@REMOVE.THIS.cybersource.com.au> <1tkMh.115$mG4.94@newsfe12.lga> <pan.2007.03.22.07.07.29.369580@REMOVEME.cybersource.com.au> <VAyMh.35$ek6.24@newsfe12.lga> Message-ID: <etud99$rna$1@sea.gmane.org> Bart Willems schrieb: > Aaah, *now* we're getting somewhere... :-) > >>> All he wants is something that turns 'readable, >>> changeable python' into 'unreadable, immutable python'. >> >> chown scriptuser script.py # a unique user >> chmod a-rwx script.py >> chmod u+rx script.py >> >> I believe that fully meets the functional requirements. Where shall I send >> the invoice? > > If it works on the target machine - I am under the assumption that the > client is some kind of government office - more likely to run Windows > than it is to run unix/linux/etc. > > Who has a similar solution for windows? python -m py_compile script.py del script.py Thomas From paul at boddie.org.uk Sun Mar 4 17:26:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Mar 2007 14:26:42 -0800 Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again In-Reply-To: <1173038307.594909.292330@s48g2000cws.googlegroups.com> References: <yTtGh.5001$M65.1427@newssvr21.news.prodigy.net> <45eab67a@news.vo.lu> <3hDGh.5963$jx3.2552@newssvr25.news.prodigy.net> <mailman.4653.1173030677.32031.python-list@python.org> <IRDGh.2764$iw4.51@newssvr23.news.prodigy.net> <1173038307.594909.292330@s48g2000cws.googlegroups.com> Message-ID: <1173047202.430201.240360@30g2000cwc.googlegroups.com> MonkeeSage wrote: > > The configure script checks for libraries and headers that are > required for a base build, and (according to the options passed to > configure, or using the defaults) optional components. There is NO WAY > for it to know which PACKAGES, on any of the 500 linux distributions, > provide those libs and headers. True, but it would be nice to be able to do a configure --with-some- library[=path] and have it give an error if that library isn't found. A lot of tests for specific libraries and headers exist in the autoconf universe, and it's also possible to write custom tests. Of course, this may be academic since distutils has apparently taken over a lot of the work concerning optional modules. > That is the job of the PACKAGER, or > (gasp) the end user if you use a distro without a package system or > trying to build from raw source. There is no passing the buck. If a > package is broken, the packager must fix it. If the source is broken, > the developer must fix it. I guess if you're building from source, you're the packager, yes. These days when I can't find up-to-date packages for my aging distribution, I actually seek out such packages for newer distributions and backport them, mostly because the dependencies have been worked out by someone else. In such circumstances, I'm the packager but I'm using a package infrastructure, as opposed to having to do a lot of the hard work myself. Paul From a.schmolck at gmail.com Sat Mar 31 19:45:16 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 01 Apr 2007 00:45:16 +0100 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed References: <mailman.5803.1175334924.32031.python-list@python.org> <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> Message-ID: <yfsirchf04z.fsf@oc.ex.ac.uk> "Luis M. Gonz?lez" <luismgz at gmail.com> writes: > On Mar 31, 8:38 am, Bjoern Schliessmann <usenet- > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > Mark Dufour wrote: > > > Shed Skin allows for translation of pure (unmodified), implicitly > > > statically typed Python programs into optimized C++, and hence, > > > > ^^^^^> highly optimized machine language. > > > > ^^^^^^^^^^^^^^^^ > > > > Wow, I bet all C++ compiler manufacturers would want you to work for > > them. > > > > Regards, > > > > Bj?rn > > > > -- > > BOFH excuse #23: > > > > improperly oriented keyboard > > > Mark has been doing an heroic job so far. > Shedskin is an impressive piece of software and, if pypy hadn't been > started some time ago, it should have gotten more attention from the > community. Regardless of its merrits, it's GPL'ed which I assume is an immediate turn-off for many in the community. 'as From greg at cosc.canterbury.ac.nz Thu Mar 29 09:05:12 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 30 Mar 2007 01:05:12 +1200 Subject: Weird gcc behaviour with function pointer types Message-ID: <571s0vF2aird9U1@mid.individual.net> In my quest to eliminate C compiler warnings from Pyrex output, I've discovered some utterly bizarre behaviour from gcc 3.3. The following code: void g(struct foo *x) { } void f(void) { void (*h)(struct foo *); h = g; } produces the following warning: blarg.c: In function `f': blarg.c:6: warning: assignment from incompatible pointer type However, adding the following line at the top: typedef struct foo Foo; makes the warning go away. The mere *presence* of the typedef is all that's needed -- it doesn't even have to be used. This looks like a bug in gcc to me -- what do people think? -- Greg From timr at probo.com Wed Mar 28 03:03:29 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 28 Mar 2007 07:03:29 GMT Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916449.171929.138950@n76g2000hsh.googlegroups.com> <pan.2007.03.26.22.17.16.194451@REMOVE.THIS.cybersource.com.au> Message-ID: <2e4k03l8tj9oicmn8c21vobrnvkmdstabr@4ax.com> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote: >On Mon, 26 Mar 2007 06:40:49 -0700, kyosohma wrote: > >> Fortran also appears to be a compiled language, whereas Python is an >> interpreted language. > >Sheesh. Do Java developers go around telling everybody that Java is an >interpreted language? I don't think so. > >What do you think the "c" in ".pyc" files stands for? "Cheese"? Well, I'm being a bit argumentative here, but it's hard to deny that the use of "compiled" in the context of .pyc (or .javac) is very different from the use of "compiled" in the context of running gcc. Once upon a time, Basic enthusiasts would have used the word "tokenized" to describe .pyc files. A .pyc file is, in fact, interpreted by an intermediate language interpreter. I don't understand why anyone would be embarrassed by that. Is it fast enough? It certainly is for MY needs. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Thu Mar 8 15:36:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 17:36:28 -0300 Subject: worker thread catching exceptions and putting them in queue References: <45ec4936$0$323$e4fe514c@news.xs4all.nl> <espdoi$t2l$1@panix3.panix.com> Message-ID: <op.tov0u3gxx6zn5v@furufufa-ec0e13.cpe.telecentro.com.ar> En Thu, 08 Mar 2007 13:31:14 -0300, Aahz <aahz at pythoncraft.com> escribi?: > In article <45ec4936$0$323$e4fe514c at news.xs4all.nl>, > Paul Sijben <paul.sijben at xs4all.nl> wrote: >> >> in a worker thread setup that communicates via queues is it possible to >> catch exceptions raised by the worker executed, put them in an object >> and send them over the queue to another thread where the exception is >> raised in that scope? > > One caution: because exceptions keep stack frames alive, you can have > garbage collection problems. Make sure to del the exception when you're > done with it. Note that it's the traceback who keeps stack frames alive, not the exception itself (at least on the current Python versions, might change in the future). If no fancy processing of the traceback is needed, maybe converting it to string (using the traceback module) before posting it to the queue is enough. -- Gabriel Genellina From laurent.pointal at limsi.fr Fri Mar 30 03:56:50 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 30 Mar 2007 09:56:50 +0200 Subject: Remote XML Parsing In-Reply-To: <1175238860.680426.134400@y80g2000hsf.googlegroups.com> References: <1175238860.680426.134400@y80g2000hsf.googlegroups.com> Message-ID: <euifrk$fv3$1@news2.u-psud.fr> pyapplico at gmail.com a ?crit : > How can I parse a remote XML file with Python? > And what will I be able to do with this XML file in Python? > > Sorry if this is a noob-ish question. You can process XML data with Python as long as you can get it - you will be able to do what you want with it. How do you access your remote file ? ...more details would be wellcome... From mblume at socha.net Sat Mar 17 06:12:40 2007 From: mblume at socha.net (Martin Blume) Date: Sat, 17 Mar 2007 11:12:40 +0100 Subject: Finding the insertion point in a list References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <1174075809.968650.96030@e1g2000hsg.googlegroups.com> Message-ID: <45fbbf18$0$3816$5402220f@news.sunrise.ch> "7stud" schrieb > How about: > > ----------- > x = [0, 100, 200, 1000] > y = -1 > inserted = False > > for i in range(len(x)): > if(y <= x[i]): > x.insert(i, y) > inserted = True > break > if(not inserted): x.append(y) > > print x > ------------ > You can get rid of the sentinel "inserted" using the else clause of the for loop: for i in range(len(x)): if (y <= x[i]): x.insert(i, y) break else: x.append(y) Python is cool :-) IMHO. HTH. Martin From tobiaskk at mac.com Fri Mar 16 15:05:04 2007 From: tobiaskk at mac.com (tobiaskk at mac.com) Date: Fri, 16 Mar 2007 20:05:04 +0100 Subject: Finding the insertion point in a list In-Reply-To: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> Message-ID: <79E19058-8F4A-4DCD-AA6C-E15C623F4C34@mac.com> Or like this: x = [0, 100, 200, 1000] y = 435 for n, i in enumerate(x): if y < i: n = n - 1 break x.insert(n + 1, y) If you decide to stick with n = sum ( y>x[i] for i in range(len(x)) ) - 1 Replace it with: n = sum(y > i for i in x) - 1 Tobias K. From sri1025 at gmail.com Thu Mar 22 09:00:01 2007 From: sri1025 at gmail.com (Srikanth) Date: 22 Mar 2007 06:00:01 -0700 Subject: Removing a particular index from a list Message-ID: <1174568401.369232.106990@b75g2000hsg.googlegroups.com> Hi, list.remove(item) removes the first item from the list, but how do I say to remove a particular index from a list without using it's value? Let's say I have 4 items in my list as >>> li = ["sri", "s", "srikanth", "s"] And if I want to remove the last item ("s"), how do I remove it? li.remove(-1) doesn't do it. This is my problem. Thanks, Srikanth From steve at REMOVE.THIS.cybersource.com.au Sun Mar 4 08:47:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 05 Mar 2007 00:47:37 +1100 Subject: pop method question References: <mailman.4633.1172954118.32031.python-list@python.org> <1172968335.511875.255750@p10g2000cwp.googlegroups.com> <mailman.4638.1172976888.32031.python-list@python.org> <1172979629.812957.156820@i80g2000cwc.googlegroups.com> <mailman.4647.1173011758.32031.python-list@python.org> Message-ID: <pan.2007.03.04.13.47.36.717482@REMOVE.THIS.cybersource.com.au> On Sun, 04 Mar 2007 07:36:50 -0500, Nicholas Parsons wrote: > Hi Jordan, > > That is true what you say about pop() behavior with stack-like > objects. But the definition of pop() for a stack-like structure is > stronger than that. That's okay, we're not talking about pop for stack-like structures, we're talking about pop for dictionaries. > A stack is a LIFO data structure. Therefore the > pop() operation is defined to not only mutate the receiver and return > the item popped but also ensure that the LAST item in the stack is > removed. Not so. Pop can also be defined to take an argument telling the data structure (not necessarily a stack) which item to remove. Pop can also operate on queues, in which case it removes the FIRST item in the queue. Pop can also be defined for dequeues (double-ended queue), in which case it can remove from either the first or the last position. Pop can also be defined for balloons, which is what they do when you stick a pin in them. > This makes perfect sense for a list type in python since > lists are mutable sequences that have a specified order. But for > dictionaries this does not hold since they are unordered sequences by > definition. That's okay, since unordered sequences can define pop too. Obviously pop for a dictionary has to be defined slightly differently, but the essential characteristics -- remove an item and return it -- remain the same. > So for dictionaries it would not make sense for a > programmer to simulate a stack-like type. Dictionaries don't simulate stacks. We can talk about pushing a value onto a stack, and about pushing a value into a register, and yet registers are not stacks. We use the same word, multiply, for both scalar multiplication (3*5=15), matrix multiplication, and mixed scalar-to-matrix multiplication, even though they are quite different. (For starters, XY = YX if X and Y are both scalars, but not if they are matrices.) We use "concatenate" to describe the different procedures of joining linked lists, arrays and strings. We talk about "inserting" into linked lists, B-trees, heaps, arrays and priority queues. Why shouldn't we talk about popping a value from a dictionary? > While we're on the subject I'm also curious as to why the author of > the built-in list class called the method "append" to add an element > to the end of a list and not something like "push". Well, gosh, I really don't know what they were thinking, using "append" as the name of the method that, um, APPENDS an item to the end of a list. How confusing is that? > But this is not > really much of a problem if the programmer could create an alias for > it. It isn't a problem at all. -- Steven. From joshua at eeinternet.com Wed Mar 21 15:28:06 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 21 Mar 2007 11:28:06 -0800 Subject: python QT or python-GTK References: <45fdb561$0$17201$4c368faf@roadrunner.com> <CFkLh.128940$_73.66143@newsread2.news.pas.earthlink.net> Message-ID: <46017ac9$0$16316$88260bb3@free.teranews.com> Dennis Lee Bieber wrote: > On Sun, 18 Mar 2007 11:55:47 -1000, "Jon Van DeVries" > <j23212 at hotmail.com> declaimed the following in comp.lang.python: > >> ** All the posts found in google are old. I'm assuming new improvements >> have been made to both IDEs. ** >> >> Please correct me if I'm wrong, I'm a newbie. >> >> 1. Which one of them requires fewer lines to accomplish the same thing? >> from what I understand QT it's just like Borland J-Builder. Meaning, you >> want a button, you draw it, then you double-click on it, a window opens >> up and you type events and behavior. And with GTK, you just type >> everything. >> > For the most part, none of the GUI TOOLKITS (not IDEs) includes a > drag&drop GUI BUILDER. Toolkits are libraries defining an API (in the > case of Python to an underlying toolkit... wxPython is the Python > front-end to wxWidgets). For all the toolkits, the basic operation is > "just type everything" -- an intermediate mode is where one manipulates > a configuration file that gets loaded at run-time, and which one > registers handlers against (my largest GUI application was 15 years ago, > emulating a Ramtek graphics engine using DECWindows -- it had > multi-thousand lines of config file in xt; the config file was nearly as > long as the C code that used it). I'm not sure if you're referring to something else, or aren't aware of Qt Designer. You can design your GUI's in the designer, run py-uic (comes with PyQt) and you have python code for your GUI. You then load that up, and do your custom slot connections at run time. You can also take the XML files generated by Qt Designer and load and render them at runtime too. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From bignose+hates-spam at benfinney.id.au Tue Mar 6 16:58:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 07 Mar 2007 08:58:13 +1100 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <mailman.4685.1173114917.32031.python-list@python.org> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <45ec9ba3$0$2333$426a34cc@news.free.fr> <1173167617.207318.22400@h3g2000cwc.googlegroups.com> <45ed41f7$0$21515$426a74cc@news.free.fr> <1173198244.092412.17400@n33g2000cwc.googlegroups.com> Message-ID: <87wt1uyqyy.fsf@benfinney.id.au> "Martin Unsal" <martinunsal at gmail.com> writes: > I think you should be asking yourselves, "Did we all abandon reload() > because it is actually an inferior workflow, or just because it's > totally broken in Python?" I never "abandoned reload()", because it never even occurred to me to use the interpreter for developing the code that I know is going to end up in a file anyway. That's what my text editor is for. -- \ "I have a microwave fireplace in my house. The other night I | `\ laid down in front of the fire for the evening in two minutes." | _o__) -- Steven Wright | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Sun Mar 4 16:14:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Mar 2007 22:14:31 +0100 Subject: Perl and Python, a practical side-by-side example. In-Reply-To: <1172894223.669617.79060@31g2000cwt.googlegroups.com> References: <mailman.4614.1172875489.32031.python-list@python.org> <45e8c931$0$8646$426a34cc@news.free.fr> <1172894223.669617.79060@31g2000cwt.googlegroups.com> Message-ID: <45eb2ec4$0$26053$426a74cc@news.free.fr> John Machin a ?crit : > On Mar 3, 12:36 pm, Bruno Desthuilliers > > [snip] > >> DATE = 5 >> TARGET = 6 > > [snip] > >>Now for the bad news: I'm afraid your algorithm is broken : here are my >>test data and results: >> >>input = [ >> #ID STATE ... ... ... TARG DATE >> "aaa\tAAA\t...\t...\t...\tBBB\t20071212\n", > > [snip] > > Bruno, The worse news is that your test data is broken. Re-reading the OP's specs, the bad news is that my only neuron left is broken. Shouldn't code at 2 o'clock in the morning :( From gregturn at mindspring.com Wed Mar 28 16:19:17 2007 From: gregturn at mindspring.com (Goldfish) Date: 28 Mar 2007 13:19:17 -0700 Subject: newbi question on python rpc server, how it works? In-Reply-To: <gqidnWn2ZNOAIZfbnZ2dnUVZ_uiknZ2d@comcast.com> References: <mailman.5720.1175107122.32031.python-list@python.org> <gqidnWn2ZNOAIZfbnZ2dnUVZ_uiknZ2d@comcast.com> Message-ID: <1175113157.444584.166910@y80g2000hsf.googlegroups.com> > > I have a need where I need to create a layer of business logic that > > will connect to mysql database at one end and a wxpython based thin > > client at the other end. Spring Python offers something similar (http://springpython.python- hosting.com/wiki/DistributedRemoting) to link up clients withs servers. You can code locally, and then when it is time to split things up between different workstations, you can reconfigure the networking. There is a demo application, PetClinic (http://springpython.python- hosting.com/wiki/PetClinic) that shows a database component, remoting pieces, and finally a front end. The current version of PetClinic is a web app. In the near future, we are planning to build a wxPython front end to show more reusability of components. From bearophileHUGS at lycos.com Thu Mar 1 06:02:36 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Mar 2007 03:02:36 -0800 Subject: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple) In-Reply-To: <1172727871.032664.165240@j27g2000cwj.googlegroups.com> References: <slrneubq5t.1j3.rshepard@salmo.appl-ecosys.com> <87slcqvskr.fsf@benfinney.id.au> <mailman.4538.1172705434.32031.python-list@python.org> <54ms6fF21c6h3U2@mid.individual.net> <mailman.4550.1172720725.32031.python-list@python.org> <1172727871.032664.165240@j27g2000cwj.googlegroups.com> Message-ID: <1172746956.836438.53470@p10g2000cwp.googlegroups.com> George Sakkis, I agree with the things you say. Sometimes you may have a sequence of uniform data with unknown len (so its index doesn't have semantic meaning). You may want to use it as dict key, so you probably use a tuple meant as just an immutable list. I don't know Ruby, but I think it allows such purposes with a freezing function. Bye, bearophile From jeba_ride at yahoo.com Sat Mar 10 14:46:32 2007 From: jeba_ride at yahoo.com (Clement) Date: 10 Mar 2007 11:46:32 -0800 Subject: Help on Dict In-Reply-To: <pan.2007.02.26.06.58.33.493117@REMOVEME.cybersource.com.au> References: <1172426014.539055.300330@j27g2000cwj.googlegroups.com> <YpmEh.1332$jx3.1308@newssvr25.news.prodigy.net> <mailman.4393.1172471167.32031.python-list@python.org> <pan.2007.02.26.06.58.33.493117@REMOVEME.cybersource.com.au> Message-ID: <1173555992.697337.222390@n33g2000cwc.googlegroups.com> On Feb 26, 11:58 am, Steven D'Aprano <s... at REMOVEME.cybersource.com.au> wrote: > On Mon, 26 Feb 2007 07:15:43 +0200, Hendrik van Rooyen wrote: > > "James Stroud" <jstr... at mbi.ucla.edu> wrote: > > >> Clement wrote: > >> > Can any body tell how Dict is implemented in python... plz tell what > >> > datastructure that uses................ > > >> I think it uses a dict. > > > "Groan!" - this answer is like Microsoft documentation - > > while technically correct, it is useless... : - ) > > Which I think was deliberate. The Original Poster asked a reasonable > question in a stupid way (Python is case-insensitive -- are we supposed > to guess what a Dict is? what language is 'plz'?), and I believe James > deliberately gave a stupid answer to highlight that. > > class Dict(dict): > pass > > is what I thought of when I saw the question. I guess James might have > thought the same way. > > Unfortunately, more often than not, the sort of person who uses 'plz' in > an email probably isn't going to recognise the subtleties of James' reply. > > -- > Steven D'Aprano ada koothingala From gtcopeland at gmail.com Tue Mar 20 12:23:38 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 20 Mar 2007 09:23:38 -0700 Subject: Freezing Python Apps on Linux? Message-ID: <1174407818.180395.18480@n76g2000hsh.googlegroups.com> I seem to recall several different applications which can create standalone binaries for python on Linux. I know freeze.py and cx_Freeze.py exist. Are these still the preferred methods of creating a stand alone binary out of a python application on Linux? Greg From kw at codebykevin.com Tue Mar 27 10:07:22 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 27 Mar 2007 10:07:22 -0400 Subject: Use threads or Tkinter event loop? In-Reply-To: <ccd8f$460924a2$4275d90a$15349@FUSE.NET> References: <ccd8f$460924a2$4275d90a$15349@FUSE.NET> Message-ID: <11624$4609251b$4275d90a$15349@FUSE.NET> Kevin Walzer wrote: > I'm trying to decide whether I need threads in my Tkinter application or > not. My app is a front end to a command-line tool; it feeds commands to > the command-line program, then reads its output and displays it in a > Tkinter text widget. Some of the commands are long-running and/or return > thousands of lines of output. > > I initially thought I needed to use threading, because the GUI would > block when reading the output, even when I configured the blocking to be > non-blocking. I got threading to work, but it seemed a bit complicated. > So, I decided to try something simpler, by using the Tkinter event loop > to force the output to update/display. > > it seems to work well enough. Here is my threaded code: > > non-threaded: > > def insertDump(self): > self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > for line in self.finkinstalled: > self.t.insert(END, line) > self.update() > self.t.see(END) > > And here is my non-threaded code (needs two functions to work) > > def insertDump(self): > try: > data = self.dataQueue.get(block=False) > for line in data: > self.t.insert(END, line) > self.t.see(END) > self.update() > > > except: > print "error" > raise > > def getDump(self): > > self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) > self.dataQueue.put(self.file) > > This brings me to a design, as opposed to coding, question. The > non-threaded version seems to work just as well as the threaded one, in > terms of speed. Moreover, it is simpler to code and debug, because I > don't have to check to make sure the thread queue has data (I sometimes > get an 'Empty' error message when I first start the thread). Simply > using the Tk event loop (self.update) is also how I would have coded > this in Tcl. > > So my question is this: under what circumstances in Python are threads > considered "best practice"? Am I wrong to use the Tk event loop instead > of threads? > D'oh, I got the code snippets mixed up: non-threaded: def insertDump(self): self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) for line in self.finkinstalled: self.t.insert(END, line) self.update() self.t.see(END) threaded: def insertDump(self): try: data = self.dataQueue.get(block=False) for line in data: self.t.insert(END, line) self.t.see(END) self.update() except: print "error" raise def getDump(self): self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK) self.dataQueue.put(self.file) Sorry! -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jgodoy at gmail.com Sun Mar 4 20:20:08 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 04 Mar 2007 22:20:08 -0300 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> Message-ID: <87mz2s32rb.fsf@gmail.com> "Martin Unsal" <martinunsal at gmail.com> writes: > 1) Namespace. Python wants my namespace heirarchy to match my filesystem > heirarchy. I find that a well organized filesystem heirarchy for a > nontrivial project will be totally unwieldy as a namespace. I'm either > forced to use long namespace prefixes, or I'm forced to use "from foo import > *" and __all__, which has its own set of problems. I find it nice. You have the idea of where is something just from the import and you don't have to search for it everywhere. Isn't, e.g., Java like that? (It's been so long since I last worried with Java that I don't remember if this is mandatory or just a convention...) You might get bitten with that when moving files from one OS to another, specially if one of them disconsider the case and the other is strict with it. > 1a) Module/class collision. I like to use the primary class in a file as the > name of the file. However this can lead to namespace collisions between the > module name and the class name. Also it means that I'm going to be stuck > with the odious and wasteful syntax foo.foo everywhere, or forced to use > "from foo import *". Your classes should be CamelCased and start with an uppercase letter. So you'd have foo.Foo, being "foo" the package and "Foo" the class inside of it. > 1b) The Pythonic way seems to be to put more stuff in one file, but I > believe this is categorically the wrong thing to do in large projects. The > moment you have more than one developer along with a revision control > system, you're going to want files to contain the smallest practical > functional blocks. I feel pretty confident saying that "put more stuff in > one file" is the wrong answer, even if it is the Pythonic answer. Why? RCS systems can merge changes. A RCS system is not a substitute for design or programmers communication. You'll only have a problem if two people change the same line of code and if they are doing that (and worse: doing that often) then you have a bigger problem than just the contents of the file. Unit tests help being sure that one change doesn't break the project as a whole and for a big project you're surely going to have a lot of those tests. If one change breaks another, then there is a disagreement on the application design and more communication is needed between developers or a better documentation of the API they're implementing / using. > 2) Importing and reloading. I want to be able to reload changes without > exiting the interpreter. This pretty much excludes "from foo import *", > unless you resort to this sort of hack: > > http://www.python.org/search/hypermail/python-1993/0448.html > > Has anyone found a systematic way to solve the problem of reloading in an > interactive interpreter when using "from foo import *"? I don't reload... When my investigative tests gets bigger I write a script and run it with the interpreter. It is easy since my text editor can call Python on a buffer (I use Emacs). > I appreciate any advice I can get from the community. This is just how I deal with it... My bigger "project" has several modules now each with its own namespace and package. The API is very documented and took the most work to get done. Using setuptools, entrypoints, etc. helps a lot as well. The thing is that for big projects your design is the most important part. Get it right and you won't have problems with namespaces and filenames. If you don't dedicate enough time on this task you'll find yourself in trouble really soon. -- Jorge Godoy <jgodoy at gmail.com> From kyosohma at gmail.com Mon Mar 19 16:01:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Mar 2007 13:01:57 -0700 Subject: Anything available that can read Microsoft .MDB files from Python? In-Reply-To: <WLBLh.10082$M65.2647@newssvr21.news.prodigy.net> References: <vdBLh.1337$rj1.1043@newssvr23.news.prodigy.net> <56863eF27p5bmU1@mid.uni-berlin.de> <WLBLh.10082$M65.2647@newssvr21.news.prodigy.net> Message-ID: <1174334517.125928.274140@l75g2000hse.googlegroups.com> On Mar 19, 2:45 pm, John Nagle <n... at animats.com> wrote: > Diez B. Roggisch wrote: > > John Nagle schrieb: > > >> I'm looking for something that can read .MDB files, the format > >> Microsoft Access uses, from Python. I need to do this on > >> Linux, without using Microsoft tools. I just need to read > >> the files once, so I can load the tables into another database. > >> Speed isn't an issue, and I don't need to access the file in > >> database fashion. The files are too big to read into RAM all at once, > >> though. > > >> I tried "MDBtools", but the only (last) release was > >> a pre-release three years ago, and I've encountered > >> many build problems trying to make it work on Fedora > >> Core 6. > > > I was just gonna suggest it. Under ubuntu, it works easy as cake, and > > converts the mdb nicely to some CSV-files. > > > I think you should really try and make it work. > > > Diez > > What MDBtools did you install? The RPM, a checkout from CVS, > or the downloadable distribution? They're all different. > > John Nagle I've read .MDB files using ODBC. I don't know how big your files are, but I had a file with almost 3000 rows and I was able to fetch it in 1-2 seconds. If you want to give it whirl, you just need to create an ODBC connection and then do the following: myconn = odbc.odbc('mydb_connection_name') mycursor = myconn.cursor() mycursor.execute('SELECT * FROM db_name') mydata = mycursor.fetchall() mycursor.close() myconn.close() for each in mydata: # do something like pull the info from the variable "mydata" and send it into the other database It is fast. But you may like what the others have said more. Mike From attn.steven.kuo at gmail.com Mon Mar 12 20:04:08 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 12 Mar 2007 17:04:08 -0700 Subject: Request for a change in the csv module. In-Reply-To: <1173741982.944813@jubilee.claranet.pt> References: <1173741982.944813@jubilee.claranet.pt> Message-ID: <1173744248.195944.245550@t69g2000cwt.googlegroups.com> On Mar 12, 4:26 pm, Paulo da Silva <psdasil... at esotericaX.ptX> wrote: > Hi. > > I have just seen that csv module, more exactly the Dialect class, > does not have any variable to specify the "floating point" character! > In portuguese this is ','. Not '.'. 3.1415 -> 3,1415. > I think this is also the case of other languages/countries. > If I am correct, i.e. if there is no such possibility, where can > I file a request for a csv change? Excel, for example, automatically > converts '.' to ',' and the separator from ',' to ';'. > Try using locale.format when writing: import csv import locale locale.setlocale(locale.LC_NUMERIC, 'pt_BR.ISO8859-1') csv_writer = csv.writer(open("foo.csv","w"), dialect='excel') rows = (('testing', 1.23), ('testing', 2.34)) formatted_rows = ((string, locale.format('%g', number)) for (string,number) in rows) csv_writer.writerows(formatted_rows) locale.atof and locale.atoi can convert a string back to a number. -- Hope this helps, Steven From steve at REMOVE.THIS.cybersource.com.au Wed Mar 21 12:59:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 03:59:38 +1100 Subject: Garbage collection References: <etrb1q$t01$1@gemini.csx.cam.ac.uk> <mailman.5394.1174484981.32031.python-list@python.org> <etrhfo$bv3$1@gemini.csx.cam.ac.uk> <mailman.5398.1174490143.32031.python-list@python.org> <etrj61$euc$1@gemini.csx.cam.ac.uk> Message-ID: <pan.2007.03.21.16.59.37.377396@REMOVE.THIS.cybersource.com.au> On Wed, 21 Mar 2007 15:32:17 +0000, Tom Wright wrote: >> Memory contention would be a problem if your Python process wanted to keep >> that memory active at the same time as you were running GIMP. > > True, but why does Python hang on to the memory at all? As I understand it, > it's keeping a big lump of memory on the int free list in order to make > future allocations of large numbers of integers faster. If that memory is > about to be paged out, then surely future allocations of integers will be > *slower*, as the system will have to: > > 1) page out something to make room for the new integers > 2) page in the relevant chunk of the int free list > 3) zero all of this memory and do any other formatting required by Python > > If Python freed (most of) the memory when it had finished with it, then all > the system would have to do is: > > 1) page out something to make room for the new integers > 2) zero all of this memory and do any other formatting required by Python > > Surely Python should free the memory if it's not been used for a certain > amount of time (say a few seconds), as allocation times are not going to be > the limiting factor if it's gone unused for that long. Alternatively, it > could mark the memory as some sort of cache, so that if it needed to be > paged out, it would instead be de-allocated (thus saving the time taken to > page it back in again when it's next needed) And increasing the time it takes to re-create the objects in the cache subsequently. Maybe this extra effort is worthwhile when the free int list holds 10**7 ints, but is it worthwhile when it holds 10**6 ints? How about 10**5 ints? 10**3 ints? How many free ints is "typical" or even "common" in practice? The lesson I get from this is, instead of creating such an enormous list of integers in the first place with range(), use xrange() instead. Fresh running instance of Python 2.5: $ ps up 9579 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND steve 9579 0.0 0.2 6500 2752 pts/7 S+ 03:42 0:00 python2.5 Run from within Python: >>> n = 0 >>> for i in xrange(int(1e7)): ... # create lots of ints, one at a time ... # instead of all at once ... n += i # make sure the int is used ... >>> n 49999995000000L And the output of ps again: $ ps up 9579 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND steve 9579 4.2 0.2 6500 2852 pts/7 S+ 03:42 0:11 python2.5 Barely moved a smidgen. For comparison, here's what ps reports after I create a single list with range(int(1e7)), and again after I delete the list: $ ps up 9579 # after creating list with range(int(1e7)) USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND steve 9579 1.9 15.4 163708 160056 pts/7 S+ 03:42 0:11 python2.5 $ ps up 9579 # after deleting list USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND steve 9579 1.7 11.6 124632 120992 pts/7 S+ 03:42 0:12 python2.5 So there is another clear advantage to using xrange instead of range, unless you specifically need all ten million ints all at once. -- Steven. From gregor at hostgis.com Wed Mar 7 11:35:08 2007 From: gregor at hostgis.com (Gregor Mosheh) Date: Wed, 7 Mar 2007 09:35:08 -0700 (MST) Subject: How to build a Windows service using win32? In-Reply-To: <1173272513.976647.99630@n33g2000cwc.googlegroups.com> References: <mailman.4748.1173263972.32031.python-list@python.org> <1173272513.976647.99630@n33g2000cwc.googlegroups.com> Message-ID: <3791.168.103.93.50.1173285308.squirrel@maps.hostgis.com> Giles Brown wrote: > Yeah. You've cleverly decided to simplify the "smallest possible > python service" by removing the > if __name__ == '__main__': Ha ha. :) Seriously, though, I removed that long after it was failing to work, and have since replaced it and it didn't affect a thing. Gabriel Genellina wrote: > Have you installed the pywin32 package from > https://sourceforge.net/projects/pywin32/ ? > The code skeleton looks OK to me. Indeed, I have win32 installed. I'm used to writing wx applications, compiling into exes, etc. Services are a new direction for me. So, both of you say that the program I sent *did* work? -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: EDMS-to-CG.py URL: <http://mail.python.org/pipermail/python-list/attachments/20070307/f34f1ebe/attachment.ksh> From kyosohma at gmail.com Fri Mar 23 14:04:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Mar 2007 11:04:40 -0700 Subject: exit to interpreter? In-Reply-To: <mailman.5522.1174672336.32031.python-list@python.org> References: <mailman.5522.1174672336.32031.python-list@python.org> Message-ID: <1174673079.976162.307960@n76g2000hsh.googlegroups.com> On Mar 23, 12:52 pm, belinda thom <b... at cs.hmc.edu> wrote: > Hi, > > I'm writing a function that polls the user for keyboard input, > looping until it has determined that the user has entered a valid > string of characters, in which case it returns that string so it can > be processed up the call stack. My problem is this. I'd also like it > to handle a special string (e.g. 'quit'), in which case control > should return to the Python command line as opposed to returning the > string up the call stack. > > sys.exit seemed like a good choice, but it exits the python interpreter. > > I could use an exception for this purpose, but was wondering if > there's a better way? > > --b If you're using a function, wouldn't using the keyword "return" work? Mike From _karlo_ at _mosor.net_ Wed Mar 21 14:54:39 2007 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Wed, 21 Mar 2007 18:54:39 +0000 (UTC) Subject: How to copy a ClassObject? References: <Xns98F98FEF2B9A6mosornet@161.53.160.64> <Xns98F993D63F87Dmosornet@161.53.160.64> <Xns98F995B5964F6duncanbooth@127.0.0.1> Message-ID: <Xns98FACA8AE3544mosornet@161.53.160.64> Duncan Booth <duncan.booth at invalid.invalid> wrote in news:Xns98F995B5964F6duncanbooth at 127.0.0.1: > Consider yourself corrected. > > You could do what you are attempting with: > > tmp = new.classobj('tmp', First.__bases__, dict(First.__dict__)) > > which creates a new class named 'tmp' with the same base classes and > a copy of First's __dict__ except that the __name__ attribute for the > new class will be set to 'tmp'. The attribute values are still shared > between the classes (which is significant only if they are mutable), > but otherwise they won't be sharing state. > I have no idea why you would want to do this, nor even why you would > want a 'name' attribute when Python already gives you '__name__'. First of all, thanks for a clarification. 'name' attribute was just a (dumb) example, it was the first thing to come to mind. The idea behind all of this was to create classes dynamicaly, without knowing in advance their names, or base class(es). So I figured I'd just copy the base class and modify the attributes. Instead, this way of subclassing seems to work just right for my purposes. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Mar 3 18:46:22 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 04 Mar 2007 00:46:22 +0100 Subject: Problem with returning prime number in a simple calculation program References: <1172964996.193310.251650@j27g2000cwj.googlegroups.com> Message-ID: <54ufmeF22b8naU1@mid.individual.net> QHorizon at gmail.com wrote: > [reformatted indentation] > def prime(): > num = input("Number ") > i = num - 1 > divcounter = 0 > while i > 1: > if num % i != 0 > divcounter += 1 > i -= 1 > if divcounter == num - 2: > print num, "is a prime number" > else: > print num, "is not a prime number" > [...] > As it says in the title, I'm having trouble with the prime number > function. It will print the sentence if the number is prime, but > it if isn't, the program goes into a state in the terminal where > the program never ends and you can just keep on typing. Sure thing. You designed the function to behave this way. Look at the while loop -- especially think what happens if (num % i == 0). i will never be decremented then and the function will not terminate. Try inserting print statements for debugging if you don't get what I meant here. > Maybe the else statement is ineffective? No one can read your thoughts. In which way effective? Regards, Bj?rn -- BOFH excuse #86: Runt packets From mmara at fibertel.com.ar Wed Mar 28 16:44:46 2007 From: mmara at fibertel.com.ar (mmara at fibertel.com.ar) Date: Wed, 28 Mar 2007 17:44:46 -0300 Subject: Creating a new data structure while filtering its data origin. Message-ID: <a6f5531646c8.460aa98e@fibertel.com.ar> Hi everyone. I'm trying to work with very simple data structures but I'm stuck in the very first steps. If someone has the luxury of a few minutes and can give an advice how to resolve this, I'll really appreciate it. 1- I have a list of tuples like this: lista= [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2), (168, 141, 2), (168, 141, 2), (201, 141, 1), (213, 141, 1), (203, 141, 1), (562, 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568, 142, 2), (568, 142, 2), (501, 142, 1), (513, 142, 1), (503, 142, 1)] and I want to end with a dict like this: {141: {1: [203, 213, 201], 2: [168, ], 3: [162, ]}, 142: {1: [503, 513, 501], 2: [568, ], 4: [562, ]}} the logic of the final output: a) the outer dict's key is a set() of the 2rd value of the input. b) the inner dict's key is a set() of the 3th value for tuples which 3rd value equals a). c) the inner list will be fill up with the 1st value of every tuple which 3rd value equals b) and its 2rd value equals a). So far, the only thing it seems I can achieve is the first part: outer_dict = dict([(x,dict()) for x in set(row[1] for row in lista)]) >From then on, I'm starting to get tired after several successful failures (I tried with itertools, with straight loops ...) and I don't know which can be the easier way to get that final output. Thanks in advance. From pecora at anvil.nrl.navy.mil Sat Mar 10 12:22:50 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sat, 10 Mar 2007 12:22:50 -0500 Subject: Is this right? Multiple imports of same module. References: <pecora-B92BB8.09304609032007@ra.nrl.navy.mil> <mailman.4878.1173485909.32031.python-list@python.org> Message-ID: <pecora-C6EE6E.12225010032007@ra.nrl.navy.mil> In article <mailman.4878.1173485909.32031.python-list at python.org>, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > Lou Pecora <pecora at anvil.nrl.navy.mil> writes: > > > ['import mymodule' in three separate modules] > > > > Then mymodule is imported only once, but each module has access to > > it through the module name (mod1 and mod2) and the alias MM (mod3). > > Is that right? > > Not quite. The module is imported three times, and is assigned to > three different namespaces; but the code in the module is executed > only once, the first time it is imported. Each subsequent import skips > the "execute the code" step. Thanks. That's clear. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From MonkeeSage at gmail.com Fri Mar 2 23:23:54 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 2 Mar 2007 20:23:54 -0800 Subject: class attrdict In-Reply-To: <1hud4hf.r52pr7wyx0adN%aleax@mac.com> References: <hbf.20070302nsi@bombur.uio.no> <1hud4hf.r52pr7wyx0adN%aleax@mac.com> Message-ID: <1172895832.352834.313300@p10g2000cwp.googlegroups.com> On Mar 2, 9:25 pm, a... at mac.com (Alex Martelli) wrote: > The problem is mostly that, given an instance a of attrdict, whether you > can call (e.g.) a.update(foo) depends on whether you ever set > a['update'], making the whole program extremely fragile -- a very high > price to pay for some modest amount of syntax sugar. How about something like... class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) for k, v in self.items(): dict.__setattr__(self, str(k), v) def __setitem__(self, k, v): dict.__setitem__(self, k, v) dict.__setattr__(self, str(k), v) __setattr__ = __setitem__ Regards, Jordan From MonkeeSage at gmail.com Fri Mar 2 21:06:03 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 2 Mar 2007 18:06:03 -0800 Subject: Sort with extra variables In-Reply-To: <pan.2007.03.03.01.34.16@gmail.com> References: <pan.2007.03.02.19.29.39@gmail.com> <54rchkF21jehuU1@mid.uni-berlin.de> <pan.2007.03.02.23.12.08@gmail.com> <1172877633.676612.141450@31g2000cwt.googlegroups.com> <pan.2007.03.02.23.51.54@gmail.com> <1172881667.825628.93490@t69g2000cwt.googlegroups.com> <pan.2007.03.03.01.34.16@gmail.com> Message-ID: <1172887563.909151.191340@8g2000cwh.googlegroups.com> On Mar 2, 7:34 pm, Thomas Dybdahl Ahle <lob... at gmail.com> wrote: > Well, you'd have to define the function inside the sortMoves function, as > it is where the variables exists. Oh, sorry, I wasn't thinking there! Regards, Jordan From kyosohma at gmail.com Thu Mar 29 16:19:06 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 Mar 2007 13:19:06 -0700 Subject: How can I get the content of a web site using http library In-Reply-To: <MPG.20762cd6f9219cf99896a0@news.individual.de> References: <1175195899.489572.73300@y66g2000hsf.googlegroups.com> <MPG.20762cd6f9219cf99896a0@news.individual.de> Message-ID: <1175199546.203818.193270@b75g2000hsg.googlegroups.com> On Mar 29, 3:07 pm, Thorsten Kampe <thors... at thorstenkampe.de> wrote: > * silverburgh.me... at gmail.com (29 Mar 2007 12:18:19 -0700) > > > I am trying to get the content of a web site like this: > > But my question is how can I do a 'GET' request without putting the '/ > > index.html'' > > import urllib > print urllib.urlopen('http://www.yahoo.com/').read() Posting to a form: urllib: http://www.thescripts.com/forum/thread23871.html httplib: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 http://www.python.org/infogami-faq/library/how-can-i-mimic-cgi-form-submission-method-post/ Mike From daniel.lipovetsky at gmail.com Sun Mar 11 20:36:22 2007 From: daniel.lipovetsky at gmail.com (Daniel Lipovetsky) Date: Sun, 11 Mar 2007 17:36:22 -0700 Subject: Object instance "reporting" to a container class instance Message-ID: <d13a83780703111736p3c4cbbf2o9f689919629a80d3@mail.gmail.com> I would like for an object to "report" to a container object when a new instance is created or deleted. I could have a container object that is called when a new instance is created, as below. class AnyObject: pass class Container: links = [] def add(self,other): while other not in self.links: self.links.append(other) def rem(self,other): while other in self.links: self.links.remove(other) ... container = Container() a = AnyObject() container.add(a) My question is: can (should? :-) this "reporting" be done inside the instance's __init__ and __del__ methods (that is, an instance "reports" to the container as soon as it is created or deleted)? Thanks! Daniel --- I'm working out a design where Object A is "linked" to Object B, and both objects become aware of that relationship. I have implemented an example successfully; the code is below. My main question is above, but I would appreciate comments on the code! (For example, I'm wondering whether my way of defining variables in the class but assigning them locally to each instance (in the "Object.init" method) is really a bad kludge...) class Object(): def __del__(self): print "buh-bye!", self # Verbose for understanding garbage cleanup def init(self,name): self.links = [] self.name = name def add(self,other): while other not in self.links: self.links.append(other) other.add(self) def rem(self,other): while other in self.links: self.links.remove(other) other.rem(self) class Student(Object): def __init__(self,name): self.init(name) class Section(Object): def __init__(self,name): self.init(name) class Task(Object): def __init__(self,name): self.init(name) ## Construct test instances! students = {} for name in ['Jose','Daniel','Rusty']: student = Student(name) students[name] = student sections = {} for name in ['English 1']: section = Section(name) sections[name] = section tasks = {} for name in ['Homework 1','Exam 1','Homework 2','Exam 2']: task = Task(name) tasks[name] = task # Display example connections def show_connections(): for section in sections: print sections[section].name for link in sections[section].links: print "\t", link.name # Add some connections... print "Now adding connections..." for name in tasks: sections['English 1'].add(tasks[name]) show_connections() # Remove some connections... print "Now removing connections..." for name in tasks: sections['English 1'].rem(tasks[name]) show_connections() for task in tasks: print tasks[task].links for section in sections: print sections[section].links ## Test garbage cleanup sections['English 1'].add(tasks['Exam 1']) print sections['English 1'].links sections['English 1'].rem(tasks['Exam 1']) del sections['English 1'] From mail at microcorp.co.za Sun Mar 11 06:48:22 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 11 Mar 2007 12:48:22 +0200 Subject: Python in a desktop environment References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> Message-ID: <01ae01c763cc$02b764c0$03000080@hendrik> "David Cramer" <dc...er at gmail.com> wrote: > If you had an application that you were about to begin development on > which you wanted to be cross platform (at least Mac and Windows), > would you suggest using c++ and Python? > > I'm asking because we were originally thinking about doing c# but > after attending PyCon this year I'm reconsidering. We are already > using Python for the website and I figure a c++ backend w/ a Python > GUI may work really well, and would be pretty easy to port. > > Any opinions? Why drag in the C++ ? What do you intend to do in it that you can't do in python? Seems unnecessarily complex to me. And on a desktop, speed issues are kind of irrelevant - Python is snappy enough on modern hardware for most things. My style would be to have the gui connect via pipes to the local backend as a separate process, with a third process if there are any communications needed to off box dbs. But that is just the way I think - YMMV - Hendrik From psdasilvaX at esotericaX.ptX Thu Mar 8 13:52:34 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Thu, 08 Mar 2007 18:52:34 +0000 Subject: Where to "import"? Message-ID: <1173379952.901004@iceman.esoterica.pt> Hi! If I have two files .py such as m.py from c import * ... x=c() ... os.any_method ... ... c.py class c: def __init__(self, ...): ... os.any_method ... ... ... both using os module where should I put the "import os"? In both files? Thanks Paulo From sgeiger at ncee.net Wed Mar 21 14:45:21 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 21 Mar 2007 13:45:21 -0500 Subject: flattening/rolling up/aggregating a large sorted text file In-Reply-To: <1174479568.427193.132740@n59g2000hsh.googlegroups.com> References: <1174479568.427193.132740@n59g2000hsh.googlegroups.com> Message-ID: <46017D41.4030400@ncee.net> Apparently you want to use this data to know how many blue circles, blue squares, red circles and red squares. In other words, I doubt you want to output redundant data columns, you just want this data in a more usable format and that you don't actually need to do multiple passes over it. This is a fun problem to solve because it uses two very powerful tools: cvs.dictreader and bitwise categorization. Note: your initial data has three records with the same ID. I assumes the ID is the unique key. So I changed the data slightly. adtvff at yahoo.com wrote: > Hi, > > Given a large ascii file (delimited or fixed width) with one ID field > and dimensions/measures fields, sorted by dimensions, I'd like to > "flatten" or "rollup" the file by creating new columns: one for each > combination of dimension level, and summing up measures over all > records for a given ID. > > If the wheel has already been invented, great, please point me in the > right direction. If not, please share some pointers on how to think > about this problem in order to write efficient code. > > Is a hash with dimension level combinations a good approach, with > values reset at each new ID level? > > I know mysql, Oracle etc will do this , but they all have a cap on # > of columns allowed. SAS will allow unlimited columns, but I don't own > SAS. > > Thanks. > > > ID,color,shape,msr1 > ------------------------------ > 001, blue, square, 4 > 001, red , circle, 5 > 001, red, circle, 6 > > > ID, blue_circle, blue_square, red_circle, red_square > -------------------------------------------------------------------------- > 001,0,4,11,0 > 002 ... > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: data_categories.py URL: <http://mail.python.org/pipermail/python-list/attachments/20070321/8f14ee8f/attachment.ksh> -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20070321/8f14ee8f/attachment.vcf> From bruno.desthuilliers at gmail.com Thu Mar 1 03:20:05 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 1 Mar 2007 00:20:05 -0800 Subject: Curious UnboundLocalError Behavior In-Reply-To: <mailman.4517.1172682923.32031.python-list@python.org> References: <mailman.4517.1172682923.32031.python-list@python.org> Message-ID: <1172737205.386931.85040@z35g2000cwz.googlegroups.com> On 28 f?v, 18:15, "Matthew Franz" <mdfr... at gmail.com> wrote: > I'm probably fundamentally misunderstanding the way the interpreter > works with regard to scope, but is this the intended behavior... > (snip traceback) > import os,sys > > SOMEGLOBAL=1 > > def foo(): > dome=False > if dome: > SOMEGLOBAL = 0 This makes SOMEGLOBAL local !-) Look for the 'global' statement. Or better, try to avoid rebinding globals from within a function. As as side note: by convention, ALL_UPPER names denote constants. From http Fri Mar 2 14:44:27 2007 From: http (Paul Rubin) Date: 02 Mar 2007 11:44:27 -0800 Subject: Sort with extra variables References: <pan.2007.03.02.19.29.39@gmail.com> Message-ID: <7xlkifh1lw.fsf@ruckus.brouhaha.com> Thomas Dybdahl Ahle <lobais at gmail.com> writes: > Do you have any ideas how I can sort these moves the fastest? One idea: if you're using alpha-beta pruning, maybe you can use something like heapq instead of sorting, since a lot of the time you only have to look at the first few moves (ordered best-first). From steve at holdenweb.com Thu Mar 15 15:48:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Mar 2007 15:48:25 -0400 Subject: os.path.isfile with *.tar.gz In-Reply-To: <09042D621CD4AA479C678463F3A646D0E87D10@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0E87D10@sottemail1.ent.ad.cognos.com> Message-ID: <etc80v$ibc$1@sea.gmane.org> Boudreau, Emile wrote: > Hello All, > I'm new to Python and it looks like people that post here do get > a good answer back so I figured I'd try my luck. > > I'm trying to check a directory to see if there is a file that has the > name "startOfString" + some version number + "inst.tar.gz" > (component-8.3.16-inst.tar.gz) The version number will change quite > frequently so I just want to check if there is a file with that format name. > > I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\", > "rqp-win32-app", "*.tar.gz")) > but nothing seem to work. Does anyone have suggestions on how I could > get this to work? > > Thanks in advance for the help, > Emile > > > This message may contain privileged and/or confidential > information. If you have received this e-mail in error or are not the > intended recipient, you may not use, copy, disseminate or distribute it; > do not open any attachments, delete it immediately from your system and > notify the sender promptly by e-mail that you have done so. Thank you. > Take a look at the glob module documentation. Glob.glob will almost certainly do what you want, as it's specifically written to match wildcard filenames. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From sjmachin at lexicon.net Sat Mar 10 10:48:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Mar 2007 07:48:39 -0800 Subject: UTF-8 In-Reply-To: <mailman.4899.1173535209.32031.python-list@python.org> References: <mailman.4899.1173535209.32031.python-list@python.org> Message-ID: <1173541719.669447.71330@30g2000cwc.googlegroups.com> On Mar 11, 1:00 am, Olivier Verdier <cht... at gmail.com> wrote: > First off: i thoroughly enjoy python. I use it for scientific > computing with scipy, numpy and matplotlib and it's an amazingly > efficient and elegant language. > > About this mailing list: it is very hard to search. I can't find any > search field on the page:http://mail.python.org/mailman/listinfo/ > python-list. I would greatly appreciate if you moved that list over > to google, for instance, so that it be both searchable and rss-feedable. > The mailing list and the Usenet newsgroup comp.lang.python mirror each other. Google Groups provides access to Usenet newsgroups; try http://groups.google.com/group/comp.lang.python Other possibilities are gmane.org and Yahoo Groups; see http://www.python.org/community/lists/ HTH, John From codecraig at gmail.com Tue Mar 20 09:46:27 2007 From: codecraig at gmail.com (abcd) Date: 20 Mar 2007 06:46:27 -0700 Subject: help - Module needs access to another module Message-ID: <1174398386.976864.109350@p15g2000hsd.googlegroups.com> I have the following directory/file structure... c:\foo\utils.py c:\foo\bar\ok.py In ok.py I want to do something like... import utils utils.helpMeDoSomething(....) However, it seems that ok.py doesn't "know" about utils. Other than manually configuring sys.path what can I do? thanks From vatamane at gmail.com Tue Mar 27 23:11:15 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 27 Mar 2007 20:11:15 -0700 Subject: urllib timeout issues In-Reply-To: <1175028104.429759.165920@n76g2000hsh.googlegroups.com> References: <1175023315.536080.276550@n76g2000hsh.googlegroups.com> <mailman.5681.1175026431.32031.python-list@python.org> <1175028104.429759.165920@n76g2000hsh.googlegroups.com> Message-ID: <1175051475.534486.195200@e65g2000hsc.googlegroups.com> On Mar 27, 4:41 pm, "supercooper" <supercoo... at gmail.com> wrote: > On Mar 27, 3:13 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > wrote: > > > > > En Tue, 27 Mar 2007 16:21:55 -0300, supercooper <supercoo... at gmail.com> > > escribi?: > > > > I am downloading images using the script below. Sometimes it will go > > > for 10 mins, sometimes 2 hours before timing out with the following > > > error: > > > > urllib.urlretrieve(fullurl, localfile) > > > IOError: [Errno socket error] (10060, 'Operation timed out') > > > > I have searched this forum extensively and tried to avoid timing out, > > > but to no avail. Anyone have any ideas as to why I keep getting a > > > timeout? I thought setting the socket timeout did it, but it didnt. > > > You should do the opposite: timing out *early* -not waiting 2 hours- and > > handling the error (maybe using a queue to hold pending requests) > > > -- > > Gabriel Genellina > > Gabriel, thanks for the input. So are you saying there is no way to > realistically *prevent* the timeout from occurring in the first > place? And by timing out early, do you mean to set the timeout for x > seconds and if and when the timeout occurs, handle the error and start > the process again somehow on the pending requests? Thanks. > > chad Chad, Just run the retrieval in a Thread. If the thread is not done after x seconds, then handle it as a timeout and then retry, ignore, quit or anything else you want. Even better, what I did for my program is first gather all the URLs (I assume you can do that), then group by servers, i.e. n # of images from foo.com, m # from bar.org .... Then start a thread for each server (with some possible maximum number of threads), each one of those threads will be responsible for retrieving images from only one server (this is to prevent a DoS pattern). Let each of the server threads start a 'small' retriever thread for each image (this is to handle the timeout you mention). So you have two different threads -- one per server to parallelize downloading, which in turn will spawn and one per download to handle timeout. This way you will (ideally) saturate your bandwidth but you only get one image per server at a time so you still 'play nice' with each of the servers. If you want to have a max # of server threads running (in case you have way to many servers to deal with) then run batches of server threads. Hope this helps, Nick Vatamaniuc From deets at nospam.web.de Fri Mar 9 10:49:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 09 Mar 2007 16:49:07 +0100 Subject: 2 new comment-like characters in Python to aid development? References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <mailman.4847.1173435205.32031.python-list@python.org> <1173436274.346506.200920@q40g2000cwq.googlegroups.com> <55cs24F23meg4U1@mid.individual.net> <1173438105.600342.243200@n33g2000cwc.googlegroups.com> <55d34sF24ijrdU1@mid.individual.net> <1173448114.905480.47200@h3g2000cwc.googlegroups.com> <55d7t9F240tp2U1@mid.uni-berlin.de> <1173449933.926669.90810@n33g2000cwc.googlegroups.com> <55d9ehF24cdi0U1@mid.uni-berlin.de> <1173452206.029944.255750@j27g2000cwj.googlegroups.com> Message-ID: <55ddvkF251n88U1@mid.uni-berlin.de> dbhbarton at googlemail.com wrote: >> > I'm sorry I don't follow your logic. Meaningless to the interpreter, >> > yes, meaningless to the IDE or to me, no. I "_can't_ profit from these >> > conveniences"? Why ever not? >> >> Exactly, the ? is meaningless to the language itself, it's only a comment >> sign - ... >> ... it has nothing to do with _python_ the language, so it doesn't >> belong there. > > But # is 'only a comment sign' as well, and equally meaningless to the > interpreter. But it's still part of the language, very very useful and > I profit from its existence every day. A language has to have a comment mechanism, some even several. But all of them are clear on how they work: they affect one line, or have a bracket style like /* */ and thus demark clearly what they affect. Even someone not fluent in the language in question will quickly grab what they mean. But the key-difference is that the comment in python has a meaning for the interpreter - ignore this. The ? has no meaning. It only has a meaning for an editor. >> But for python itself, it has no meaning whatsoever, and would just be a >> character to overread, introducing visual clutter. > > If you can highlight an entire block with a single character, won't > there be _less_ visual clutter than the current way of achieving the > same effect with # comments? Not in my opinion - # fixme def foo(): pass is much more clear than a rather obscure and by the occasional beholder maybe misinterpreted ?def foo(): pass > Would if I could! Well, grab eric3, it's written in python, and teach it to do so! It's an exercise in python then :) It already has some features like bookmarks, shouldn't be too hard to build upon that. > What we're talking about here is a form of 'alternate commenting > style'. With the IDE's cooperation it'd work on whole blocks at once, > it would highlight without disrupting the code concerned (at least the > way I'm envisaging it), it would be versatile (could probably be used > for as big a variety of purposes as the # comment), and yes, it'd be > persistent, which is how it would be different from any IDE-based > highlighting. I think you contradict yourself here. On the one side, you want it not disturbing to the eye, yet it should be highlighted, so it will be directly noticed by that same eyes. This is why I believe that your idea by itself - the visually marking of code parts - is a good thing, but the embedding into code is not, because it _is_ an disturbance. And with an IDE that stores such information in e.g. project metainformation, you can even have the persistence, without the disturbance and without altering python. Diez From gtcopeland at gmail.com Tue Mar 20 14:36:02 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 20 Mar 2007 11:36:02 -0700 Subject: freeze.py and dom.minidom Message-ID: <1174415762.618919.273600@l75g2000hse.googlegroups.com> I am attempting to freeze an application which uses the dom.minidom parser. When I execute my application, I get an import error of: ImportError: No module named dom.minidom. During the freeze process, I can see: freezing xml ... freezing xml.dom ... freezing xml.dom.NodeFilter ... freezing xml.dom.domreg ... freezing xml.dom.expatbuilder ... freezing xml.dom.minicompat ... freezing xml.dom.minidom ... freezing xml.dom.pulldom ... freezing xml.dom.xmlbuilder ... freezing xml.parsers ... freezing xml.parsers.expat ... freezing xml.sax ... freezing xml.sax._exceptions ... freezing xml.sax.expatreader ... freezing xml.sax.handler ... freezing xml.sax.saxutils ... freezing xml.sax.xmlreader ... And in my target directory, I can see: $ ls M_xml* M_xml.c M_xml__dom.o M_xml__sax___exceptions.o M_xml__dom.c M_xml__dom__pulldom.c M_xml__sax__expatreader.c M_xml__dom__domreg.c M_xml__dom__pulldom.o M_xml__sax__expatreader.o M_xml__dom__domreg.o M_xml__dom__xmlbuilder.c M_xml__sax__handler.c M_xml__dom__expatbuilder.c M_xml__dom__xmlbuilder.o M_xml__sax__handler.o M_xml__dom__expatbuilder.o M_xml.o M_xml__sax.o M_xml__dom__minicompat.c M_xml__parsers.c M_xml__sax__saxutils.c M_xml__dom__minicompat.o M_xml__parsers__expat.c M_xml__sax__saxutils.o M_xml__dom__minidom.c M_xml__parsers__expat.o M_xml__sax__xmlreader.c M_xml__dom__minidom.o M_xml__parsers.o M_xml__sax__xmlreader.o M_xml__dom__NodeFilter.c M_xml__sax.c M_xml__dom__NodeFilter.o M_xml__sax___exceptions.c As you can see, minidom is being frozen and M_xml__dom__minidom.o is compiled. Likewise, I can confirm it linked into the application. What do I need to do to get this to work with a frozen application? Greg From no at spam.it Thu Mar 1 12:15:01 2007 From: no at spam.it (Pablo was Paolo) Date: Thu, 01 Mar 2007 18:15:01 +0100 Subject: Reading csv files using SQL In-Reply-To: <mailman.4568.1172751025.32031.python-list@python.org> References: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> <WItFh.7822$Jl.2517@newsread3.news.pas.earthlink.net> <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> <mailman.4568.1172751025.32031.python-list@python.org> Message-ID: <45e70a14$0$37202$4fafbaef@reader3.news.tin.it> skip at pobox.com ha scritto: > If you want to work directly with the files why not just use Python's csv > module? Now, with Java, I use the same class to read several databases and csv files (with SQL instructions). I'd like to find a library for using the same approach in Python. Thank you, Paolo From mail at microcorp.co.za Tue Mar 20 01:49:54 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 20 Mar 2007 07:49:54 +0200 Subject: Timeout to readline()/readlines() References: <1174312248.404607.212110@b75g2000hsg.googlegroups.com> Message-ID: <000301c76ab8$336481a0$03000080@hendrik> "Horta" <danilo.horta at gmail.com> wrote: > Sometimes, when I do an os.popen*(), the process executed by the > command hangs, and the script stops forever on the readline()/ > readlines() calls. I found that I can use select, but I'm thinking... > if, after a sellect() call returns, the stdout (for example) has more > than one line? or if it has just some characters, no newline, and the > process just hangs? > > I just want a readline(timeout) and readlines(timeout) like > functions. Do I need to create my owns or there're already > implemented? you have to unblock the file and use try - except. look at the fcntl module - Hendrik From deets at nospam.web.de Mon Mar 19 06:49:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Mar 2007 11:49:51 +0100 Subject: XML based programming language References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> Message-ID: <56786fF2743atU2@mid.uni-berlin.de> stefaan wrote: > Thank you Diez for answering. > As far as I can see, it more or less corresponds to what I have. > > But my question was perhaps more this: > > "If elementtree is "lex", what is "yacc" ? " Elementtree isn't lex. You are comparing apples and oranges here. Lex tokenizes, yacc creates trees. Both of is covered in XML itself - it's defined the tokenization and parsing, built into elementtree. So, elemnttree is lex _and_ yacc for XML. And if your language is written in XML, that's all there is to it. Diez From vatamane at gmail.com Mon Mar 12 01:12:43 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 11 Mar 2007 22:12:43 -0700 Subject: Watching a file another app is writing In-Reply-To: <mOydnfTB9YK7x2nYnZ2dnUVZ_gydnZ2d@comcast.com> References: <mOydnfTB9YK7x2nYnZ2dnUVZ_gydnZ2d@comcast.com> Message-ID: <1173676363.653940.133030@30g2000cwc.googlegroups.com> On Mar 11, 3:36 pm, Gordon Airporte <JHoo... at fbi.gov> wrote: > I'm trying to find a way to take a file that another program has opened > and writes to periodically, open it simultaneously in Python, and > automatically update some of my objects in Python when the file is > written to. > I can open the file and manually readlines() from it to keep up to date, > it's the automatic part I'm having trouble with. This is on Windows. You might need to look at pywin32 for Windows specific ways to listen to "file changed" event. On Unix a quick shortcut would be to simply read the output of 'tail - f <file>' command... From exarkun at divmod.com Mon Mar 5 14:54:41 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 Mar 2007 14:54:41 -0500 Subject: Webserver balance load In-Reply-To: <1173124034.130806.316750@30g2000cwc.googlegroups.com> Message-ID: <20070305195441.17852.300056054.divmod.quotient.3539@ohm> On 5 Mar 2007 11:47:15 -0800, Johny <python at hope.cz> wrote: >Can anyone suggest a way how to balance load on Apache server where I >have Python scripts running? >For example I have 3 webservers( Apache servers) and I would like to >sent user's request to one of the three server depending on a load on >the server. >Thank you . >L. > http://pythondirector.sourceforge.net/ might be interesting. >-- >http://mail.python.org/mailman/listinfo/python-list > From apoliveiraleite at gmail.com Mon Mar 19 18:55:51 2007 From: apoliveiraleite at gmail.com (Ana Paula Leite) Date: Mon, 19 Mar 2007 18:55:51 -0400 Subject: urgent - Matplolib with IDLE! In-Reply-To: <a749952d0703191411u1ce36ca4lbb4ad50d705ab074@mail.gmail.com> References: <26f4c9e60703191308j55287087ydc12c24656b4df6b@mail.gmail.com> <a749952d0703191411u1ce36ca4lbb4ad50d705ab074@mail.gmail.com> Message-ID: <26f4c9e60703191555x2b848fa1rf6d2051522c822e2@mail.gmail.com> Hi, in site-packages/matplotlib/backends/backend_tkagg.py I commented out in the show function the line Tk.mainloop() In addition to the changes I mentioned in my first email, this has solved my problem! On 3/19/07, Rob Clewley <rhc28 at cornell.edu> wrote: > > I have the same problem with a similar setup (except Python 2.4.3) and > have tried the same solutions (BTW those steps really did used to work > on my machine using Python 2.3.5). In the short term you could either > try IPython (a proper solution to this problem, which returns me to > the prompt just fine after closing the figure) or try the following > "quick and dirty fix" with IDLE: > > 1) If your script does stuff other than define classes and functions, > put in a command that prevents it getting to the calculations (e.g. > insert a "1/0" line) or, for instance, turn all your calculations into > function calls that you can easily comment out (temporarily). Run your > script using F5 so that you just get the prompt. > 3) Create an empty figure using pylab.figure() or whatever. > 2) Close the figure and the IDLE console (command prompt window) that > opened when you ran the script (you have to say Yes when it asks about > killing a python process). > 3) This leaves an orphaned python process which you have to clean up > later using your Task Manager, but ... > 4) you can now continue to interact with any new IDLE console created > in the current session when you bring up new figures. i.e. uncomment > the parts of your script that actually do stuff and run it again. > > At least that's a quick fix that's working for me while I await a > better answer too... Perhaps this hack will outrage someone's > sensibilities sufficiently that we'll hear of a better IDLE solution. > > HTH, > Rob > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070319/60562de9/attachment.html> From bignose+hates-spam at benfinney.id.au Sat Mar 3 02:39:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Mar 2007 18:39:32 +1100 Subject: implementing SFTP using Python References: <683868.19200.qm@web38806.mail.mud.yahoo.com> Message-ID: <873b4m3he3.fsf@benfinney.id.au> kadarla kiran kumar <kadarlakiran at yahoo.com> writes: > I have to implement SFTP conection from client to the server using > Python script. Iam very new new to python , and i dont't have much > time to complete this. So I need some pointers from you. You will probably want to investigate the "paramiko" package, a pure-Python implementation of the SSH2 protocol. <URL:http://www.lag.net/paramiko/> On Debian ("etch" or newer), you can install the 'python-paramiko' package. Alternatively, download it from the website. -- \ "I was in a bar the other night, hopping from barstool to | `\ barstool, trying to get lucky, but there wasn't any gum under | _o__) any of them." -- Emo Philips | Ben Finney From facundo at taniquetil.com.ar Tue Mar 20 16:00:29 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Tue, 20 Mar 2007 20:00:29 +0000 (UTC) Subject: Patchs and bugs resume Message-ID: <etpegs$gc2$1@sea.gmane.org> People: At the beginning of March, there was a thread in python-dev about patchs and bugs that teorically weren't checked out. The thread discussed how to involve more people in checking patchs and bugs, and to create other dinamic around them. >From that discussion, I asked myself: "How can I know the temporal location of a patch/bug?". Are there a lot of old patchs/bugs? Those that are old, don't have any update or there're a big discussion with each one? Are they abandoned? To help me with this analisys, I made a tool that taking information from SourceForge it creates a resume table, for the patchs... http://www.taniquetil.com.ar/facundo/py_patchs.html ...and the bugs: http://www.taniquetil.com.ar/facundo/py_bugs.html My idea is to update them periodically (something like each day, at the end of the html you have the update date and time). Enjoy it. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From sjmachin at lexicon.net Sat Mar 17 09:38:40 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 Mar 2007 06:38:40 -0700 Subject: Finding the insertion point in a list In-Reply-To: <mailman.5220.1174128479.32031.python-list@python.org> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <7xird0bom3.fsf@ruckus.brouhaha.com> <pan.2007.03.17.06.01.12.113236@REMOVE.THIS.cybersource.com.au> <7xfy845q24.fsf@ruckus.brouhaha.com> <mailman.5220.1174128479.32031.python-list@python.org> Message-ID: <1174138720.344398.214480@b75g2000hsg.googlegroups.com> On Mar 17, 9:46 pm, Steve Holden <s... at holdenweb.com> wrote: > Paul Rubin wrote: > > Steven D'Aprano <s... at REMOVE.THIS.cybersource.com.au> writes: > >> or even > > >> len(filter(lambda t, y=y: y>t, x)) > > > How about > > > min(i for i,t in enumerate(x) if t >= y) > > > or > > > max(i for i,t in enumerate(x) if t <= y) > > > Those are actually pretty direct. > > How about a solution (like the bisect one suggested almost as soon as > this thread started) that doesn't iterate over the whole list. > > Having said which, for the promoted use cases I agree that the append() > and sort() paradigm wins hands down until it starts to make a real and > observable difference to the run time. > Unfortunately for sort/append, the OP wants to find the insertion point -- he hasn't mentioned actually doing the insertion. From ntv1534 at gmail.com Fri Mar 2 05:08:38 2007 From: ntv1534 at gmail.com (MooMaster) Date: 2 Mar 2007 02:08:38 -0800 Subject: decimal and context objects! Message-ID: <1172830118.276246.101820@30g2000cwc.googlegroups.com> Hey guys, I'm trying to do some black magic voodoo and it's a little late, so forgive me if this question seems obvious or has been asked before. I tried doing a search on context objects and didn't find anything that popped out, and I'm too tired to keep digging. I'm making a little program that is trying to do weird and sexy things by fully leveraging the power of all the built-in beauty of Python. I was trying to play around with the new features added into Python 2.5, and ran into an unexpected issue...check this out: >>> moo = lambda x, y : decimal.Context(3).sqrt(decimal.Context(3).power(x,2) + decimal.Context(3).power(y,2)) >>> moo <function <lambda> at 0x02CD0EB0> >>> row = [1,2,3,4,5] >>> weight_vector = .00556 >>> moo(sum(row), weight_vector) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> moo(sum(row), weight_vector) File "<pyshell#1>", line 1, in <lambda> moo = lambda x, y : decimal.Context(3).sqrt(decimal.Context(3).power(x,2) + decimal.Context(3).power(y,2)) File "C:\Python25\lib\decimal.py", line 2662, in power return a.__pow__(b, modulo, context=self) TypeError: wrapper __pow__ doesn't take keyword arguments I have no idea what keyword argument is getting passed to __pow__, anyone know what's going on? This should compute sqrt(5^2 + 3^2) From michael at jedimindworks.com Sun Mar 25 01:55:30 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 25 Mar 2007 00:55:30 -0500 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174794013.752495.42220@o5g2000hsb.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <mailman.5571.1174789089.32031.python-list@python.org> <1174794013.752495.42220@o5g2000hsb.googlegroups.com> Message-ID: <9F9FBF4C-B418-4788-B041-69B8C5337AC5@jedimindworks.com> > > /Libary/Frameworks/ is an empty directory(except for . and ..) on my > Mac, and I have 2.3.5 installed somewhere. Ye sorry 'bout that... Apple's default install is under /System/ Library... Framework builds from python.org get installed under / Library From kw at codebykevin.com Mon Mar 26 22:32:11 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 26 Mar 2007 22:32:11 -0400 Subject: Associate image name with list item Message-ID: <b8eda$4608822b$4275d90a$15798@FUSE.NET> I'm trying to avoid a *lot* of typing in my Tkinter application by associating image names with items in a list. Here is my sample list: self.catlist = [ 'all', 'installed', 'base', 'crypto', 'database', 'devel', 'editors', 'games', 'gnome', 'graphics', 'kde', 'languages', 'libs', 'libs_perlmods', 'libs_pythonmods', 'libs_rubymods', 'net', 'sci', 'shells', 'sound', 'text', 'web', 'x11_system', 'x11-wm', 'x11' ] I've also already created a bunch of images with names that correspond to the list above, i.e. self.all, self.installed, and so on. Here's the rest of my code: for item in self.catlist: print item self.categorytable.insert(END, item) self.categorytable.cellconfigure("end,0", image=self.item) This yields the following error: AttributeError: item because, of course, I don't actually have an image called self.item. What I'm trying to do is get the value of the variable "item" and plug it into the image name, so that self.item actually corresponds to self.installed, self.base, etc. Trying something like self.categorytable.cellconfigure("end,0", image=self.%s % item) just yields a syntax error: SyntaxError: invalid syntax Can anyone point me in the right direction? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From george.sakkis at gmail.com Thu Mar 1 00:44:31 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 28 Feb 2007 21:44:31 -0800 Subject: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple) In-Reply-To: <mailman.4550.1172720725.32031.python-list@python.org> References: <slrneubq5t.1j3.rshepard@salmo.appl-ecosys.com> <87slcqvskr.fsf@benfinney.id.au> <mailman.4538.1172705434.32031.python-list@python.org> <54ms6fF21c6h3U2@mid.individual.net> <mailman.4550.1172720725.32031.python-list@python.org> Message-ID: <1172727871.032664.165240@j27g2000cwj.googlegroups.com> On Feb 28, 10:45 pm, Ben Finney <bignose+hates-s... at benfinney.id.au> wrote: > Bjoern Schliessmann <usenet-mail-0306.20.chr0n... at spamgourmet.com> writes: > > I know tuples as immutable lists ... > > That's a common misconception. And this catch phrase, "that's a common misconception", is a common aping of the BDFL's take on this. As several long threads have shown, it is a highly controversial topic and claiming that one side has misconceived it doesn't make it more true than a Catholic claiming that Protestants are misconceived about the True Christianity or vice versa. > Tuples are intended for use as heterogeneous data structures: every > index in the sequence *means* something, a semantic meaning applied to > the item at that index. It's for this reason that a tuple is > immutable: removing items, inserting them in the middle, etc. would > imply that the index doesn't have semantic meaning for the structure, > which is not true. > > Lists are intended for use as homogeneous sequences: not that every > value is of the same type, but that a particular index in the sequence > doesn't *mean* anything about the semantic interpretation of the item > at that position. It's for this reason that a list is mutable: since > the index of an item has no semantic meaning, inserting new items or > removing them from anywhere in the sequence doesn't alter the meaning > of the structure. > > James Tauber explains further: > > <URL:http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constan...> Nice, that's a good summary of the straw man arguments about the "true" distinction between tuples and lists. Now can you please explain why an "heterogeneous data structure": 1) does not support __setitem__, changing the value of an existing item from 3 to 4, 2) supports iteration over its ("heterogeneneous") elements, but not an index() method, and 3) why using indices rather than names for implied semantics is a good idea anyway. As for addition/removal/insertion of elements not making sense for a heterogeneous data structure, have you heard of database schema change ? Heterogeneous data structures are well known for several decades now; they are commonly spelled "records" though, not tuples, and have a more reasonable API to support their semantics. George From aleax at mac.com Sat Mar 24 12:36:56 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 24 Mar 2007 09:36:56 -0700 Subject: PyImport_ImportModule/embedding: surprising behaviors References: <mailman.5359.1174435375.32031.python-list@python.org> <eu3h1h$li2$1@panix3.panix.com> Message-ID: <1hvh39c.1hxaek1vuz71N%aleax@mac.com> Aahz <aahz at pythoncraft.com> wrote: > In article <mailman.5359.1174435375.32031.python-list at python.org>, > David Abrahams <dave at boost-consulting.com> wrote: > > > >I was under the impression that both the current directory *and* the > >python library directory were already, automatically, in sys.path, so > >I'm really surprised to see this. Am I doing something wrong, or is > >this simply the expected behavior (and if so, where is it documented)? > > IIRC (without bother to test), there has been some change in the > definition of "current directory" -- it used to be the actual current > directory of os.getcwd(), but since changed to the startup directory. In 2.3 and later, at least (sorry, no 2.2 and earlier around to check), site.py makes every directory along sys.path an absolute path at Python startup. This _should_ probably be documented at <http://docs.python.org/lib/module-site.html>, but it doesn't appear to be clearly stated there (the page only speaks of site's job of "appending site specific paths", and not of the other jobs it also performs, such as normalizing sys.path by turning all paths into absolute ones and removing duplicates). Alex From jconxus at gmail.com Fri Mar 30 20:08:31 2007 From: jconxus at gmail.com (jconxus at gmail.com) Date: 30 Mar 2007 17:08:31 -0700 Subject: Web-based personal development co. looking for programmers Message-ID: <1175299711.012374.312610@n59g2000hsh.googlegroups.com> Mylinia.com Live purposefully! Who: Mylinia.com is a personal development company located in the heart of the Silicon Valley, started in 2006 by 3 Stanford business school students who are dedicated to helping people all over the world reach their full potential. We envision a better world where people have the freedom to live purposefully, learn freely, and love unconditionally. What: We provide an online platform that enables our co-owners (not users; we?re not here to use anybody!) to customize their personal development experiences and realized their dreams by allowing them to find resources that are relevant to their passions. How: We trademarked a straightforward formula Problems + Passions = Purpose? to help people begin the process of answering life?s most important question, ?What is my purpose?? Via our online community, co-owners are able to share their journey, tag and find tools, set goals, and engage their best friends in the pursuit of their purpose. Software Engineer We?re seeking a bright, energetic, and dedicated team player who has strong, versatile computer science fundamentals who will be a core contributor to architecting, building, and scaling mylinia?s backend. You will need strong skills in application and server-side development; experience and/or interest in designing and maintaining high-volume systems is a big plus. Responsibilities: Architect and maintain a reliable backend system to support dynamic web frontend * Assist in scaling and optimizing communication integration between frontend and backend * Assist in testing and optimizing regularly scheduled releases * Proactively recommend architecture changes and suggest new coding practices * Collaborate with frontend programmers to optimize scalability and network efficiency * Stay up-to-date with new technologies Ideal Candidate: The Senior .NET Developer will have at least five years of experience in software development and IT. You must have good communication skills and can work with other developers and independently. You are expected to take a lead role in project management. Compensation: Negotiable mix of equity and salary dependent on cultural fit, skill set, experience, and the amount of time you are able to commit per through our series A round. Process: Email Jullien Gordon with your resume at Gordon_Jullien at gsb.stanford.edu From olsonas at gmail.com Wed Mar 14 15:14:00 2007 From: olsonas at gmail.com (Drew) Date: 14 Mar 2007 12:14:00 -0700 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: <mailman.5103.1173898419.32031.python-list@python.org> References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <et958a$o9c$1@news2.u-psud.fr> <mailman.5103.1173898419.32031.python-list@python.org> Message-ID: <1173899640.547531.99260@l75g2000hse.googlegroups.com> On Mar 14, 2:53 pm, s... at pobox.com wrote: > >> When is it appropriate to use dict.items() vs dict.iteritems. > > Laurent> Both work, you may prefer xrange/iteritems for iteration on > Laurent> large collections... > > I find "iter<anything>" to be extremely ugly and hope to avoid using them > altogether until they are gone in Py3k. > > Skip Skip - Ugly, maybe, but don't you take a decent performance hit when loading the entire dict into memory at once? Especially if the dict is large? From mailmaverick666 at gmail.com Wed Mar 7 03:47:43 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Wed, 7 Mar 2007 14:17:43 +0530 Subject: Videos inside(adult-fun-romantic-love-movies-songs)singles-profiles-chating-mails-earn money ! In-Reply-To: <1173256550.541680.176410@8g2000cwh.googlegroups.com> References: <1173256550.541680.176410@8g2000cwh.googlegroups.com> Message-ID: <180b672e0703070047o4d996727sca330a8e2573cba@mail.gmail.com> This is totally un-acceptable.This list is not for advertising things that are not related to python On 7 Mar 2007 00:35:50 -0800, sudha madhuri <sudharani4fun at yahoo.com> wrote: > > Videos inside(adult-fun-romantic-love-movies-songs)singles-profiles- > chating-mails-earn money ! > > http://tinyurl.com/yr28hh > > India's largest social network place-Many people with good profiles. > chating-videos-messages-mails-contest-parttime earning-unlimited fun-1 > stop for everything > > signup and get fun > http://tinyurl.com/yr28hh > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070307/671194de/attachment.html> From mattheww at chiark.greenend.org.uk Fri Mar 9 14:00:58 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 09 Mar 2007 19:00:58 +0000 (GMT) Subject: 2 new comment-like characters in Python to aid development? References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <m11wjyy7p5.fsf@chezmarshall.freeserve.co.uk> <slrnev2m9v.179.nick@irishsea.home.craig-wood.com> <45f185f2$0$21511$426a34cc@news.free.fr> Message-ID: <Aai*6UgFr@news.chiark.greenend.org.uk> Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com> wrote: >>>> Nick Craig-Wood a ecrit : >>>>> I use # FIXME for this purpose or /* FIXME */ in C etc. >>>>> >>>>> I have an emacs macro which shows it up in bright red / yellow text >>>>> so it is easy to see > Thanks you both. For what it's worth, sufficiently recent versions of emacs python-mode have this built in. -M- From mail at timgolden.me.uk Thu Mar 1 12:26:34 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 01 Mar 2007 17:26:34 +0000 Subject: Reading csv files using SQL In-Reply-To: <45e70a14$0$37202$4fafbaef@reader3.news.tin.it> References: <45e5cda7$0$17940$4fafbaef@reader1.news.tin.it> <WItFh.7822$Jl.2517@newsread3.news.pas.earthlink.net> <45e6731d$0$4786$4fafbaef@reader4.news.tin.it> <mailman.4568.1172751025.32031.python-list@python.org> <45e70a14$0$37202$4fafbaef@reader3.news.tin.it> Message-ID: <45E70CCA.6050205@timgolden.me.uk> Pablo was Paolo wrote: > skip at pobox.com ha scritto: >> If you want to work directly with the files why not just use Python's csv >> module? > > Now, with Java, I use the same class to read several databases and csv > files (with SQL instructions). > I'd like to find a library for using the same approach in Python. I vaguely remember that you can get an ODBC driver for CSV. If I'm right, you could access it using one of the several Python ODBC DBAPI modules... just a thought. TJG From deets at nospam.web.de Fri Mar 30 05:00:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 Mar 2007 11:00:49 +0200 Subject: Game programming for kids: looking for open source 2D game development kit In-Reply-To: <euid24$ugc$1@online.de> References: <euid24$ugc$1@online.de> Message-ID: <5741ueF2bgl92U1@mid.uni-berlin.de> Max Kubierschky schrieb: > Hello, > > I'm planning to give a game programming course for kids of mixed age. > For this, I am looking for an open source 2D game development kit. > I am also willing to participate in the development of the development kit. > > Features I'd like to see > - Possibility to construct simple games via drag and drop without > programming > - Integration into an IDE > - Based on Java or Python > Pluses: > - Good Tutorial > - German documentation Squeak. Smalltalk, but especially targeted at your requirements. http://www.squeak.org/ Diez From chowroc.z at gmail.com Fri Mar 16 08:34:29 2007 From: chowroc.z at gmail.com (Rocky Zhou) Date: 16 Mar 2007 05:34:29 -0700 Subject: getopt or optparse options/arguments wrapping? Message-ID: <1174048469.334735.185750@l77g2000hsb.googlegroups.com> I wonder is there any way to make the wrapper program can wrap options && arguments for the the subprocess/command the wrapper will execute? by getopt or optparse module? This is something like the shell script like this: optwrap="" while [ $# -gt 0 ]; do case $1 in -a) do-something; shift ;; -b) do-something; shift ;; *) optwrap="$optwrap $1 $2" # collect the option and argument shift ;; esac shift done $command $optwrap # execute the command with $optwrap as subprocess I want that all the options and arguments which are feed to this scripts command line will be used by executing the sub command. I need this because I now have finished a fs_backup script written in python, it will execute tar && find to complete full and differentiating/incremental backup for the file system level files, and their restoring. This script will do different things by the command line arguments, and execute find/tar in different ways, but for being more flexible, I want some options of tar/find can also been specified from the command line directly, and the script just transmit those to tar/find simply. Is there anyone can give me some advices? Thank you. From andre.roberge at gmail.com Sun Mar 11 19:35:23 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 11 Mar 2007 16:35:23 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: <1173653364.059431.19990@v33g2000cwv.googlegroups.com> References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <mailman.4944.1173629658.32031.python-list@python.org> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <no_Ih.8899$PL.2303@newsread4.news.pas.earthlink.net> <7xy7m3tqq8.fsf@ruckus.brouhaha.com> <1173653364.059431.19990@v33g2000cwv.googlegroups.com> Message-ID: <1173656123.303867.134390@64g2000cwx.googlegroups.com> On Mar 11, 7:49 pm, "Paddy" <paddy3... at googlemail.com> wrote: > > Isn't negative zero mathematically the same as zero? Isn't -0 just an > artefact of the representation of floating point numbers? Shouldn't > f(0) == f(-0) for all functions f? Read the original post again... The relevant part is: ==== I'm working in a situation involving complex arithmetic where branch cuts, and hence signed zeros, are important, and it would be handy if the above code could be relied upon to do the right thing. ==== You may want to read about branch cuts and complex arithmetics. I don't mean this as a putdown - simply as a useful suggestion for you to read. Andr? From python at hope.cz Mon Mar 5 14:47:15 2007 From: python at hope.cz (Johny) Date: 5 Mar 2007 11:47:15 -0800 Subject: Webserver balance load Message-ID: <1173124034.130806.316750@30g2000cwc.googlegroups.com> Can anyone suggest a way how to balance load on Apache server where I have Python scripts running? For example I have 3 webservers( Apache servers) and I would like to sent user's request to one of the three server depending on a load on the server. Thank you . L. From crosseyedpenguin at cox.net Sun Mar 4 21:18:20 2007 From: crosseyedpenguin at cox.net (Roger) Date: Sun, 04 Mar 2007 19:18:20 -0700 Subject: Alternatives for Extracting EXIF and JPEG Data from Images In-Reply-To: <mailman.4661.1173053793.32031.python-list@python.org> References: <45EB3404.3030401@cox.net> <mailman.4661.1173053793.32031.python-list@python.org> Message-ID: <45EB7DEC.4080702@cox.net> Max Erickson wrote: > Roger <crosseyedpenguin at cox.net> wrote: > >> Does anybody have a pointer to a Python library/utility that will >> extract the chrominance and luminance quantization tables from >> JPG images? >> >> I have been using the _getexif method from PIL, which works fine, >> but doesn't extract the quantization data. I am a bit fuzzy on >> the terminology, but the quantization data seems to be JPEG data >> rather than EXIF data. One utility that extracts the >> quantization tables is JPEGsnoop -- there is a link to download >> the utility here: >> http://www.impulseadventure.com/photo/jpeg-quantization.html >> >> The source code for the above isn't available and may not be >> callable from a Python script even if it were available. >> >> Roger >> > > I don't know what the format is, etc, but jpegs I open with PIL have a > quantization attribute, e.g: > >>>> im.quantization > {0: array('b', [6, 4, 4, 5, 4, 4, 6, 5, 5, 5, 6, 6, 6, 7, 9, 14, 9, 9, > 8, 8, 9, 18, 13, 13, 10, 14, 21, 18, 22, 22, 21, 18, 20, 20, 23, 26, > 33, 28, > <snip a bunch more numbers> > > > max > Thank you, I wasn't aware of the quantization method. I was unable to find any documentation for it. The 0: array() output would appear to be the luminance 8x8 array and the 1: array() to be the chrominance 8x8 array. A curiosity is the values disagree with the output of the JPEGsnoop utility. For my Canon Powershot S2 IS set to "fine", im.quantization yields (after formatting): {0: array('b', [ 1, 1, 1, 2, 1, 1, 2, 2, 2, 2, 3, 2, 2, 3, 3, 6, 4, 3, 3, 3, 3, 7, 5, 8, 4, 6, 8, 8, 10, 9, 8, 7, 11, 8, 10, 14, 13, 11, 10, 10, 12, 10, 8, 8, 11, 16, 12, 12, 13, 15, 15, 15, 15, 9, 11, 16, 17, 15, 14, 17, 13, 14, 14, 14 ]), 1: array('b', [ 4, 4, 4, 5, 4, 5, 9, 5, 5, 9, 15, 10, 8, 10, 15, 26, 19, 9, 9, 19, 26, 26, 26, 26, 13, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26])} The JPEGsnoop output for the same jpg file is (pardon the line wrap): Precision=0 bits Destination ID=0 (Luminance) DQT, Row #0: 1 1 1 2 3 6 8 10 AnnexRatio: 16.0 11.0 10.0 8.0 8.0 6.7 6.4 6.1 DQT, Row #1: 1 1 2 3 4 8 9 8 AnnexRatio: 12.0 12.0 7.0 6.3 6.5 7.3 6.7 6.9 DQT, Row #2: 2 2 2 3 6 8 10 8 AnnexRatio: 7.0 6.5 8.0 8.0 6.7 7.1 6.9 7.0 DQT, Row #3: 2 2 3 4 7 12 11 9 AnnexRatio: 7.0 8.5 7.3 7.3 7.3 7.3 7.3 6.9 DQT, Row #4: 3 3 8 11 10 16 15 11 AnnexRatio: 6.0 7.3 4.6 5.1 6.8 6.8 6.9 7.0 DQT, Row #5: 3 5 8 10 12 15 16 13 AnnexRatio: 8.0 7.0 6.9 6.4 6.8 6.9 7.1 7.1 DQT, Row #6: 7 10 11 12 15 17 17 14 AnnexRatio: 7.0 6.4 7.1 7.3 6.9 7.1 7.1 7.2 DQT, Row #7: 14 13 13 15 15 14 14 14 AnnexRatio: 5.1 7.1 7.3 6.5 7.5 7.1 7.4 7.1 Approx quality factor = 92.96 (scaling=14.08 variance=5.28) ---- Precision=0 bits Destination ID=1 (Chrominance) DQT, Row #0: 4 4 5 9 15 26 26 26 AnnexRatio: 4.3 4.5 4.8 5.2 6.6 3.8 3.8 3.8 DQT, Row #1: 4 4 5 10 19 26 26 26 AnnexRatio: 4.5 5.3 5.2 6.6 5.2 3.8 3.8 3.8 DQT, Row #2: 5 5 8 9 26 26 26 26 AnnexRatio: 4.8 5.2 7.0 11.0 3.8 3.8 3.8 3.8 DQT, Row #3: 9 10 9 13 26 26 26 26 AnnexRatio: 5.2 6.6 11.0 7.6 3.8 3.8 3.8 3.8 DQT, Row #4: 15 19 26 26 26 26 26 26 AnnexRatio: 6.6 5.2 3.8 3.8 3.8 3.8 3.8 3.8 DQT, Row #5: 26 26 26 26 26 26 26 26 AnnexRatio: 3.8 3.8 3.8 3.8 3.8 3.8 3.8 3.8 DQT, Row #6: 26 26 26 26 26 26 26 26 AnnexRatio: 3.8 3.8 3.8 3.8 3.8 3.8 3.8 3.8 DQT, Row #7: 26 26 26 26 26 26 26 26 AnnexRatio: 3.8 3.8 3.8 3.8 3.8 3.8 3.8 3.8 Approx quality factor = 88.24 (scaling=23.52 variance=21.42) I don't understand the "AnnexRatio" data JPEGsnoop is adding to each row. Anyone have an explanation on how to translate the im.quantization values to the JPEGsnoop values? Or am I looking at two different types of "quantization" tables? Roger From ianare at gmail.com Sun Mar 25 19:07:16 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 25 Mar 2007 16:07:16 -0700 Subject: call to function by text variable In-Reply-To: <1174863710.576989.235290@o5g2000hsb.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> <eu6ufc$s0q$1@nemesis.news.tpi.pl> <1174863710.576989.235290@o5g2000hsb.googlegroups.com> Message-ID: <1174864036.639848.178440@b75g2000hsg.googlegroups.com> On Mar 25, 7:01 pm, "ianar?" <ian... at gmail.com> wrote: > Cool now I can run it through the translator. > > ops = (_("Directory"), _("Replace"), _("ChangeCase"), > _("Move"), _("Swap"), _("Insert"), _("ChangeLength")) > > self.operations.insert(pos, getattr(operations, ops[n]).Panel(self, > main)) > > Thanks guys! erm ... brainfart LOL. But now I can link it to the translated list. From adriancico at gmail.com Thu Mar 1 16:24:17 2007 From: adriancico at gmail.com (adriancico at gmail.com) Date: 1 Mar 2007 13:24:17 -0800 Subject: Questions about app design - OOP with python classes In-Reply-To: <45e733aa$0$25247$426a74cc@news.free.fr> References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> Message-ID: <1172784257.370311.272620@8g2000cwh.googlegroups.com> On Mar 1, 9:45 pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > As a side note : hungarian notation is usually considered bad form here. > Look here for usual naming conventions:http://www.python.org/dev/peps/pep-0008/ Thanks for the tip. It's been too many years of VB6, and its difficult to leave old habits behind :-) > > > With this design, pretty much everything is encapsulated in it > > respective > > class. However, that means that the main program logic is in the Frame > > class. > > What do you call "main program logic" exactly ? What I mean is that in the frame code is where all decisions are taken. The frame handles the other controls events, decides what needs to be done, calls the necesary methods of the other controls, etc. The other widgets just "do the work" when called from the Frame. But this is not necesarily bad, as you point out below. > Using the main frame as a mediator between the different widgets is a > well-known design pattern, named - suprisingly - mediator. The > motivation is that it avoid each and every widget to know about the > existence of every other widget. You may want to read about this pattern > - but note that most litterature about design patterns is expressed in > terms of statically typed languages (Java, C++ etc), and that dynamic > languages like Python usually don't need that much boilerplate and > complication (IOW : try to understand the pattern itself, not to blindly > apply it). > > What's your looking for IMHO is the "controller" part - the one that > glue together the "view" (main frame and all it's widgets) and the > "model" (mostly, your document). Here again, googling for > "model/view/controller" (MVC) may be a good idea. > I understand (I've been in wikipedia :-) ). Right now the Frame is the controller as well as the view. Moving out the "controller" code to another module seems to me the path to follow. I'll start to look out for MVC related material. My problem was that, altough I knew OOP basics, I didn't know how to apply them exactly. Thanks for your answer, it has cleared many things. > Note that there's nothing Python-specific in your question. But since > comp.object is one of the worst places on earth to ask questions about OO... I am developing in Python, so it made sense to me to post here. But you are right, the question is off-topic. Sorry for that. Thanks again and regards Adri?n Garrido From hg at nospam.org Thu Mar 15 03:22:47 2007 From: hg at nospam.org (hg) Date: Thu, 15 Mar 2007 08:22:47 +0100 Subject: looking for a simple crypto library References: <mailman.5125.1173940891.32031.python-list@python.org> Message-ID: <WLbKh.15650$zJ1.1142@newsfe24.lga> P?nar Yanarda? wrote: > Hi all, > > I'm looking for a crypto library which can simply: > > - extracts a public key from a (X.509) certificate, > > - supports public-key algorithms. > > Any suggestions? > > With love, > -- > P?nar "PINguAR" Yanarda? > http://pinguar.org pyopenssl ? From carsten at uniqsys.com Mon Mar 19 15:06:24 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 19 Mar 2007 15:06:24 -0400 Subject: Load three different modules which have the same name In-Reply-To: <1174329764.310542.298430@b75g2000hsg.googlegroups.com> References: <1174329389.488531.270010@p15g2000hsd.googlegroups.com> <1174329764.310542.298430@b75g2000hsg.googlegroups.com> Message-ID: <1174331184.3472.24.camel@dot.uniqsys.com> On Mon, 2007-03-19 at 11:42 -0700, abcd wrote: > nevermind this took care of it: > > import sys > > def tryAllThree(): > a = "c:\\alpha" > b = "c:\\beta" > g = "c:\\gamma" > > sys.path.append(a) > import Person > alpha = Person.Person() > > sys.path.remove(a) > sys.path.append(b) > reload(Person) > beta = Person.Person() > > sys.path.remove(b) > sys.path.append(g) > reload(Person) > gamma = Person.Person() That sort of works, but it's really unclean. I suggest you turn each directory that contains an implementation of Person into a package. That can be done by simply putting an __init__.py file into each of those directories. This __init__.py file can be empty or only contain a "pass" statement, but as long as it's there, the directory containing it becomes a package. Then, add the directory that contains your packages (C:\ in your example) to your path, and you can import and use your Person modules like this: import alpha.Person, beta.Person, gamma.Person alpha_person = alpha.Person.Person() beta_person = beta.Person.Person() gamma_person = gamma.Person.Person() The main advantages are that the different implementations of Person don't shadow each other in your name space, and you don't gratuitously force module reloads. Hope this helps, Carsten. From aisaac at american.edu Thu Mar 1 09:18:05 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 01 Mar 2007 14:18:05 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01><mailman.4438.1172534289.32031.python-list@python.org><xnQEh.3928$854.1781@trnddc04><1172561344.290126.191530@h3g2000cwc.googlegroups.com><OV0Fh.4396$tR1.2778@trnddc05><mailman.4475.1172614860.32031.python-list@python.org><3c5Fh.3664$Tg7.2156@trnddc03> <mailman.4487.1172628385.32031.python-list@python.org> <fMeFh.1995$N63.147@trnddc08> <45e60fdc$0$30655$426a34cc@news.free.fr> Message-ID: <xgBFh.4185$854.1692@trnddc04> "Bruno Desthuilliers" <bdesth.quelquechose at free.quelquepart.fr> wrote in message news:45e60fdc$0$30655$426a34cc at news.free.fr... > I don't share your definition of "reasonable". But you should have > guessed by now My view may be shaped by a different experience. I have found dynamic attribute creation convenient when doing something "quick and dirty", but I have never wanted it as a design feature in a more serious project. Can you give me an example where design considerations make dynamic attribute creation particularly desirable? Thank you, Alan Isaac From http Wed Mar 14 17:16:41 2007 From: http (Paul Rubin) Date: 14 Mar 2007 13:16:41 -0800 Subject: dict.items() vs dict.iteritems and similar questions References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <et958a$o9c$1@news2.u-psud.fr> Message-ID: <7xlkhzttja.fsf@ruckus.brouhaha.com> Laurent Pointal <laurent.pointal at limsi.fr> writes: > Both work, you may prefer xrange/iteritems for iteration on large > collections, you may prefer range/items when processing of the result > value explicitly need a list (ex. calculate its length) or when you are > going to manipulate the original container in the loop. You can use len(d) if d is a dict. From bdesth.quelquechose at free.quelquepart.fr Tue Mar 13 16:53:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 13 Mar 2007 21:53:22 +0100 Subject: Iterating across a filtered list In-Reply-To: <7xmz2hndh0.fsf@ruckus.brouhaha.com> References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <7xveh5nfwz.fsf@ruckus.brouhaha.com> <1173812047.578137.223430@j27g2000cwj.googlegroups.com> <7xmz2hndh0.fsf@ruckus.brouhaha.com> Message-ID: <45f70709$0$5892$426a34cc@news.free.fr> Paul Rubin a ?crit : > "Drew" <olsonas at gmail.com> writes: > >>You're exactly on the mark. I guess I was just wondering if your first >>example (that is, breaking the if statement away from the iteration) >>was preferred rather than initially filtering and then iterating. > > > I think the multiple statement version is more in Python tradition. I don't know if I qualify as a Python traditionalist, but I'm using Python since the 1.5.2 days, and I usually favor list comps or generator expressions over old-style loops when it comes to this kind of operations. > Python is historically an imperative, procedural language with some OO > features. Python has had functions as first class objects and (quite-limited-but) anonymous functions, map(), filter() and reduce() as builtin funcs at least since 1.5.2 (quite some years ago). > Iterators like that are a new Python feature List comps are not that new (2.0 or 2.1 ?): print "\n".join([contact for name, contact in contacts.items() \ if search.match(name)]) > and they have > some annoying characteristics, like the way they mutate when you touch > them. While sequences are iterables, all iterables are not sequences. Know what you use, and you'll be fine. > It's usually safest to create and consume them in the same > place, e.g. creating some sequence and passing it through map, filter, etc. Safest ? Why so ? From mail at microcorp.co.za Tue Mar 13 01:50:06 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Mar 2007 07:50:06 +0200 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com><1173629090.993914.55570@30g2000cwc.googlegroups.com><mailman.4944.1173629658.32031.python-list@python.org><1173631052.614449.51370@h3g2000cwc.googlegroups.com><no_Ih.8899$PL.2303@newsread4.news.pas.earthlink.net><7xy7m3tqq8.fsf@ruckus.brouhaha.com><1173653364.059431.19990@v33g2000cwv.googlegroups.com> <1173677725.341019.270100@j27g2000cwj.googlegroups.com> Message-ID: <003001c76533$74ad4b40$03000080@hendrik> "Paddy" <pa...y3118 at googlemail.com> wrote > > Hey, I'm still learnin'. Sweet! > contrary to popular belief, the answer to life, the universe, happiness and everything is not 42, but the above. - Hendrik From cfbolz at gmx.de Wed Mar 28 12:04:30 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 28 Mar 2007 18:04:30 +0200 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <6AFD137D-BE66-4BD6-84C5-0D473FCC3377@stackless.com> References: <mailman.5685.1175032114.32031.python-list@python.org> <1175041489.368797.281750@d57g2000hsg.googlegroups.com> <460A297A.5030605@gmx.de> <6AFD137D-BE66-4BD6-84C5-0D473FCC3377@stackless.com> Message-ID: <460A920E.504@gmx.de> Hi Christian! Christian Tismer wrote: > On 28.03.2007, at 10:38, Carl Friedrich Bolz wrote: > >> Brain error on our side: the gc_pypy.dll is the dll of the Boehm >> garbage >> collector, which you would need to compile yourself (which makes >> precompiled binaries a bit useless :-) ). We updated the zip file, >> would >> you mind checking whether it works better now? > > Why can't we provide a pre-compiled binary? > Is this a license issue? We can. That's exactly what we did. Cheers, Carl Friedrich Bolz From MonkeeSage at gmail.com Sat Mar 3 21:43:57 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Mar 2007 18:43:57 -0800 Subject: portable Python ifconfig In-Reply-To: <1172973137.492188.85100@s48g2000cws.googlegroups.com> References: <slrneujqni.6uk.bbbart@charles.inGen.islamabad> <1172971079.137861.316170@h3g2000cwc.googlegroups.com> <1172973137.492188.85100@s48g2000cws.googlegroups.com> Message-ID: <1172976237.808280.292150@j27g2000cwj.googlegroups.com> Bart, Can you try this and let us know if it works for FreeBSD? import socket, fcntl, struct def _ifinfo(sock, addr, ifname): iface = struct.pack('256s', ifname[:15]) info = fcntl.ioctl(sock.fileno(), addr, iface) if addr == 0x8927: hwaddr = [] for char in info[18:24]: hwaddr.append(hex(ord(char))[2:]) return ':'.join(hwaddr) else: return socket.inet_ntoa(info[20:24]) def ifconfig(ifname): ifreq = {'ifname': ifname} sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: ifreq['addr'] = _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) # SIOCGIFBRDADDR ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) # SIOCGIFNETMASK ifreq['hwaddr'] = _ifinfo(sock, 0x8927, ifname) # SIOCSIFHWADDR except: pass sock.close() return ifreq Regards, Jordan From arnodel at googlemail.com Sun Mar 4 15:03:14 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 4 Mar 2007 12:03:14 -0800 Subject: looking for Java final/Ruby freeze functionality in Python In-Reply-To: <45eb1fdf$1@news.vo.lu> References: <45eb1fdf$1@news.vo.lu> Message-ID: <1173038594.837631.322630@c51g2000cwc.googlegroups.com> On Mar 4, 7:38 pm, Antoine De Groote <anto... at vo.lu> wrote: > Hello, > > I've been googling for quite a while now but can't find anything about a > function/keyword to make a list (or something else) immutable. Could > anybody point me to docs about this matter or give me a reason why this > (apparently) doesn't exist in Python? First result from google 'python freeze object': http://www.python.org/dev/peps/pep-0351/ The PEP was rejected but the document contains a link to a discussion about why there is no such thing in python: http://mail.python.org/pipermail/python-dev/2006-February/060793.html HTH -- Arnaud From thomas.dunham at gmail.com Wed Mar 7 18:48:26 2007 From: thomas.dunham at gmail.com (Tombo) Date: 7 Mar 2007 15:48:26 -0800 Subject: Calling a function with unknown arguments? In-Reply-To: <1173308108.239943.174560@j27g2000cwj.googlegroups.com> References: <1173308108.239943.174560@j27g2000cwj.googlegroups.com> Message-ID: <1173311306.370427.219650@c51g2000cwc.googlegroups.com> On Mar 7, 10:55 pm, "Rob" <crow... at mit.edu> wrote: > I can get a list of a function's arguments.>>> def bob(a, b): > > ... return a+b > ...>>> bob.func_code.co_varnames > > ('a', 'b') > > Let's say that I also have a dictionary of possible arguments for this > function. > > >>> possible = {'a':10, 'b':5, 'c':-3} > > How do I proceed to call bob(a=10, b=5) with this information? > > Thanks! You can do this with a list comprehension: bob(*[possible[k] for k in bob2.func_code.co_varnames]) The LC creates a list of arg values in the same order as the var names for the function. Putting a * before the list when you call bob() turns that list into it's arguments. Alternativly (and this may not be useful) you can call a function with a dictionary of arguments: def bob(**kwargs): print kwargs possible = {'a' : 10, 'b':5, 'c':-3} >>> bob(**possible) {'a': 10, 'c': -3, 'b': 5} >>> Tom From aisaac at american.edu Thu Mar 1 09:39:17 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 01 Mar 2007 14:39:17 GMT Subject: design question: no new attributes References: <8BIEh.1349$QI4.489@trnddc01><mailman.4438.1172534289.32031.python-list@python.org><xnQEh.3928$854.1781@trnddc04><1172561344.290126.191530@h3g2000cwc.googlegroups.com><OV0Fh.4396$tR1.2778@trnddc05> <mailman.4475.1172614860.32031.python-list@python.org> <3c5Fh.3664$Tg7.2156@trnddc03> <54njqjF21q8jlU1@mid.individual.net> Message-ID: <pABFh.4186$854.3719@trnddc04> "greg" <greg at cosc.canterbury.ac.nz> wrote in message news:54njqjF21q8jlU1 at mid.individual.net... > There's a problem with that when you want to subclass: Agreed. The following addresses that and, I think, some of the other objections that have been raised. Alan class Lockable: a = 0 def __init__(self, lock=False): self.b = 1 self.lock = lock def __setattr__(self, attr, val): if not hasattr(self,attr) and hasattr(self,'lock') and self.lock: raise ValueError("This object accepts no new attributes.") self.__dict__[attr] = val From paul at boddie.org.uk Wed Mar 14 08:55:07 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Mar 2007 05:55:07 -0700 Subject: Grep Equivalent for Python In-Reply-To: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> References: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> Message-ID: <1173876907.128955.57410@o5g2000hsb.googlegroups.com> On 14 Mar, 13:37, "tereglow" <tom.rectenw... at eglow.net> wrote: > Hello all, > > I come from a shell/perl background and have just to learn python. Welcome aboard! > To start with, I'm trying to obtain system information from a Linux > server using the /proc FS. For example, in order to obtain the amount > of physical memory on the server, I would do the following in shell: > > grep ^MemTotal /proc/meminfo | awk '{print $2}' > > That would get me the exact number that I need. Now, I'm trying to do > this in python. Here is where I have gotten so far: > > memFile = open('/proc/meminfo') > for line in memFile.readlines(): > print re.search('MemTotal', line) You could even use the regular expression '^MemTotal' as seen in your original, or use the match function instead of search. However... > memFile.close() > > I guess what I'm trying to logically do is... read through the file > line by line, grab the pattern I want and assign that to a variable. > The above doesn't really work, it comes back with something like > "<_sre.SRE_Match object at 0xb7f9d6b0>" when a match is found. This is because re.search and re.match (and other things) return match objects if the regular expression has been found in the provided string. See this page in the library documentation: http://docs.python.org/lib/match-objects.html > Any help with this would be greatly appreciated. The easiest modification to your code is to replace the print statement with this: match = re.search('MemTotal', line) if match is not None: print match.group() You can simplify this using various idioms, I imagine, but what you have to do is to test for a match, then to print the text that matched. The "group" method lets you get the whole matching text (if you don't provide any arguments), or individual groups (applicable when you start putting groups in your regular expressions). Paul From bj_666 at gmx.net Sun Mar 4 04:38:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 04 Mar 2007 10:38:51 +0100 Subject: pop method question References: <mailman.4633.1172954118.32031.python-list@python.org> <1172968335.511875.255750@p10g2000cwp.googlegroups.com> <mailman.4638.1172976888.32031.python-list@python.org> Message-ID: <pan.2007.03.04.09.38.50.319215@gmx.net> In <mailman.4638.1172976888.32031.python-list at python.org>, Nicholas Parsons wrote: > Just from my computer science background when I see pop(), I think of a > stack data structure. Then question your presumptions. There are also many people thinking `list` must be something with nodes and pointers when they see the interface and usage of Python lists. > But then again, there are other examples of ambiguity in the python > language such as allowing operators like '+' to be overloaded. Why not > just have a "add()" method like Java? Why does this remove ambiguity? I even would expect different behaviour from both. I expect the ``+`` operator to return either an immutable or entirely new object, while `add()` can be something on containers that mutates the object. Ciao, Marc 'BlackJack' Rintsch From nmw at ion.le.ac.uk Thu Mar 22 13:11:10 2007 From: nmw at ion.le.ac.uk (Nigel Wade) Date: Thu, 22 Mar 2007 17:11:10 +0000 Subject: On Java's Interface (the meaning of interface in computer programing) References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <BMmdneR6mfcvt5zbnZ2dnUVZ_rCsnZ2d@comcast.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> <1174557840.338374.25990@d57g2000hsg.googlegroups.com> <57idnf5DTKfj55_bnZ2dnUVZ_uzinZ2d@comcast.com> Message-ID: <etudbe$gbf$1@south.jnrs.ja.net> Lew wrote: > Jim Burton wrote: >> Or you could stop feeding the trolls. > > People need to stop saying that. The original post was a detailed if incorrect > exposition of Java information. How in the world do you rate that trollish? a) Xah's posting history. b) the cross-posting c) the advocacy of the contents > > I have absolutely no reason to rate the OP as a troll or their post as trollish. > In time you will learn... It wasn't even a good troll. To be a good troll the message actually needs to be interesting enough to get people to read it. -- Nigel Wade, System Administrator, Space Plasma Physics Group, University of Leicester, Leicester, LE1 7RH, UK E-mail : nmw at ion.le.ac.uk Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555 From steve at holdenweb.com Mon Mar 26 14:07:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 26 Mar 2007 14:07:26 -0400 Subject: how to abort on syntax errors In-Reply-To: <1174930640.724685.72160@y80g2000hsf.googlegroups.com> References: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> <1174930640.724685.72160@y80g2000hsf.googlegroups.com> Message-ID: <eu924v$gat$1@sea.gmane.org> kyosohma at gmail.com wrote: > On Mar 26, 12:21 pm, "Josh" <n... at nowhere.com> wrote: >> I have a lot of except Exception, e statements in my code, which poses some >> problems. One of the biggest is whenever I refactor even the triviallest >> thing in my code. >> >> I would like python to abort, almost as if it were a compile-time error, >> whenever it cannot find a function, or if I introduced a syntax error. But, >> instead, it merrily proceeds on its way. >> >> Is there some idiom that you use in situations like these? >> thanks, >> josh > > Try sticking in an > > try: > #do something > except SyntaxError, e: > print e > sys.exit(0) > except Exception, e: > print e > > > # You put in as many exceptions as you like. > Of course the main problem with this solution is that a piece of code will raise a syntax error when it's compiled (i.e. at module import time, or when the main program starts up). So in the case where "#do something" has a syntax error it won;t be trapped because the program hasn't got to execution by the time the error is detected. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From anton.vredegoor at gmail.com Sat Mar 24 14:45:41 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 24 Mar 2007 19:45:41 +0100 Subject: A better webpage filter Message-ID: <eu3rhk$vpi$2@news3.zwoll1.ov.home.nl> Since a few days I've been experimenting with a construct that enables me to send the sourcecode of the web page I'm reading through a Python script and then into a new tab in Mozilla. The new tab is automatically opened so the process feels very natural, although there's a lot of reading, filtering and writing behind the scene. I want to do three things with this post: A) Explain the process so that people can try it for themselves and say "Hey stupid, I've been doing the same thing with greasemonkey for ages", or maybe "You're great, this is easy to see, since the crux of the biscuit is the apostrophe." Both kind of comments are very welcome. B) Explain why I want such a thing. C) If this approach is still valid after all the before, ask help for writing a better Python htmlfilter.py So here we go: A) Explain the process We need : - mozilla firefox http://en-us.www.mozilla.com/en-US/ - add-on viewsourcewith https://addons.mozilla.org/firefox/394/ - batch file (on windows): (htmfilter.bat) d:\python25\python.exe D:\Python25\Scripts\htmlfilter.py "%1" > out.html start out.html - a python script: #htmfilter.py import sys def htmlfilter(fname, skip = []): f = file(fname) data = f.read() L = [] for i,x in enumerate(data): if x == '<': j = i elif x =='>': L.append((j,i)) R = list(data) for i,j in reversed(L): s = data[i:j+1] for x in skip: if x in s: R[i:j+1] = ' ' break return ''.join(R) def test(): if len(sys.argv) == 2: skip = ['div','table'] fname = sys.argv[1].strip() print htmlfilter(fname,skip) if __name__=='__main__': test() Now install the htmlfilter.py file in your Python scripts dir and adapt the batchfile to point to it. To use the viewsourcewith add-on to open the batchfile: Go to some webpage, left click and view the source with the batchfile. B) Explain why I want such a thing. OK maybe this should have been the thing to start with, but hey it's such an interesting technique it's almost a waste no to give it a chance before my idea is dissed :-) Most web pages I visit lately are taking so much room for ads (even with adblocker installed) that the mere 20 columns of text that are available for reading are slowing me down unacceptably. I have tried clicking 'print this' or 'printer friendly' or using 'no style' from the mozilla menu and switching back again for other pages but it was tedious to say the least. Every webpage has different conventions. In the end I just started editing web pages' source code by hand, cutting out the beef and saving it as a html file with only text, no scripts or formatting. But that was also not very satisfying because raw web pages are *big*. Then I found out I often could just replace all 'table' or 'div' elements with a space and the page -although not very html compliant any more- still loads and often the text looks a lot better. This worked for at least 50 percent of the pages and restored my autonomy and independence in reading web pages! (Which I do a lot by the way, maybe for most people the problem is not very irritating, because they don't read as much? Tell me that too, I want to know :-) C) Ask help writing a better Python htmlfilter.py Please. You see the code for yourself, this must be done better :-) A. From steve at holdenweb.com Thu Mar 22 11:23:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 11:23:25 -0400 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: <Xns98FB8961DA528duncanbooth@127.0.0.1> References: <ett5h2$1ll$1@sea.gmane.org> <mailman.5443.1174553746.32031.python-list@python.org> <Xns98FB8961DA528duncanbooth@127.0.0.1> Message-ID: <etu740$vir$2@sea.gmane.org> Duncan Booth wrote: > Steve Holden <steve at holdenweb.com> wrote: > >> Help me out here. It looks as though the real syntax should >> be something like >> >> assignment_stmt ::= (target_list "=")+ expression_list | >> (target_list "=")+ assignment_stmt > > That is precisely the point. If it was: > > assignment_stmt ::= (target_list "=") expression_list | > (target_list "=") assignment_stmt > > (i.e. removing the '+' which your eyes jumped over) > then the actual assignments would have to apply right to left with each > assignment giving the result for the next one. > > But since it is: > > assignment_stmt ::= (target_list "=")+ expression_list > > the repeated target lists may be expected, and are indeed defined, to > assign left to right. Thanks, I see the plus sign now and appreciate that it indicates "one or more of", so the syntax is correct. But syntax doesn't imply semantics, so a left-recursive or right-recursive syntax formulation wouldn't require any change to the semantics of assignment. In other words, assignment_stmt ::= (target_list "=") expression_list | (target_list "=") assignment_stmt and assignment_stmt ::= (target_list "=") assignment_stmt | (target_list "=") expression_list are entirely equivalent, and neither imply any order of execution. I'm sure you understand that syntax only specifies what's legal, not how it should be interpreted. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From bignose+hates-spam at benfinney.id.au Wed Mar 14 20:58:11 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Mar 2007 11:58:11 +1100 Subject: Circular Class Logic References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> Message-ID: <87slc79vbw.fsf@benfinney.id.au> half.italian at gmail.com writes: > Short of making 'Disk' no longer a subclass of Folder, is there any > other way to include a subclassed instance in the base class of that > object? (this is very hard to put in to words) It's a little difficult to visualise what you're describing, but IIUC your problem is of this form: ===== foo.py ===== import bar class Foo(bar.Bar): pass ===== ===== bar.py ===== import baz class Bar(baz.Baz): pass ===== ===== baz.py ===== import foo class Baz(foo.Foo): pass ===== That is, each of the classes want to inherit from the others. The usual solution in these cases is to find the common required functionality and factor that out to a separate class that is then the superclass of two of the existing classes, breaking the circle. ===== wibble.py ===== # no dependencies class Wibble(object): pass ===== ===== foo.py ===== import wibble import bar class Foo(wibble.Wibble, bar.Bar): pass ===== ===== baz.py ===== import wibble class Baz(wibble.Wibble): pass ===== Note that Baz no longer subclasses foo.Foo, and both Foo and Baz get the common functionality they share from wibble.Wibble. -- \ "Buy not what you want, but what you need; what you do not need | `\ is expensive at a penny." -- Cato, 234-149 BC, Relique | _o__) | Ben Finney From vinjvinj at gmail.com Tue Mar 13 23:08:14 2007 From: vinjvinj at gmail.com (vj) Date: 13 Mar 2007 20:08:14 -0700 Subject: Questions on migrating from Numeric/Scipy to Numpy In-Reply-To: <mailman.5051.1173838059.32031.python-list@python.org> References: <1173835370.353415.8000@e1g2000hsg.googlegroups.com> <mailman.5051.1173838059.32031.python-list@python.org> Message-ID: <1173841694.932998.290390@d57g2000hsg.googlegroups.com> > Note that the mask needs to be a bool array. >>> mask = zeros(5) >>> mask = zeros(5, numpy.int8) >>> mask[1] = True >>> mask[2] = True >>> a = zeros(5) >>> a[mask] = [100, 200] >>> a array([ 100., 100., 0., 0., 0.]) I found this strange. It should just give an error if you try to use a mask array of non booleans. It's working great so far. Thanks for all the hard work. VJ From CRhode at LacusVeris.com Fri Mar 23 22:58:23 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Fri, 23 Mar 2007 21:58:23 -0500 Subject: [JOB] Sr. Python Developer, Northern VA References: <mailman.5428.1174517933.32031.python-list@python.org> <ettgei$rki$1@news2.zwoll1.ov.home.nl> <mailman.5446.1174557039.32031.python-list@python.org> <ettk02$6kc$1@news1.zwoll1.ov.home.nl> <mailman.5460.1174570842.32031.python-list@python.org> <etui34$24l$1@news4.zwoll1.ov.home.nl> <mailman.5471.1174584477.32031.python-list@python.org> <etul70$l3b$1@news4.zwoll1.ov.home.nl> <87aby59dy1.fsf@pobox.com> Message-ID: <pan.2007.03.24.02.58.22.896945@LacusVeris.com> John J. Lee wrote this on Thu, 22 Mar 2007 21:16:13 +0000. My reply is below. > I sympathise but conventional wisdom (which surely has a lot of > truth in it) is that employers are not faced with the problem of > minimising false negatives (failing to hire when they should have > hired). They are faced with the problem of minimising false > positives (hiring when they should not have hired). That's a gross > simplification of course, but I'm sure you appreciate the point -- > if you're hiring employees, being fairly risk-averse is probably > quite rational. ... so what's this we hear of employers' (in the US) being so starved for talent that they're willing to bring in young men from overseas with 3.5 kids and 1.5 wives? -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 44? ? Wind SSE 7 mph ? Sky overcast. Light rain; mist. From kyosohma at gmail.com Thu Mar 15 16:32:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 15 Mar 2007 13:32:24 -0700 Subject: problem with str() In-Reply-To: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> Message-ID: <1173990743.998399.82020@b75g2000hsg.googlegroups.com> On Mar 15, 2:49 pm, "7stud" <bbxx789_0... at yahoo.com> wrote: > I can't get the str() method to work in the following code(the last > line produces an error): > > ============ > class test: > """class test""" > def __init__(self): > """I am init func!""" > self.num = 10 > self.num2 = 20 > def someFunc(self): > """I am someFunc in test!""" > print "hello" > > obj = test() > obj.someFunc() > names = dir(obj) > print names > > methodList = [str for str in names if callable(getattr(obj, str))] > print methodList > > x = getattr(obj, methodList[0]).__doc__ > print x > print type(x) > print str(getattr(obj, methodList[0]).__doc__) > =========== > > Here is the output: > > $ python test1.py > hello > ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc'] > ['__init__', 'someFunc'] > I am init func! > <type 'str'> > Traceback (most recent call last): > File "test1.py", line 23, in ? > print str(getattr(obj, methodList[0]).__doc__) > TypeError: 'str' object is not callable > > This is part of some code in Diving Into Python,Chapter 4. In case a > function doesn't have a __doc__ string, and therefore __doc__ returns > None, the code needs to convert each __doc__ to a string so that the > result is guaranteed to be a string. Your string comprehension over wrote the str built-in method, turning it into a variable. If you just type "str" (without the quotes) into the interpreter, it'll spit out 'someFunc'. Thus, you cannot use str as the iterator in your code: methodList = [str for str in names if callable(getattr(obj, str))] instead, do something like this: methodList = [i for i in names if callable(getattr(obj, i))] Have fun! Mike From gagsl-py2 at yahoo.com.ar Fri Mar 9 23:49:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Mar 2007 01:49:23 -0300 Subject: bisect on a list of lists References: <1173471342.957772@iceman.esoterica.pt> <mailman.4874.1173477506.32031.python-list@python.org> <1173486322.393479@iceman.esoterica.pt> <mailman.4886.1173492553.32031.python-list@python.org> <1173500591.747311@iceman.esoterica.pt> Message-ID: <op.toyiclqyx6zn5v@gabriel2.softlabbsas.com.ar> En Sat, 10 Mar 2007 01:23:11 -0300, Paulo da Silva <psdasilvaX at esotericaX.ptX> escribi?: > Gabriel Genellina escreveu: > >> Just omit the __init__ method, if you don't have anything additional to >> do. The inherited method will be used instead, as always: > > > Then, if I have something additional, I can do > def __init__(self,l=None): > if l!=None: > list.__init__(self,l) > ... Yes, something like that. -- Gabriel Genellina From bbxx789_05ss at yahoo.com Mon Mar 26 12:51:09 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 Mar 2007 09:51:09 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: <4607a991$0$23165$426a74cc@news.free.fr> References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <gsidnUEwIpYIZZjbnZ2dnUVZ_oytnZ2d@comcast.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> <4607a991$0$23165$426a74cc@news.free.fr> Message-ID: <1174927869.003534.107350@d57g2000hsg.googlegroups.com> On Mar 26, 5:08 am, Bruno Desthuilliers <bruno. 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > Most of Python's object model is documented here: > > http://www.python.org/download/releases/2.2.3/descrintro/http://users.rcn.com/python/download/Descriptor.htm > Thanks. I've looked at both of those, and the second one is very good. From attn.steven.kuo at gmail.com Tue Mar 13 14:54:39 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 13 Mar 2007 11:54:39 -0700 Subject: How to capture environment state after running a shell script. In-Reply-To: <1173790656.886985.65660@v33g2000cwv.googlegroups.com> References: <1173790656.886985.65660@v33g2000cwv.googlegroups.com> Message-ID: <1173812079.750152.289300@n33g2000cwc.googlegroups.com> On Mar 13, 5:57 am, "Gerard Flanagan" <grflana... at yahoo.co.uk> wrote: > Hello, > > I have a third party shell script which updates multiple environment > values, and I want to investigate (and ultimately capture to python) > the environment state after the script has run. But running the script > as a child process only sets values for that process, which are lost > after execution. So I thought I could simply tack on an 'env' command > line to the script input lines as shown below. However, using > subprocess.Popen gives the error shown (even though the docs say that > any file object may be used for stdin), and using popen2 hangs > indefinitely. I think I'm missing something basic, any advice? Or is > there a better approach? > (snipped) > ########## first method ########## > p = Popen('/bin/sh', stdin=buf) > print p.stdout.readlines() > > Traceback (most recent call last): > File "scratch.py", line 36, in ? > p = Popen('/bin/sh', stdin=buf) > File "/usr/local/lib/python2.4/subprocess.py", line 534, in __init__ > (p2cread, p2cwrite, > File "/usr/local/lib/python2.4/subprocess.py", line 830, in > _get_handles > p2cread = stdin.fileno() > AttributeError: StringIO instance has no attribute 'fileno' > > ########## second method ########## > cmdout, cmdin = popen2('/bin/sh') > for line in buf: > cmdin.write(line) > > ret = cmdout.readlines() > cmdout.close() > cmdin.close() > > print ret First close the input so that the (sub) process knows to terminate and flush the output. Then, you can read from the output: import subprocess import popen2 p = subprocess.Popen(["/bin/sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.stdin.write("env -i FOO=BAR\n") p.stdin.close() status = p.wait() ret = p.stdout.readlines() p.stdout.close() print ret # Or cmdout, cmdin = popen2.popen2("/bin/sh") cmdin.write("env -i FOO=BAR\n") cmdin.close() ret = cmdout.readlines() cmdout.close print ret -- Hope this helps, Steven From __peter__ at web.de Fri Mar 23 13:31:52 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Mar 2007 18:31:52 +0100 Subject: fine grain logging cotrol References: <mailman.5451.1174567188.32031.python-list@python.org> <etu19j$nqi$03$1@news.t-online.com> <mailman.5464.1174579174.32031.python-list@python.org> <etuvoj$pqs$03$1@news.t-online.com> <etvvij$7h3$01$1@news.t-online.com> <mailman.5519.1174663861.32031.python-list@python.org> Message-ID: <eu12qc$1n5$00$1@news.t-online.com> Eric S. Johansson wrote: > Peter Otten wrote: >> Eric S. Johansson wrote: >> >> [in private mail -- please don't, Eric] > > sorry. my preference is for private mail. it's my way of trying to be > kind to others by reducing list clutter. It is not list clutter in my book; it gives others the chance to correct, add to, or even profit from our conversation. >> I don't understand. The logging package detects the function name without >> user intervention. > not in 2.4 afaik. Hmm, I must have overread that constraint in your previous posts... Here is yet another revision of my example then: import logging import sys class LoggedType(type): def __new__(mcl, name, bases, classdict): def get_logger(self): return logging.getLogger("%s.%s" % (name, sys._getframe(1).f_code.co_name)) classdict["_%s__logger" % name] = property(get_logger) return type.__new__(mcl, name, bases, classdict) class Logged: __metaclass__ = LoggedType class Felis(Logged): def alpha(self): self.__logger.info("Felis.alpha") def gamma(self): self.__logger.info("Felis.gamma") class Catus(Felis): def alpha(self): self.__logger.info("Catus.alpha") def beta(self): self.__logger.info("Catus.beta") if __name__ == "__main__": logging.basicConfig( format="EXPECTED %(message)s GOT %(name)s", level=logging.INFO) f = Felis() f.alpha() f.gamma() c = Catus() c.alpha() c.beta() c.gamma() Peter From sgeiger at ncee.net Tue Mar 27 12:53:58 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 27 Mar 2007 11:53:58 -0500 Subject: enumerating processes In-Reply-To: <4608A870.5000302@ncee.net> References: <3abd07c80703262117k42bcdebdp9c160675fa42918f@mail.gmail.com> <4608A870.5000302@ncee.net> Message-ID: <46094C26.1090303@ncee.net> > I believe you are looking for os.getpid() I apologize for providing that bit of incorrect info. It looks to me as if Python 1.5 had os.process which might have done what you wanted (although perhaps not in an OS-independent way). I wonder why there isn't an OS-independent way to do that in Python now. After having seen your message about tomcat.exe, I assume we are talking just about Windows. ;-) This looks like an excellent way to deal with processes on Windows: # http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes # List all running processes import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name # List all running notepad processes import wmi c = wmi.WMI () for process in c.Win32_Process (name="notepad.exe"): print process.ProcessId, process.Name # Create and then destroy a new notepad process import wmi c = wmi.WMI () process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe") for process in c.Win32_Process (ProcessId=process_id): print process.ProcessId, process.Name result = process.Terminate () > > ??? wrote: >> hi ,all >> any one knows how to enumerate the current running processes , or >> how to obtain a specific process by its name or process id. I know I >> can do this in many programming languages , but how in python? any >> one know? >> Thanks for any guidance. >> >> -- >> li xianmin >> >> lixianmin at gmail.com <mailto:lixianmin at gmail.com> > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20070327/59b26b9d/attachment.vcf> From gigs at hi.t-com.hr Fri Mar 9 12:04:12 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 09 Mar 2007 18:04:12 +0100 Subject: tkinter text editor In-Reply-To: <espfgv$6q7$1@ss408.t-com.hr> References: <espfgv$6q7$1@ss408.t-com.hr> Message-ID: <espfmi$7ev$1@ss408.t-com.hr> Gigs_ wrote: > I'm writing text editor. > > How to enable/disable (cut, copy etc.) when text is selected/not selected Btw it is cut copy ... in edit menu From beliavsky at aol.com Mon Mar 26 20:36:01 2007 From: beliavsky at aol.com (Beliavsky) Date: 26 Mar 2007 17:36:01 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174923080.941888.198340@p77g2000hsh.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174918286.213517.100190@l77g2000hsb.googlegroups.com> <1174923080.941888.198340@p77g2000hsh.googlegroups.com> Message-ID: <1174955761.486086.256910@o5g2000hsb.googlegroups.com> On Mar 26, 10:31 am, "Carl Banks" <pavlovevide... at gmail.com> wrote: <snip> > > You can write programs in Python that do usefully complicated things, > > and you can get them to work in a reasonable time. Fortran can't do > > this, for anything more than the trivial. "Classic" Fortran tasks of > > the past are now seen as trivial. OK, so they did it to a lot of data, > > but they really didn't do anything very complex to it. > > You couldn't be more incorrect. I have run some very old (pre-Fortran > 77) programs that are very far from trivial. > > > You can also write Python that other people can read and maintain. You > > can't do this in Fortran, without a truly insane amount of trouble. > > This is a lie. I've seen some Fortran code that was hellspawned, and > some that was clear as glass. The latter came about without a "truly > insane amount of trouble". I quite agree with you. People have written big, mission-critical programs to run nuclear reactors and design planes in Fortran 66 and 77, although I hoped that they ran static analysis programs such as FTNCHEK to verify them. Fortran 90 and later versions has modules, whose use allows the compiler to check types in procedure calls. I used Fortran 77 in my physics PhD program and find that I am much more productive in Fortran 95 now, making fewer errors not caught at compile time. The operations on arrays and array sections in Fortran 90+ help one to write number-crunching code that is "clear as glass". From a.schmolck at gmail.com Wed Mar 14 13:06:40 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 14 Mar 2007 17:06:40 +0000 Subject: Python equivalents to MATLAB str2func, func2str, ischar, isfunc? References: <1173891444.243400.41690@e65g2000hsc.googlegroups.com> Message-ID: <yfsy7lz7o0v.fsf@oc.ex.ac.uk> "dmitrey" <openopt at ukr.net> writes: > I can't find these via web serch > > thank you in advance, > Dmitrey str2func: getattr(some_module, 'f') func2str: f.__name__ ischar: isinstance(x, basestring) and len(x) == 1 isfunc: callable(x) # is most likely to be what you want 'as From martin at v.loewis.de Sat Mar 31 14:02:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 31 Mar 2007 20:02:58 +0200 Subject: When will 2.5.1 be released? In-Reply-To: <1173220493.492862.299210@q40g2000cwq.googlegroups.com> References: <1173037797.127119.248300@h3g2000cwc.googlegroups.com> <1173208347.506758.166620@30g2000cwc.googlegroups.com> <1173220493.492862.299210@q40g2000cwq.googlegroups.com> Message-ID: <460EA252.5050804@v.loewis.de> >> And while we're waiting for 2.5.1, can somebody post a clear (as >> opposed to the one that comes with Tix ;)) explanation of how to >> manually install Tix into python 2.5? It should be possible... > > LLoyd > -Not possible - this is a known bug and won't be fixed until 2.5.1 This is not true. Copying the tix files into the Python installation will work just fine. Regards, Martin From grante at visi.com Wed Mar 7 18:14:24 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 07 Mar 2007 23:14:24 -0000 Subject: Calling a function with unknown arguments? References: <1173308108.239943.174560@j27g2000cwj.googlegroups.com> Message-ID: <12uuhqggp71ikad@corp.supernews.com> On 2007-03-07, Rob <crowell at mit.edu> wrote: > I can get a list of a function's arguments. >>>> def bob(a, b): > ... return a+b > ... >>>> bob.func_code.co_varnames > ('a', 'b') > > Let's say that I also have a dictionary of possible arguments for this > function. >>>> possible = {'a':10, 'b':5, 'c':-3} > > How do I proceed to call bob(a=10, b=5) with this information? bob(a=possible['a'],b=possible['b']) -- Grant Edwards grante Yow! BRILL CREAM is at CREAM O' WHEAT in another visi.com DIMENSION... From anton.vredegoor at gmail.com Wed Mar 28 13:12:20 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 28 Mar 2007 19:12:20 +0200 Subject: Hpw make lists that are easy to sort. Message-ID: <eue7lg$3ce$1@news2.zwoll1.ov.home.nl> Python's sorting algorithm takes advantage of preexisting order in a sequence: #sort_test.py import random import time def test(): n = 1000 k = 2**28 L = random.sample(xrange(-k,k),n) R = random.sample(xrange(-k,k),n) t = time.time() LR = [(i+j) for i in L for j in R] print time.time()-t LR.sort() print time.time()-t print t = time.time() #L.sort() R.sort() presorted_LR = [(i+j) for i in L for j in R] print time.time()-t presorted_LR.sort() print time.time()-t if __name__=='__main__': test() On this -very slow- computer this prints: >d:\python25\pythonw -u "sort_test.py" 1.10000014305 8.96000003815 1.10000014305 5.49000000954 >Exit code: 0 Presorting the second sequence gains us more than three seconds. I wonder if there is a way to generate the combined items in such a way that sorting them is even faster? Is there some other sorting algorithm that can specifically take advantage of this way -or another way- of generating this list? The final sequence is len(L)*len(R) long but it is produced from only len(L)+len(R) different items, is it possible to exploit this fact? I'd also be interested in a more general solution that would work for summing the items of more than two lists in this way. A. From carsten at uniqsys.com Mon Mar 12 11:21:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 12 Mar 2007 11:21:19 -0400 Subject: backslashes in lists In-Reply-To: <BAY126-W6DD4F050FEF6036835FEFD37D0@phx.gbl> References: <BAY126-W6DD4F050FEF6036835FEFD37D0@phx.gbl> Message-ID: <1173712879.3463.49.camel@dot.uniqsys.com> On Mon, 2007-03-12 at 18:08 +0300, Fabio Gomes wrote: > Yes, Luca. > > I noticed that printing the list item will show the string as > expected. But I need to print the entire list in the script I'm > writing and doing that, the list will will be repr()'ed. Is there any > way to print the entire list without being parsed by repr()? It would be easier to help you if you told us what you are actually trying to achieve. What does printing the entire list give you that printing its individual items does not? -Carsten From gagsl-py2 at yahoo.com.ar Fri Mar 9 20:22:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 22:22:14 -0300 Subject: Are Lists thread safe? References: <1173467014.510693.60330@30g2000cwc.googlegroups.com> <1173469137.897102.298120@p10g2000cwp.googlegroups.com> <1173469517.797876.262330@t69g2000cwt.googlegroups.com> <1173469804.756713.41700@q40g2000cwq.googlegroups.com> Message-ID: <op.tox8rcxwx6zn5v@gabriel2.softlabbsas.com.ar> En Fri, 09 Mar 2007 16:50:04 -0300, abcd <codecraig at gmail.com> escribi?: > I guess this might be overkill then... That depends on your target. For the *current* CPython implementation, yes, because it has an internal lock. But other versions (like Jython or IronPython) may not behave that way. > class MyList(list): > def __init__(self): > self.l = threading.Lock() Better to use an RLock, and another name instead of l: self.lock = threading.RLock() (A method may call another, and a Lock() won't allow that) > def append(self, val): > try: > self.l.acquire() > list.append(self, val) > finally: > if self.l.locked(): > self.l.release() I'd write it as: def append(self, val): self.lock.acquire() try: list.append(self, val) finally: self.lock.release() > ....performing the same locking/unlocking for the other methods (i.e. > remove, extend, etc). Note that even if you wrap *all* methods, operations like mylist += other are still unsafe. py> def f(self): self.mylist += other ... py> import dis; dis.dis(f) 1 0 LOAD_FAST 0 (self) 3 DUP_TOP 4 LOAD_ATTR 0 (mylist) 7 LOAD_GLOBAL 1 (other) 10 INPLACE_ADD 11 ROT_TWO 12 STORE_ATTR 0 (mylist) 15 LOAD_CONST 0 (None) 18 RETURN_VALUE INPLACE_ADD would call MyList.__iadd__ which you have wrapped. But you have a race condition between that moment and the following STORE_ATTR, a context switch may happen in the middle. It may not be possible to create an absolutely thread-safe list without some help on the client side. (Comments, someone?) -- Gabriel Genellina From troy.melhase at gmail.com Sat Mar 17 16:08:04 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Sat, 17 Mar 2007 12:08:04 -0800 Subject: Pickle and Instance Methods In-Reply-To: <1174160685.098122.29780@l77g2000hsb.googlegroups.com> References: <1174160685.098122.29780@l77g2000hsb.googlegroups.com> Message-ID: <d50f6c8a0703171308v101cb196t97b52d6e5b17c5af@mail.gmail.com> > I understand that this cannot be saved by pickle. > My question is, is there another way of setting a callback that would > agree with pickle? > If not is there some way to make pickle ignore the problem attribute? Try adding a __getstate__ method to your class: http://docs.python.org/lib/pickle-inst.html From deets at nospam.web.de Sun Mar 11 06:18:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 11 Mar 2007 11:18:37 +0100 Subject: Python in a desktop environment In-Reply-To: <1173605193.585675.217210@30g2000cwc.googlegroups.com> References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> <1173595945.530722.273030@30g2000cwc.googlegroups.com> <1173605193.585675.217210@30g2000cwc.googlegroups.com> Message-ID: <55i3btF251if5U1@mid.uni-berlin.de> David Cramer schrieb: > On Mar 10, 10:52 pm, "sjdevn... at yahoo.com" <sjdevn... at yahoo.com> > wrote: >> David Cramer wrote: >>> If you had an application that you were about to begin development on >>> which you wanted to be cross platform (at least Mac and Windows), >>> would you suggest using c++ and Python? >> I'd strongly consider a pure python solution (I'd choose wxpython), >> but if I needed to code backend stuff in a lower level language I'd >> use C rather than C++. > > Well we want it to be very robust, and python isn't exactly the > fastest language, or one with the lowest overhead :) Erm, and what has _robustness_ with fast & less overhead to do? It's exactly the other way round, a python program is much less likely to crash that C/C++, and if so in manners that are much easier to manage and fix. I've done extensive GUI-development with PyQt, and can say that it's a very productive and powerful combination. And GUI-code usually isn't troublesome performance-wise. Diez From rune.strand at gmail.com Sat Mar 10 16:24:34 2007 From: rune.strand at gmail.com (Rune Strand) Date: 10 Mar 2007 13:24:34 -0800 Subject: How to test if a key in a dictionary exists? In-Reply-To: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> References: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> Message-ID: <1173561873.899180.321480@s48g2000cws.googlegroups.com> Yes, you have name.has_key(name_key) and perhaps better, the in operator: if name_key in name: do something From http Thu Mar 8 21:30:58 2007 From: http (Paul Rubin) Date: 08 Mar 2007 18:30:58 -0800 Subject: any better code to initalize a list of lists? References: <esqc9r$cn09$1@netnews.upenn.edu> <7xlki7dx5m.fsf@ruckus.brouhaha.com> <esqfea$cne0$1@netnews.upenn.edu> Message-ID: <7xps7j6tct.fsf@ruckus.brouhaha.com> "John" <rds1226 at sh163.net> writes: > I want to radix sort non-negative integers that can fit into 32-bits. But why do you want to do that? Why not just use Python's built-in sorting operation? From sgeiger at ncee.net Tue Mar 20 01:51:02 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 20 Mar 2007 00:51:02 -0500 Subject: using regexp In-Reply-To: <1174368793.835787.57710@e1g2000hsg.googlegroups.com> References: <1174368793.835787.57710@e1g2000hsg.googlegroups.com> Message-ID: <45FF7646.5030801@ncee.net> You don't even need regex. def split_seq(seq,size): # this is sort of the inverse of flatten # Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 return [seq[i:i+size] for i in range(0, len(seq), size)] line = '123456789123456789' print split_seq(line,3) Will that work for you? s99999999s2003 at yahoo.com wrote: > hi > how can i use regexp to group these digits into groups of 3? > > eg > line 123456789123456789 > > i have : > > pat = re.compile("line\s+(\d{3})" , re.M|re.DOTALL) > > but this only gives the first 3. I also tried > > "line\s+(\d{3})+" > but also not working. > I need output to be ['123' ,'456','789', '123','456','789', .....] > thanks. > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20070320/7e147968/attachment.vcf> From brad at allendev.com Sat Mar 10 12:54:00 2007 From: brad at allendev.com (Brad Allen) Date: Sat, 10 Mar 2007 11:54:00 -0600 Subject: [python-advocacy] A Pythonic Way to Measure and Improve Your Programming Skills? In-Reply-To: <1173546636.14230.57.camel@workshop> References: <45F14D7E.3060707@taupro.com> <a06230908c2187f182731@[192.168.1.242]> <1173546636.14230.57.camel@workshop> Message-ID: <a0623090cc2189ef69f28@[192.168.1.242]> At 9:10 AM -0800 3/10/07, Michael Bernstein wrote: >On Sat, 2007-03-10 at 10:01 -0600, Brad Allen wrote: > >> When I discussed this problem with Michael Bernstein at PyCon he suggested >> the idea of creating a "chroot jail" for each web session which could run >> the Python interpreter in a secure sandbox. That might be easier than giving >> each session a whole virtual server. > >Note that this wasn't an original idea of mine, I got it from brief >mentions associated with two existing interactive python-in-a-web-page >implementations: > > Try Python: http://www.mired.org/home/mwm/try_python/ > > TryPy: http://trac.pocoo.org/wiki/TryPy > Cool! The first link appears to work with Firefox and provides a real example of using a Python interactive prompt via a non-local web interface. Interestingly, it doesn't seem to use Crunchy, but instead uses TryPy. Apparently you can't define classes or functions with TryPy, but I recall you can using Crunchy. This is important for creating tutorials in which you ask the student to define a class or function to solve a problem. From half.italian at gmail.com Thu Mar 15 08:01:07 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 15 Mar 2007 05:01:07 -0700 Subject: Circular Class Logic In-Reply-To: <mailman.5124.1173937103.32031.python-list@python.org> References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> <mailman.5118.1173920321.32031.python-list@python.org> <1173921593.166607.240390@e65g2000hsc.googlegroups.com> <mailman.5124.1173937103.32031.python-list@python.org> Message-ID: <1173960067.782597.96840@e1g2000hsg.googlegroups.com> > Remove the line above > and add this below: > def initFoo(): > import baz > Foo.baz = baz.Baz() > initFoo() I got it to work, but I had to add a check to see if the class variable had been set.. def initBaz(): import Baz Foo.baz = Baz.Baz() class Foo: baz = None def __init__(self): if Foo.baz == None: Foo.baz = True initBaz() What exactly is being accomplished by having the init function outside of the class? If there is no check, wouldn't it just execute every time an object is instantiated anyway? > Instead of initFoo, you could use a custom metaclass. Or a class decorator (if > and when they become available...) I haven't tried either of those yet. The names scare me. :) Sounds like this might be a good time to explore them. > The code above is an effective way of doing what you want. But I'd think about > the actual need of doing such things - are you sure it's a good design? > I thought it was a good design, but now I'm not so sure. I'm untrained, so often I dont know the right way to do things. As I build this into the libraries, I'll keep an eye on how the code is developing and go from there. Thanks for the help! ~Sean From skip at pobox.com Fri Mar 30 16:49:10 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 30 Mar 2007 15:49:10 -0500 Subject: [Pythonmac-SIG] MacPython wiki "moved" to Python wiki - now it's your turn... In-Reply-To: <460D76F8.4050601@codebykevin.com> References: <17873.15892.286360.853505@montanaro.dyndns.org> <460D76F8.4050601@codebykevin.com> Message-ID: <17933.30662.861059.441920@montanaro.dyndns.org> Kevin> I was just looking at the new MacPython pages at the Python Kevin> wiki--it appears nothing has been done with them since Skip moved Kevin> them over. I'm thinking this is a terrific opportunity to bring Kevin> them up to date: would anyone mind if I got started? A lot of Kevin> this stuff doesn't appear to have been touched for three or four Kevin> years. I say go for it. You are correct in presuming the functional content has not been improved. The spammers have rediscovered it at its new home and continue to play their silly games, but there are a group of us committed to keeping the Python wiki cleaned up in that respect. Skip From jjl at pobox.com Thu Mar 22 17:16:13 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 22 Mar 2007 21:16:13 GMT Subject: [JOB] Sr. Python Developer, Northern VA References: <mailman.5428.1174517933.32031.python-list@python.org> <ettgei$rki$1@news2.zwoll1.ov.home.nl> <mailman.5446.1174557039.32031.python-list@python.org> <ettk02$6kc$1@news1.zwoll1.ov.home.nl> <mailman.5460.1174570842.32031.python-list@python.org> <etui34$24l$1@news4.zwoll1.ov.home.nl> <mailman.5471.1174584477.32031.python-list@python.org> <etul70$l3b$1@news4.zwoll1.ov.home.nl> Message-ID: <87aby59dy1.fsf@pobox.com> > > Michael Bentley wrote: > > > Perhaps it is different where you live, but here you can put on your > > resume relevant things that aren't paying jobs. Otherwise nobody > > would ever get their first job, right? > > Sure you can. But around here if one has been unemployed for a while > it's nearly impossible to get hired ever again. It doesn't matter how > many years programming Python one puts on the resume. Unpaid > activities are just not *visible*. So HRM people keep asking questions > like 'But what have you been doing?' In the end I just started my own > company, and while I'm not always employed as a freelancer I can at > least now say I'm running my own business. You may not realise it if you haven't been applying for work since you did that, but I'm sure you've done a lot for your "employability" (I hate that word, it implies that it's a one-sided business, clearly false) by working as a freelancer. Your original rant seemed rather one-sided, though. > The basic problem however is that it's just not anyones business > whether one has been walking through the country making pictures or > doing some desk job. All that should matter is can he do the job and > is he motivated. Asking a person who he *is* (resume) is not Pythonic! I sympathise but conventional wisdom (which surely has a lot of truth in it) is that employers are not faced with the problem of minimising false negatives (failing to hire when they should have hired). They are faced with the problem of minimising false positives (hiring when they should not have hired). That's a gross simplification of course, but I'm sure you appreciate the point -- if you're hiring employees, being fairly risk-averse is probably quite rational. I've often thought that randomness is a good thing here though, globally -- a world of perfectly rational selfish employers would fail to employ legions of highly productive people. Luckily incompetence in hiring steps in often enough to save the day, in this best of all possible worlds <0.75 wink> (no hiring incompetence at the employer I'm just about to move to, it goes without saying :-) John From john.pye at gmail.com Wed Mar 21 01:48:47 2007 From: john.pye at gmail.com (John Pye) Date: 20 Mar 2007 22:48:47 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: <etqecu$kl5$1@rumours.uwaterloo.ca> References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> <mailman.5372.1174450550.32031.python-list@python.org> <etqecu$kl5$1@rumours.uwaterloo.ca> Message-ID: <1174456127.741403.198150@e65g2000hsc.googlegroups.com> On Mar 21, 4:04 pm, Ross Ridge <rri... at caffeine.csclub.uwaterloo.ca> wrote: > Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: > >You can get the file descriptor from the Python file object using its > >fileno() method. The file descriptor lives at the OS level, so it's safe > >to pass around. > > Not under Windows. Windows doesn't have Unix-like descriptors, so the > C runtime emulates them. I am trying the following... any thoughts? %typemap(in) FILE * { if (!PyFile_Check($input)) { PyErr_SetString(PyExc_TypeError, "Need a file!"); return NULL; } %#ifdef __MINGW32__ PyFileObject *fo = (PyFileObject *)$input; $1 = fdopen(_fileno(fo->f_fp),PyString_AsString(fo->f_mode)); fprintf(stderr,"FDOPEN(%d,\"%s\")\n",fo->f_fp,PyString_AsString(fo- >f_mode)); %#else $1 = PyFile_AsFile($input); %#endif } From _karlo_ at _mosor.net_ Tue Mar 20 09:08:58 2007 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Tue, 20 Mar 2007 13:08:58 +0000 (UTC) Subject: How to copy a ClassObject? Message-ID: <Xns98F98FEF2B9A6mosornet@161.53.160.64> Hi all, how would one make a copy of a class object? Let's say I have: class First: name = 'First' And then I write: tmp = First then 'tmp' becomes just a reference to First, so if I write tmp.name = "Tmp", there goes my First.name. So, how to make 'tmp' a copy of First, I tried using copy.copy and copy.deepcopy, but that doesn't work. P.S. Yes, I can do a: class tmp(First): pass but I'd rather make a copy than a subclass. Thanks. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From sergio.correia at gmail.com Tue Mar 6 14:40:37 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Tue, 6 Mar 2007 14:40:37 -0500 Subject: Getting external IP address In-Reply-To: <1173206863_18689@sp6iad.superfeed.net> References: <pan.2007.03.05.08.49.56.620290@REMOVEME.cybersource.com.au> <1173206863_18689@sp6iad.superfeed.net> Message-ID: <f1aa6d810703061140m27b5f169gc3dab7b24ffe53c1@mail.gmail.com> The above suggestions seem nice, but I find this one easier: import urllib2 ext_ip = urllib2.urlopen('http://whatismyip.org/').read() print ext_ip The nice thing about the above code is that http://whatismyip.org/ only contains exactly what you want (the ip, nothing more, nothing less), so no parsing is necessary Best, Sergio On 3/6/07, Cousin Stanley <cousinstanley at hotmail.com> wrote: > > > I have a PC behind a firewall, and I'm trying to programmatically > > determine the IP address visible from outside the firewall. > > .... > > Steven .... > > Following is another alternative that might at least > be worth consideration .... > > I use the lynx command shown as a command-line alias > under Debian linux .... > > >>> > >>> import os > >>> > >>> pipe_in = os.popen( 'lynx --dump http://checkip.dyndns.org' ) > >>> > >>> ip_addr = pipe_in.readlines() > >>> > >>> for this in ip_addr : > ... print this > ... > > > Current IP Address: 65.39.92.38 > > > -- > Stanley C. Kitching > Human Being > Phoenix, Arizona > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups > ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Tue Mar 27 14:22:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 Mar 2007 15:22:02 -0300 Subject: How can I catch all exception in python? References: <1175018958.602131.145190@y80g2000hsf.googlegroups.com> Message-ID: <op.tpu1a0bix6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 27 Mar 2007 15:09:18 -0300, yinglcs at gmail.com <yinglcs at gmail.com> escribi?: > I read the document here about exception handling in python: > > http://www.diveintopython.org/file_handling/index.html > > Can you please tell me how can I catch all exception in python? > like this in Java: > try { > .... > } catch (Throwable t) { > ... > } See the Further Reading section on that same page. Exceptions are covered in the Python Tutorial here: http://docs.python.org/tut/node10.html -- Gabriel Genellina From paolopantaleo at gmail.com Tue Mar 6 11:01:58 2007 From: paolopantaleo at gmail.com (PAolo) Date: 6 Mar 2007 08:01:58 -0800 Subject: Wrong exist status for os.system, os.poepen, etc. In-Reply-To: <1173196282.319123.230430@p10g2000cwp.googlegroups.com> References: <mailman.4719.1173195592.32031.python-list@python.org> <1173196282.319123.230430@p10g2000cwp.googlegroups.com> Message-ID: <1173196918.161093.292930@30g2000cwc.googlegroups.com> On 6 Mar, 16:51, "Paul Boddie" <p... at boddie.org.uk> wrote: > On 6 Mar, 16:39, "Paolo Pantaleo" <paolopanta... at gmail.com> wrote: > > > > > The os.system() (but all the other funciont with similar behavior) reports > > wrong exit status. I can reproduce the bug in the following way > > I think you should look at some previous threads related to this > (obtained by searching Google Groups for "os.system exit status > code"): > > "grabbing return codes from os.system() call"http://groups.google.com/group/comp.lang.python/browse_frm/thread/efe... > > "please help me understand os.system() result"http://groups.google.com/group/comp.lang.python/browse_frm/thread/4a9... > > "os.system() << 8 ?"http://groups.google.com/group/comp.lang.python/browse_frm/thread/f12... > > In short, the returned code is actually a combination of two values, > and you need to extract the expected status code by shifting the > result 8 bits to the right. It may actually be more complicated than > that, but the man page for system ("man 3 system") explains this in > more detail. > > Paul Sorry, for the mistake, I just missed the words "encoded in the format specified for wait()" in the documentation of popen() Thnx for the immediate answer PAolo From randomtalk at gmail.com Fri Mar 16 13:42:49 2007 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 16 Mar 2007 10:42:49 -0700 Subject: TypeError: 'module' object is not callable Message-ID: <1174066969.563803.216040@p15g2000hsd.googlegroups.com> Hello everyone! i have the following test code: class temp: def __init__(self): self.hello = "hello world!" def printworld(self): print(self.hello) t = temp() and i tried to call profile('t.printworld()') but i received the following error: Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: 'module' object is not callable I'm not sure what is wrong exactly, if anyone can point me to the right direction, it would be much appreciated! From steven.bethard at gmail.com Wed Mar 21 13:50:07 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 21 Mar 2007 11:50:07 -0600 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) In-Reply-To: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Message-ID: <2_SdnSgt_r_N7ZzbnZ2dnUVZ_s-rnZ2d@comcast.com> dmitrey wrote: > I looked to the PEPs & didn't find a proposition to remove brackets & > commas for to make Python func call syntax caml- or tcl- like: instead > of > result = myfun(param1, myfun2(param5, param8), param3) > just make possible using > result = myfun param1 (myfun2 param5 param8) param3 You should really post this somewhere that Guido will see it so he can add it to PEP 3099: "Things that will Not Change in Python 3000". Really, there's no way this is going to fly, so you might as well drop it or write your own language. STeVe P.S. If you use IPython, I believe you can get some of this. From zzhao at laika.com Tue Mar 13 21:02:23 2007 From: zzhao at laika.com (ZiZi Zhao) Date: Tue, 13 Mar 2007 18:02:23 -0700 Subject: list of dictionary in embedded Python References: <ACCA22ED08500745AE88FEDED5B6F2EA02BC0B4F@exchange.wvs> <op.towjcjt7x6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <ACCA22ED08500745AE88FEDED5B6F2EA02BC0B68@exchange.wvs> You are right! I added Py_INCREF(pDict); right behind pDict = PyDict_New(); it seems to work correctly. thanks, zz -----Original Message----- From: python-list-bounces+zzhao=laika.com at python.org on behalf of Gabriel Genellina Sent: Thu 3/8/2007 7:15 PM To: python-list at python.org Subject: Re: list of dictionary in embedded Python En Thu, 08 Mar 2007 22:26:59 -0300, ZiZi Zhao <zzhao at laika.com> escribi?: > I tried to build a list of dictionaries using embedded Python2.5 > in the following way to append dictionaries to a list. > > Py_Object *pList = PyList_New(0); > > for (i=0; i<MAXSIZE; i++) { > Py_Object *pDict = PyDict_New(); > // > // build this dictionary of keys & values > // > if (pDict != NULL) { > if (PyList_Append(pList, pDict) < 0) { > printf ("Failed to append new dict to dict-list\n"); > } > Py_DECREF(pDict); > } > } > > In this way, I found the PyList_Append only appends the pointer > of pDict to pList. All Python objects are seen as pointers on C code. > After Py_DECREF(pDict) and going back to, > Py_Object *pDict = PyDict_New(); > for next run in loop, it gets the same pointer as last time, Perhaps (in the non-posted block) there is a Py_INCREF missing, and that last Py_DECREF destroys the object. (You don't see the printf message, I presume) > which finally makes all dictionaries in the list are the same > as the last one. (BTW, in Python, the result is correct.) > Now, I have to do no Py_DECREF(pDict) in the loop, but do once at > the end, when the loop is finished, like You could check using sys.getrefcount; if all of them say 2 (including the last dict) you know the list holds the only reference to them. (And all id() should be different, too). Maybe this code is useful; builds a list of empty dictionaries. (Note that I *know* the list is empty and has the right size, so I can use PyList_SET_ITEM instead of the non-macro version PyList_SetItem or the insert/append variants). /* flistdict - fast list of dictionaries flistdict(size) -> [{},{},...] = [{} for _ in range(size)] Devuelve una lista de diccionarios vac?os (todos diferentes) */ static PyObject * flistdict(PyObject *self, PyObject *args) { int i, size; PyObject *result=NULL, *dict=NULL; if (!PyArg_ParseTuple(args, "i", &size)) return NULL; result = PyList_New(size); if (result==NULL) goto error; for (i=0; i<size; i++) { dict = PyDict_New(); if (dict==NULL) goto error; PyList_SET_ITEM(result, i, dict); } goto normalexit; error: Py_XDECREF(result); result = NULL; normalexit: return result; } -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070313/f8dadaa5/attachment.html> From gagsl-py2 at yahoo.com.ar Tue Mar 13 03:18:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Mar 2007 04:18:00 -0300 Subject: Calling cpp from python/SWIG References: <1173767623.632550.148000@64g2000cwx.googlegroups.com> Message-ID: <op.to388ag9x6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 13 Mar 2007 03:33:43 -0300, Frank <supervau at gmail.com> escribi?: > I want to parse an array M1 from python to a cpp function fct which > returns an array M2. > > How can I do this best? Is SWIG appropriate or is there something > else? If you're going to call a single function, declare it with extern "C" (or write a wrapper function) and use ctypes from Python. Try to keep the memory allocation in Python: instead of returning another array, make the function use the *same* input array, or give it -from Python- a previously allocated array. ctypes comes with Python 2.5, and you can download and install it for previous versions too. -- Gabriel Genellina From lobais at gmail.com Mon Mar 26 02:30:16 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Mon, 26 Mar 2007 08:30:16 +0200 Subject: Sending ECHO_REQUEST (pinging) with python Message-ID: <pan.2007.03.26.06.30.33@gmail.com> Hi, I've writing a python application in which I'd like to have a small "ping label", to always tell the current ping time to the server. It seems however that I have to be root to send those imcp packages, but I guess there must be a workaround since I can easily use the "ping" command as ordinary user. Do anybody know how to do this in python? From sbassi at clubdelarazon.org Sun Mar 18 01:08:51 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 18 Mar 2007 02:08:51 -0300 Subject: How to parse the os.system() output in python In-Reply-To: <etifo0$vj7$1@news.yaako.com> References: <1174177736.241481.115150@d57g2000hsg.googlegroups.com> <mailman.5237.1174189740.32031.python-list@python.org> <etifo0$vj7$1@news.yaako.com> Message-ID: <9e2f512b0703172208x475b323cy91f7f9605c69031@mail.gmail.com> On 3/18/07, bruce peng <pengning at kingsoft.net> wrote: > how to redirect the putput of the > program to a file? like this: program_name -parameters > outfile.txt From irstas at gmail.com Mon Mar 26 10:15:22 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 26 Mar 2007 07:15:22 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174916838.757839.143310@e65g2000hsc.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <mailman.5628.1174916538.32031.python-list@python.org> <1174916838.757839.143310@e65g2000hsc.googlegroups.com> Message-ID: <1174918522.211602.260290@l75g2000hse.googlegroups.com> On Mar 26, 4:47 pm, "Noma... at gmail.com" <Noma... at gmail.com> wrote: > > You can get the speed of fortran in Python by using libraries like > > Numeric without losing the readability of Python. > > Can you back this up with some source?? > Chris If you execute one command in Python which tells a super-optimized Fortran-routine to do lots of work, the overhead of Python will be neglible. That's all there is to it, no need for a source. From tgrav at mac.com Mon Mar 5 11:15:15 2007 From: tgrav at mac.com (Tommy Grav) Date: Mon, 5 Mar 2007 11:15:15 -0500 Subject: Newbie question Message-ID: <01B89435-9EFC-4CBE-8EA2-C4BFE842345D@mac.com> Hi list, this is somewhat of a newbie question that has irritated me for a while. I have a file test.txt: 0.3434 0.5322 0.3345 1.3435 2.3345 5.3433 and this script lines = open("test.txt","r").readlines() for line in lines: (xin,yin,zin) = line.split() x = float(xin) y = float(yin) z = float(zin) Is there a way to go from line.split() to x,y,z as floats without converting each variable individually? Cheers Tommy From gagsl-py2 at yahoo.com.ar Fri Mar 9 23:47:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Mar 2007 01:47:30 -0300 Subject: C++ and Python References: <1173420288.646573.327340@h3g2000cwc.googlegroups.com> <slrnev2q3q.cis.mandus@oro.simula.no> <d2fIh.4$iC.1@newsfe22.lga> <mailman.4872.1173474874.32031.python-list@python.org> <2iqIh.2485$_R.1335@newsfe23.lga> Message-ID: <op.toyh9gb6x6zn5v@gabriel2.softlabbsas.com.ar> En Fri, 09 Mar 2007 18:16:43 -0300, hg <hg at nospam.org> escribi?: > I'm not very familiar with the technology as I just have had to modify an > extension here and there. > > I guess my question is off topic as a C++ dll / shared lib is not my main > target but rather C: I need to integrate a printer driver and and would > like if possible to avoid all of the .h stuff involved with SWIG (I am > not > being sarcastic): if I can setup my prototypes directly in python, why go > through an extra layer ? > > Aren't ctypes better suited to such an application ? Sure, if you have a C (not C++) DLL, using ctypes should be OK. -- Gabriel Genellina From steve at holdenweb.com Mon Mar 19 17:01:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 17:01:37 -0400 Subject: Load three different modules which have the same name In-Reply-To: <1174329764.310542.298430@b75g2000hsg.googlegroups.com> References: <1174329389.488531.270010@p15g2000hsd.googlegroups.com> <1174329764.310542.298430@b75g2000hsg.googlegroups.com> Message-ID: <etmtq7$db2$1@sea.gmane.org> abcd wrote: > nevermind this took care of it: > > import sys > > def tryAllThree(): > a = "c:\\alpha" > b = "c:\\beta" > g = "c:\\gamma" > > sys.path.append(a) > import Person > alpha = Person.Person() > > sys.path.remove(a) > sys.path.append(b) > reload(Person) > beta = Person.Person() > > sys.path.remove(b) > sys.path.append(g) > reload(Person) > gamma = Person.Person() > > thanks > Blerch! Why not just call the modules by the right names in the first place? Then each will have its own sys.modules entry for a start ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From arkanes at gmail.com Tue Mar 6 11:56:42 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 10:56:42 -0600 Subject: Project organization and import In-Reply-To: <1173199320.094675.58350@p10g2000cwp.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> <45ec8f2c$0$29110$426a34cc@news.free.fr> <1173199320.094675.58350@p10g2000cwp.googlegroups.com> Message-ID: <4866bea60703060856x29d756f5o30708019fdc7b644@mail.gmail.com> On 6 Mar 2007 08:42:00 -0800, Martin Unsal <martinunsal at gmail.com> wrote: > On Mar 5, 2:18 pm, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: > > Martin Unsal a ?crit : > > > For example, say > > > you want to organize the widgets package as follows: > > > > > widgets/scrollbar/*.py > > > widgets/form/*.py > > > widgets/common/util.py > > > > > Other than messing around with PYTHONPATH, which is horrible, I don't > > > see how to import util.py from the widget code. > > > > Some of us still manage to do so without messing with PYTHONPATH. > > How exactly do you manage it? > > The only way I can see to do it is to have widgets/__init__.py look > something like this: > > from common import util > from scrollbar import Scrollbar > from form import Form > > Then Scrollbar.py doesn't have to worry about importing util, it just > assumes that util is already present in its namespace. > > BUT ... this means that Scrollbar.py can only be loaded in the > interpreter as part of package "widgets". You can't run an interpreter > and type "import widgets.scrollbar.Scrollbar" and start going to town, > because Scrollbar doesn't import its own dependencies. > > So what I want to clarify here: Do Python programmers try to design > packages so that each file in the package can be individually loaded > into the interpreter and will automatically import its own > dependencies? Or do you design packages so they can only be used by > importing from the top level and running the top level __init__.py? > > I hope that made sense. :) > Scrollbar *can't* assume that util will be present in its namespace, because it won't be unless it imports it. Scrollbar needs to import its own dependencies. But why do you think thats a problem? > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > From AWasilenko at gmail.com Sun Mar 18 20:08:32 2007 From: AWasilenko at gmail.com (AWasilenko at gmail.com) Date: 18 Mar 2007 17:08:32 -0700 Subject: Trying to print from inside a method In-Reply-To: <1hv6is1.icavxo1xmrwhpN%aleax@mac.com> References: <1174256116.872955.180040@l77g2000hsb.googlegroups.com> <1hv6is1.icavxo1xmrwhpN%aleax@mac.com> Message-ID: <1174262912.218027.53780@l75g2000hse.googlegroups.com> On Mar 18, 7:32 pm, a... at mac.com (Alex Martelli) wrote: > Here, the message1 and message2 names are LOCAL variables of the > respective methods: each disappear as soon as its method ends. > > If you want to make them into INSTANCE attributes, so they'll stick > around for later, assign to self.message1 and self.message2 instead (and > of course use these composite names too if need be). Ah ha, the nugget of info I was forgetting! Looking back now I can see why the author used the self.whatever, and why my code is not working. When I'm reading along all his code looks find and dandy, makes perfect sense; but soon as I try to do something on my own quickly find that my understanding of how things work is very porous :) > This would be pretty weird, but legal Python. > Weirder and weirder, but still legal Python. This is usually how most of my code turns out :( I'm afraid if I ever learn enough to make a serious program I will be burned at the stake for such un- pythonic practices :P From godzillaismad at gmail.com Fri Mar 23 20:47:11 2007 From: godzillaismad at gmail.com (Godzilla) Date: 23 Mar 2007 17:47:11 -0700 Subject: Create new processes over telnet in XP In-Reply-To: <1174658259.620897.171480@o5g2000hsb.googlegroups.com> References: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> <1174658259.620897.171480@o5g2000hsb.googlegroups.com> Message-ID: <1174697231.075546.317470@l75g2000hse.googlegroups.com> On Mar 24, 12:57 am, "Rob Wolfe" <r... at smsnet.pl> wrote: > Godzilla wrote: > > Hello, > > > How do you create/spawn new processes in XP over telnet using python? > > I.e. I would like to create a new process and have it running in the > > background... when I terminate the telnet connection, I would what the > > spawned processes to keep running until I shut it off... > > > I got the os.popen method to spawn a new process running in the > > backgroun, but not over telnet... tried os.popen[2, 3, 4] and also > > subprocesses.popen without any luck... > > I don't know what kind of OS there is on that remote host you telnet > to. > The idea boils down to appropriate using of methods > `read_until` and `write` from class `telnetlib.Telnet`. > > For more complicated stuff you can consider using pyexpect. > > Here is a small example of connecting to HP-UX. > You can adjust that to your needs. > > <code> > import telnetlib, time > > def login(tn, login, passwd, prompt): > tn.read_until("login: ") > tn.write(login + "\n") > if passwd: > tn.read_until("Password: ") > tn.write(passwd + "\n") > tn.read_until(prompt) > time.sleep(2) > print "logged in" > > def run_proc(tn, progname): > tn.write("nohup %s &\n" % progname) > tn.write("exit\n") > print "program <%s> running" % progname > > def kill_proc(tn, login, prompt, progname): > tn.write("ps -u %s\n" % login) > buf = tn.read_until(prompt) > pid = get_pid(buf, progname) > if not pid: > print "program <%s> not killed" % progname > tn.write("exit\n") > return > tn.write("kill -TERM %s\n" % pid) > tn.write("exit\n") > print "program <%s> killed" % progname > > def get_pid(buf, progname): > pid, comm = None, None > for line in buf.split("\n"): > try: > pid, _, _, comm = line.split() > except ValueError: > continue > if comm == progname: > return pid > > tn = telnetlib.Telnet(HOST, PORT) > #tn.set_debuglevel(1) > login(tn, "login", "passwd", "/home/user") > run_proc(tn, "python ~/test.py") > #kill_proc(tn, "login", "/home/user", "python") > </code> > > -- > HTH, > Rob Rob, I would be logging into another XP machine to do some software installation... the code you provided, correct me if I'm wrong, seems to work under Unix/Linux. Any idea how to do the equivalent in XP? From jjl at pobox.com Wed Mar 21 20:30:23 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 22 Mar 2007 00:30:23 GMT Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <871wjiuz5q.fsf@pobox.com> <1174508599.250404.176510@y66g2000hsf.googlegroups.com> Message-ID: <87slbyt908.fsf@pobox.com> "Paddy" <paddy3118 at googlemail.com> writes: > On Mar 21, 8:20 pm, j... at pobox.com (John J. Lee) wrote: > > "Paddy" <paddy3... at googlemail.com> writes: > > > I just had a link to Tim peters first post on doctest: > > >http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > > > removed fromhttp://en.wikipedia.org/wiki/Doctestas it doesn't fit > > > their guidelines for external links. > > > I wonder, could maybe the official website be persuaded to host a copy > > > so that it could be linked to? > > > > > Tim, would you object? > > > > It (wikipedia) is a wiki, why not edit the page and paste it in? > > > > John > > They have rules, and periodically trawl pages and clean them. I'd like > to stay within the rules. Which rule would pasting in the post break? You've explained that *linking* to a non-permanent URL would break the rules. You haven't explained why *pasting in* the text of the post would break the rules (I don't say it wouldn't break them, I'm just curious). John From sigzero at gmail.com Sun Mar 25 15:03:03 2007 From: sigzero at gmail.com (Robert Hicks) Date: 25 Mar 2007 12:03:03 -0700 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174820918.565521.44750@p15g2000hsd.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <1174820918.565521.44750@p15g2000hsd.googlegroups.com> Message-ID: <1174849383.513515.216000@n76g2000hsh.googlegroups.com> On Mar 25, 7:08 am, "has" <has.te... at virgin.net> wrote: > On 24 Mar, 18:30, "Robert Hicks" <sigz... at gmail.com> wrote: > > > I want to upgrade to 2.5 but I don't see any unistall instructions > > anywhere. > > To repeat what others have said: don't uninstall existing > Python.framework builds. Frameworks support multiple versions quite > happily, and removing them is more hassle than it's worth. Just > install the official framework build from python.org (http://www.python.org/ftp/python/2.5/python-2.5-macosx.dmg), which should > also update your shell profiles as necessary. > > HTH > > has Thanks... Robert From paddy3118 at googlemail.com Thu Mar 8 00:02:06 2007 From: paddy3118 at googlemail.com (Paddy3118) Date: 7 Mar 2007 21:02:06 -0800 Subject: VIM: Python type indented-block command equivalent to % for C? Message-ID: <1173330126.098105.275160@n33g2000cwc.googlegroups.com> Not python: but python type indented text Notice the blank line above. It could have several spaces or tabs, and still be a part of the block beginning 'Not python:': The block ends at the first non-blank line with less indent. Assuming that only space characters are allowed for indenting, is their a way to yank a Python block like y% works for C , or a way to move to the end of a block defined by indentation? I have tried help indent but could not find anything. Thanks, Paddy. From nagle at animats.com Tue Mar 20 14:29:46 2007 From: nagle at animats.com (John Nagle) Date: Tue, 20 Mar 2007 18:29:46 GMT Subject: Exceptions when closing a file In-Reply-To: <etp7jo$vol$1@rumours.uwaterloo.ca> References: <pan.2007.03.20.17.24.58.746758@REMOVE.THIS.cybersource.com.au> <etp7jo$vol$1@rumours.uwaterloo.ca> Message-ID: <uKVLh.9516$Um6.3423@newssvr12.news.prodigy.net> Ross Ridge wrote: > Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote: > >>Closing a file can (I believe) raise an exception. Is that documented >>anywhere? > > > In a catch-all statement for file objects: "When a file operation fails > for an I/O-related reason, the exception IOError is raised." The fact > that close() is a file operation that might fail is revealed by "file > objects are implemented using C's stdio package" and the fact the C's > fclose() function can fail. > > >>Is IOError the only exception it can raise? Closing a file that's being written can, of course, fail. An I/O error is possible as the file is flushed to disk. This is useful; after the close has returned, you have some confidence that the file has been fully written. If you want to force this error, write to a drive reached over a network, or a removable medium like a floppy or flash card. Open a file for writing and disconnect the network or remove the removable medium. John Nagle From dayakarbabu at gmail.com Thu Mar 8 05:43:57 2007 From: dayakarbabu at gmail.com (alex) Date: 8 Mar 2007 02:43:57 -0800 Subject: Here is a link to sign up www.agloco.com/r/BBBV2104 AGLOCO works with a toolbar type software called a Viewbar. Privacy is very strict so no spyware, popups or spam. As to how much money you can make, there is a study which says the average user should get $5 to $15 a month. (But less at the beginning.) Click here to read the report. http://simmonsreport.spaces.live.com How much can you make helping to build the network? The Simmons Report predicts $30 per referral. I have 200, but a friend of mine RZ McCall has over 8, 000. He has a great blog site http://mccallsnotes.spaces.live.com . AGLOCO is in their beta phase which is the best time to help them build out the network. So please join now and help build the network. Have questions? Their website has all the details so go there www.agloco.com/r/BBBV2104. www.agloco.com/r/BBBV2104 read this friends .... how good it is ? Message-ID: <1173350637.007613.325250@n33g2000cwc.googlegroups.com> Hi Friends, This note is mainly to offer you a chance to help build AGLOCO - it is a Member-owned Internet community. Here is why I would like you to help. First - it is free. Second - it is quick and easy to join. Third - AGLOCO's purpose is to get its members their share of the money generated on the Internet (i.e. you make money). And lastly - if you help build the AGLOCO network you can make much more. Here is a link to sign up www.agloco.com/r/BBBV2104 AGLOCO works with a toolbar type software called a Viewbar. Privacy is very strict so no spyware, popups or spam. As to how much money you can make, there is a study which says the average user should get $5 to $15 a month. (But less at the beginning.) Click here to read the report. http://simmonsreport.spaces.live.com How much can you make helping to build the network? The Simmons Report predicts $30 per referral. I have 200, but a friend of mine RZ McCall has over 8,000. He has a great blog site http://mccallsnotes.spaces.live.com . AGLOCO is in their beta phase which is the best time to help them build out the network. So please join now and help build the network. Have questions? Their website has all the details so go there www.agloco.com/r/BBBV2104. www.agloco.com/r/BBBV2104 Alexander From hancock at anansispaceworks.com Wed Mar 7 01:28:44 2007 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 07 Mar 2007 00:28:44 -0600 Subject: Project organization and import In-Reply-To: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> Message-ID: <45EE5B9C.4050500@anansispaceworks.com> Martin Unsal wrote: > I'm using Python for what is becoming a sizeable project and I'm > already running into problems organizing code and importing packages. > I feel like the Python package system, in particular the isomorphism > between filesystem and namespace, doesn't seem very well suited for > big projects. I've never worked on what you would call a "big project", but I *am* kind of a neat-freak/control-freak about file organization of code, so I have tinkered with the structure of source trees in Python quite a bit. If you want to explode a module into a lot of smaller files, you create a package. I find that this usually works best like this (this is what the filesystem looks like): package_name/ package_pre.py - contains globals for the package component_a.py - a useful-sized collection of functionality component_b.py - another component_c.py - another package_post.py - stuff that relies on the prior stuff __init__.py - or you can put the "post" stuff here Then __init__.py contains something like: from package_pre import * from component_a import * from component_b import * from component_c import * from package_post import * or you can explicitly load what you need: from package_pre import * from component_a import A, A1, A2 from component_a import A3 as A5 from component_b import B, B1 from component_c import C, C2, C5 from package_post import * if you want to keep the namespace cleaner. Also, instead of just dropping things into the module's global namespace, use an named namespace, such as a class, or use the "package_pre" in the example above. That helps to keep things separable. IOW, you can use __init__.py to set up the package's namespace anyway you want, breaking the actual code up into just about as many files as you like (I also don't like reading long source files -- I find it easier to browse directories than source files, even with outlining extensions. It's rare for me to have more than 2-3 classes per file). Of course, if you *really* want your namespace to be *completely* different from the filesystem, then there's no actual reason that all of these files have to be in the same directory. You can use Python's relative import (standard in Python 2.5+, available using __future__ in 2.4, IIRC) to make this easier. There was an obnoxious hack used in Zope which used code to extract the "package_path" and then prepend that to get absolute import locations which was necessary in earlier versions -- but I can't recommend that, just use the newer version of Python. So, you could do evil things like this in __init__.py: from .other_package.fiddly_bit import dunsel (i.e. grab a module from a neighboring package) Of course, I really can't recommend that either. Python will happily do it, but it's a great way to shoot yourself in the foot in terms of keeping your code organized! The only exception to that is that I often have a "util" or "utility" package which has a collection of little extras I find useful throughout my project. As for relying heavily on reload(), it isn't that great of a feature for debugging large projects. Any code of sufficient size to make reload() problematic, though, needs formal unit testing, anyway. The cheapest and easiest unit test method is doctests (IMHO), so you ought to give those a try -- I think you'll like the easy relationship those have to working in the interactive interpreter: just walk your objects through their paces in the interpreter, then cut-and-paste. What reload() and the interactive interpreter is good for is experimentation, not development. If you need huge amounts of code to be loaded to be able to do any useful experiments with the modules you are writing, then your code is too tightly coupled to begin with. Try to solve that by using something like "mock objects" to replace the full blown implementations of objects you need for testing. I've never formally used any of the "mock" packages, but I have done a number of tests using objects which are dumbed-down versions of objects which are really supposed to be provided from another module -- but I wanted to test the two separately (which is essentially creating my own mock objects from scratch). HTH, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From rehceb at no.spam.plz Sat Mar 31 20:36:20 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 31 Mar 2007 19:36:20 -0500 Subject: Unicode list Message-ID: <pan.2007.04.01.00.36.27@no.spam.plz> Hello, I have this little grep-like program: ++++++++++snip++++++++++ #!/usr/bin/python import sys import re pattern = sys.argv[1] inputfile = file(sys.argv[2], 'r') for line in inputfile: matches = re.findall(pattern, line) if matches: print matches ++++++++++snip++++++++++ Like this, the program prints some characters as strange escape sequences, which is due to the input file being encoded in utf-8: When I convert "re.findall..." to a string and wrap an "unicode()" around it, the matches get printed correctly. Is it possible to make "matches" unicode without saving it as a single string first? The function "unicode ()" seems only to work for strings. Or is there a general way of telling Python to abandon the ancient and evil land of iso-8859 for good and use utf-8 only? Regards, Rehceb From paul at boddie.org.uk Sat Mar 10 19:57:44 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Mar 2007 16:57:44 -0800 Subject: convert time string in UTC to time in local time In-Reply-To: <mailman.4821.1173391042.32031.python-list@python.org> References: <mailman.4821.1173391042.32031.python-list@python.org> Message-ID: <1173574664.739798.199770@h3g2000cwc.googlegroups.com> davelist at mac.com wrote: > I'm guessing there is an easy way to do this but I keep going around > in circles in the documentation. > > I have a time stamp that looks like this (corresponding to UTC time): > > start_time = '2007-03-13T15:00:00Z' > > I want to convert it to my local time. > > start_time = time.mktime( > time.strptime(start_time, '%Y-%m-%dT%H:%M:00Z') > ) Here, strptime in this case will probably produce a time whose daylight saving time (DST) status will be undecided, although I've done some tests with glibc which suggests that the native (unused by Python) strptime produces non-DST-affected times for both the given date and for a date one month later in my time zone (contrary to what one might expect). Then, mktime is called, but this may apply various time zone magic to treat the supplied time as a local time, not a GMT/ UTC time - this seems to be an artifact of the way mktime is defined and implemented in various standards. Do this to see what I'm talking about: time.mktime(time.gmtime(0)) Unless you have GMT/UTC as your time zone, the above may well not produce zero as its result. Similar tests in C behave identically. > start_time -= time.timezone So, here you've applied a time shift in order to hopefully go from GMT/ UTC to local time. Given my observations of mktime, I'm inclined to believe that you've time shifted beyond local time, but the principle seems reasonable. See below for more discussion. > This was working fine now, but if I do it for a date next week (such > as March 13th in the above example), it breaks because my local time > moves to daylight savings time this weekend. So my time is now off by > an hour. I'm guessing if I try this next week it will work okay > because time.timezone will be give a different value next week - is > that correct? The value of time.timezone should remain the same. In your time tuple/ structure (produced by strptime) there's a field called tm_isdst (it's the value in the last position) which governs when DST applies. If DST applies you need to use time.altzone instead of time.timezone to guide conversions between local time and GMT/UTC. > Is there a direct way to convert that timestamp in UTC to a local > time stamp that will always work? I think you have to test tm_isdst and then apply time.timezone (if tm_isdst is 0) or time.altzone (if tm_isdst is 1) in the way you've attempted. But as I said, you have to be careful with mktime, since tests both with Python and directly against glibc suggest that it considers the time to be local, and a subsequent call to localtime won't actually give you a different hour, minute and second than that provided in the supposedly GMT/UTC time. Paul P.S. There's more to come on this topic, since I'm trying to improve time zone support on time tuples/structures. It's an arcane business, however, and I'm still trying to make sense out of the behaviour of various library functions. From spohle at gmail.com Sat Mar 17 19:17:08 2007 From: spohle at gmail.com (spohle) Date: 17 Mar 2007 16:17:08 -0700 Subject: formatting strings to have the same width In-Reply-To: <1174172864.205137.193740@y66g2000hsf.googlegroups.com> References: <1174172864.205137.193740@y66g2000hsf.googlegroups.com> Message-ID: <1174173428.779736.298390@p15g2000hsd.googlegroups.com> sorry the code should read: foo = ["aaa", "1232"] for each in foo: print each.center(10, " ") + " | " From pydecker at gmail.com Sun Mar 18 09:09:13 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 18 Mar 2007 09:09:13 -0400 Subject: IDE for wxPython In-Reply-To: <457369853.20070317221202@ghirai.com> References: <457369853.20070317221202@ghirai.com> Message-ID: <ca55a9900703180609g6e6dd71ar1e677291f931d458@mail.gmail.com> On 3/17/07, Ghirai <ghirai at ghirai.com> wrote: > Can anyone suggest an IDE for wxPython? > Or an IDE for TkInter? Don't know about Tkinter, but for wxPython, I would suggest Dabo. You get their visual tools, along with a more robust and consistent wrapper around the wxPython API. -- # p.d. From fabiofz at gmail.com Thu Mar 1 06:16:39 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 1 Mar 2007 08:16:39 -0300 Subject: Is there a technic to avoid this bug In-Reply-To: <KzXEh.5944$3b5.3788@newsfe24.lga> References: <HrVEh.91860$5F3.44100@newsfe14.lga> <54inn6F2115doU1@mid.uni-berlin.de> <1172586643.865731.78020@m58g2000cwm.googlegroups.com> <KzXEh.5944$3b5.3788@newsfe24.lga> Message-ID: <cfb578b20703010316i39704d89qd20c7292a69dd68a@mail.gmail.com> On 2/27/07, hg <hg at nospam.org> wrote: > > Michele Simionato wrote: > > > pychecker > > Thanks all ... pydev extension does not however ... will have to install > pychecker also. > Just as a note: pydev extensions 1.2.8 supports that... (just released) Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070301/343f1e9e/attachment.html> From devrim.erdem at gmail.com Fri Mar 30 05:04:45 2007 From: devrim.erdem at gmail.com (DE) Date: 30 Mar 2007 02:04:45 -0700 Subject: Indentation for code readability Message-ID: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> Hello, Here is what I do in C++ and can not right now in python : pushMatrix() { drawStuff(); pushMatrix(); { drawSomeOtherStuff() } popMatrix(); } popMatrix(); The curly brackets have no functional meaning but increase the readability significantly. I want to be able to do the same thing in python. Since curly brackets are not available and indenting without an if or while conditional doesn't work, I have started to question if this is possible in python at all. Any ideas ? MDE From openopt at ukr.net Thu Mar 15 14:56:18 2007 From: openopt at ukr.net (dmitrey) Date: 15 Mar 2007 11:56:18 -0700 Subject: right-format of integer output as text In-Reply-To: <pan.2007.03.15.18.51.57.460777@gmx.net> References: <1173984339.188538.200880@l75g2000hse.googlegroups.com> <pan.2007.03.15.18.51.57.460777@gmx.net> Message-ID: <1173984978.433719.285100@l77g2000hsb.googlegroups.com> Thank you Marc, it is exactly the same I asked for. D. From grflanagan at yahoo.co.uk Fri Mar 9 02:49:59 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 8 Mar 2007 23:49:59 -0800 Subject: catching exceptions from an except: block In-Reply-To: <mailman.4795.1173346304.32031.python-list@python.org> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173345456.968709.128870@j27g2000cwj.googlegroups.com> <mailman.4795.1173346304.32031.python-list@python.org> Message-ID: <1173426599.403173.49240@v33g2000cwv.googlegroups.com> On Mar 8, 10:31 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Thu, 08 Mar 2007 06:17:37 -0300, Gerard Flanagan > <grflana... at yahoo.co.uk> escribi?: > > > @onfail(False) > > def a(x): > > if x == 1: > > return 'function a succeeded' > > else: > > raise > > I know it's irrelevant, as you use a bare except, but such raise looks a > bit ugly... > > -- > Gabriel Genellina Agreed. I thought a 'gentle reader' could have filled in the blanks, but I suppose I should have taken the time to put in a custom exception. Another version: import exceptions class ABCException(exceptions.Exception): pass class DoItException(exceptions.Exception): pass def onfailFalse(fn): def inner(*args, **kwargs): try: return fn(*args, **kwargs) except ABCException: return False return inner @onfailFalse def a(x): if x == 1: return 'function a succeeded' else: raise ABCException() @onfailFalse def b(x): if x == 2: return 'function b succeeded' else: raise ABCException() @onfailFalse def c(x): if x == 3: return 'function c succeeded' else: raise ABCException() def doit(x): for f in [a, b, c]: result = f(x) if result: return result raise DoItException() print doit(1) print doit(2) print doit(3) print doit(4) From shandy.b at gmail.com Tue Mar 13 14:34:34 2007 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: 13 Mar 2007 11:34:34 -0700 Subject: CD insert/eject detection In-Reply-To: <1173797681.851722.41340@64g2000cwx.googlegroups.com> References: <1173797681.851722.41340@64g2000cwx.googlegroups.com> Message-ID: <1173810874.352847.234760@c51g2000cwc.googlegroups.com> I've never used it myself, but pygame (based on SDL - so it should work for MS Windows, Linux, and Apple OSX) has a CD module with some potentially useful functions, CD.eject() and CD.get_empty(). http://www.pygame.org/docs/ref/cdrom.html#pygame.cdrom.CD -sjbrown On Mar 13, 7:54 am, "Mark Bryan Yu" <vaf... at gmail.com> wrote: > Hi, > > I'm trying to make a Audio CD ripper using python. > > is there a way (library, module, etc) to detect when a CD was inserted > or ejected? From jordan.taylor2 at gmail.com Sat Mar 3 21:20:47 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 3 Mar 2007 18:20:47 -0800 Subject: pyHook or SetWindowsHookEx In-Reply-To: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> References: <1172584873.585035.319570@m58g2000cwm.googlegroups.com> Message-ID: <1172974847.570950.218550@n33g2000cwc.googlegroups.com> On Feb 27, 9:01 am, "abcd" <codecr... at gmail.com> wrote: > I am having trouble with pyHook on python 2.4.1. Basically I have a > python app that uses pyHook to capture keyboard events and write them > straight to a file. The application is running as a service on a > windows machine. If I am at that windows machine the application > works just fine, logging my keystrokes. However, if I use Remote > Desktop to connect to the machine and open up say Notepad it doesn't > capture the keystrokes. Is this a problem with pyHook? or is it he > way Windows handles the events? > > Is there a way to setup my own hook without pyHook using just python? > i think the function I am interested in is SetWindowsHookEx. > > Thanks in advance. I'm pretty sure it's not a problem with pyHook. I'm also fairly sure that you can't log the keystrokes of someone who is logged onto your machine from another; that would be a major security flaw. The only way (I think) this would work is if you wrote your own remote desktop program that logged keystrokes, and then sent it to the remote computer when logging off. Cheers, Jordan From noone at nowhere.com Mon Mar 26 13:21:22 2007 From: noone at nowhere.com (Josh) Date: Mon, 26 Mar 2007 13:21:22 -0400 Subject: how to abort on syntax errors Message-ID: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> I have a lot of except Exception, e statements in my code, which poses some problems. One of the biggest is whenever I refactor even the triviallest thing in my code. I would like python to abort, almost as if it were a compile-time error, whenever it cannot find a function, or if I introduced a syntax error. But, instead, it merrily proceeds on its way. Is there some idiom that you use in situations like these? thanks, josh From akbarhome at gmail.com Wed Mar 7 05:25:38 2007 From: akbarhome at gmail.com (akbar) Date: 7 Mar 2007 02:25:38 -0800 Subject: finding monitor or screen resolution in Linux with standard python module Message-ID: <1173263138.611554.42140@n33g2000cwc.googlegroups.com> I googled and searched in archive. All I can find is finding resolution with Tkinter and pygame. Any idea to find monitor resolution with standard python module? I can check from output of: xprop -root _NET_DESKTOP_GEOMETRY(CARDINAL) . The problem is when you use Beryl or Xgl, it is not correct anymore because Beryl or Xgl set this value from amount of workspaces multiplied by monitor or screen resolution. From grante at visi.com Wed Mar 14 17:10:41 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 14 Mar 2007 21:10:41 -0000 Subject: string formatting: engineering notation References: <et9l3u$e57$1@ruby.cit.cornell.edu> <mailman.5113.1173906028.32031.python-list@python.org> Message-ID: <12vgp6h1h62fg51@corp.supernews.com> On 2007-03-14, Steve Holden <steve at holdenweb.com> wrote: > Darren Dale wrote: >> Does anyone know if it is possible to represent a number as a string with >> engineering notation (like scientific notation, but with 10 raised to >> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the >> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient >> for my application (matplotlib plotting library). If it is not currently >> possible, do you think the python devs would be receptive to including >> support for engineering notation in future releases? >> > How close is this: > > >>> "%.3e" % 3.14159 > '3.142e+00' Not close at all. It should be "3.14159" >>> "%.3e" % 31.4159 '3.142e+01' should be 31.4159 >>> "%.3e" % 314.159 '3.142e+02' should be 314.159 >>> "%.3e" % 31415.9 '3.142e+04' should be 31.4159e3 -- Grant Edwards grante Yow! LOU GRANT froze at my ASSETS!! visi.com From nszabolcs at gmail.com Wed Mar 14 06:32:00 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 14 Mar 2007 03:32:00 -0700 Subject: python/C++ wrapper In-Reply-To: <mailman.5070.1173866359.32031.python-list@python.org> References: <1173848155.876995.172970@d57g2000hsg.googlegroups.com> <1173865112.666847.288360@l75g2000hse.googlegroups.com> <mailman.5070.1173866359.32031.python-list@python.org> Message-ID: <1173868320.478593.64570@n76g2000hsh.googlegroups.com> > Well, pyogre has few problems with maintenance, and new bindings to > Ogre engine was > created using Boost.Python( http://www.ogre3d.org/wiki/index.php/PyOgre ) oh last time i played with pyogre they made a transition from boost to swig :) so they are back again at boost (the problem with boost was the slow recompilation time with all the gccxml parsing and a few other problems which maybe got resolved) > -- > Roman Yakovenko > C++ Python language binding > http://www.language-binding.net/ thanks for the info this py++ looks promising From yinglcs at gmail.com Sat Mar 10 16:06:34 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 10 Mar 2007 13:06:34 -0800 Subject: Need help in using mod_python Message-ID: <1173560794.835409.34400@v33g2000cwv.googlegroups.com> Hi, I am trying to setup Apache with Trac which uses mod_python. I get the following error: assert have_pysqlite > 0 And I have verify this via command line as well, that seem no problem. # python Python 2.3.4 (#1, Feb 2 2005, 11:44:49) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import trac.db.sqlite_backend >>> trac.db.sqlite_backend._ver (3, 3, 13) >>> trac.db.sqlite_backend.have_pysqlite 2 >>> trac.db.sqlite_backend.sqlite.version '2.3.3' But when i access the Trac via Apache (with mod_python), i get the following error: File "/usr/lib/python2.3/site-packages/trac/db/pool.py", line 101, in get_cnx cnx = self._connector.get_connection(**self._kwargs) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 113, in get_connection return SQLiteConnection(path, params) File "/usr/lib/python2.3/site-packages/trac/db/sqlite_backend.py", line 140, in __init__ assert have_pysqlite > 0 From bdesth.quelquechose at free.quelquepart.fr Mon Mar 5 16:43:09 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Mar 2007 22:43:09 +0100 Subject: New to Python In-Reply-To: <1173119634.739433.240520@s48g2000cws.googlegroups.com> References: <1173119634.739433.240520@s48g2000cws.googlegroups.com> Message-ID: <45ec86f2$0$472$426a74cc@news.free.fr> dnwurtz at gmail.com a ?crit : > I am trying to get a program to add up input from the user to get to > the number 100 using a loop. However, I am having some issues. Here > is what I have so far. I know I am just trying to hard, but I am > stuck. Where ? May I suggest this reading ? http://www.catb.org/~esr/faqs/smart-questions.html > Thank you for any help. > > print "We need to count to 100" > > high_number = 100 > total = 0 > > number = input("Enter your first number ") Please re-read *very carefully* the doc for input(). Then switch to raw_input() and perform appropriate validation and conversion. > sum = number + total don't use 'sum' as an identifier, unless you don't mind shadowing the builtin sum() function. > while sum < high_number: > print "Not there yet..." > number = input("Enter another number ") > > print "We are there!!!" We're not. number won't be automagically added to sum. From http Sun Mar 11 18:49:05 2007 From: http (Paul Rubin) Date: 11 Mar 2007 14:49:05 -0800 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> <1173635074.726444.88760@t69g2000cwt.googlegroups.com> <1hut4yc.o9f1kta318hnN%aleax@mac.com> <1hut7xu.5zs31l1cohfybN%aleax@mac.com> <Xns98F0AFA4DC7DAtim111one@216.196.97.136> <1173648587.967820.254030@8g2000cwh.googlegroups.com> Message-ID: <7xhcsrqtum.fsf@ruckus.brouhaha.com> "Mark Dickinson" <dickinsm at gmail.com> writes: > By the way, I don't suppose that anybody would be interested in > a rewritten cmath for Python 2.6? It wouldn't be hard for me to > rewrite what I already have in C, and add suitable documentation > and tests. I can't speak for the developers but my personal opinion is that this is worthwhile. I'm pretty Common Lisp and Scheme specify the branch cuts and I believe Java does the same. That is to help with the consistency and predicability of program behavior as well as to help various numerical algorithms. C has a different goal, which is to be a semi-portable assembly language, putting priority instead on minimizing intermediation between the programmer and the machine, instead of on predicability. Python should take the approach of the higher level languages and implement this stuff precisely, instead of just going along with whatever loose semantics the underlying C implementation happens to supply. From vafada at gmail.com Tue Mar 13 11:09:50 2007 From: vafada at gmail.com (Mark Bryan Yu) Date: 13 Mar 2007 08:09:50 -0700 Subject: CD insert/eject detection In-Reply-To: <45F6BE29.40802@websafe.com> References: <1173797681.851722.41340@64g2000cwx.googlegroups.com> <45F6BE29.40802@websafe.com> Message-ID: <1173798590.728979.84080@64g2000cwx.googlegroups.com> On Mar 13, 11:07 am, Larry Bates <lba... at websafe.com> wrote: > Mark Bryan Yu wrote: > > Hi, > > > I'm trying to make a Audio CD ripper using python. > > > is there a way (library, module, etc) to detect when a CD was inserted > > or ejected? > > That is going to be OS dependent, so please share with us > what OS you are on? > > -Larry Linux. I guess that means i need to make a C/C++ module extension to do such task. From steve at holdenweb.com Thu Mar 22 04:57:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 04:57:06 -0400 Subject: Regexp problem with `(' In-Reply-To: <20070322083756.GA22172@cactus.homeunix.org> References: <1174551982.865646.38620@y80g2000hsf.googlegroups.com> <20070322083756.GA22172@cactus.homeunix.org> Message-ID: <ettgfj$t94$2@sea.gmane.org> Zeng Nan wrote: > On Thu, Mar 22, 2007 at 01:26:22AM -0700, Johny wrote: >> I have the following text >> >> <title>Goods Item 146 (174459989) - OurWebSite >> >> from which I need to extract >> `Goods Item 146 ' >> >> Can anyone help with regexp? >> Thank you for help >> L. > > (Goods\s+Item\s+146\s+) > > [snigger] regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From "greenbergj\" at NOSPAM wit.edu Mon Mar 12 06:35:26 2007 From: "greenbergj\" at NOSPAM wit.edu (Jordan Greenberg) Date: Mon, 12 Mar 2007 06:35:26 -0400 Subject: Object instance "reporting" to a container class instance In-Reply-To: References: Message-ID: Daniel Lipovetsky wrote: > I would like for an object to "report" to a container object when a > new instance is created or deleted. I could have a container object > that is called when a new instance is created, as below. I've run into a similar problem before, in my case it was easiest to allow the container to create the new instances, sort of like: class Something(object): def __init__(self, *args): self.x=args class Container(object): def __init__(self): self.instances=[] def newinstance(self, newclass, *args): tmp=newclass(args) self.instances.append(tmp) return tmp def delinstance(self, inst): self.instances.remove(inst) cont=Container() a=cont.newinstance(Something, 5, 6) b=cont.newinstance(Something, 7, 8) c=cont.newinstance(Something, 8, 9) print len(cont.instances) cont.delinstance(b) print len(cont.instances) #note that b is still defined, unless you remove that name explicitly... print b del b print b This can be very, very, very ugly. I don't particularly actually recommend doing anything like this. Usually you should re-think your organization to make this unnecessary. I suppose, though, it can come in handy in certain situations. -Jordan G From jkn_gg at nicorp.f9.co.uk Tue Mar 13 14:02:09 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 13 Mar 2007 11:02:09 -0700 Subject: Communicating with a DLL under Linux In-Reply-To: References: Message-ID: <1173808929.670120.5800@8g2000cwh.googlegroups.com> Hi Mikael It is probably worth you finding out more about the specific Hardware that Velleman use for this kit. Depending on the chip manufacturer, there may be more or less support already available. For instance, I have recently been communicating with the FTDI USB chips under windows. There is a PyUSB module which might help you do something similar, and the FTDI website has quite a lot of information. As it turns out, I didn't use PyUSB - for reasons connected with the version number of Python and annoying things like that (aside - has anyone got PyUSB compiled for 2.5?). I developed my own pure python interface to the FTDI chips DLL, using ctypes. So yes, this can be done. I think you'd be on quite a learning curve for this, from what you say, but don't let that put you off! Unfortunately I can't share my code with you, but just knowing that it can be done is sometimes a help... FTDI make some evaluation boards for their USB chips and you might consider going that route... http://www.ftdichip.com BTW. No connection, just a customer/developer. HTH jon N From metaperl at gmail.com Tue Mar 13 08:43:32 2007 From: metaperl at gmail.com (metaperl) Date: 13 Mar 2007 05:43:32 -0700 Subject: most complete xml package for Python? Message-ID: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> Without even checking them all out, I'm thinking the Amara XML Toolkit must be the most feature-packed. The developers are readily available on IRC for support and they seem to make regular releases. As a meld3 user, I have been using ElementTree under the hood, but was dismayed to find out that you can't find elements by attribute and I am finding it difficult to remove elements. So I am out shopping for a new friend to grok XML. Input welcome. From mensanator at aol.com Tue Mar 13 13:59:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Mar 2007 10:59:03 -0700 Subject: Eureka moments in Python In-Reply-To: References: Message-ID: <1173808743.312252.195650@t69g2000cwt.googlegroups.com> On Mar 13, 2:16 am, Steven D'Aprano wrote: > I'd be interested in hearing people's stories of Eureka moments in Python, > moments where you suddenly realise that some task which seemed like it > would be hard work was easy with Python. > ## I have this problem where, given a list of non-zero ## positive integers (sv), I need to calculate threee constants ## x, y, z where ## ## x is 2 raised to the power of the sum of the elements in sv, ## ## y is 3 raised to the power of the count of the elements in sv, ## ## and ## ## z is 3**a*2**A + 3**b*2**B + ... + 3**m*2**M + 3**n*2**N ## ## where a,b,...m,n are 0,1,...len(sv)-2,len(sv)-1 and ## N is the sum of all elements of sv except the last one, ## M is the sum of all elements of sv except the last two, ## ... ## B is the sum of all elements of sv except the last len(sv)-1, ## A is the sum of all elements of sv except the last len(sv). ## ## This turned out to be one of those things that's ## easier to code than to describe. ## ## And if you saw my original Excel spreadsheet where I ## developed it, you'd say Eureka too. def calc_xyz(sv): x = 2**sum(sv) y = 3**len(sv) z = 0 for i in xrange(len(sv)): z += 3**i * 2**sum(sv[:-(i+1)]) return (x,y,z) sv = [1,2,3,4] print calc_xyz(sv) ## (1024, 81, 133) From tron.thomas at verizon.net Wed Mar 28 22:33:51 2007 From: tron.thomas at verizon.net (tron.thomas at verizon.net) Date: 28 Mar 2007 19:33:51 -0700 Subject: Can't use class variable with private nested class In-Reply-To: <1hvnmot.1tmqpcq173vcowN%aleax@mac.com> References: <1175057276.163869.12850@y66g2000hsf.googlegroups.com> <1hvnmot.1tmqpcq173vcowN%aleax@mac.com> Message-ID: <1175135631.742221.178970@p15g2000hsd.googlegroups.com> On Mar 27, 10:08 pm, a... at mac.com (Alex Martelli) wrote: > > Forget all the naming silliness and use self.__class__.printOnce > instead. > > Alex I tried self.__class__.printOnce and that worked. Thanks for your help. From pascal.costanza at gmail.com Tue Mar 6 11:51:21 2007 From: pascal.costanza at gmail.com (Pascal Costanza) Date: 6 Mar 2007 08:51:21 -0800 Subject: [CfP] Dynamic Languages Symposium 2007 Message-ID: <1173199877.954109.112670@h3g2000cwc.googlegroups.com> ************************************************************************ * * * Dynamic Languages Symposium 2007 * * at ooPSLA 2007 - http://www.oopsla.org * * * * Montreal, Quebec, Canada, October 22, 2007 * * * * http://www.swa.hpi.uni-potsdam.de/dls07/ * * * ************************************************************************ Important dates: **************** * Submission of papers: June 1, 2007 *hard deadline* * Author notification: June 30, 2007 * Final versions due: July 7, 2007 * DLS 2007: October 22, 2007 * OOPSLA 2007: October 21-25, 2007 Scope: ****** The Dynamic Languages Symposium (DLS) at OOPSLA 2007 in Montreal, Canada, is a forum for discussion of dynamic languages, their implementation and application. While mature dynamic languages including Smalltalk, Lisp, Scheme, Self, and Prolog continue to grow and inspire new converts, a new generation of dynamic scripting languages such as Python, Ruby, PHP, and JavaScript are successful in a wide range of applications. DLS provides a place for researchers and practitioners to come together and share their knowledge, experience, and ideas for future research and development. DLS 2007 invites high quality papers reporting original research, innovative contributions or experience related to dynamic languages, their implementation and application. Accepted Papers will be published in the OOPSLA conference companion and the ACM Digital Library. Areas of interest include but are not limited to: ************************************************* * Innovative language features and implementation techniques * Development and platform support, tools * Interesting applications * Domain-oriented programming * Very late binding, dynamic composition, and runtime adaptation * Reflection and meta-programming * Software evolution * Language symbiosis and multi-paradigm languages * Dynamic optimization * Hardware support * Experience reports and case studies * Educational approaches and perspectives * Object-oriented, aspect-oriented, and context-oriented programming Submissions and proceedings *************************** We invite original contributions that neither have been published previously nor are under review by other refereed events or publications. Research papers should describe work that advances the current state of the art. Experience papers should be of broad interest and should describe insights gained from substantive practical applications. The program committee will evaluate each contributed paper based on its relevance, significance, clarity, and originality. Papers are to be submitted electronically at http://www.dcl.hpi.uni-potsdam.de/dls2007/ in PDF format. Submissions must not exceed 12 pages and need to use the ACM format, templates for which can be found at http://www.acm.org/sigs/pubs/proceed/template.html. Program chairs: *************** * Pascal Costanza, Programming Technology Lab, Vrije Universiteit Brussel, Belgium * Robert Hirschfeld, Hasso-Plattner-Institut, University of Potsdam, Germany Program committee: ****************** * Gilad Bracha, Cadence Design Systems, USA * Johan Brichau, Universite Catholique de Louvain, Belgium * William Clinger, Northeastern University, USA * William Cook, University of Texas at Austin, USA * Pascal Costanza, Vrije Universiteit Brussel, Belgium * Stephane Ducasse, Universite de Savoie, France * Brian Foote, Industrial Logic, USA * Robert Hirschfeld, Hasso-Plattner-Institut Potsdam, Germany * Jeremy Hylton, Google, USA * Shriram Krishnamurthi, Brown University, USA * Michele Lanza, University of Lugano, Switzerland * Michael Leuschel, Universitaet Duesseldorf, Germany * Henry Lieberman, MIT Media Laboratory, USA * Martin von Loewis, Hasso-Plattner-Institut Potsdam, Germany * Philippe Mougin, OCTO Technology, France * Oscar Nierstrasz, University of Berne, Switzerland * Kent Pitman, PTC, USA * Ian Piumarta, Viewpoints Research Institute, USA * Nathanael Schaerli, Google, Switzerland * Anton van Straaten, AppSolutions.com, USA * Dave Thomas, Bedarra Research Labs, Canada * Dave Ungar, USA * Allen Wirfs-Brock, Microsoft, USA * Roel Wuyts, IMEC & Unversite Libre de Bruxelles, Belgium From marek.rocki at wp.pl Fri Mar 16 16:05:14 2007 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: 16 Mar 2007 13:05:14 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> Message-ID: <1174075514.144163.211660@o5g2000hsb.googlegroups.com> My attempt uses a different approach: create two sorted arrays, n^2 elements each; and then iterate over them looking for matching elements (only one pass is required). I managed to get 58,2250612857 s on my 1,7 MHz machine. It requires numpy for decent performance, though. import numpy import time def parse_input(): al, bl, cl, dl = [], [], [], [] for i in xrange(int(raw_input())): a, b, c, d = map(int, raw_input().split()) al.append(a) bl.append(b) cl.append(c) dl.append(d) return al, bl, cl, dl def count_zero_sums(al, bl, cl, dl): n = len(al) # Assume others are equal # Construct al extended (every element is repeated n times) ale = numpy.array(al).repeat(n) del al # Construct bl extended (whole array is repeated n times) ble = numpy.zeros((n*n,), int) for i in xrange(n): ble[i*n:(i+1)*n] = bl del bl # Construct abl - sorted list of all sums of a, b for a, b in al, bl abl = numpy.sort(ale + ble) del ale, ble # Construct cl extended (every element is repeated n times) cle = numpy.array(cl).repeat(n) del cl # Construct dl extended (whole array is repeated n times) dle = numpy.zeros((n*n,), int) for i in xrange(n): dle[i*n:(i+1)*n] = dl del dl # Construct cdl - sorted list of all negated sums of a, b for a, b in cl, dl cdl = numpy.sort(-(cle + dle)) del cle, dle # Iterate over arrays, count matching elements result = 0 i, j = 0, 0 n = n*n try: while True: while abl[i] < cdl[j]: i += 1 while abl[i] > cdl[j]: j += 1 if abl[i] == cdl[j]: # Found matching sequences ii = i + 1 while ii < n and abl[ii] == abl[i]: ii += 1 jj = j + 1 while jj < n and cdl[jj] == cdl[j]: jj += 1 result += (ii - i)*(jj - j) i, j = ii, jj except IndexError: pass return result t = time.clock() print count_zero_sums(*parse_input()) print time.clock() - t From MonkeeSage at gmail.com Sat Mar 3 22:40:29 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Mar 2007 19:40:29 -0800 Subject: pop method question In-Reply-To: References: <1172968335.511875.255750@p10g2000cwp.googlegroups.com> Message-ID: <1172979629.812957.156820@i80g2000cwc.googlegroups.com> Nick, In regards to stack-like objects, pop() implies mutation of the reciever and returning the item 'popped' off the stack. The same _semantic_ meaning can be used for pop() regarding dictionaries, even though the _implementation_ would be different: dict.pop(key) mutates the reciever and returns the value associated with the key. Regards, Jordan From wescpy at gmail.com Thu Mar 22 14:36:17 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 22 Mar 2007 11:36:17 -0700 Subject: [ANN] Python courses this Spring In-Reply-To: <78b3a9580703221134s14d026ebgd59d1af30fb4f5c5@mail.gmail.com> References: <78b3a9580703221134s14d026ebgd59d1af30fb4f5c5@mail.gmail.com> Message-ID: <78b3a9580703221136v15c9b4a9q892a228a32486053@mail.gmail.com> I'll be giving a variety of Python courses this Spring. Daytime courses are for visitors and locals who need Python training in the shortest amount of time possible via consecutive workdays. Python is certainly gaining momentum as our February course filled up completely! Although I had planned on scheduling the same set to be taught in November, it is likely that these May daytime sessions are the last ones of 2007. In contrast, I'm experimenting with a *weekly evening* course in Silicon Valley designed mainly for locals. It represents a viable alternative to those who cannot take time off during the week as well as being more budget-friendly, as I am partnering with a local community college (Foothill) to offer this course. Class takes place on the main campus and you must register through the college to attend. For more information, such as cost and other course details, see the corresponding websites below. Contact me privately if you have any more questions. cheers, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DAYTIME ======= - (Intensive) Introduction to Python (Mon-Wed, May 14-16) - Advanced Python Programming (Wed-Fri, May 16-18) - Advanced Python (short course; Thu-Fri, May 17-18) - Core Python (Intro+Advanced combo; Mon-Fri, May 14-18) These courses run daily 9a-5p and will take place in San Bruno right near the San Francisco International Airport at the: Staybridge Suites - San Francisco Airport 1350 Huntington Ave San Bruno, CA 94066 USA http://www.ichotelsgroup.com/h/d/sb/1/en/hd/sfobr Discounts are available for students and teachers, as well as multiple registrations from those working at the same company. For more info and registration, go to http://cyberwebconsulting.com (click on "Python Training") LOCALS: free parking and 101/280/380 access, BART across the street and CalTrain down the road (San Bruno stations) VISITORS: free hotel shuttle to/from the San Francisco airport, lots of free food and wireless, 2-bedroom suites w/private baths and a common work/living area available for traveling coworkers, and of course, The City by the Bay - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - EVENING ======= - Intermediate Python Programming (Tues, Apr 10-Jun 26) This course will cover the same topics as the advanced course above as well as critical portions of the intensive introductory course. It will be held once a week on Tuesday evenings from 6-9:40p. Foothill College 12345 El Monte Road Los Altos Hills, CA 94022 USA (right off 280, just south of Stanford) http://www.foothill.edu/schedule/schedule.php search for CIS 68L for Spring Quarter 2007 From stargaming at gmail.com Mon Mar 5 12:00:04 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 05 Mar 2007 18:00:04 +0100 Subject: worker thread catching exceptions and putting them in queue In-Reply-To: <45ec4936$0$323$e4fe514c@news.xs4all.nl> References: <45ec4936$0$323$e4fe514c@news.xs4all.nl> Message-ID: Paul Sijben schrieb: > All, > > in a worker thread setup that communicates via queues is it possible to > catch exceptions raised by the worker executed, put them in an object > and send them over the queue to another thread where the exception is > raised in that scope? > > considering that an exception is an object I feel it ought to be > possible, however I do not see how to go about it. > > does anyone have a pointer towards the solution? > > Paul You're right, even exceptions are objects in Python. For further studies, read http://docs.python.org/lib/module-exceptions.html You can catch an exception like this: try: worker.do_some_work_that_may_raise_an_exception() except Exception, e: # the first argument is the type of error you want to handle # it is Exception here, the baseclass of all computation exceptions # the second argument is the variable (name) where you want to save # the specific exception raised to # it's 'e' here, a common shortcut for exception exception_handler.handle(e) # notice that you can pass e around as you like For further information on exceptions and how to handle them, read chapter 8 of the tutorial, especially starting from 8.3: http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 P.S. I don't know if what I told still applies to Python 3.0 -- a lot of changes are upcoming related to exception raising and handling. From http Sat Mar 10 19:47:11 2007 From: http (Paul Rubin) Date: 10 Mar 2007 16:47:11 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <55fbgjF2492skU1@mid.individual.net> <1173573654.009953.266280@30g2000cwc.googlegroups.com> Message-ID: <7xbqj01u9c.fsf@ruckus.brouhaha.com> "MonkeeSage" writes: > Taking your comment and running with it...this is pretty much > cheating, and requires that M be evenly divisible by N, and only works > well with smaller N values, and selections are limited to numbers in > the 1 to (M/N)+(M/N) range...but hey; other than that it's perfect, heh. This still doesn't make terribly much sense in terms of the distribution you get. The fencepost method still seems to be simplest: t = sorted(random.sample(xrange(1,50), 4)) print [(j-i) for i,j in zip([0]+t, t+[50])] From gagsl-py2 at yahoo.com.ar Fri Mar 23 00:59:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 01:59:20 -0300 Subject: #!/usr/bin/env python > 2.4? References: <1174407745.208492.264020@l75g2000hse.googlegroups.com> <1174415242.455972.51400@d57g2000hsg.googlegroups.com> Message-ID: En Wed, 21 Mar 2007 07:07:20 -0300, Jon Ribbens escribi?: > In article , Stargaming wrote: >> from sys import version_info >> if version_info[0] < 2 or version_info[1] < 4: >> raise RuntimeError("You need at least python2.4 to run this >> script") > > That'll fail when the major version number is increased (i.e. Python > 3.0). > > You want: > > if sys.hexversion < 0x020400f0: > ... error ... (what means the final f0?) I find a lot easier to use (and read) this: if sys.version_info < (2,4): raise RuntimeError("You need at least python2.4...") (Does the f0 account for the prereleases?) -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 11 08:16:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 11 Mar 2007 13:16:52 +0100 Subject: a better solution for GUI in python References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> Message-ID: <55ia9kF24d6qgU1@mid.individual.net> ce wrote: > My question is which solution would be better for the GUI (and > easier to implement)? I knew there are something like wxidgets, (wxWidgets. It's the C++ lib, its Python bindings are wxPython) > QT (same as above, it's called pyQt. Check licensing, it's not as liberal as the others'.) > and pyGTK? actually we will need some complicated stuff in the GUI > and yet I don't know much about GUI programming. > > Any recommendation guys? Mostly matter of taste. Without any further details of your needs, no experienced people will be able to help. Why don't you go to the projects' homepages and read, and perhaps check a tutorial. Though biased, this may help: http://www.wxwidgets.org/wiki/index.php/WxWidgets_Compared_To_Other_Toolkits (it's for the C++ original only, but much applies to python bindings) Regards, Bj?rn -- BOFH excuse #137: User was distributing pornography on server; system seized by FBI. From f98dawa at dd.chalmers.se Mon Mar 5 07:36:01 2007 From: f98dawa at dd.chalmers.se (Dag) Date: Mon, 5 Mar 2007 12:36:01 +0000 (UTC) Subject: Python GUI + OpenGL References: <45e84025$0$15959$9b4e6d93@newsspool4.arcor-online.net> <54r59qF228m8bU1@mid.uni-berlin.de> Message-ID: On Fri, 02 Mar 2007 18:30:34 +0100, Diez B. Roggisch wrote: > Achim Domma wrote: > >> Hi, >> >> I'm developing a GUI app in Python/C++ to visualize numerical results. >> Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there >> are no windows binaries for Python 2.5 for quite some time now. >> >> I need a OpenGL context without restrictions and some settings dialogs. >> Is wx + PyOpenGL the way to go? Or could somebody recommend a better set >> of tools/libs? > > PyQt, but then there is the licensing question of course. I'm facing a similar problem. Would you care to explain why PyQt is better in this particular case. I've used both PyQt and wx for 'normal' GUI programming (but I'm more familiar with wx) so I know about their difference in general. But why is PyQt better than wx for working with OpenGL? Dag From anna.me at gmail.com Fri Mar 23 05:29:11 2007 From: anna.me at gmail.com (Vixen) Date: 23 Mar 2007 02:29:11 -0700 Subject: Free backlinks & promotion of your site Message-ID: <1174642151.491584.198050@e65g2000hsc.googlegroups.com> Articles offer one of the best opportunities for any webmaster to backlink their site in keyword rich content. Unfortunately the majority of article submission sites will not accept promotional site articles. The Internet Menu Browser not only welcomes your promotional content, but is established exclusively for that purpose. All webmasters are invited to submit articles describing their website and the benefits of using it. Your article can be as long, or as short as you like. The only restriction is that you may only include one link to your site. Fill your article with appropriate keywords and promote away. You will never be asked for payment, or spammed by the administrators. Take a look at the new Internet Menu Browser and promote your site for free http://www.menu-browser.com From n00m at narod.ru Thu Mar 15 18:42:03 2007 From: n00m at narod.ru (n00m) Date: 15 Mar 2007 15:42:03 -0700 Subject: To count number of quadruplets with sum = 0 Message-ID: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> http://www.spoj.pl/problems/SUMFOUR/ 3 0 0 0 0 0 0 0 0 -1 -1 1 1 Answer for this input data is 33. My solution for the problem is ====================================================================== import time t = time.clock() q,w,e,r,sch,h = [],[],[],[],0,{} f = open("D:/m4000.txt","rt") n = int(f.readline()) for o in range(n): row = map(long, f.readline().split()) q.append(row[0]) w.append(row[1]) e.append(row[2]) r.append(row[3]) f.close() for x in q: for y in w: if h.has_key(x+y): h[x+y] += 1 else: h[x+y] = 1 for x in e: for y in r: sch += h.get(-(x+y),0) q,w,e,r,h = None,None,None,None,None print sch print time.clock() - t =============================================================== Alas it gets "time limit exceeded". On my home PC (1.6 GHz, 512 MB RAM) and for 4000 input rows it executes ~1.5 min. Any ideas to speed it up say 10 times? Or the problem only for C-like langs? From lixianmin at gmail.com Tue Mar 27 00:17:54 2007 From: lixianmin at gmail.com (=?UTF-8?B?5p2O546w5rCR?=) Date: Tue, 27 Mar 2007 12:17:54 +0800 Subject: enumerating processes Message-ID: <3abd07c80703262117k42bcdebdp9c160675fa42918f@mail.gmail.com> hi ,all any one knows how to enumerate the current running processes , or how to obtain a specific process by its name or process id. I know I can do this in many programming languages , but how in python? any one know? Thanks for any guidance. -- li xianmin lixianmin at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From soyrush at gmail.com Sat Mar 24 21:00:34 2007 From: soyrush at gmail.com (Rodrigo Lopez-Negrete) Date: 24 Mar 2007 18:00:34 -0700 Subject: "persistent" plot windows In-Reply-To: References: <1174779770.134013.256280@b75g2000hsg.googlegroups.com> Message-ID: <1174784434.617961.49790@p15g2000hsd.googlegroups.com> Hi James, Thanks for the answer, the ampersand only works if I use the show() command at the end of my script. I guess that helps although I haven't tested it with plotting subroutines. cheers, Rodrigo On Mar 24, 6:50 pm, James Stroud wrote: > Rodrigo Lopez-Negrete wrote: > > Hi all, > > > I'm trying to write a python script using plotting form pylab. > > Unfortunatelly I've encountered a problem. When I run the script via > > 'python myscript.py' the plot windows open and close very quickly, or > > when I added the show() command the shell window was locked until I > > closed the figures. > > > My question is: is there a way to open those windows in the background > > without blocking the shell and without running it interactively?? > > something like gnuplot -persist? > > > Thanks all, > > Rodrigo Lopez-Negrete > > python whatever.py & > > (Don't forget the ampersand!) > > James From fredrik at pythonware.com Mon Mar 19 10:46:55 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Mar 2007 15:46:55 +0100 Subject: class objects, method objects, function objects References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> Message-ID: "7stud" wrote: > But the last part of the passage makes no sense to me: > ------ > When the method object is called with an argument list, it is unpacked > again, a new argument list is constructed from the instance object and > the original argument list, and the function object is called with > this new argument list. > ------ > Can anyone interpret that for me? when you call obj.method(arg1, arg2), Python prepends the actual instance object (obj) to the argument list, so you end up calling (obj.method) with the arguments (obj, arg1, arg2). From dartsch at dicad.de Sun Mar 25 06:59:52 2007 From: dartsch at dicad.de (dartsch at dicad.de) Date: 25 Mar 2007 03:59:52 -0700 Subject: Strange behavior when printing a returned closure function Message-ID: <1174820392.652008.123550@y80g2000hsf.googlegroups.com> Hello, when I execute the following code (python 2.5) def f(x): def g(): return x return g print f(1) print f(2) I get an output like So according to print I get the same function object returned at both calls. That's surprising, I would expect to get two distinct function objects because their func_closure attribute has to be different. And indeed, if I do print f(1) is f(2) instead, it prints False. Even more confusing, if I do g1 = f(1) g2 = f(2) print g1 print g2 I get something like ie. two distinct function objects are printed. What's happening here? Some clever optimization reusing function objects in special cases or what ...? Thomas From aleax at mac.com Tue Mar 20 11:11:26 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 20 Mar 2007 08:11:26 -0700 Subject: When is List Comprehension inappropriate? References: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> <1hv8wz8.19mj0kb1k9m2m8N%aleax@mac.com> Message-ID: <1hv9kdf.1vamq9cb1ea91N%aleax@mac.com> Aahz wrote: > In article <1hv8wz8.19mj0kb1k9m2m8N%aleax at mac.com>, > Alex Martelli wrote: > > > >list(iterimage(etc etc)) > > > >is surely a better way to express identical semantics. More generally, > >[x for x in whatever] (whether x is a single name or gets peculiarly > >unpacked and repacked like here) is a good example of inappropriate LC, > >to get back to the question in the subject: list(whatever) is the "one > >obvious way" to perform the same task. > > Except of course, when it's > > [x for x in whatever if x] > > I'm exceedingly fond of replacing filter() with listcomps. They're so > much more readable and often faster. Sure, if there are other clauses in the LC (be they for or if ones) you can't just call list(...) -- and I do entirely agree that filter can be put out to pasture. Similarly, you need the LC if you're performing some processing on the items -- for example, if you have an iterator yielding pairs, [(y,x) for x,y in whatever] you do need the unpacking and repacking to achieve this swapping of items within each pair -- what I was pointing out was re the simpler and most common case: [(x,y) for x,y in whatever] no processing needed, no if clauses, etc, and thus better expressed as list(whatever) Alex From duncan.booth at invalid.invalid Mon Mar 19 15:24:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2007 19:24:48 GMT Subject: When is List Comprehension inappropriate? References: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> Message-ID: "Ben" wrote: > What's the most "pythony" way to do this: > > even = [] > for x in range(0,width,2): > for y in range(0,height,2): > color = im.getpixel((x,y)) > even.append(((x,y), color)) > > versus list comprehension: > > even2 = [((x,y), im.getpixel((x,y))) for x in range(0,width,2) for y > in range(0,height,2)] > ... > > Feel free to tell me a different way to do this, as well. > Untested code, but I would try to avoid calling getpixel: data = list(im.getdata()) width, height = im.size even = [ data[i:i+width:2] for i in range(0, width*height, 2*width)] That creates a 2 dimensional list rather than one long list, and doesn't create the x,y tuples, but since they are implied by the position in the list I don't actually see why you would want to create them at all. You can calculate them separately if you actually need them. From irmen.NOSPAM at xs4all.nl Wed Mar 21 14:23:35 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 21 Mar 2007 19:23:35 +0100 Subject: replace illegal xml characters In-Reply-To: <1174482222.951043.27070@y80g2000hsf.googlegroups.com> References: <1174464899.057656.177410@d57g2000hsg.googlegroups.com> <1174482222.951043.27070@y80g2000hsf.googlegroups.com> Message-ID: <4601785e$0$334$e4fe514c@news.xs4all.nl> killkolor wrote: >> Does InDesign export broken XML documents? What exactly is your problem? > > yes, unfortunately it does. it uses all possible unicode characters, > though not all are alowed in valid xml (see link in the first post). Are you sure about this? Could you post a small example? If this is true, don't forget to file a bug report with Adobe too. --Irmen From hg at nospam.org Tue Mar 27 15:35:11 2007 From: hg at nospam.org (hg) Date: Tue, 27 Mar 2007 21:35:11 +0200 Subject: socket read timeout References: Message-ID: Facundo Batista wrote: > hg wrote: > >> Do you mean use select ? > > No, socket's timeout: > >>>> import socket >>>> s = socket.socket() >>>> s.settimeout(5) >>>> ... > > Regards, > > -- > . Facundo > . > Blog: http://www.taniquetil.com.ar/plog/ > PyAr: http://www.python.org/ar/ My issue with that is the effect on write: I only want a timeout on read ... but anyway ... Thanks, hg From arkanes at gmail.com Tue Mar 6 14:31:38 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 13:31:38 -0600 Subject: Project organization and import In-Reply-To: <1173207494.053325.100540@p10g2000cwp.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> <1173203395.649560.249930@p10g2000cwp.googlegroups.com> <1173207494.053325.100540@p10g2000cwp.googlegroups.com> Message-ID: <4866bea60703061131q375d4ba8la57a1d08ac6f79b4@mail.gmail.com> On 6 Mar 2007 10:58:14 -0800, Martin Unsal wrote: > On Mar 6, 10:13 am, "Chris Mellon" wrote: > > You have to reload the importing module as well as the module that > > changed. That doesn't require rewriting the import infrastructure. > > As far as I can tell, the moment you use "from foo_module import bar", > you've broken reload(). Reloading higher level packages doesn't help. > The only practical solution I can see is to rewrite __import__ and > reload. > Example: a.py AExport = object() b.py from a import AExport class Object(object): pass BExport = Object() BExport.a = AExport interpreter session: >>> import b >>> b.AExport >>> b.BExport.a >>> import a >>> a.AExport >>> "changed a.py such that AExport = list()" 'changed a.py such that AExport = list()' >>> reload(b) >>> b.AExport >>> "note no change" 'note no change' >>> reload(a) >>> b.AExport >>> "note still no change" 'note still no change' >>> reload(b) >>> b.AExport [] >>> "now its changed" 'now its changed' >>> b.BExport.a [] >>> From aleax at mac.com Tue Mar 20 11:33:28 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 20 Mar 2007 08:33:28 -0700 Subject: Load three different modules which have the same name References: <1174329389.488531.270010@p15g2000hsd.googlegroups.com> <1174329764.310542.298430@b75g2000hsg.googlegroups.com> <1174387253.412138.124830@d57g2000hsg.googlegroups.com> Message-ID: <1hv9m99.wrjdaa1l5era9N%aleax@mac.com> Gabriel Genellina wrote: ... > > example i could load Person from Person (in alpha) as, "Person_Alpha" > > or something like that in sys.modules? not sure how I might do that. > > Use the "as" clause when importing; it's almost the same phrase you wrote > above: > from alpha.Person import Person as Person_Alpha > or something like that. > alpha should be a package, as someone already said. Right, but the as clause does NOT affect sys.modules -- the entry in sys.modules will still be sys.modules['alpha.Person']. I doubt this matters, but since the OP had very specifically askd about "in sys.modules" I thought it better to clarify. If you want to make fake entries in sys.modules you need to do that explicitly,importing sys and assigning to the entry: sys.modules['veryweird'] = extremely_tricky_stuph The only purpose of that is to "fool" future "import veryweird" statements (executed under any circumstances) to use said extremely tricky stuph. NOT recommended unless you know what you're doing. Alex From skip at pobox.com Mon Mar 26 08:46:14 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 26 Mar 2007 07:46:14 -0500 Subject: Calling Queue experts In-Reply-To: <1174904972.597317.27240@e65g2000hsc.googlegroups.com> References: <1174899202.355092.209590@l75g2000hse.googlegroups.com> <1174904972.597317.27240@e65g2000hsc.googlegroups.com> Message-ID: <17927.49302.950988.200965@montanaro.dyndns.org> jrpfinch> # Some other I/O problem, reraise error jrpfinch> raise err I'd just execute a bare raise (without err). That way the caller gets the stack trace of the actual IOError. Skip From paddy3118 at googlemail.com Fri Mar 30 01:59:12 2007 From: paddy3118 at googlemail.com (Paddy) Date: 29 Mar 2007 22:59:12 -0700 Subject: PyPy for dummies In-Reply-To: <460c5515$0$90269$14726298@news.sunsite.dk> References: <460c5515$0$90269$14726298@news.sunsite.dk> Message-ID: <1175234352.463435.36720@n76g2000hsh.googlegroups.com> On Mar 30, 1:10 am, Damjan wrote: > .. like me. > > Ok, this is what I understood why PyPy is important. > > Writing programing languages and implementations (compilers, interpreters, > JITs, etc) is hard. Not many people can do it from scratch and create > something comparable to what's available today. But we need people with new > aproaches, exploring new ideas (to boldly go where no hacker has gone > before). > > Also, evolving the current Python language and implementation is not easy > either. As it becomes more complex, it's hard for newcomers to comprehend > it as a whole, and as it is still harder and harder to work on details > without understanding the whole. > > What PyPy provides is, making this easier, thus allowing for: > *rapid turnaround* of language features and implementation details - this > enables easier experimentation and testing of wild ideas. Most of them will > fail of course, but some will succed and some will succed and suprise > (NOBODY expects the Spanish Inquisition!). > > So that's how I see PyPy ... at the same time an interesting - let's call > it - academic experiment, but also something very close to beeing usefull > at the level of the current CPython. > > -- > damjan It is also European funding for an open source project with sprints. I'm sure some eurocrat will be dissecting the project to see if it is aa good way to fund technical projects. - Paddy. From steve at REMOVEME.cybersource.com.au Wed Mar 7 23:07:52 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Mar 2007 15:07:52 +1100 Subject: Bug in python!? persistent value of an optional parameter in function! References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> <7xfy8gqwof.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 08 Mar 2007 03:14:53 +0000, John Nagle wrote: > Paul Rubin wrote: >> "C Barr Leigh" writes: >> >>>Help! Have I found a serious bug? >>>This seems like highly undesired behaviour to me. From the program >>>below, I get output: >> >> >> It is intentional, not a bug, see the docs. Whether it's desirable is >> a different question. > > True. It would make sense to disallow mutable values as > initial values for optional arguments. The present behavior > is silly. It's just *different*, not silly. It's also quite useful in some circumstances, e.g. cheap caching without using a global variable. def factorial(n, _cache={}): try: return _cache[n] except KeyError: # fall back to slow calculation if n <= 1: result = 1 else: result = factorial(n-1)*n _cache[n] = result return result There are other ways of implementing caches, but this is quick and easy and works well for many functions. -- Steven D'Aprano From johnjsal at NOSPAMgmail.com Thu Mar 22 11:34:31 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 22 Mar 2007 11:34:31 -0400 Subject: Been a while... Message-ID: <4602a1be$0$32400$c3e8da3@news.astraweb.com> Hi guys. It's been a while since I've used Python, so I got a little rusty, but I really want to start using it again, just out of habit and for fun. Can anyone suggest a book or a website with little projects I could work on to keep me busy? (I do have Beginning Python with the 10 projects in the back, but those might be a little too involved for me right now.) Thanks! John From gagsl-py2 at yahoo.com.ar Sat Mar 17 05:53:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Mar 2007 06:53:11 -0300 Subject: File extension References: Message-ID: En Fri, 16 Mar 2007 19:59:09 -0300, Anil Kumar escribi?: > But when I try a python script with extension .sh in windows, the file is > not getting recognized by the Python interpreter. Is this supported? Or > is > there any way we can achieve the same? C:\TEMP>type test.sh print "Hello!" C:\TEMP>python test.sh Hello! For a *script* that you run explicitely, Python doesn't care of the extension. But a *module* (used with the import statement) must be a .py/.pyc/.pyo Also, if you run the script with: python scriptname.sh, it's ok; but if you run it just using: scriptname.sh, won't work; Windows uses the file extension to determine the program to run, instead of the !# line. > The reason I am trying to change the extension is, it reduces lot of > porting > changes. No need to go to each of our file which were referencing .sh > file > before and change it to .py. I assume you're not using Cygwin - you can create a stub version of each script, so that foo.sh contains: python foo.py, and associate .sh extension with cmd.exe -- Gabriel Genellina From tiedon_jano at hotmail.com Tue Mar 6 12:31:31 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 06 Mar 2007 17:31:31 GMT Subject: askstring Window to the top under Windows In-Reply-To: <1173194286.807112.180370@c51g2000cwc.googlegroups.com> References: <1173186819.622405.121170@30g2000cwc.googlegroups.com> <1173188906.327302.291650@s48g2000cws.googlegroups.com> <1173194286.807112.180370@c51g2000cwc.googlegroups.com> Message-ID: iwl kirjoitti: > On 6 Mrz., 14:48, "Tim Golden" wrote: >> On Mar 6, 1:13 pm, "iwl" wrote: >> >> It's not clear whether you're talking about the usual >> "Why do I get a DOS window when I run my python script?" >> question -- to which the answer is, in essence, change >> your script's extension to .pyw or use the pythonw.exe >> executable -- or "Why _when I use askstring_ do I get >> an empty window?". If it's the latter, then I don't >> know, but can you provide a small example script which >> exhibits the behaviour. >> >> TJG > >>>> import tkSimpleDialog >>>> tkSimpleDialog.askstring("a","b") > > at the python Console under XP (not pythonw). > > -> instead of only showing the Inputwindow at the top, > some additional empty window is shown, both not on top. > I assumed that by "python Console" you mean the IDLE editor/interpreter. I entered your 2 lines and the behaviour is the same on Win XP. I doubt it has nothing to do with the OS, though. (A word of warning but don't tell anyone: I've never used Tkinter, I use wxPython!) Every GUI implementation has a command loop and things to initiate the correct execution environment. I think that's what you are missing here and that's causing the odd behaviour. I found an example (16.1.2.2 A Simple Hello World Program) in Python 2.4 and modified as shown: #=============================================== from Tkinter import * import tkSimpleDialog # <<<=== modification here class Application(Frame): def say_hi(self): print "hi there, everyone!" def createWidgets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.hi_there = Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() tkSimpleDialog.askstring("a","b") # <<<=== modification here root.destroy() #=============================================== If you run it, it first shows the "Hello dialog" and after clicking the QUIT button, your askstring gets run. So: nothing wrong with Python, Tkinter or tkSimpleDialog.askstring. Just carry on having fun with Python! HTH, Jussi From kyosohma at gmail.com Fri Mar 23 09:29:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Mar 2007 06:29:07 -0700 Subject: Catching an unknown error In-Reply-To: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> References: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> Message-ID: <1174656547.825228.54240@e65g2000hsc.googlegroups.com> On Mar 23, 8:16 am, "Harlin Seritt" wrote: > Using the code below: > > ---BEGIN CODE--- > > value = raw_input("Type a divisor: ") > try: > value = int(value) > print "42 / %d = %d" % (value, 42/value) > except ValueError: > print "I can't convert the value to an integer" > except ZeroDivisionError: > print "Your value should not be zero" > except: > print "Something unexpected happened" > > ---END CODE--- > > In the last 'except' block, how can I print out the particular error > name even though one is not specifically named? > > Thanks, > > Harlin Make the last 'except' block like this: Except Exception, e: print e Mike From steve at holdenweb.com Fri Mar 16 09:28:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Mar 2007 09:28:49 -0400 Subject: String formatting with fixed width In-Reply-To: References: Message-ID: Alexander Eisenhuth wrote: > Hello alltogether, > > is it possible to format stings with fixed width of let's say 7 character. T > need a floating point with 3 chars before dot, padded with ' ' and 3 chars after > dot, padded with '0'. > > Followingh is my approach > >>> f = 21.1 > >>> s = "%.03f" % f > >>> s > '21.100' > > But there are missing ' '. How can I get that? (For bigger numbers than 999 they > might be cut: 1021 -> 021) > >>> def f(x): ... return "%7.3f" % (x % 1000.0) ... >>> for x in (9.9, 99.9, 999.9, 9999.9): ... print f(x) ... 9.900 99.900 999.900 999.900 >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From jan.schilleman at xs4all.nl Sun Mar 25 18:53:55 2007 From: jan.schilleman at xs4all.nl (Jan Schilleman) Date: Mon, 26 Mar 2007 00:53:55 +0200 Subject: call to function by text variable References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: Hi, try this: func = getattr(operations, ["Replace", "ChangeCase", "Move"][n]) HTH, Jan "ianar?" schreef in bericht news:1174862186.134912.117270 at p15g2000hsd.googlegroups.com... > yeah the subject doesn't really make sense does it? > > anyway want I want to do is this: > if n == 1: > > self.operations.insert(pos, operations.Replace.Panel(self, main)) > > elif n == 2: > > self.operations.insert(pos, operations.ChangeCase.Panel(self, > main)) > > elif n == 3: > > self.operations.insert(pos, operations.Move.Panel(self, main)) > > As you can see all the different functions have the same variables, so > it would be easier if I could just make a list and use that. > > like this: > > > list = ["Replace", "ChangeCase", "Move"] > textVariable = list[n] > self.operations.insert(pos, operations.[textVariable].Panel(self, > main)) > > Is something sort of like that possible? > > > TIA > > -- > http://mail.python.org/mailman/listinfo/python-list > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Mar 10 20:45:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 11 Mar 2007 02:45:00 +0100 Subject: unsigned integer? References: <7xr6rwhpdb.fsf@ruckus.brouhaha.com> <7xhcssllyi.fsf@ruckus.brouhaha.com> <7xslccr6hb.fsf@ruckus.brouhaha.com> Message-ID: <55h58sF258g2nU3@mid.individual.net> Paul Rubin wrote: > The OP specified that the expected result was 3. But that's not what he'd get with his C conversion ;) Regards, Bj?rn -- BOFH excuse #348: We're on Token Ring, and it looks like the token got loose. From http Wed Mar 14 11:49:29 2007 From: http (Paul Rubin) Date: 14 Mar 2007 07:49:29 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <55fbgjF2492skU1@mid.individual.net> <1173573654.009953.266280@30g2000cwc.googlegroups.com> <7xbqj01u9c.fsf@ruckus.brouhaha.com> <01f501c7653e$1ee8cee0$03000080@hendrik> <55osfiF25uqm7U1@mid.individual.net> <45f76346.0@entanet> <1173843736.982126.211530@l77g2000hsb.googlegroups.com> <7xabygti89.fsf@ruckus.brouhaha.com> Message-ID: <7xtzwnbzau.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > If you generate all the possible sets of five numbers between 1 and 50, > there are 50**5 of them, not 2611. Yes, the idea is generate only the sets that add up to 50. > unique_partitions(60, 6) takes 0.8 seconds; unique_partitions(80, 8) > takes about 25 seconds; unique_partitions(80, 10) takes about 80 seconds, > and unique_partitions(81, 10) takes over 90 seconds. Hmm, interesting. Maybe some more optimization is possible. > (E.g. unique_partitions(80, 10) returns 533,975 unique lists. > _partitions(80, 10) gives 3,233,568 non-unique lists.) Well that's just 6x "inflation" due to duplicates, so I dunno what else can be done for exhaustive enumeration. Maybe another approach to generating the k'th partition is possible. I'll try to think about this. From DierkErdmann at mail.com Fri Mar 2 11:49:43 2007 From: DierkErdmann at mail.com (DierkErdmann at mail.com) Date: 2 Mar 2007 08:49:43 -0800 Subject: Sorting strings containing special characters (german 'Umlaute') In-Reply-To: References: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> Message-ID: <1172854183.478333.220760@j27g2000cwj.googlegroups.com> On 2 Mrz., 15:25, Peter Otten <__pete... at web.de> wrote: > DierkErdm... at mail.com wrote: > > For sorting the letter "?" is supposed to be treated like "Ae", There are several way of defining the sorting order. The variant "? equals ae" follows DINDIN 5007 (according to wikipedia); defining (a equals ?) complies with DIN 5007-1. Therefore both options are possible. > The default locale is not used by default; you have to set it explicitly > > >>> import locale > >>> locale.strcoll("?rger", "Beere") > 1 > >>> locale.setlocale(locale.LC_ALL, "") > 'de_DE.UTF-8' > >>> locale.strcoll("?rger", "Beere") > > -1 On my machine >>> locale.setlocale(locale.LC_ALL, "") gives 'German_Germany.1252' But this does not affect the sorting order as it does on your computer. >>> locale.strcoll("?rger", "Beere") yields 1 in both cases. Thank you for your hint using unicode from the beginning on, see the difference: >>> s1 = unicode("?rger", "latin-1") >>> s2 = unicode("Beere", "latin-1") >>> locale.strcoll(s1, s2) 1 >>> locale.setlocale(locale.LC_ALL, "") -1 compared to >>> s1 = "?rger" >>> s2 = "Beere" >>> locale.strcoll(s1, s2) 1 >>> locale.setlocale(locale.LC_ALL, "") 'German_Germany.1252' >>> locale.strcoll(s1, s2) 1 Thanks for your help. Dierk > > ['Ara', '\xc3\x84rger', 'Ast'] > > Peter > > (*) German for "trouble" From flgoms at hotmail.com Mon Mar 12 11:30:59 2007 From: flgoms at hotmail.com (Fabio Gomes) Date: Mon, 12 Mar 2007 18:30:59 +0300 Subject: backslashes in lists Message-ID: Nice, Lucas. But help me again, please. What about "echoing" the list:>>> str(alist).replace('\\\\','\\')"['a', 'b', 'c:\\some\\path']" Because in my script I'm echoing the list to mount lists into lists, like:>>> list1 = ['name', 'test']>>> list2 = ['path', 'c:\some\path']>>> list = [list1, list2]>>> print list[['name', 'test'], ['path', 'c:\\some\\path']] That's how it is coded in my script. What do you think. Is it possible to print "list" without the doubled backslash? Thank again, Lucas. Date: Mon, 12 Mar 2007 12:15:10 -0300From: lucastorri at gmail.comTo: flgoms at hotmail.comSubject: Re: backslashes in listsCC: python-list at python.orgI don't know how ugly this look like, but { print str(alist).replace('\\\\', '\\') } works...On 3/12/07, Fabio Gomes wrote: Yes, Luca. I noticed that printing the list item will show the string as expected. But I need to print the entire list in the script I'm writing and doing that, the list will will be repr()'ed. Is there any way to print the entire list without being parsed by repr()? Date: Mon, 12 Mar 2007 12:00:19 -0300From: lucastorri at gmail.comTo: flgoms at hotmail.comSubject: Re: backslashes in listsCC: python-list at python.orgThe backslash is a key to enter especial characters, like breakline: '\n'There is two backslashes cause of this especial condition of this char, but if you try print the specific string you will see that only one backslash remain: print alist[2]On 3/12/07, Fabio Gomes wrote: Hi list, I'm trying to use a string with backslashes in a list. But Python parses strings in lists with repr().>>> alist = ['a', 'b', 'c:\some\path']>>> alist ['a', 'b', 'c:\\some\\path']>>> print alist['a', 'b', 'c:\\some\\path'] I already tried str() and raw (r) but it didn't work. All I want is to keep a single backslash in the string since it is a path information. Can anyone help me, please? Thank you.O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na Web e sua rede amigos. Confira! --http://mail.python.org/mailman/listinfo/python-list Busque em qualquer p?gina da Web com alta prote??o. Obtenha o Windows Live Toolbar GRATUITO ainda hoje! Experimente agora! --http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na Web e sua rede amigos. http://spaces.live.com/signup.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 17 05:53:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Mar 2007 06:53:14 -0300 Subject: lock problem References: <1174026699.143415.69940@n59g2000hsh.googlegroups.com> Message-ID: En Fri, 16 Mar 2007 04:40:27 -0300, Ritesh Raj Sarraf escribi?: > Leo Kislov wrote: > >> You're changing environmental variable __kabc_ldap that is shared >> between your threads. Environment is not designed for that kind of >> usage, it was designed for settings. Either use an option to set >> output file or just redirect stdout. If the interface of ldapsearch is >> so lame that it requires environmental variable use env to set the >> variable: "env __kabc_ldap=/tmp/wrjhdsf ldapsearch ..." > > The environment variable is set with temp_file_name which gets the name > from > tempfile.mkstemp(), which is run in every thread. So I don't think the > environment variable is going to be the same. But the environment is global for all threads. I don't know how ldapsearch works, but can't you pass it an additional argument, instead of setting an environment variable? From the long commandline you're building, I bet it has a suitable option. Or, instead of os.system, use subprocess.Popen, wich lets you specify the new environment of the child process. -- Gabriel Genellina From DustanGroups at gmail.com Sun Mar 18 08:17:53 2007 From: DustanGroups at gmail.com (Dustan) Date: 18 Mar 2007 05:17:53 -0700 Subject: Private data In-Reply-To: References: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> Message-ID: <1174220273.356129.222080@n76g2000hsh.googlegroups.com> On Mar 18, 5:26 am, "Gabriel Genellina" wrote: > En Sat, 17 Mar 2007 13:31:01 -0300, Dustan > escribi?: > > >http://dustangroups.googlepages.com/privateattributesinpython > > > This is something that I just threw together this morning, after a > > eureka moment. It's a way of creating private class attributes and > > static function variables (I'm not 100% sure if that's the correct > > terminology, but you get what I mean). I haven't tried to create > > private instance attributes, mainly because it would just be too > > difficult, and it would be awful syntax. I'm not considering actually > > using this, but I do have a couple questions about it. > > I feel so dumb, but I can't see how to use it, or what's for. Perhaps an > example? > > -- > Gabriel Genellina There are two examples - one demonstrating static function variables and one demonstrating private class attributes. Both perform some kind of counting. The function returns how many times it's been called. Here it is: @PrivateDataEngine(numCalls = 0) def testPrivateStaticFunctionVariables(internalData): """returns the number of times this function has been called.""" internalData.numCalls += 1 return internalData.numCalls There's a comment explaining how the decorator works on the page I linked you to. A common pythonic workaround for this is something like this: def testMutableDefaultArgs(_cache = {'internalData':0}): """returns the number of times this function has been called.""" _cache['internalData'] += 1 return _cache['internalData'] The default argument only gets evaluated once, and since it's mutable and being modified in the function, it magically becomes {'internalData':1} after 1 call and {'internalData':1348372} after 1348372 calls. The other example, explaining private class attributes, has a method getNumInstances that returns how many instances have been created. Here that is: class TestPrivateClassAttributes(object): # pca here obviously stands for Private Class Attributes. pcaManager = PrivateDataEngine(numInstances = 0) # Notice that the internal data is an implicit parameter that comes first, # even before the self parameter. @pcaManager def __init__(internalData, self): internalData.numInstances += 1 @staticmethod @pcaManager def getNumInstances(internalData): return internalData.numInstances # Don't forget to delete the pcvManager, or it will have all been in vain. del pcaManager I'm thinking this is going to look rather ugly when the text gets wrapped; that's why I linked to an external page in the first place. Notice it requires more advanced usage of the PrivateDataEngine if you want multiple functions to have access to the same data, as you normally would in a class. Note also that the double-decorated method getNumInstances requires that staticmethod be the first decorator. This is equivalent to the code "getNumInstances = staticmethod(pcaManager(getNumInstances))". I got an error when I tried it with pcaManager preceding staticmethod, so my educated guess is that staticmethods are somehow specially recognized by the class, and therefore they have to actually BE staticmethods, not dressed over by a pcaManager. Now that I think of it, for clarity, pcaManager may not have been a good name for the function returned by PrivateDataEngine; pcaDecorator would have been better, seeing as it IS a decorator. Perhaps I'll change that soon. The pythonic way would be: class TestPythonsPrivateClassAttributes(object): _numInstances = 0 def __init__(self): # class attributes can be accessed from self. self.numInstances += 1 @staticmethod def getNumInstances(internalData): return self.numInstances It should immediately stick out as being much more concise syntactically, and therefore much less bug-prone. Obviously, these examples are a lot like "Hello, World!" in their usefulness; one would very rarely want to track how many times a function has been called. Hope that helps. From paddy3118 at googlemail.com Mon Mar 12 01:35:25 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Mar 2007 22:35:25 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: <1173653364.059431.19990@v33g2000cwv.googlegroups.com> References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <7xy7m3tqq8.fsf@ruckus.brouhaha.com> <1173653364.059431.19990@v33g2000cwv.googlegroups.com> Message-ID: <1173677725.341019.270100@j27g2000cwj.googlegroups.com> On Mar 11, 10:49 pm, "Paddy" wrote: > On Mar 11, 9:28 pm, Paul Rubin wrote: > > > Dennis Lee Bieber writes: > > > > Pardon? What is "the right thing with signed zeros"... In the last > > > 30 years I've been on machines that normalize floating zero into a true > > > zero (all bits are zero: mantissa, exponent, and sign). This is the > > > first time I've even seen a variable output as a negative 0.0! > > > Most machines these days use IEEE 754 which supports negative zero. > > >http://en.wikipedia.org/wiki/Negative_zero > > Isn't negative zero mathematically the same as zero? Isn't -0 just an > artefact of the representation of floating point numbers? Shouldn't > f(0) == f(-0) for all functions f? > I read the wikipedia article about meteorologists using -0 to denote a > negative number rounded to zero for the purposes of binning, i.e. if > you want to tally days with temperature above and below zero, but it > doesn't seem right. You should arrange for any temperature to be in > only one range and record temperatures to their determined accuracy. a > temperature of zero would only be in one bin and if a temperature is > read as -0.2 and th rounding says it should be taken as zero then it > should go in the same bin as any positive reading that is rounded to > zero. > Getting back to Python, shouldn't we strive to remove any distinction? > a zero is a zero regardless of sign and a function like atan returning > one of two different vaues for an argument of zero is actually > mathematically not a bad thing to do? > > - Paddy. A big thanks to Paul and Andre, I think I have it now. The OP is investigating multivalued functions where the function converges to different values when approached from different directions. Floating point arithmetic being a best compromise solution to the rational number system, distinguishes between zero and minus zero as an important part of the compromise. The OP wants to compute a function of zero and minus zero distinctly and is hampered by Python not preserving the zero/minus zero distinction in some cases - hence it being a bug. Swell, Ta! - Paddy. Hey, I'm still learnin'. Sweet! From danb_83 at yahoo.com Sat Mar 10 14:38:37 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 10 Mar 2007 11:38:37 -0800 Subject: Formatted Input In-Reply-To: <1173554949.335778.324720@8g2000cwh.googlegroups.com> References: <1173554949.335778.324720@8g2000cwh.googlegroups.com> Message-ID: <1173555516.924984.155470@v33g2000cwv.googlegroups.com> On Mar 10, 1:29 pm, "Deep" wrote: > Hi all, > I am a newbie to python > I have an input of form > space > ie. > 4 3 > how can i assign these numbers to my variables?? n1, n2 = map(int, raw_input().split()) From martinunsal at gmail.com Tue Mar 6 02:53:37 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 5 Mar 2007 23:53:37 -0800 Subject: Project organization and import In-Reply-To: <45ec9ba3$0$2333$426a34cc@news.free.fr> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <45ec9ba3$0$2333$426a34cc@news.free.fr> Message-ID: <1173167617.207318.22400@h3g2000cwc.googlegroups.com> On Mar 5, 3:11 pm, Bruno Desthuilliers wrote: > Your own experience *with Python* ? No, my experience with Visual Basic. ;) Of course my experience with Python! Sorry, I can continue writing snarky replies to your snarky comments but that won't get us anywhere productive. Instead I think the following really gets to the crux of the issue. > May I say that the problem here comes from your insistance on putting > each class in a single module ? No, it doesn't. It really doesn't matter how many classes you have in a module; either you use "from foo import bar", or you are stuck with a file structure that is isomorphic to your design namespace. The former breaks reload; the latter breaks large projects. Martin From crowell at mit.edu Wed Mar 7 20:15:47 2007 From: crowell at mit.edu (Rob) Date: 7 Mar 2007 17:15:47 -0800 Subject: Calling a function with unknown arguments? In-Reply-To: <1173311306.370427.219650@c51g2000cwc.googlegroups.com> References: <1173308108.239943.174560@j27g2000cwj.googlegroups.com> <1173311306.370427.219650@c51g2000cwc.googlegroups.com> Message-ID: <1173316547.027316.147630@n33g2000cwc.googlegroups.com> > You can do this with a list comprehension: > bob(*[possible[k] for k in bob2.func_code.co_varnames]) > > The LC creates a list of arg values in the same order as the var names > for the function. Putting a * before the list when you call bob() > turns that list into it's arguments. Thanks Tom! This turns out to be exactly what I needed. From justin.mailinglists at gmail.com Tue Mar 27 00:42:15 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 26 Mar 2007 21:42:15 -0700 Subject: shutil.copy Problem In-Reply-To: References: Message-ID: <1174970535.061022.141230@l77g2000hsb.googlegroups.com> On Mar 27, 11:10 am, David Nicolson wrote: > Hi, > > I wasn't exactly sure where to send this, I don't know if it is a bug > in Python or not. This is rare, but it has occurred a few times and > seems to be reproducible for those who experience it. > > Examine this code: > >>> try: > >>> shutil.copy("/file.xml","/Volumes/External/file.xml") > >>> except Exception, err: > >>> print sys.exc_info()[0] > >>> print err > > This is the output: > exceptions.UnicodeDecodeError > 'ascii' codec can't decode byte 0xd6 in position 26: ordinal not in > range(128)] > > What could the possible cause of this be? Shouldn't shutil simply be > reading and writing the bytes and not character decoding them? > > Cheers, > David what if you try it without the try...except? perhaps the UnicodeDecodeError is in the print... From gregpinero at gmail.com Fri Mar 9 15:57:25 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 9 Mar 2007 12:57:25 -0800 Subject: How to Start a (thread?) and Leave In-Reply-To: <1173473154.354891.97530@t69g2000cwt.googlegroups.com> References: <1173471722.668943.126700@h3g2000cwc.googlegroups.com> <1173471925.876213.170820@j27g2000cwj.googlegroups.com> <1173472226.698504.147260@h3g2000cwc.googlegroups.com> <1173473154.354891.97530@t69g2000cwt.googlegroups.com> Message-ID: <1173473845.525128.119160@8g2000cwh.googlegroups.com> On Mar 9, 3:45 pm, "abcd" wrote: > > But a thread leaves the script running until the thread exits, right? > > So the webpage would just keep saying "loading" at the bottom I think. > > > -Greg > > give it a shot. if you spawn off a new thread your code should keep > executing while the thread does its work in the "background". That's the thing though, I don't want my code to keep executing, I want the script to exit/finish completely. I'm leaning towards os.startfile right now. I also see some os.spawn beasties in there but I don't understand those. -Greg From malaclypse2 at gmail.com Fri Mar 16 18:23:59 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 16 Mar 2007 18:23:59 -0400 Subject: SQLite3, data not found In-Reply-To: <200703161755.58549.inq1ltd@verizon.net> References: <200703161755.58549.inq1ltd@verizon.net> Message-ID: <16651e80703161523m12462f6s554593551b164444@mail.gmail.com> On 3/16/07, jim-on-linux wrote: > Below, the first select produces results but, > after closing then re-opening the database the > select produces an empty list. Anyone know the > reason ?? When you first open a connection, you implicitly begin a transaction. You need to call con.commit() before you close the connection, or your transaction will be rolled back when you close() it. If don't want to bother with transaction handling, you can turn it off when you open the connection, like this: con = sqlite3.connect('myData', isolation_level=None) See the Python Database API 2.0 PEP for more details about the behavior required of DB-API 2.0 compliant interfaces: http://www.python.org/dev/peps/pep-0249/ -- Jerry From pavlovevidence at gmail.com Mon Mar 26 11:31:20 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 26 Mar 2007 08:31:20 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174918286.213517.100190@l77g2000hsb.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174918286.213517.100190@l77g2000hsb.googlegroups.com> Message-ID: <1174923080.941888.198340@p77g2000hsh.googlegroups.com> On Mar 26, 10:11 am, "Andy Dingley" wrote: > On 26 Mar, 14:20, "Noma... at gmail.com" wrote: > > > what are the advantages of using Python for > > creating number crunching apps over Fortran?? > > If you have to ask, you've not experienced enough Fortran to know its > sheer horror. > > You can write programs in Python that do usefully complicated things, > and you can get them to work in a reasonable time. Fortran can't do > this, for anything more than the trivial. "Classic" Fortran tasks of > the past are now seen as trivial. OK, so they did it to a lot of data, > but they really didn't do anything very complex to it. You couldn't be more incorrect. I have run some very old (pre-Fortran 77) programs that are very far from trivial. > You can also write Python that other people can read and maintain. You > can't do this in Fortran, without a truly insane amount of trouble. This is a lie. I've seen some Fortran code that was hellspawned, and some that was clear as glass. The latter came about without a "truly insane amount of trouble". > As > Fortran programs have historically been authored and hacked on by > successive generations of grad students, this is the most vital > feature of all. Perhaps this is your impression because it's the only Fortran code you've ever been exposed to? > Finally we're no longer so interested in "number crunching". Number > crunching used to consist of simple operations over vast arrays of > data, although this was data with remarkably simple structure by > today's standards. These just aren't the major class of problems of > interest today. I suspect you're speaking from a narrow perspective, because "number crunching", as you define it, is still a problem of interest and heavily researched. Maybe it's not in your field. Anyways, you seem to be ignorant of the complexities of "simple operations over vast arrays", as if it you could accomplish these operations with a few lines of Python and numpy. That might be true for your homework, but good number-crunching codes often did a lot of stuff under the covers. > There's a massive difference between old-school FEA > (bashing Newton and Hooke into tinier and tinier cells) and > bioinformatics or anything involving the representation of big data > graphs. Ok, but exactly how do bioinformatics or big data graphs help you determine the stress profile in a beam? > > Python is a tad slower than Fortran > > If the Fortran program turns out to have been broken all along, then > who cares? That Fortran code is inherently broken is a pretty asinine thing to suggest. No one's under the impression that Fortran is a great, all- purpose language like Python is, but it does what it was designed to do well. When faced with a numerical problem, it's reasonable to consider using Fortran (especially knowing you can interface it with Python). Carl Banks From richardjones at optushome.com.au Fri Mar 30 22:17:37 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 31 Mar 2007 12:17:37 +1000 Subject: Cheeseshop needs mirrors References: <1175238342.963086.234370@e65g2000hsc.googlegroups.com> <1175249588.897793.24450@o5g2000hsb.googlegroups.com> <460d874b$0$5746$afc38c87@news.optusnet.com.au> <1175295540.423095.34560@r56g2000hsd.googlegroups.com> Message-ID: <460dc4c1$0$11540$afc38c87@news.optusnet.com.au> Paul Boddie wrote: > Richard Jones wrote: >> And of course I'll reiterate the same line I always do: the Cheese Shop >> was set up by a volunteer, enhanced by some other volunteers and exactly >> nothing more will get done unless more volunteers offer their time. > > Sure. I wasn't criticising the Cheese Shop Sorry, my comment wasn't directed at you. Your post was just a convenient target for my reply-to button :) > However, if people are starting to use it as some kind of auto- > download site where potentially thousands of users acquire a release > of, say, Pylons or TurboGears and then aim their tools and start > downloading many different packages, all without being aware of the > other side of the transaction, then I think the developers of those > tools (as opposed to you and the other infrastructure volunteers) need > to step up and responsibly consider the effects that those tools have. Indeed :) Richard From fredrik at pythonware.com Mon Mar 5 04:00:15 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 5 Mar 2007 10:00:15 +0100 Subject: list-like behaviour of etree.Element References: <1173080656.077853.249520@8g2000cwh.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On Mar 4, 12:48 pm, "Daniel Nogradi" wrote: >> The etree.Element (or ElementTree.Element) supports a number of >> list-like methods: append, insert, remove. Any special reason why it >> doesn't support pop and extend (and maybe count)? > > Those methods would not be hard to add. Perhaps, submit a feature > request to Fredrik Lundh on SourceForge and see what he thinks there > is merit in more closely emulating the list API. Of the methods you > listed, the case is probably strongest for extend(). extend() will be in the next release: http://effbot.org/zone/elementtree-changes-13.htm (lxml.etree already has it, btw). not sure I see the point of pop() and count(). a successful feature request would need to include some really compelling use cases. From john.pye at gmail.com Thu Mar 22 10:34:55 2007 From: john.pye at gmail.com (John Pye) Date: 22 Mar 2007 07:34:55 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> <1174529579.990955.116390@l77g2000hsb.googlegroups.com> Message-ID: <1174574095.731406.318790@l77g2000hsb.googlegroups.com> On Mar 22, 7:23 pm, Giovanni Bajo wrote: > I personally don't use MSYS so I don't know exactly. I use SCons too, and I > simply run it from the normal command prompt. > > I *believe* it's sufficient to unpack MSYS somewhere (you can either unpack it > *over* the directory where you installed my GCC package, or somewhere else, I > believe it works either way); since the GCC binaries are added to the system > PATH by the installer, you should able to run it anyway. You can try by simply > invoking "gcc -v" at the MSYS prompt and see if it's picking up the right > version of GCC. > > I would appreciate if you give some feedback about this. I would like to > incorporate your findings on the webpage. Hi Giovanni I downloaded your package and installed it in c:/mingw1. It complained that it could not detect Python, although I have Python 2.4 installed on my system (did you check HKCU as well as HKLM, perhaps?) I note that the gccmrt utility does not work from MSYS. You will need to provide a shell-script equivalent version, in order for that to be useful for MSYS users. So I opened a cmd prompt and ran the command, then restarted my MSYS session. There is also a need to be able to query the *current state* of the gccmrt option. Next I built my code. It all compiled OK, all the way through to my NSIS bundle. So that was nice. It includes gfortran, flex, bison, SWIG/ Python and Tcl/Tk linkage: a bit of a coup. BUT when I try to run my program, I get a windows error msgbox, "python.exe - Entry Point Not Found: The procedure entry point _ctype could not be located in the dynamic link library msvcr71.dll". I don't know what the cause of that missing symbol could be, unless it has something to do with the fact that I am linking with -lgfortran. As well as the python module that fails to load (above) I also have a Tcl/Tk based executable which crashes on launch. Also seems to be something with msvcr71, but I can't tell for sure. Have you got any ideas? From arkanes at gmail.com Tue Mar 6 11:06:00 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 10:06:00 -0600 Subject: wxPython import error... In-Reply-To: <1173055327.592532.256350@p10g2000cwp.googlegroups.com> References: <1173055327.592532.256350@p10g2000cwp.googlegroups.com> Message-ID: <4866bea60703060806l669df337hae103c7687a96473@mail.gmail.com> On 4 Mar 2007 16:42:07 -0800, king kikapu wrote: > Hi, > > i am just completed installing Python/Pydev/Eclipse/wxPython on an > Ubuntu system and all are running fine except program that contains > references to wx > > It gives me: > ImportError: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-unicode/wx/ > _core_.so: undefined symbol: PyUnicodeUCS4_FromEncodedObject > > I installed the wx packages the way the wx web site says, especially > for Ubuntu. > > Can anyone help with this as i have been searching the net for this > with no luck... > > Thanks for any help > > -- This looks like you somehow installed the Redhat packages instead - Redhat builds their Python with UCS4, everyone else uses UCS2. Did you download the RPMs and convet them rather than adding the wxCommunity repo to your sources.lst? From steveo at syslang.net Mon Mar 5 14:03:50 2007 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 5 Mar 2007 14:03:50 -0500 (EST) Subject: Is every number in a list in a range? Message-ID: I have a list ll of intergers. I want to see if each number in ll is within the range of 0..maxnum I can write it but I was wondering if there's a better way to do it? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From half.italian at gmail.com Thu Mar 15 14:55:08 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 15 Mar 2007 11:55:08 -0700 Subject: Circular Class Logic In-Reply-To: <1173962904.306751.86160@n76g2000hsh.googlegroups.com> References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> <1173921593.166607.240390@e65g2000hsc.googlegroups.com> <1173960067.782597.96840@e1g2000hsg.googlegroups.com> <1173962904.306751.86160@n76g2000hsh.googlegroups.com> Message-ID: <1173984908.706651.50260@y80g2000hsf.googlegroups.com> > Just initialize Folder at module level - see below. > -- Paul > > class Disk(Folder): > def __init__(self,driveLetter): > super(Disk,self).__init__(driveLetter+":/") What is going on there? Is it just explicitly calling the super's init function? How is that really different from this: class Disk(Folder): def __init__(self,driveLetter): Folder.Folder.__init__(self.path) # ??? Being that Folder is the superclass? I'd like to be able to use the shared Disk objects in any class that is a subclass of Data. Will the above method still make the Disk objects available in File.py? Also, what if the classes are in different modules. I'll try to experiment with it this afternoon. I'm using more information than just the drive letter. What if the user wants to find out the unc path to the share given the drive letter, or copy a file to the local disk that is not a system disk that has the most available space on it, or wants to mount or unmount a network drive. pause... I'm trying to justify why the Folders/Files really need the drive info beyond just the paths and I'm having a hard time. I even just tried to give an example of how it would be used, and couldn't. It seems to make sense on a gut level, but maybe it's just as usefull on it's own. There's definitely justification for having Disks be a subclass of Folder, but not necessarily for there to be an instance of it available within the classes. All that kind of work will be external to the class. I think I'll backtrace and keep it separate. Thanks for letting me think it through. ~Sean From bdesth.quelquechose at free.quelquepart.fr Mon Mar 5 17:18:14 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Mar 2007 23:18:14 +0100 Subject: Project organization and import In-Reply-To: <1173111489.163974.89990@30g2000cwc.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> Message-ID: <45ec8f2c$0$29110$426a34cc@news.free.fr> Martin Unsal a ?crit : > On Mar 5, 12:45 am, "bruno.desthuilli... at gmail.com" > wrote: > >>Remember that you can put code in >>the __init__.py of a package, and that this code can import sub- >>packages/modules namespaces, making the package internal organisation >>transparent to user code > > > Sure, but that doesn't solve the problem. > > Say you have a package "widgets" with classes ScrollBar, Form, etc. > You want the end user to "import widgets" and then invoke > "widgets.ScrollBar()". As far as I know there are only two ways to do > this, both seriously flawed: 1) Put all your code in one module > widgets.py, 2) use "from scrollbar import *" in widgets/__init__.py, > which is semi-deprecated "deprecated" ? Didn't see any mention of this so far. But it's bad form, since it makes hard to know where some symbol comes from. # widgets.__init from scrollbar import Scrollbar, SomeOtherStuff, some_function, SOME_CONST > and breaks reload(). > >>Also remember that you can "import as", ie: >> >>import some_package.some_subpackage.some_module as some_module > > > Sure but that doesn't eliminate the unfortunate interaction between > Python class organization and filesystem heirarchy. *class* organization ? It's not Java here. Nothing forces you to use classes. > For example, say > you want to organize the widgets package as follows: > > widgets/scrollbar/*.py > widgets/form/*.py > widgets/common/util.py > > Other than messing around with PYTHONPATH, which is horrible, I don't > see how to import util.py from the widget code. Some of us still manage to do so without messing with PYTHONPATH. > >>Bad form IMHO. Packages and module names should be all_lower, >>classnames CamelCased. > > > You're still stuck doing foo.Foo() everywhere in your client code, from foo import Foo But: > which is ugly It's not ugly, it's informative. At least you know where Foo comes from. > and wastes space, My. Three letters and a dot... > or using "from foo import *" which is > broken. cf above. > >>>but I >>>believe this is categorically the wrong thing to do in large projects. >> >>Oh yes ? Why ? > > > For myriad reasons, just one of them being the one I stated -- smaller > files with one functional unit each Oh. So you're proposing that each and any single function goes in a separate file ? > are more amenable to source code > management with multiple developers. This is not my experience. > We could discuss this till we're blue in the face but it's beside the > point. For any given project, architecture, and workflow, the > developers are going to have a preference for how to organize the code > structurally into files, directories, packages, etc. The language > itself should not place constraints on them. The mere fact that it is > supposedly "Pythonic" to put more functionality in one file indicates > to me that the Python package system is obstructing some of its users > who have perfectly good reasons to organize their code differently. It has never been an issue for me so far. > >>>you're going to want files to contain the smallest >>>practical functional blocks. I feel pretty confident saying that "put >>>more stuff in one file" is the wrong answer, even if it is the >>>Pythonic answer. >> >>Is this actually based on working experience ? It seems that there are >>enough not-trivial Python projects around to prove that it works just >>fine. > > > Yes. I've worked extensively on several projects in several languages > with multi-million lines of code I meant, based on working experience *with Python* ? I've still not seen a "multi-million" KLOC project in Python - unless of course you include all the stdlib and the interpreter itself, and even then I doubt we get so far. > and they invariably have coding > styles that recommend one functional unit (such as a class), or at > most a few closely related functional units per file. Which is what I see in most Python packages I've seen so far. But we may not have the same definition for "a few" and "closely related" ? > In Python, most of the large projects I've looked at use "from foo > import *" liberally. I've seen few projects using this. And I wouldn't like having to maintain such a project. > I guess my question boils down to this. Is "from foo import *" really > deprecated or not? This syntax is only supposed to be a handy shortcut for quick testing and exploration in an interactive session. Using it in production code is considered bad form. > If everyone has to use "from foo import *" I never did in 7 years. > despite > the problems it causes, how do they work around those problems (such > as reloading)? Do you often have a need for "reloading" in production code ??? Martin, I'm not saying Python is perfect, but it really feels like you're worrying about things that are not problems. From jfine at pytex.org Wed Mar 21 07:19:58 2007 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 21 Mar 2007 11:19:58 +0000 Subject: Wanted: a python24 package for Python 2.3 References: <45FFFEB6.2080403@pytex.org> <1174406681.405930.237930@e1g2000hsg.googlegroups.com> Message-ID: <460114DE.80908@pytex.org> Gerald Klix wrote: > Hi, > You can't import subproces from future, only syntactic and semantic > changes that will become standard feature in future python version can > be activated that way. > > You can copy the subprocess module from python 2.4 somewhere where it > will be found from python 2.3. At least subporcess is importable after > that: > > --- snip --- > klix at vesuv6:~/ttt> cp -av /usr/local/lib/python2.4/subprocess.py . > ?/usr/local/lib/python2.4/subprocess.py? -> ?./subprocess.py? > klix at vesuv6:~/ttt> python2.3 > Python 2.3.3 (#1, Jun 29 2004, 14:43:40) > [GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import subprocess > >>> You're quite right about the use of __future__. I decided to put subprocess in a package, so that my system can choose which one to find, whether running Python 2.3 or 2.4. (Well, in 2.3 there's no choice, but in 2.4 I don't want the "just for 2.3" module to hide the real 2.4 module.) The responses I've had indicate that my approach might be a good idea, and might be useful to others. For me, that's enough for now. -- Jonathan From gagsl-py2 at yahoo.com.ar Mon Mar 12 17:12:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 Mar 2007 18:12:23 -0300 Subject: New to Python References: <55kmslF249ihcU1@mid.uni-berlin.de> <1173704503.459048.310560@t69g2000cwt.googlegroups.com> <20070312131325.M21752@centroin.com.br> Message-ID: En Mon, 12 Mar 2007 10:25:15 -0300, Alberto Monteiro escribi?: > For example, yesterday I wanted to open a window, draw some > image, and make it move. I tried it with tkinter and with pygame, > but I didn't succeed - there was no way I could find how to > begin the image in the center of the window (!!!). > > Such basic things are usually solved with a google search, like > "python image position", but there was no inchantation I could utter > that would bring me the effect I wanted (oops. Bad example. I guess > "python image position" would give a useful answer...) That's the problem: you have to search on how to do that using "pygame", or "TkInter" (or Tk actually), or wxWidgets, or GTK, or whatever framework you choose to make the GUI. Python itself is not bound to a single framework so "how to do this in Python" has no sense, or has many answers depending on the chosen framework. > Another example, I found in pygame functions that would return > something called an "EventList". But whenever I searched for > "EventList" to see what is that, I got back to the page with > the functions that returned the EventList :-) You can always check yourself if in doubt. At the interpreter prompt, use any of these to inspect any object: repr(xxx) # a string representation of object xxx type(xxx) # the actual type of xxx dir(xxx) # list of attributes, including methods vars(xxx) # name and value for all instance attributes, if any help() help(xxx) help(modules) help('keyword') py> b py> repr(b) '' py> type(b) py> dir(b) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash_ _', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr_ _', '__setattr__', '__str__', '__weakref__', 'args', 'basename', 'name', 'open', 'open_new', 'open_new_tab'] py> vars(b) {'basename': '', 'name': ''} py> help(b) Help on WindowsDefault in module webbrowser object: class WindowsDefault(BaseBrowser) | Method resolution order: | WindowsDefault | BaseBrowser | __builtin__.object | | Methods defined here: | | open(self, url, new=0, autoraise=1) (...) > Also, basic things like how does "+" operate on object "xxx" > are impossible to google search. Usually you find that on the documentation for "xxx", either online http://docs.python.org/lib/lib.html or using help(xxx) -- Gabriel Genellina From andres at lacordilleraandina.com.ar Mon Mar 19 18:32:41 2007 From: andres at lacordilleraandina.com.ar (=?iso-8859-1?Q?Andr=E9s?= Martinelli) Date: Mon, 19 Mar 2007 19:32:41 -0300 Subject: struct.pack returns nothing [3] In-Reply-To: References: <1174331199.134156.105430@n59g2000hsh.googlegroups.com> Message-ID: <20070319223241.GA21961@mail.lacordilleraandina.com.ar> I'm using the example of the site http://docs.python.org/lib/module-struct.html : import struct pack('hhl', 1, 2, 3) I should get: >>> '\x00\x01\x00\x02\x00\x00\x00\x03' I get an empty line, a '\n': >>> >>> _ I know it should work. The code is OK. What could be wrong? Doesnt find the library module? I repeat that the unpack works ok. I use debian etch and sarge. Same situation in both of them. Thanks. Andr?s M. From sjmachin at lexicon.net Fri Mar 23 16:15:29 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Mar 2007 13:15:29 -0700 Subject: Join strings - very simple Q. In-Reply-To: <1174675011.244339@jubilee.claranet.pt> References: <1174675011.244339@jubilee.claranet.pt> Message-ID: <1174680929.492601.140270@o5g2000hsb.googlegroups.com> On Mar 24, 5:37 am, Paulo da Silva wrote: > Hi! > > I was told in this NG that string is obsolet. I should use > str methods. > > So, how do I join a list of strings delimited by a given > char, let's say ','? > > Old way: > > l=['a','b','c'] > jl=string.join(l,',') > > New way? > Self-help #1: reading the documentation: http://www.python.org/doc/2.0/lib/string-methods.html ? Change "0" to "5" to get the latest released version -- which hasn't changed the description of the join method AFAICT. Self-help #2: help() at the interactive prompt: 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. | >>> help("".join) Help on built-in function 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. | >>> OK, I'll bite: This was "new" in late 2000 when Python 2.0 was released. Where have you been in the last ~6.5 years? HTH, John From lbates at websafe.com Mon Mar 19 18:18:44 2007 From: lbates at websafe.com (Larry Bates) Date: Mon, 19 Mar 2007 17:18:44 -0500 Subject: screen size/resolution in win32 in python In-Reply-To: <1174225888.752421.56410@l75g2000hse.googlegroups.com> References: <1174225888.752421.56410@l75g2000hse.googlegroups.com> Message-ID: <45FF0C44.6050607@websafe.com> adri80386 wrote: > Hi: > > How I can get the current screen resolution settings (screen.width and > screen.heigth in pixels) in python. > > Thanks in advance > > Adrian > Please think about the fact that people sometimes now have 2 and even 3 monitors. Don't do anything with this that would stretch your application across all 2 (or 3) monitors. I think screensize isn't going to give you enough information to automatically size or position a window. -Larry From sean_mcilroy at yahoo.com Fri Mar 9 15:32:17 2007 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 9 Mar 2007 12:32:17 -0800 Subject: is this a bug? (python 2.3) Message-ID: <1173472337.094165.65510@8g2000cwh.googlegroups.com> hi all when i run this code in python 2.3 ###################### BEGIN CODE class warfare: def __init__(self): self.pairs = [[0,0]]*2 def __str__(self): return str(self.pairs) def setfirst (self,i,value): self.pairs[i][0] = value def setsecond(self,i,value): self.pairs[i][1] = value w = warfare() print w w.setfirst(0,'hello') print w ###################### END CODE i get this result ###################### BEGIN ACTUAL RESULT [[0, 0], [0, 0]] [['hello', 0], ['hello', 0]] ###################### END ACTUAL RESULT instead of the expected result ###################### BEGIN EXPECTED RESULT [[0, 0], [0, 0]] [['hello', 0], [0, 0]] ###################### END EXPECTED RESULT is there a reasonable explanation for this behavior? peace stm From gregturn at mindspring.com Mon Mar 5 15:52:22 2007 From: gregturn at mindspring.com (Goldfish) Date: 5 Mar 2007 12:52:22 -0800 Subject: package_data question In-Reply-To: <1173077773.569831.249980@t69g2000cwt.googlegroups.com> References: <1173077773.569831.249980@t69g2000cwt.googlegroups.com> Message-ID: <1173127941.717284.116010@q40g2000cwq.googlegroups.com> On Mar 5, 1:56 am, "bytecolor" wrote: > I have a simple package. I'm trying to add an examples subdirectory > with distutils. I'm using Python 2.4 on Linux. My file layout and > setup.py can be found here: > > http://www.deadbeefbabe.org/paste/3870 > > I've tried using data_files as well, with the same result; examples/ > fig2.3.apt is not added to the tarball. > > -- > bytecolor I have a package along with a samples section. I have both a setup.py script along with a MANIFEST.in file to make sure everything gets in. You can see both of the files at https://springpython.python-hosting.com/browser/trunk/samples That is for the samples section. For my main package, I have something similar at https://springpython.python-hosting.com/browser/trunk/src From gagsl-py2 at yahoo.com.ar Fri Mar 9 20:41:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 22:41:42 -0300 Subject: bisect on a list of lists References: <1173471342.957772@iceman.esoterica.pt> <1173486322.393479@iceman.esoterica.pt> Message-ID: En Fri, 09 Mar 2007 21:25:24 -0300, Paulo da Silva escribi?: > Thanks Gabriel. This sounds very nice for my purpose. > I have some doubts however. How do I "transform" a list into > MyList? Is this the best way? > > class MyList(list): > def __init__(self,l=None): > if l != None: > self=copy(l) (or self.extend(l) - this does not need copy module) > > Then I can do something like xl=MyList([ ... ]) Just omit the __init__ method, if you don't have anything additional to do. The inherited method will be used instead, as always: py> class MyList(list): ... def cdr(self): ... return self[1:] ... py> a = MyList([1,2,3]) py> a [1, 2, 3] py> type(a) py> a.cdr() [2, 3] > I read the description of __new__ but I didn't fully understand it and > didn't find any examples on how it is used. > Is it usable in this context? How? Not really. Would be useful for a tuple (inmutable), because it has no __init__. But ask again when you really need it :) -- Gabriel Genellina From metaperl at gmail.com Wed Mar 14 18:04:44 2007 From: metaperl at gmail.com (metaperl) Date: 14 Mar 2007 15:04:44 -0700 Subject: most complete xml package for Python? In-Reply-To: <1173908076.351577.75000@n59g2000hsh.googlegroups.com> References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> <45F811A3.1050208@web.de> <1173887937.251026.175260@y66g2000hsf.googlegroups.com> <1173908076.351577.75000@n59g2000hsh.googlegroups.com> Message-ID: <1173909884.822838.264030@n76g2000hsh.googlegroups.com> On Mar 14, 5:34 pm, "John Machin" wrote: > > Given keywords like "Amara" and "Elementtree" and past history, it > looked to me like a troll of one kind trying to incite a troll of > another kind to pop out from under the bridge and chew on his > ankle :-) Well, I'm not a troll. And I am now even less impressed with ElementTree. It does not preserve the document but reforms it in certain cases. gets rewritten as > > gets rewritten as > > > > gets rewritten as > > > > > > gets rewritten as > > > > I note that such things are mentioned here (the first search result for "CDATA" when I tried): http://www.w3schools.com/xml/xml_cdata.asp Paul P.S. I'm off to fix CDATA support in libxml2dom, but I'm sure lxml supports CDATA. Not sure about Amara, though. ;-) From nogradi at gmail.com Fri Mar 23 18:30:00 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 23 Mar 2007 23:30:00 +0100 Subject: On text processing Message-ID: <5f56302b0703231530k275a574gb51045fe28fe348d@mail.gmail.com> Hi list, I'm in a process of rewriting a bash/awk/sed script -- that grew to big -- in python. I can rewrite it in a simple line-by-line way but that results in ugly python code and I'm sure there is a simple pythonic way. The bash script processed text files of the form: ############################### key1 value1 key2 value2 key3 value3 key4 value4 spec11 spec12 spec13 spec14 spec21 spec22 spec23 spec24 spec31 spec32 spec33 spec34 key5 value5 key6 value6 key7 value7 more11 more12 more13 more21 more22 more23 key8 value8 ################################### I guess you get the point. If a line has two entries it is a key/value pair which should end up in a dictionary. If a key/value pair is followed by consequtive lines with more then two entries, it is a matrix that should end up in a list of lists (matrix) that can be identified by the key preceeding it. The empty line after the last line of a matrix signifies that the matrix is finished and we are back to a key/value situation. Note that a matrix is always preceeded by a key/value pair so that it can really be identified by the key. Any elegant solution for this? From bdesth.quelquechose at free.quelquepart.fr Mon Mar 12 18:31:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 12 Mar 2007 23:31:07 +0100 Subject: Interface in IronPython In-Reply-To: <1173734174.730471.149680@j27g2000cwj.googlegroups.com> References: <1173734174.730471.149680@j27g2000cwj.googlegroups.com> Message-ID: <45f5cc7e$0$27190$426a74cc@news.free.fr> edfialk a ?crit : > Hi all, I'm pretty much totally new to IronPython and have come to the > point that I need an interface to interact with a co-worker's code, > but I can't seem to find any documents or discussion on syntax for > writing an interface. > > Does anyone know of a link that talks about interfaces in IronPython > or feel like explaining one too me? :) > > Any advice would be greatly appreciated. My best advice would be to repost your question here: http://lists.ironpython.com/listinfo.cgi/users-ironpython.com From skip at pobox.com Sat Mar 24 19:40:27 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 24 Mar 2007 18:40:27 -0500 Subject: bugs.python.org has been compromised (urgent) In-Reply-To: References: Message-ID: <17925.46827.975322.334362@montanaro.dyndns.org> John> Just got comment spam in: John> http:// bugs.py thon.org/file7722/order-cialis.html John> http:// bugs.py thon.org/file7722/order-cialis.html order cialis John> http:// bugs.py thon.org/file7723/order-tramadol.html order tramadol Yes, we know about it and are working on solving the problem. Thanks, Skip From trentm at activestate.com Fri Mar 9 21:11:27 2007 From: trentm at activestate.com (Trent Mick) Date: Fri, 09 Mar 2007 18:11:27 -0800 Subject: nokia s60 python code debugging with komodo In-Reply-To: References: Message-ID: <45F213CF.5070801@activestate.com> worlman385 at yahoo.com wrote: > anyway I can setup and debug nokia s60 python in komodo ( a python IDE > )? Apoloies for the crazy-late reply. We tried to get Python debugging working on Nokia phones a while back but couldn't get far because the socket implementation of the Nokia Python port wasn't up to snuff. Cheers, Trent -- Trent Mick trentm at activestate.com From h.b.furuseth at usit.uio.no Fri Mar 2 06:04:33 2007 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Fri, 02 Mar 2007 12:04:33 +0100 Subject: class attrdict Message-ID: Does this class need anything more? Is there any risk of a lookup loop? Seems to work... class attrdict(dict): """Dict where d['foo'] also can be accessed as d.foo""" def __init__(self, *args, **kwargs): self.__dict__ = self dict.__init__(self, *args, **kwargs) def __repr__(self): return dict.__repr__(self).join(("attrdict(", ")")) >>> a = attrdict([(1,2)], a=3, b=4) >>> a attrdict({'a': 3, 1: 2, 'b': 4}) >>> a = attrdict([(1,2)], b=3, c=4) >>> a attrdict({1: 2, 'c': 4, 'b': 3}) >>> a.b 3 >>> a.d = 5 >>> a['d'] 5 >>> a.e Traceback (most recent call last): File "", line 1, in ? AttributeError: 'attrdict' object has no attribute 'e' >>> a.__getattr__ = 'xyzzy' >>> a.__getattribute__ = 'xyzzy' >>> a.__setattr__ = 'xyzzy' >>> a.__delattr__ = 'xyzzy' >>> a.c 4 >>> a[1] 2 >>> del a.c >>> -- Hallvard From david.bear at asu.edu Mon Mar 5 18:13:15 2007 From: david.bear at asu.edu (David Bear) Date: Mon, 05 Mar 2007 16:13:15 -0700 Subject: persistent fifo queue class Message-ID: <3240528.rhEsMVbDK6@teancum> I'm looking to see if there are any examples or prewritting fifo queue classes. I know this is a broad topic. I'm looking to implement a simple application where a web server enqueue and pickle using a local socket on to a 'queue server' -- and then I will have another application dequeue the pickles again using a local socket. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From mensanator at aol.com Sat Mar 10 21:08:19 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Mar 2007 18:08:19 -0800 Subject: How to test if a key in a dictionary exists? In-Reply-To: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> References: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> Message-ID: <1173578899.046177.104890@j27g2000cwj.googlegroups.com> On Mar 10, 3:17?pm, "Frank" wrote: > Hi, > > does anyone know how one can test if, e.g., a dictionary 'name' has a > key called 'name_key'? > > This would be possible: > > keys_of_names = names.keys() > L = len(keys_of_names) > > for i in range(L): > if keys_of_names[i] == name_key: > print 'found' > > But certainly not efficient. I would expect there is something like: > > name.is_key(name_key) > > I appreciate your help! I often build histograms using dictionaries. if hist.has_key(outcome): hist[outcome] += 1 # if key already exists, increment else: hist[outcome] = 1 # else create a new key > > Frank From savalon at ukr.net Mon Mar 19 16:58:49 2007 From: savalon at ukr.net (Orin) Date: 19 Mar 2007 13:58:49 -0700 Subject: coverage.py problem Message-ID: <1174337929.621691.307390@p15g2000hsd.googlegroups.com> Hi, I have a problem in using coverage.py module in my project: ./cov -c Traceback (most recent call last): File "./cov", line 10, in ? coverage.the_coverage.command_line(sys.argv[1:]) File "/usr/lib/python2.4/site-packages/coverage.py", line 363, in command_line self.collect() File "/usr/lib/python2.4/site-packages/coverage.py", line 467, in collect for file in os.listdir(cache_dir): OSError: [Errno 2] No such file or directory: '' The make file, in which coverage.py are been used is: ................ pythonpath=.. # Targets .PHONY: pylint build test clean coverage pylint: test $(MAKE) -C .. pylint test: build clean_coverage $(test_results) coverage coverage: ./cov -c ./cov -r -m ../src*py build: $(MAKE) -C ../src clean_coverage: -rm .coverage* ./cov -e clean: -rm *~* $(test_results) # Tests %.pass :: %.py $(srcs) -rm $@ PYTHONPATH=$(pythonpath) DJANGO_SETTINGS_MODULE=$(settings) ./cov -x - p $< && touch $@ ................... If anybody knows what can be the reason of this error, please tell me With best regards, Orin From dudaraster at gmail.com Sun Mar 4 06:51:09 2007 From: dudaraster at gmail.com (Aviroce) Date: Sun, 04 Mar 2007 11:51:09 +0000 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST) In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: On Feb 24, 11:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. <<<<<<<<<<<"The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. ">>>>>>>>>>>>>>>> THAT IS CALLED PROTECTING CIVIL RIGHTS. IN THE UNITED STATES OF AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE NOT PROTECTED BY THE GENEVA CONVENTION. DR. EVIL, V.P. CHENEY, AND MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION. THIS MEANS ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO. WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER. From jzgoda at o2.usun.pl Mon Mar 19 16:21:29 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 19 Mar 2007 21:21:29 +0100 Subject: XML based programming language In-Reply-To: <1174332767.221788.252460@l77g2000hsb.googlegroups.com> References: <1174231372.650216.271030@y66g2000hsf.googlegroups.com> <5655asF26decfU1@mid.uni-berlin.de> <1174298711.440674.114510@o5g2000hsb.googlegroups.com> <56786fF2743atU2@mid.uni-berlin.de> <1174307748.936567.191440@e1g2000hsg.googlegroups.com> <567h7sF287idqU1@mid.uni-berlin.de> <1174332767.221788.252460@l77g2000hsb.googlegroups.com> Message-ID: stefaan napisa?(a): > No schema checker can take this specification and simply output "22". > XSLT might be able to implement it, but it is complex for anything > real-life. Elementtree can immediately give me the concrete syntax > tree, > but any semantic actions have to be implemented during a > manually programmed tree traversal. Don't you think the lex/yacc combo is complex even in anything in real-life? The "XML tree simplification implementations" (as Elementtree can be considered) has other complex tasks to do. Usually implementors look from document processing perspective and the interface is tailored to such tasks. ;) -- Jarek Zgoda http://jpa.berlios.de/ From adam at atlas.st Tue Mar 27 02:37:57 2007 From: adam at atlas.st (Adam Atlas) Date: 26 Mar 2007 23:37:57 -0700 Subject: Python C extension providing... Python's own API? In-Reply-To: <1174963301.590013.167030@r56g2000hsd.googlegroups.com> References: <1174936892.381509.178770@p15g2000hsd.googlegroups.com> <1174942538.061137.93130@r56g2000hsd.googlegroups.com> <1174957359.286188.178330@y66g2000hsf.googlegroups.com> <1174963301.590013.167030@r56g2000hsd.googlegroups.com> Message-ID: <1174977477.332544.166930@n59g2000hsh.googlegroups.com> Wow! I'll have to read through that tomorrow when I'm (hopefully) less tired. :D Anyway, I somehow already managed to get this working. I'm calling it DoublePy. Here's the alpha or proof-of-concept or whatever we're to call it. http://adamatlas.org/2007/03/doublepy-0.1.tar.gz Not bad for an 0.1 written in a couple of hours, methinks. This could have some really interesting possibilities when it's more mature. From mark at agtechnical.co.uk Sun Mar 25 18:44:17 2007 From: mark at agtechnical.co.uk (mark at agtechnical.co.uk) Date: 25 Mar 2007 15:44:17 -0700 Subject: How to find to HTML strings and 'save' them? In-Reply-To: <874po95hz5.fsf@gmail.com> References: <1174842241.781281.72500@p77g2000hsh.googlegroups.com> <874po95hz5.fsf@gmail.com> Message-ID: <1174862657.151504.136350@b75g2000hsg.googlegroups.com> Great, thanks so much for posting that. It's worked a treat and I'm getting HTML files with the list of h2 tags I was looking for. Here's the code just to share, what a relief :) : ............................... from BeautifulSoup import BeautifulSoup import re page = open("soup_test/tomatoandcream.html", 'r') soup = BeautifulSoup(page) myTagSearch = str(soup.findAll('h2')) myFile = open('Soup_Results.html', 'w') myFile.write(myTagSearch) myFile.close() del myTagSearch ............................... I do have two other small queries that I wonder if anyone can help with. Firstly, I'm getting the following character: "[" at the start, "]" at the end of the code. Along with "," in between each tag line listing. This seems like normal behaviour but I can't find the way to strip them out. There's an example of stripping comments and I understand the example, but what's the *reference* to the above '[', ']' and ',' elements? for the comma I tried: soup.find(text=",").replaceWith("") but that throws this error: AttributeError: 'NoneType' object has no attribute 'replaceWith' Again working with the 'Removing Elements' example I tried: soup = BeautifulSoup("you are a banana, banana, banana") a = str(",") comments = soup.findAll(text=",") [",".extract() for "," in comments] But if I'm doing 'import beautifulSoup' this give me a "soup = BeautifulSoup("you are a banana, banana, banana") TypeError: 'module' object is not callable" error, "import beautifulSoup from BeautifulSoup" does nothing Secondly, in the above working code that is just pulling the h2 tags - how the blazes do I 'prettify' before writing to the file? Thanks in advance! Mark. .................. On Mar 25, 6:51 pm, Jorge Godoy wrote: > m... at agtechnical.co.uk writes: > > Hi All, > > > Apologies for the newbie question but I've searched and tried all > > sorts for a few days and I'm pulling my hair out ;[ > > > I have a 'reference' HTML file and a 'test' HTML file from which I > > need to pull 10 strings, all of which are contained within

tags, > > e.g.: > >

Go Someplace

> > > Once I've found the 10 I'd like to write them to another 'results' > > html file. Perhaps a 'reference results' and a 'test results' file. > >>From where I would then like to 'diff' the results to see if they > > match. > > > Here's the rub: I cannot find a way to pull those 10 strings so I can > > save them to the results pages. > > Can anyone please suggest how this can be done? > > > I've tried allsorts but I've been learning Python for 1 week and just > > don't know enough to mod example scripts it seems. don't even get me > > started on python docs.. ayaa ;] Please feel free to teach me to suck > > eggs because it's all new to me :) > > > Thanks in advance, > > > Mark. > > Take a look at BeautifulSoup. It is easy to use and works well with some > malformed HTML that you might find ahead. > > -- > Jorge Godoy - Hide quoted text - > > - Show quoted text - From beliavsky at aol.com Mon Mar 26 19:28:57 2007 From: beliavsky at aol.com (Beliavsky) Date: 26 Mar 2007 16:28:57 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <3f8d9$4607d352$83aef404$23393@news2.tudelft.nl> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916838.757839.143310@e65g2000hsc.googlegroups.com> <3f8d9$4607d352$83aef404$23393@news2.tudelft.nl> Message-ID: <1174951737.418328.313630@y66g2000hsf.googlegroups.com> On Mar 26, 9:06 am, stef wrote: > As said by others, "Portability, scalability & RAD" as an advantage of > Python are probably far more important. All of those claimed advantages can be debated, although they may exist for some tasks. (1) Portability. Fortran has been run on hundreds if not thousands of platforms since 1957. People who value portability often want assurance that their code will be supported by compilers/interpreters produced in the future. Standard-conforming Fortran 95 code is conforming Fortran 2003 code, and the standards committee has decided not to remove features in future versions. Python 3 is still somewhat up in the air, and it will NOT be backward compatible with Python 2.x, although migration tools will be provided. (2) Scalability. If talking about parallel computing, the widely used OpenMP Application Program Interface (API) supports multi-platform shared-memory parallel programming only in C/C++ and Fortran. In general, high performance computing is done in C, C++, and Fortran. (3) RAD. Scripting programs WILL be faster to write in Python, because of duck typing, the many built-in data structures, and other features. For larger programs, a Fortran (or C++ or Java) compiler will catch some errors at compile time that are caught only at run time in Python, perhaps after considerable time has elapsed. Furthermore, the higher speed of Fortran may mean that the time between program runs is 1 minute vs. 10 minutes in the corresponding Python program. This can speed the development cycle. From jordan.taylor2 at gmail.com Thu Mar 8 12:50:57 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 8 Mar 2007 09:50:57 -0800 Subject: Reading a portion of a file In-Reply-To: <1173375977.853461.68240@v33g2000cwv.googlegroups.com> References: <1173370347.799134.119100@v33g2000cwv.googlegroups.com> <1173372768.823896.32710@n33g2000cwc.googlegroups.com> <1173375977.853461.68240@v33g2000cwv.googlegroups.com> Message-ID: <1173376256.933492.71410@c51g2000cwc.googlegroups.com> On Mar 8, 12:46 pm, "Jordan" wrote: > On Mar 8, 11:52 am, "Rune Strand" wrote: > > > > > On Mar 8, 5:12 pm, cmfvulcan... at gmail.com wrote: > > > > I am using a script with a single file containing all data in multiple > > > sections. Each section begins with "#VS:CMD:command:START" and ends > > > with "#VS:CMD:command:STOP". There is a blank line in between each > > > section. I'm looking for the best way to grab one section at a time. > > > Will I have to read the entire file to a string and parse it further > > > or is it possible to grab the section directly when doing a read? I'm > > > guessing regex is the best possible way. Any help is greatly > > > appreciated. > > > Seems like something along these line will do: > > > _file_ = "filepart.txt" > > > begin_tag = '#VS:CMD:command:START' > > end_tag = '#VS:CMD:command:STOP' > > > sections = [] > > new_section = [] > > for line in open(_file_): > > line = line.strip() > > if begin_tag in line: > > new_section = [] > > elif end_tag in line: > > sections.append(new_section) > > else: > > if line: new_section.append(line) > > > for s in sections: print s > > > If your want more control, perhaps flagging "inside_section", > > "outside_section" is an idea. > > You probably don't want to use regex for something this simple; it's > likely to make things even more complicated. Is there a space between > the begin_tag and the first word of a section (same question with the > end_tag)? Sent the post too soon. What is the endline character for the file type? What type of file is it? An example section would be nice too. Cheers. From carsten at uniqsys.com Fri Mar 9 10:42:48 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 09 Mar 2007 10:42:48 -0500 Subject: number generator In-Reply-To: <1173453432.893222.308610@j27g2000cwj.googlegroups.com> References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> Message-ID: <1173454968.3450.25.camel@dot.uniqsys.com> On Fri, 2007-03-09 at 07:17 -0800, cesco wrote: > On Mar 9, 3:51 pm, Paul Rubin wrote: > > "cesco" writes: > > > I have to generate a list of N random numbers (integer) whose sum is > > > equal to M. If, for example, I have to generate 5 random numbers whose > > > sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a > > > simple pattern or function in Python to accomplish that? > > > > Erm, yes, lots of ways, there are probably further constraints on the > > problem, such as the size of the integers, how the lists are supposed > > to be distributed, etc. Can you be more specific? Is this for an > > application? If it's a homework problem, that's fine, but it's better > > in that case for respondents to suggest hints rather than full solutions. > > Given two positive integers, N and M with N < M, I have to generate N > positive integers such that sum(N)=M. No more constraints. Paul still had a point, since the word "positive" is a vital piece of information that never appeared in your original description. -Carsten From theemails at gmail.com Tue Mar 27 12:56:14 2007 From: theemails at gmail.com (Brian Erhard) Date: 27 Mar 2007 09:56:14 -0700 Subject: Auto execute python in USB flash disk Message-ID: <1175014574.359563.26630@o5g2000hsb.googlegroups.com> I am still fairly new to python and wanted to attempt a home made password protection program. There are files that I carry on a USB flash drive that I would like to password protect. Essentially, I would like to password protect an entire directory of files. Is there a way to auto execute a python script after a user double clicks to open a folder on the USB drive? How can you capture that double click event on a specific folder? Thanks. From rdm at rcblue.com Tue Mar 13 22:29:43 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 13 Mar 2007 19:29:43 -0700 Subject: number generator Message-ID: <20070314023001.CA1821E4008@bag.python.org> At 06:20 PM 3/13/2007, Paul Rubin wrote: >Dick Moores writes: > > I understand what zip() and random.sample() are doing, and the above > > helps me get inside the fencepost method, but I don't understand WHY > > it works, or how in the world anyone could have devised it. It is > > truly magical to me! > >It's Gerald Flanagan's telegraph pole method that you quoted (I >misremembered it as "fencepost"): > > "Suppose you have a fixed telegraph pole at N and a fixed telegraph > pole at M, and you're given 5 more telegraph poles..." (Gerard Flanagan), > >Consider this diagram for the numbers from 1 to 50: > > |--------------------------------------------------| > >The vertical bar at the left represents 0 and the vertical bar >at the right represents 51. The fifty dashes represent 1,2,3...50. >You can also view the fifty dashes as a line segment of length 50. > >The fencepost method is to simply chop the line segment into smaller >pieces. You do that by choosing some random points inside the segment: > > >>> import random > >>> random.sample(xrange(1,50), 4) > [49, 37, 22, 5] > >so mark those points with plus signs (let's see if I got this right) >and label the points from left to right, calling them p0,p1,p2,p3: > > |----+----------------+--------------+-----------+-| > p0 p1 p2 p3 > >So the length of the leftmost small segment is p0-0, the length of the >second segment is p1-p0, the third is p2-p1, the fourth is p3-p2, and >the fifth is 50-p3. So those lengths are the numbers you want. > >The zip thing was just a way to avoid using messy subscripts to >compute the lengths. Another way to do it is (untested): > > t2 = [0] + t + [50] > lst = [(t2[i] - t2[i-1]) for i in xrange(1, len(t2))] Works fine! >I'm not sure which is better from a Python stylistic perspective. I'm not sure, but I think if you had written it this way at first, I would have understood it. But I'm glad to have learned the zip way! >Using zip that way is fairly natural in Haskell, which I've been >fooling around with lately. All you're doing is subtracting adjacent >elements by making two versions of the list, one of them shifted over >one place, then subtracting element by element, instead of jumping >around inside a single list, with more ways to make off-by-one errors. >It looked more symmetrical in the Python code so I did it that way. Thank you, thank you! You've made it very clear up to this point. I'll worry about the Haskell approach later, much later. ;) Dick Moores >FWIW, the actual Haskell approach would translate to something more like: > > from itertools import chain, izip > lst = [(j-i) for i,j in izip(chain([0],t), chain(t,[50]))] > >which avoids making the intermediate zipped list. From laurent.pointal at limsi.fr Thu Mar 8 08:43:54 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 08 Mar 2007 14:43:54 +0100 Subject: Generator expression parenthesis mixed with function call ones In-Reply-To: References: <45ef01c7$0$5085$ba4acef3@news.orange.fr> Message-ID: Gabriel Genellina a ?crit : > If you want to review the original discussion on how to spell a > generator expression (called "accumulator display" by that time) see > http://mail.python.org/pipermail/python-dev/2003-October/038868.html That's a long discussion... and it seem I'm not alone to dislike parens confusion. http://mail.python.org/pipermail/python-dev/2003-October/038906.html Thanks for the pointer. Laurent. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 12 11:37:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 12 Mar 2007 16:37:42 +0100 Subject: Python in a desktop environment In-Reply-To: <12vas8rhv0ji28d@corp.supernews.com> References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> <1173595945.530722.273030@30g2000cwc.googlegroups.com> <1173605193.585675.217210@30g2000cwc.googlegroups.com> <12vas8rhv0ji28d@corp.supernews.com> Message-ID: <45f573c4$0$27462$426a34cc@news.free.fr> Grant Edwards a ?crit : (snip) > > Python is _far_ more robust than C++. > I wouldn't say so - robustness is a quality of a program, not of a language !-) From deets at nospam.web.de Fri Mar 16 13:12:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 Mar 2007 18:12:43 +0100 Subject: Mastering Python References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> Message-ID: <5601gbF26bm07U1@mid.uni-berlin.de> Dennis Lee Bieber wrote: > On 16 Mar 2007 04:41:38 -0700, "Gerald" declaimed > the following in comp.lang.python: > >> Hi ,Im a BSc4 Maths/Computer Science student.Unfortunately my >> curriculum did not include Python programming yet I see many vacancies >> for Python developers.I studied programming Pascal,C++ and Delphi.So I > > > > Pardon my surprise, but what school only covers simple Pascal, > Object Pascal (in the guise of Delphi), and C++ without at least > introducing other languages. Three fairly similar languages (with the > same similar flaws -- like needing to remember to put begin/end ({}) > around multi-line blocks... Nowadays, you can get through CS graduate studies with only Java. Sad, but true. Diez From tismer at stackless.com Wed Mar 28 17:51:56 2007 From: tismer at stackless.com (Christian Tismer) Date: Wed, 28 Mar 2007 23:51:56 +0200 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: References: Message-ID: On 28.03.2007, at 23:36, Jarek Zgoda wrote: > Carl Friedrich Bolz napisa?(a): > >> Welcome to the PyPy 1.0 release - a milestone integrating the results >> of four years of research, engineering, management and sprinting >> efforts, concluding the 28 months phase of EU co-funding! > > So it took 4 yars of work and over 2 yaers of consumption of EU funds, > yeah, great. > > Could anybody explain, what this gives to Python and its users? Would > we, eventually, get GIL-free VM, that is capable to consume all > available power of multicore processors? Or, maybe, we'll get > something > special, I am unable to dream of? Or is it purely academic project to > create Python VM in Python? It will eventually give you a GIL-free VM, and it already gives you a lot more than you have dreamt of. There is one feature missing that is probably hard to add. Handling the 'posters who are not willing to read before they post' syndrome. cheers - chris From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 07:10:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 13:10:02 +0200 Subject: Other classes in a module In-Reply-To: References: <46068EEF.6070000@adm.umu.se> Message-ID: <4607aa09$0$23165$426a74cc@news.free.fr> Daniel Nogradi a ?crit : >> Can an instance of a class in a module, in any simple way find out which >> other classes that exists in said module ? > > > ##### module x ########## > class c1: > pass > > class c2: > pass > ####################### > > > Python 2.5 (r25:51908, Nov 1 2006, 11:42:37) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import types >>>> import x >>>> for i in dir(x): > ... if type(getattr(x,i)) is types.ClassType: > ... print "Hey, '%s' is a class!" % i > ... > Hey, 'c1' is a class! > Hey, 'c2' is a class! >>>> > > > It might be not exactly what you want but maybe still helps. Doesn't work with new-style classes: >>> class Foo(object): pass ... >>> import typs Traceback (most recent call last): File "", line 1, in ? ImportError: No module named typs >>> import types >>> type(Foo) is types.ClassType False >>> From sjmachin at lexicon.net Thu Mar 1 11:18:12 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 Mar 2007 08:18:12 -0800 Subject: finding out the precision of floats In-Reply-To: <1172745203.824496.208840@h3g2000cwc.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172674419.411077.4210@t69g2000cwt.googlegroups.com> <1172683149.885750.323640@j27g2000cwj.googlegroups.com> <1172698199.219016.57710@v33g2000cwv.googlegroups.com> <1172745203.824496.208840@h3g2000cwc.googlegroups.com> Message-ID: <1172765892.645783.125420@h3g2000cwc.googlegroups.com> On Mar 1, 9:33 pm, "Bart Ogryczak" wrote: > On Feb 28, 10:29 pm, "John Machin" wrote: > > > > > On Mar 1, 4:19 am, "BartOgryczak" wrote: > > > > On Feb 28, 3:53 pm, "John Machin" wrote: > > > > > On Feb 28, 10:38 pm, "BartOgryczak" wrote: > > > > > > [1] eg. consider calculating interests rate, which often is defined as > > > > > math.pow(anualRate,days/365.0). > > > > > More importantly, the formula you give is dead wrong. The correct > > > > formula for converting an annual rate of interest to the rate of > > > > interest to be used for n days (on the basis of 365 days per year) is: > > > > > (1 + annual_rate) ** (n / 365.0) - 1.0 > > > > or > > > > math.pow(1 + annual_rate, n / 365.0) - 1.0 > > > > if you prefer. > > > > YPB? Anyone with half a brain knows, that you can either express rate > > > as 0.07 and do all those ridiculous conversions above, or express it > > > as 1.07 and apply it directly. > > > A conversion involving an exponentiation is necessary. "All those"?? I > > see only two. > > > Please re-read your original post, and note that there are *TWO* plus- > > or-minus 1.0 differences between your formula and mine. For an annual > > rate of 10%, yours would calculate the rate for 6 months (expressed as > > 182.5 days) as: > > math.pow(0.10, 0.5) = 0.316... i.e. 31.6% > > You're assuming that I'd store annual rate as 0.1, while actually it'd > stored as 1.1. > Which is logical and applicable directly. Storing 1.1 and using it in calculations may save you a few microseconds a day in your real-time apps. However the annual rate of interest is 10% aka 0.1; naming 1.1 as "anualRate" (sic) is utterly ludicrous. From ckkart at hoc.net Tue Mar 27 01:26:48 2007 From: ckkart at hoc.net (Christian) Date: Tue, 27 Mar 2007 14:26:48 +0900 Subject: build python on Celeron D In-Reply-To: <1174972091.173999.9650@n59g2000hsh.googlegroups.com> References: <1174972091.173999.9650@n59g2000hsh.googlegroups.com> Message-ID: Chris Lasher wrote: > On Mar 26, 10:48 pm, Christian wrote: >> Traceback (most recent call last): >> File "setup.py", line 89, in ? >> setup_package() >> File "setup.py", line 59, in setup_package >> from numpy.distutils.core import setup >> File "/mnt/home/ck/prog/scipy/numpy-1.0.1/numpy/__init__.py", line 36, in ? >> File "numpy/core/__init__.py", line 5, in ? >> import multiarray >> ImportError: >> /media/hda6/home/ck/prog/scipy/numpy-1.0.1/numpy/core/multiarray.so: undefined >> symbol: Py_InitModule4 >> >> which is related to 32<->64 issues, right? > > > > Do you have more than one Python installation on this machine? The > link above indicates that if you build NumPy with a different build of > Python than you will run it from, you will get this same error. Yes, but I took care to not confuse them. > Granted, I'm sure there are many ways to get said error, but that was > the most obvious from a five minute search. I found that: "To prevent loading extension modules that assume a 32-bit size type into an interpreter that has a 64-bit size type, Py_InitModule4 is renamed to Py_InitModule4_64." (http://www.python.org/dev/peps/pep-0353/) So as numpy's setup.py cannot call 'Py_InitModule4' this means, that the interpreter is built for 64bit systems. Maybe numpy is more accurate in testing wether it run's on 64 or on 32 bit than the python build script itself and therefore expect's Py_InitModule4 to be present. Isn't there perhaps a configure option to force 32 bit? Christian From tinaweb at bestemselv.com Tue Mar 20 02:56:00 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 20 Mar 2007 07:56:00 +0100 Subject: difference between urllib2.urlopen and firefox view 'page source'? In-Reply-To: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> References: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> Message-ID: cjl wrote: > Hi. > > I am trying to screen scrape some stock data from yahoo, so I am > trying to use urllib2 to retrieve the html and beautiful soup for the > parsing. > > Maybe (most likely) I am doing something wrong, but when I use > urllib2.urlopen to fetch a page, and when I view 'page source' of the > exact same URL in firefox, I am seeing slight differences in the raw > html. > > Do I need to set a browser agent so yahoo thinks urllib2 is firefox? > Is yahoo detecting that urllib2 doesn't process javascript, and > passing different data? > > -cjl > Unless the data you you need depends on the site detecting a specific browser you will probably receive a 'cleaner' code that's more easily parsed if you don't set a user agent. Usually the browser optimization they do is just eye candy, bells and whistles anyway in order to give you a more 'pleasing experience'. I doubt that your program will care about that ;) Tina From steve at REMOVE.THIS.cybersource.com.au Sat Mar 10 18:53:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Mar 2007 10:53:03 +1100 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7xr6rxkqp6.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 10 Mar 2007 08:29:09 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> Doesn't mean that it isn't random. After all, the first four numbers are >> random, therefore their sum is random. 50 - (something random) is also >> random. > > What does it mean for the first 4 numbers to be random? For example, > is 27 random? In isolation, no, but 27 could have been chosen at random and hence would have been unpredictable. That was my point: if we generate four unpredictable numbers (using random.randint or similar) and sum them, the sum is also unpredictable, and hence the difference between 50 and that sum is unpredictable. > By your method, what is the probability of the first number being > higher than 30? What is the probability of the fifth number being > higher than 30? If these probabilities are unequal, can we really say > the sequences are random? Of course we can! "Uniform probability distribution" is a special case of random. Most random quantities are far from uniform. The Python random module includes a couple of non-uniform distributions, including exponential distribution (random.expovariate) and the famous bell curve distribution (random.normalvariate). One common distribution which seems to have been missed is the Poisson distribution, which applies to (among many, many others) the number of 18th Century Prussian cavalry officers who fell off their horse and broke a limb, and the number of cars arriving at a petrol station in any hour. -- Steven. From gagsl-py2 at yahoo.com.ar Sun Mar 25 15:53:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 Mar 2007 16:53:55 -0300 Subject: Interactive session, alternating prompt. readline? curses? References: <20070325170409.GA2313@dotmpe.com> Message-ID: En Sun, 25 Mar 2007 14:04:09 -0300, Berend van Berkum escribi?: > I'm looking at building an interactive session in front of some > rdfobj instances. I've used cmd and just found code.Interactive*. > > However, my question, can I change the "prompt" string in respond > to user input using readline? AFAIK I'll need curses to do this? > And colored prompts? I've never used code.Interactive* and it looks like it interprets Python code, not arbitrary code. Using cmd, you can set the prompt attribute. For colors, I think you may need curses or ncurses or similar... -- Gabriel Genellina From jjl at pobox.com Sat Mar 10 18:05:49 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 10 Mar 2007 23:05:49 GMT Subject: merits of Lisp vs Python References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <7xtzww5nu6.fsf@ruckus.brouhaha.com> <1huohy5.1273xi3mtqdc2N%aleax@mac.com> Message-ID: <874pos1yy6.fsf@pobox.com> "Gabriel Genellina" writes: > En Fri, 09 Mar 2007 16:10:51 -0300, Tim Bradshaw escribi???: [...] > > ill-conceived idea (not because of Python, note!). The electronic > > gadget people need in the developing world is a mobile phone not a > > computer. > > What for? > That requires a phone company, installed antennas everywhere, and > available power to charge batteries. Without forgetting you to pay > the bill, of course. > I don't think OLPC would actually help people so much, but a mobile > phone would be almost useless. [...] How wrong can you get? Mobile phones have been making a significant economic impact in many places in the third world. Sub-saharan Africa has seen huge growth in access to mobile phones over the past few years, for example. A recent report indicates there are now over 100 million mobile phones in use in Africa. That's a huge change im communications from five years ago, but more than that, since people often don't own a mobile, but rent them by the minute from at the roadside, access levels must be much higher than that would imply (i.e., much greater than 10% of the continent's population). Mobile connections are intrinsically cheaper than fixed-line networks, can be rolled out faster, and have a disproportionately large impact in places where such electronic communications have in the past been absent, when compared with places like Europe and the US. For example, farmers report that they find mobile phones valuable to get information on market prices; without them, they would in the past have little choice but to physically go to market and hope for the best. http://www.timesonline.co.uk/tol/news/world/article737130.ece I know nothing about OLPC, but I hope they're spending lots of time talking to children, teachers, and academics, and to anybody with a good criticism. It must be tricky for big projects to stay connected to reality. John From wuwei23 at gmail.com Wed Mar 7 23:59:26 2007 From: wuwei23 at gmail.com (alex23) Date: 7 Mar 2007 20:59:26 -0800 Subject: merits of Lisp vs Python In-Reply-To: References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> Message-ID: <1173329966.266070.283130@8g2000cwh.googlegroups.com> John Nagle wrote: > Hosting providers and distro > makers aren't concerned over whether Python works. They > care if C, C++, Java, PHP, and Perl work, but not Python or LISP. > Ask them. Do you have any real experience with recent linux distros? Or with any _real_ hosting providers? Because what you've said is clearly not true. Just because the situation isn't as easy _for you_ as you would like, doesn't mean that Python is being ignored to the extent you're trying to claim. -alex23 From bbxx789_05ss at yahoo.com Tue Mar 20 20:33:54 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 20 Mar 2007 17:33:54 -0700 Subject: Imports In-Reply-To: <1174416672.629041.122320@l77g2000hsb.googlegroups.com> References: <1174415496.395993.72080@l77g2000hsb.googlegroups.com> <1174416672.629041.122320@l77g2000hsb.googlegroups.com> Message-ID: <1174437234.349310.304400@l77g2000hsb.googlegroups.com> On Mar 20, 12:51 pm, kyoso... at gmail.com wrote: > I typically just import sys and then do a > sys.path.append(directoryPath). This basically makes whatever modules > in that path available at run time. If you need a beginners reference > book, I recommend "Beginning Python" by Hetland. "Python Programming > for the Absolute Beginner" by Dawson was a lot of fun, but he doesn't > get into the internals of the language like Hetland does. Once you're > a snake charmer too, you can "graduate" to the "Programming Python" > book by Lutz. > > Mike I can't access any modules using the sys.path.append() method. Here is my directory structure: / ----Users ---------Me ------------2testing ------------------dir1 ---------------------test1.py ---------------------programs_python -----------------------------testA.py testA.py: ------------------------ def show(x): print x if __name__ == "__main__": show("hello") ------------------------ test1.py: ------------------------ import sys sys.path.append("/Users/Me/2testing/dir1/programs_python") testA.show("hello") ------------------------ command: ~/2testing/dir1$ python test1.py output: Traceback (most recent call last): File "test1.py", line 4, in ? testA.show("hello") NameError: name 'testA' is not defined Any idea how to do that? From gagsl-py2 at yahoo.com.ar Mon Mar 19 18:35:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 19:35:02 -0300 Subject: Pycron for windows - please help References: <1174330804.722975.84900@n59g2000hsh.googlegroups.com> Message-ID: En Mon, 19 Mar 2007 16:00:04 -0300, Al escribi?: > I looked in the pycron.log file, and I noticed that for the entires of > my new job, I see "rc=4" and the end of each line. All other jobs have > "rc=0" at the end of the line. I assume then, that rc=4 is a reference > to an error code of some kind, but there is no information on this in > the readme.txt, at the pycron website, or here in groups. > > Does anyone know how to troubleshhot this? Thanks in advance. Contacting the author? -- Gabriel Genellina From ptmcg at austin.rr.com Thu Mar 29 14:33:18 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Mar 2007 11:33:18 -0700 Subject: Any "consumer review generators" available? In-Reply-To: References: Message-ID: <1175193198.147869.293260@d57g2000hsg.googlegroups.com> On Mar 29, 1:19 pm, aral... at aol.com wrote: > I am looking for a fake consumer review generator that could generate realistic looking reviews for any products, kind of like on amazon.com but generated by Artificial Intelligence. Is there a package available in your favorite programing language... thx alan I have a fake supervisor reference generator for job interviews, a fake house inspection generator for real estate transactions, and a fake parole testimony generator - maybe you could adapt one of them (unfortunately, they are written in dissembler). -- Paul From aleax at mac.com Wed Mar 21 01:53:04 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 20 Mar 2007 22:53:04 -0700 Subject: dictionary.copy()? References: <1174456167.319603.88020@l75g2000hse.googlegroups.com> Message-ID: <1hvaq4z.1ct3azj5ddn53N%aleax@mac.com> 7stud wrote: > Here is some example code: > > d = {"a":"hello", "b":[1, 2, 3]} > > x = d.copy() > d["b"][0]=10 > print x > > output: > {'a': 'hello', 'b': [10, 2, 3]} > > It looks like the key names of a dictionary store pointers to the > values? Or does a dictionary object manage pointers to keys and > values, so copy() above just copies 4 pointers? dict objects hold references (roughly the same as C pointers) to keys and values, and dict.copy does a shallow copy. If you want a deep copy, import copy and x=copy.deepcopy(d) instead. Deep copies are very costly (because they copy a lot of data bits rather than just references), so it's quite sensible to have to ask for one very specifically in the rare cases in which you really want it. Alex From joshua at eeinternet.com Wed Mar 7 15:01:25 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 07 Mar 2007 11:01:25 -0900 Subject: Why does SocketServer default allow_reuse_address = false? References: <45e3668e$0$16385$88260bb3@free.teranews.com> <1173278345.027948.94700@j27g2000cwj.googlegroups.com> Message-ID: <45ef0d8e$0$16290$88260bb3@free.teranews.com> Greg Copeland wrote: >> Is there some history to this of which I'm not aware? Is there a good >> reason for it to default to false? > Long story short, it is not a bug. It is a feature. The proper > default is that of the OS, which is to ensure SO_REUSEADDR is disabled > unless you absoluetely understand what you're buying by enabling it. Thanks for your reply. Those are all point of which I had not been aware. My problem (and the reason I set reuse to True) is this: if I have connections active when I restart my service, upon restart, the socket will fail to bind because there is still a connection in a WAIT state. And until that old connection goes away (30 seconds or so?) I cannot restart the service. So, the only option would be to sit there in a loop calling serve_forever until it doesn't throw a "can't bind to socket" exception. Or is there something I'm *really* missing about the way SocketServer is supposed to work? Am I supposed to notify my connection threads to shut down and disconnect "properly?" Which gets even more fun since they are sitting there waiting for input on the connection and not in a position to respond to other events...gets back to the fun of "killing" threads that are blocking. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From steve at REMOVE.THIS.cybersource.com.au Sat Mar 10 08:45:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Mar 2007 00:45:30 +1100 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> Message-ID: On Fri, 09 Mar 2007 18:41:39 +0000, Dennis Lee Bieber wrote: > On 9 Mar 2007 06:44:01 -0800, "cesco" declaimed > the following in comp.lang.python: > >> I have to generate a list of N random numbers (integer) whose sum is >> equal to M. If, for example, I have to generate 5 random numbers whose >> sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a >> simple pattern or function in Python to accomplish that? >> > Well... Just that the last number is not random -- it has to equal > (using your limit of 50 and 5 numbers): > > fifth = 50 - sum(first, second, third, fourth) Doesn't mean that it isn't random. After all, the first four numbers are random, therefore their sum is random. 50 - (something random) is also random. In practice, one would deterministically generate the last number needed, but that last number is unpredictable because the first four numbers are unpredictable. Remember that random numbers are not necessarily unconstrained, nor are they necessarily uniformly distributed. We blithely talk about "random numbers", but of course there is a constraint that we're selecting from a finite range. Any finite range of numbers, no matter how big, is a vanishingly small percentage of all the possible numbers. -- Steven. From exarkun at divmod.com Thu Mar 29 07:52:22 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 29 Mar 2007 06:52:22 -0500 Subject: socket read timeout In-Reply-To: <000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: <20070329115222.18920.994320595.divmod.quotient.6408@ohm> On Thu, 29 Mar 2007 07:29:35 +0200, Hendrik van Rooyen wrote: > wrote: > > >> >> hg> My issue with that is the effect on write: I only want a timeout on >> hg> read ... but anyway ... >> >> So set a long timeout when you want to write and short timeout when you want >> to read. >> > >Are sockets full duplex? Uh, yes. > >I know Ethernet isn't. Not that this is relevant, but unless you're using a hub, ethernet _is_ full duplex. Jean-Paul From turd.flop.down.mleg at gmail.com Thu Mar 15 03:24:30 2007 From: turd.flop.down.mleg at gmail.com (Turd Flop Down M'leg) Date: 15 Mar 2007 00:24:30 -0700 Subject: Python eggs and openSuse 10.2 errors In-Reply-To: <1173942600.262524.196550@n59g2000hsh.googlegroups.com> References: <1173942600.262524.196550@n59g2000hsh.googlegroups.com> Message-ID: <1173943470.349789.167060@e1g2000hsg.googlegroups.com> Ahh bother... After messing around with yast, I realized that I didnt have the python dev packages installed. Once I installed them with yast, I just had to create a directory 'site-packages' under /usr/local/lib/ python2.5 and it all worked fine... Bah! From ntv1534 at gmail.com Fri Mar 2 05:23:32 2007 From: ntv1534 at gmail.com (MooMaster) Date: 2 Mar 2007 02:23:32 -0800 Subject: decimal and context objects! In-Reply-To: <1172830118.276246.101820@30g2000cwc.googlegroups.com> References: <1172830118.276246.101820@30g2000cwc.googlegroups.com> Message-ID: <1172831011.999674.212210@p10g2000cwp.googlegroups.com> On Mar 2, 3:08 am, "MooMaster" wrote: > Hey guys, I'm trying to do some black magic voodoo and it's a little > late, so forgive me if this question seems obvious or has been asked > before. I tried doing a search on context objects and didn't find > anything that popped out, and I'm too tired to keep digging. > > I'm making a little program that is trying to do weird and sexy things > by fully leveraging the power of all the built-in beauty of Python. I > was trying to play around with the new features added into Python 2.5, > and ran into an unexpected issue...check this out: > > >>> moo = lambda x, y : decimal.Context(3).sqrt(decimal.Context(3).power(x,2) + decimal.Context(3).power(y,2)) > >>> moo > > at 0x02CD0EB0>>>> row = [1,2,3,4,5] > >>> weight_vector = .00556 > >>> moo(sum(row), weight_vector) > > Traceback (most recent call last): > File "", line 1, in > moo(sum(row), weight_vector) > File "", line 1, in > moo = lambda x, y : > decimal.Context(3).sqrt(decimal.Context(3).power(x,2) + > decimal.Context(3).power(y,2)) > File "C:\Python25\lib\decimal.py", line 2662, in power > return a.__pow__(b, modulo, context=self) > TypeError: wrapper __pow__ doesn't take keyword arguments > > I have no idea what keyword argument is getting passed to __pow__, > anyone know what's going on? > > This should compute sqrt(5^2 + 3^2) Oh sorry, ignore that last line, that was a copy/paste from another example I forgot to remove...OBVIOUSLY it's going to compute something else, that's not what I'm asking about...stupid late night hacking! XD From steven.bethard at gmail.com Mon Mar 19 23:00:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 19 Mar 2007 21:00:23 -0600 Subject: an enumerate question In-Reply-To: <1174356075.710324.321150@b75g2000hsg.googlegroups.com> References: <1174354730.832021.263940@p15g2000hsd.googlegroups.com> <7xr6rkr8gw.fsf@ruckus.brouhaha.com> <1174356075.710324.321150@b75g2000hsg.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > for n,l in enumerate(open("file")): > print n,l # this prints current line > print next line in this current iteration of the loop. Depends what you want to happen when you request "next". If you want to renumber the lines, you can call .next() on the iterator:: >>> open('temp.txt', 'w').write('1\n2\n3\n4\n5\n6\n7\n') >>> lines_iter = open('temp.txt') >>> for i, line in enumerate(lines_iter): ... print 'LINE %i, %r %r' % (i, line, lines_iter.next()) ... LINE 0, '1\n' '2\n' LINE 1, '3\n' '4\n' LINE 2, '5\n' '6\n' Traceback (most recent call last): File "", line 2, in StopIteration If you want to peek ahead without removing the line from the iterator, check out this recipe:: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 Which allows code like:: >>> lines_iter = peekable(open('temp.txt')) >>> for i, line in enumerate(lines_iter): ... print 'LINE %i, %r %r' % (i, line, lines_iter.peek()) ... LINE 0, '1\n' '2\n' LINE 1, '2\n' '3\n' LINE 2, '3\n' '4\n' LINE 3, '4\n' '5\n' LINE 4, '5\n' '6\n' LINE 5, '6\n' '7\n' Traceback (most recent call last): ... StopIteration (Note that the recipe doesn't try to catch the StopIteration, but if you want that suppressed, it should be a pretty simple change.) STeVe From n00m at narod.ru Thu Mar 15 20:04:36 2007 From: n00m at narod.ru (n00m) Date: 15 Mar 2007 17:04:36 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174000951.999433.149760@n59g2000hsh.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <1174000951.999433.149760@n59g2000hsh.googlegroups.com> Message-ID: <1174003476.900115.233410@e65g2000hsc.googlegroups.com> Your suggestion speeded it up 1.5 times (on my 4000 test input rows)! From steve at REMOVE.THIS.cybersource.com.au Mon Mar 26 18:17:16 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Mar 2007 08:17:16 +1000 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916449.171929.138950@n76g2000hsh.googlegroups.com> Message-ID: On Mon, 26 Mar 2007 06:40:49 -0700, kyosohma wrote: > Fortran also appears to be a compiled language, whereas Python is an > interpreted language. Sheesh. Do Java developers go around telling everybody that Java is an interpreted language? I don't think so. What do you think the "c" in ".pyc" files stands for? "Cheese"? -- Steven. From carsten at uniqsys.com Fri Mar 16 10:13:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 16 Mar 2007 10:13:20 -0400 Subject: Writing python module in C: wchar_t or Py_UNICODE? In-Reply-To: <1174043065.189483.123640@b75g2000hsg.googlegroups.com> References: <1174043065.189483.123640@b75g2000hsg.googlegroups.com> Message-ID: <1174054400.3500.29.camel@dot.uniqsys.com> On Fri, 2007-03-16 at 04:04 -0700, Yury wrote: > I am new to python and programming generally, but someday it is time > to start :) > I am writing a python module in C and have a question about multibyte > character strings in python<=>C. > I want a C function which takes a string as argument from python > script: > > static PyObject * > connect_to_server(PyObject *self, PyObject * authinfo){ > wchar_t * login; /* Must support unicode */ > char * serveraddr; > int * port; > > if(!PyArgsParseTuple(authinfo, "sdu", &serveraddr, &port, &login)) > return NULL; > > ... > > Will that code work? > Or i should use Py_UNICODE * data type? Will it be compatible with > standard C string comparison/concantenation functions? You should familiarize yourself with the Python/C API documentation. It contains the answers to all the above questions. http://docs.python.org/api/arg-parsing.html says this about the "u" format character: "a pointer to the existing Unicode data is stored into the Py_UNICODE pointer variable whose address you pass." http://docs.python.org/api/unicodeObjects.html says this about Py_UNICODE: "On platforms where wchar_t is available and compatible with the chosen Python Unicode build variant, Py_UNICODE is a typedef alias for wchar_t to enhance native platform compatibility." The first quote says that, to be strictly correct, "login" should be a "Py_UNICODE*", but the second quote says that under the right circumstances, Py_UNICODE is the same as wchar_t. It's up to you to determine if your platform provides the right circumstances for this to be the case. Hope this helps, Carsten. From mail at timgolden.me.uk Thu Mar 29 09:23:31 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 Mar 2007 14:23:31 +0100 Subject: Finding User Profile path In-Reply-To: <1175173141.277735.192020@o5g2000hsb.googlegroups.com> References: <1175116080.934888.171450@n76g2000hsh.googlegroups.com> <1175173141.277735.192020@o5g2000hsb.googlegroups.com> Message-ID: <460BBDD3.7080103@timgolden.me.uk> kyosohma at gmail.com wrote: > One of my co-workers thought I could do > something like this: > > c = wmi.WMI() > for i in c.Win32_UserAccount(Name=user): > # Get user paths somehow. > > I messed around with that, but I think he was mistaken. It has lots of > good info, but not what I need. > > I apologize for not being specific. I will look at those win32net > functions. > > Mike Might depend on what you mean by "profile" but would the users' homeDirectory/homeDrive active directory attributes or the profilePath be of use here? If so, they're fairly easy to get hold of. TJG From trentm at activestate.com Mon Mar 12 18:24:45 2007 From: trentm at activestate.com (Trent Mick) Date: Mon, 12 Mar 2007 15:24:45 -0700 Subject: Python for amd64 and x86 on Windows In-Reply-To: References: Message-ID: <45F5D32D.6070705@activestate.com> Hengel, Simon wrote: > Hello List, > I need the amd64 and the x86 version of Python installed on one Windows machine. Is there a way to do this? (I think I read about it somewhere, but now I can't find it anymore) Bit of a hack but you could install the MSI ActivePython package for one and the "AS Package" (*) ActivePython package for the other. http://downloads.activestate.com/ActivePython/windows/2.4/ ActivePython-2.4.3.12-win32-x86.msi ActivePython-2.4.3.12-win64-x64-nopywin32.zip (*) "AS Package" is simple "zip file plus an install script" installer that ActivePython includes in addition to the usual (and preferred MSI installer). Trent p.s. ActivePython 2.5 builds will be out this week. -- Trent Mick trentm at activestate.com From aspineux at gmail.com Thu Mar 29 11:48:14 2007 From: aspineux at gmail.com (aspineux) Date: 29 Mar 2007 08:48:14 -0700 Subject: make RE more cleaver to avoid inappropriate : sre_constants.error: redefinition of group name In-Reply-To: <1175178128.472167.137970@n76g2000hsh.googlegroups.com> References: <1175178128.472167.137970@n76g2000hsh.googlegroups.com> Message-ID: <1175183294.220096.105870@l77g2000hsb.googlegroups.com> On 29 mar, 16:22, "aspineux" wrote: > I want to parse > > 'foo at bare' or '' and get the email address foo at bar > > the regex is > > r'<\w+@\w+>|\w+@\w+' > > now, if I want to give it a name > > r'<(?P\w+@\w+)>|(?P\w+@\w+)' > > sre_constants.error: redefinition of group name 'email' as group 2; > was group 1 > > BUT because I use a | , I will get only one group named 'email' ! THEN my regex is meaningful, and the error is meaningless and somrthing should be change into 're' But maybe I'm wrong ? > > Any comment ? I'm trying to start a discussion about something that can be improved in 're', not looking for a solution about email parsing :-) > > PS: I know the solution for this case is to use r'(?P<)?(?P > \w+@\w+)(?(lt)>)' From steve at holdenweb.com Thu Mar 22 05:55:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 05:55:03 -0400 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: References: <1174528562.192439.84480@l77g2000hsb.googlegroups.com> Message-ID: Duncan Booth wrote: > "Virgil Dupras" wrote: > >> I think I see what Marcin means. The 'node' is changed too fast in the >> chain, and next is assigned to 'nextnode' instead of being assigned to >> node. > > I can see why Marcin was confused. Many other languages assignment is an > expression, so a=b=c is simply a=(b=c). In Python it isn't an expression, > the chained assignment is a specific part of the syntax, so (as with > chained comparisons) the semantics may be surprising to the uninitiated. > > As a matter of interest do PyLint or PyChecker check for this situation > (chained assignment where the target of an assignment is also a > subexpression of a later assignment)? > Where's the published syntax for chained assignment? > Also it may be worth noting that unpacking has a similar behaviour: > > node, node.next = nextnode, nextnode > > has the same result as the chained assignment: the RHS is a tuple and is > fully evaluated before the assignment, but the LHS is not a tuple and the > assignment happens strictly left to right with each assignment fully > completed before proceeding to the next one. > Well that is explained (albeit badly) in the reference manual: """An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.""" That wording appears to be a rather bad mix of factoids from unpacking and chained assignment. Is it just me, or does this whole section need a rewrite? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From gdamjan at gmail.com Thu Mar 29 19:26:32 2007 From: gdamjan at gmail.com (Damjan) Date: Fri, 30 Mar 2007 01:26:32 +0200 Subject: socket read timeout References: <17930.25631.86693.827473@montanaro.dyndns.org> Message-ID: <460c4ae5$0$90276$14726298@news.sunsite.dk> >> So set a long timeout when you want to write and short timeout when you >> want to read. >> > > Are sockets full duplex? > > I know Ethernet isn't. Both are full duplex. -- damjan From mail at microcorp.co.za Tue Mar 27 08:43:10 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 27 Mar 2007 14:43:10 +0200 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: <000201c770f9$6bb8f6c0$03000080@hendrik> "Nick Craig-Wood" wrote: > Hendrik van Rooyen wrote: > > > But would be useful to be able to do without messing with > > threads and GUI and imports. > > Could be hard to implement as the interpreter would have > > to be assured of getting control back periodically, so a > > ticker interrupt routine is called for - begins to sound more > > like a kernel function to me. > > Isn't there something available that could be got at via ctypes? > > I think if we aren't executing python bytecodes (ie are blocked in the > kernel or running in some C extension) then we shouldn't try to > interrupt. It may be possible - under unix you'd send a signal - > which python would act upon next time it got control back to the > interpreter, but I don't think it would buy us anything except a whole > host of problems! Don't the bytecodes call underlying OS functions? - so is there not a case where a particular bytecode could block, or all they all protected by time outs? Embedded code would handle this sort of thing by interrupting anyway and trying to clear the mess up afterward - if the limit switch does not appear after some elapsed time, while you are moving the 100 ton mass, you should abort and alarm, regardless of anything else... And if the limit switch sits on a LAN device, the OS timeouts could be wholly inappropriate... - Hendrik From supervau at gmail.com Tue Mar 27 15:50:50 2007 From: supervau at gmail.com (Frank) Date: 27 Mar 2007 12:50:50 -0700 Subject: rpy: parsing arrays from python to R Message-ID: <1175025050.708740.261370@e65g2000hsc.googlegroups.com> Hi, I use rpy on linux to call R functions. Works fine up to the following problem: How to parse arrays (no vectors, that means 2-dimensional) to R without much effort? The following code solves the problem (in two different ways). However, it seems to me that there might be a way to do it more efficiently. rpy.r.assign("N", N) rpy.r("A2 <- array(1:N^2, dim=c(N,N))") rpy.r("A3 <- array(1:N^2, dim=c(N,N))") for i in range(N): # two alternative ways to parse arrays rpy.r.assign("Wi", W[i]) rpy.r.assign("i", i+1) rpy.r("""for( j in 1:N ){ A2[i,j] <- Wi[j]}""") for k in range(N): rpy.r.assign("k", k+1) rpy.r("A3[i,k] <- Wi[k]") print rpy.r("A3") print rpy.r("A2") As I see it, the problem is, that the 'assign' command works only either for scalars or vectors (one-dimensional arrays but not more- dimensional arrays). I tried it for 2-dimensional arrays and the result is a list whose components are vectors. Again, this is easy to convert to a two-dimensional array but the point here is that one has to do it. Maybe there are people using R with python who have some more experience. I would be interested how they solved this problem. Thanks! Frank From python at rcn.com Mon Mar 5 02:31:30 2007 From: python at rcn.com (Raymond Hettinger) Date: 4 Mar 2007 23:31:30 -0800 Subject: Descriptor/Decorator challenge Message-ID: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> I had an idea but no time to think it through. Perhaps the under-under name mangling trick can be replaced (in Py3.0) with a suitably designed decorator. Your challenge is to write the decorator. Any trick in the book (metaclasses, descriptors, etc) is fair game. Raymond -------- how we currently localize method access with name mangling ------ class A: def __m(self): print 'A.__m' def am(self): self.__m() class B(A): def __m(self): print 'B.__m' def bm(self): self.__m() m = B() m.am() # prints 'A.__m' m.bm() # prints 'B.__m' -------- how I would like to localize method access with a decorator ------ class A: @localmethod def m(self): print 'A.m' def am(self): self.m() class B(A): @localmethod def m(self): print 'B.m' def bm(self): self.m() m = B() m.am() # prints 'A.m' m.bm() # prints 'B.m' --------------------- P.S. Here's a link to the descriptor how-to: http://users.rcn.com/python/download/Descriptor.htm From aahz at pythoncraft.com Wed Mar 28 19:58:15 2007 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2007 16:58:15 -0700 Subject: how can I clear a dictionary in python References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> <570dbbF28iktlU1@mid.individual.net> Message-ID: In article <570dbbF28iktlU1 at mid.individual.net>, Bjoern Schliessmann wrote: >Aahz wrote: >> >> Go back and read Christian's post, then post a followup explaning >> why his solution is better than yours. Your explanation should >> use id(). > >I wonder how you two seem to know exactly what the OP wants ... We don't. However, we do know exactly what the OP said... (Perhaps you didn't read the Subject: line?) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From vel.accel at gmail.com Tue Mar 27 21:39:14 2007 From: vel.accel at gmail.com (D.Hering) Date: 27 Mar 2007 18:39:14 -0700 Subject: PyDoc -g call to Alt-Installed Python Message-ID: <1175045954.295216.105830@d57g2000hsg.googlegroups.com> I have both python2.4 and 2.5 installed on a (k)ubuntu linux box. I'm trying to get the call to pydoc -g (pydoc server called from the system console) to recognize python2.5 rather than the system's default 2.4 release. I've tried several different things so far, to no avail. My console scripting knowledge, so far, is minimal. Any help here is appreciated. Thanks, -Dieter From fabio.fzero at gmail.com Tue Mar 20 09:44:27 2007 From: fabio.fzero at gmail.com (Fabio FZero) Date: 20 Mar 2007 06:44:27 -0700 Subject: Problem with sockets and python 2.5 In-Reply-To: References: <200703192207.08178.jareguero@telefonica.net> Message-ID: <1174398267.091816.296180@e65g2000hsc.googlegroups.com> On Mar 20, 10:05 am, Facundo Batista wrote: > Jose Alberto Reguero wrote: > > 2: > > server.py at x86_64 python 2.5 > > client.py at i386 python 2.4 > > Don't work > > What do you mean with "don't work"? > > They crash? Your machine hungs? Your house explodes? Traceback (most recent call last): File "server.py", line 1, in DontWorkError: YOUR HEAD A SPLODE! :D FZ From luismgz at gmail.com Mon Mar 19 19:46:56 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 Mar 2007 16:46:56 -0700 Subject: Passing arguments to a command line from a python script Message-ID: <1174348016.873087.179750@d57g2000hsg.googlegroups.com> Please forgive me if what I'm asking is non sense... I created a little program to authomate the creation of the "setup.py" script for py2exe. It simply prompts for the main executable script name and then creates setup.py, as follows: # this is "makesetup.py" nombre = raw_input('File name?: ') f = open('setup.py', 'w') f.write(''' from distutils.core import setup import py2exe setup( name = "%s", windows = ["%s.pyw"], data_files = [ (".", ["%s.rsrc.py"]) ] ) ''' %(nombre, nombre, nombre)) f.close() # end of script What I want now is execute the script I just created. As far as I know, the only way to execute the script is from a command line and typing "setup.py py2exe". Can I do this authomatically right from my program? If so, how? Any hint would be highly appreciated... regards, Luis From kyosohma at gmail.com Tue Mar 20 11:59:22 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Mar 2007 08:59:22 -0700 Subject: os.wait() for Windows In-Reply-To: References: Message-ID: <1174406362.923831.202230@l75g2000hse.googlegroups.com> On Mar 20, 10:32 am, "Damien Byrne" wrote: > Hello, > > I am new to python. I am using the os module to run a command in a > bashshell. However I need this process to complete before continuing. Is > there a command that will wait for this process to complete? I am using > Windows XP and the os.wait() command only works for UNIX systems, and > therefore doesn't work. > > My code is as follows: > > import os > FileName = raw_input('Enter the file name: ') > os.system('abaqus job=FileName') > resultsFile = open('FileName.dat','r') > > Abaqus will take a few minutes to complete and create the associated results > file. However once I run this code I get the following error ... "IOError: > [Errno 2] No such file or directory: 'FileName.dat'" ... as the file does > not exist yet. Is there any way of waiting for the job to complete before > continuing? > > I'd appreciate any help. > > _________________________________________________________________ > Share folders without harming wildlife!http://www.communicationevolved.com/en-ie/ I would recommend subprocess.call(programToRun) or subprocess.Popen(programToRun).wait() Mike From stefan.behnel-n05pAM at web.de Mon Mar 5 12:34:49 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 05 Mar 2007 18:34:49 +0100 Subject: How use XML parsing tools on this one specific URL? In-Reply-To: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> References: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> Message-ID: <45ec54ba$0$23132$9b4e6d93@newsspool1.arcor-online.net> seberino at spawar.navy.mil schrieb: > I understand that the web is full of ill-formed XHTML web pages but > this is Microsoft: > > http://moneycentral.msn.com/companyreport?Symbol=BBBY > > I can't validate it and xml.minidom.dom.parseString won't work on it. Interestingly, no-one mentioned lxml so far: http://codespeak.net/lxml http://codespeak.net/lxml/dev/parsing.html#parsers Parse it as HTML and then use anything from XPath to XSLT to treat it. Have fun, Stefan From arkanes at gmail.com Mon Mar 5 12:22:00 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 5 Mar 2007 11:22:00 -0600 Subject: Python GUI + OpenGL In-Reply-To: <552vcfF2339mvU1@mid.uni-berlin.de> References: <45e84025$0$15959$9b4e6d93@newsspool4.arcor-online.net> <54r59qF228m8bU1@mid.uni-berlin.de> <552vcfF2339mvU1@mid.uni-berlin.de> Message-ID: <4866bea60703050922o1a2b3047n73d9914af12fa81e@mail.gmail.com> On 3/5/07, Diez B. Roggisch wrote: > Dag wrote: > > > On Fri, 02 Mar 2007 18:30:34 +0100, Diez B. Roggisch > > wrote: > >> Achim Domma wrote: > >> > >>> Hi, > >>> > >>> I'm developing a GUI app in Python/C++ to visualize numerical results. > >>> Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there > >>> are no windows binaries for Python 2.5 for quite some time now. > >>> > >>> I need a OpenGL context without restrictions and some settings dialogs. > >>> Is wx + PyOpenGL the way to go? Or could somebody recommend a better set > >>> of tools/libs? > >> > >> PyQt, but then there is the licensing question of course. > > > > I'm facing a similar problem. Would you care to explain why PyQt is > > better in this particular case. I've used both PyQt and wx for 'normal' > > GUI programming (but I'm more familiar with wx) so I know about their > > difference in general. But why is PyQt better than wx for working with > > OpenGL? > > I didn't say so. I just pointed out an alternative, as the OP had issues > with obtaining binary packages for wx + py2.5 > I believe he was having trouble with binary packages for PyOpenGL, wxPython has 2.5 binaries and has since it was released. That said, it's my understanding that the most recent version of PyOpenGL uses ctypes and no longer requires a windows binary, which is why they are not provided. Also, if you're writing a C++/Python app on Windows then you must have the correct environment to build Python extensions, so even if my understanding is incorrect, you should be able to build PyOpenGL via distutils with minimal if any trouble. > Beside that, I do love the Qt library and would always use it in preference > to wx, but this is a general thing and by no means tied to the > OpenGL-programming. After all, that actually is done using PyOpenGL > wx and Qt support OpenGL in essentially the same manner. I believe he took from your earlier post that Qt had its own built in OpenGL wrapper (and thus didn't rely on PyOpenGL) but to my knowledge that is not correct. > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From auch-ich-m at g-kein-spam.com Tue Mar 13 05:35:43 2007 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Tue, 13 Mar 2007 10:35:43 +0100 Subject: Program __main__ function References: <1173760751.798442.300550@s48g2000cws.googlegroups.com> <87mz2hwuco.fsf_-_@benfinney.id.au> Message-ID: <55n9jkF26klgiU1@mid.individual.net> Ben Finney wrote: > Ben Finney writes: > >> Now, when I write unit tests for my program (i.e. a Python module >> designed to be run as a command), it can still be imported safely >> into my unit tests, and all the code gets covered by test cases >> except the three-line stanza at the end. > > All I need now is for Python to automatically execute a '__main__' > function if the module name is '__main__' (which it seems the OP > expected should happen), and unit test coverage could be 100% :-) Short hint to go further: exec file('/usr/lib/python2.4/timeit.py') in {'__name__': '__main__'} nd From gigs at hi.t-com.hr Fri Mar 9 12:01:14 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 09 Mar 2007 18:01:14 +0100 Subject: tkinter text editor Message-ID: I'm writing text editor. How to enable/disable (cut, copy etc.) when text is selected/not selected From MonkeeSage at gmail.com Mon Mar 5 22:13:05 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 19:13:05 -0800 Subject: Is every number in a list in a range? In-Reply-To: <7x7itvt6nw.fsf@ruckus.brouhaha.com> References: <7xk5xvgo55.fsf@ruckus.brouhaha.com> <1173149481.694255.23350@n33g2000cwc.googlegroups.com> <7x7itvt6nw.fsf@ruckus.brouhaha.com> Message-ID: <1173150785.768534.286700@8g2000cwh.googlegroups.com> On Mar 5, 9:03 pm, Paul Rubin wrote: > Maybe I didn't undrestand the question. Say maxnum is 30 in your > example above. Then as soon as 46 is seen, you can stop checking, I > thought. Yes, as long as 29 doesn't follow 46. inlist = [1, 5, 23, 46, 29, 21] If you want to preserve the items after 46, then you can't just bail when you see 46. You need to keep looking at the following values and comparing them against the boundry conditions. If the the input is sequential, then this isn't a problem, as all items above 46 are out of range....but if the input is arbitrary, then you have to look at each index individually as you know. So it really comes down to if the data set is ordered or arbitrary as to which approach is more efficient. Regards, Jordan From MonkeeSage at gmail.com Sat Mar 3 20:52:17 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Mar 2007 17:52:17 -0800 Subject: portable Python ifconfig In-Reply-To: <1172971079.137861.316170@h3g2000cwc.googlegroups.com> References: <1172971079.137861.316170@h3g2000cwc.googlegroups.com> Message-ID: <1172973137.492188.85100@s48g2000cws.googlegroups.com> On Mar 3, 7:17 pm, "MonkeeSage" wrote: > I'm pretty sure the offsets would be different for BSD Then again, mabye not. http://freebsd.active-venture.com/FreeBSD-srctree/newsrc/compat/linux/linux_ioctl.h.html Regards, Jordan From bearophileHUGS at lycos.com Wed Mar 21 14:47:16 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Mar 2007 11:47:16 -0700 Subject: why brackets & commas in func calls can't be ommited? (maybe it couldbe PEP?) In-Reply-To: References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Message-ID: <1174502836.912713.294390@y80g2000hsf.googlegroups.com> I have nothing against brackets, and I think Python has used them for too much time to allow a so big change in its syntax. But I think in some situations Ruby allows to omit them, solving some of the "impossibile" problems shown in this thread. This makes Ruby a bit better than Python to create application-specific mini languages, that are quite useful in some situations. Bye, bearophile From godzillaismad at gmail.com Thu Mar 22 18:40:21 2007 From: godzillaismad at gmail.com (Godzilla) Date: 22 Mar 2007 15:40:21 -0700 Subject: Python Oracle 10g odbc blob insertion problem In-Reply-To: References: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> <1174567006.244721.115890@n59g2000hsh.googlegroups.com> Message-ID: <1174603221.600706.62210@p15g2000hsd.googlegroups.com> On Mar 23, 4:38 am, Dennis Lee Bieber wrote: > On 22 Mar 2007 05:36:46 -0700, "Godzilla" > declaimed the following in comp.lang.python: > > > Steve, I think I've tried what you have suggested without any luck as > > well... The statement works fine, but what inserted is not correct... > > it seems like only the symbol '?' was inserted into the blob field... > > You didn't have a set of 's around the ?, did you? Parameter > substitution will add needed quotes on its own rather than you having to > put in quotes. > > Also, though I find no documentation on it, odbc module cursors have > setinputsizes() and setoutputsizes() methods -- perhaps that could > change things... OTOH: the db-api 1.0 PEP (which is, it seems, what odbc > module follows) says they may be do-nothing methods. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Everything seems to work fine right now... thanks all of you for helping... Have a great day.. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 8 03:12:52 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 08 Mar 2007 09:12:52 +0100 Subject: Bug in python!? persistent value of an optional parameter in function! In-Reply-To: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> Message-ID: <45efc562$0$21514$426a34cc@news.free.fr> C Barr Leigh a ?crit : > Help! Have I found a serious bug? No. This is a FAQ. Default arguments of functions are evaled only once - when the def statement is eval'd and the function object constructed. > This seems like highly undesired behaviour to me. Possibly, but this is unlikely to change in a near future, so you'd better get used to it. If you want mutable objects as default values for functions, the idiom is: def some_func(default=None): if default is None: default = [] # code here HTH From uri at stemsystems.com Thu Mar 29 18:02:46 2007 From: uri at stemsystems.com (Uri Guttman) Date: Thu, 29 Mar 2007 17:02:46 -0500 Subject: What are OOP's Jargons and Complexities References: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> <460c30b1$0$8750$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: please DO NOT EVER followup xah's posts into comp.lang.perl.misc. he is not wanted there and is considered a troll. he hates perl so why he crossposts there is a question. if you want to followup, post only in your own group. keep him and his useless threads out of c.l.p.misc. uri -- Uri Guttman ------ uri at stemsystems.com -------- http://www.stemsystems.com --Perl Consulting, Stem Development, Systems Architecture, Design and Coding- Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org From bj_666 at gmx.net Mon Mar 5 05:45:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 05 Mar 2007 11:45:38 +0100 Subject: Dictionary of Dictionaries References: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> Message-ID: In <1173090144.783533.163920 at p10g2000cwp.googlegroups.com>, bg_ie wrote: > What am I doing wrong? `dict.fromkeys()` stores the given object for all keys, so you end up with the *same* dictionary for 'one' and 'two'. In [18]: a = dict.fromkeys(("one","two"), {}) In [19]: a Out[19]: {'two': {}, 'one': {}} In [20]: a['one']['x'] = 42 In [21]: a Out[21]: {'two': {'x': 42}, 'one': {'x': 42}} In [22]: a['one'] is a['two'] Out[22]: True Ciao, Marc 'BlackJack' Rintsch From FlipFish2007 at yahoo.com Fri Mar 30 17:23:57 2007 From: FlipFish2007 at yahoo.com (FlipFish2007 at yahoo.com) Date: 30 Mar 2007 14:23:57 -0700 Subject: I can't get multi-dimensional array to work... In-Reply-To: <1175288195.207852.150320@p15g2000hsd.googlegroups.com> References: <1175288195.207852.150320@p15g2000hsd.googlegroups.com> Message-ID: <1175289837.359022.62220@o5g2000hsb.googlegroups.com> On Mar 30, 4:56 pm, "erikcw" wrote: > Hi, > > I'm trying to create a multidimensional data structure. However, id > doesn't seem to work past the 2nd dimension. > > Here is my method: > > def endElement(self, name): > if name == 'row' : > if not self.data.has_key(self.parent): > self.data[self.parent] = {} > elif not self.data[self.parent].has_key(self.child): > self.data[self.parent][self.child] = [] > self.data[self.parent] > [self.child].append((self.creativeid, self.clicks, self.imps)) > > I've tried all kinds of different variations, and I keep getting the > same result: > > Traceback (most recent call last): > File "sax.py", line 123, in ? > parser.parse(open('report.xml')) > File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py", > line 109, in parse > xmlreader.IncrementalParser.parse(self, source) > File "/usr/lib/python2.4/site-packages/_xmlplus/sax/xmlreader.py", > line 123, in parse > self.feed(buffer) > File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py", > line 216, in feed > self._parser.Parse(data, isFinal) > File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py", > line 315, in end_element > self._cont_handler.endElement(name) > File "sax.py", line 51, in endElement > self.data[self.parent][self.child].append((self.creativeid, > self.clicks, self.imps)) > KeyError: u'Pickup Trucks' > > I have a lot of php experience - am I accidentally doing a "php thing" > in my code? > > Thanks so much for your help! > > Erik I haven't tested it, but superficially I'd suggest giving this a try: def endElement(self, name): if name == 'row' : if not self.data.has_key(self.parent): self.data[self.parent] = {} if not self.data[self.parent].has_key(self.child): self.data[self.parent][self.child] = [] self.data[self.parent] [self.child].append((self.creativeid, self.clicks, self.imps)) From bjourne at gmail.com Wed Mar 14 09:57:51 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 14 Mar 2007 14:57:51 +0100 Subject: Grep Equivalent for Python In-Reply-To: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> References: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> Message-ID: <740c3aec0703140657k3c4e8d29n8ac69395d7185ea8@mail.gmail.com> > I come from a shell/perl background and have just to learn python. To > start with, I'm trying to obtain system information from a Linux > server using the /proc FS. For example, in order to obtain the amount > of physical memory on the server, I would do the following in shell: > > grep ^MemTotal /proc/meminfo | awk '{print $2}' > > That would get me the exact number that I need. Now, I'm trying to do > this in python. Here is where I have gotten so far: > > memFile = open('/proc/meminfo') > for line in memFile.readlines(): > print re.search('MemTotal', line) > memFile.close() import sys sys.stdout.write(L.split()[1] + '\n' for L in open('/proc/meminfo') if L.startswith('MemTotal')) -- mvh Bj?rn From davecook at nowhere.net Sun Mar 25 20:00:31 2007 From: davecook at nowhere.net (Dave Cook) Date: Mon, 26 Mar 2007 00:00:31 GMT Subject: Beginner GTK question References: <1174820246.350058.96280@y66g2000hsf.googlegroups.com> Message-ID: On 2007-03-25, dashawn888 wrote: > gui.py:79: GtkWarning: Quit: missing action > menubar = uimanager.get_widget('/MenuBar') > This should probably be action="Quit". Dave Cook From wollez at gmx.net Thu Mar 1 15:01:03 2007 From: wollez at gmx.net (WolfgangZ) Date: Thu, 01 Mar 2007 21:01:03 +0100 Subject: pycrust startup question Message-ID: Hi, I've tried to add " from __future__ import division" to the startup script of pycrust. It seems to be imported as division is listed in the namespace. But it is somehow not activated. Any suggestions? PyCrust 0.9.5 Python 2.5 From sickcodemonkey at gmail.com Thu Mar 1 18:13:55 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 1 Mar 2007 18:13:55 -0500 Subject: Python win32 tools Message-ID: <2adc542f0703011513h5fe8ad26o91b0fb6a9825eb91@mail.gmail.com> I am trying to build a python program that will reset a user's account (password) on a windows machine (NOTE: my intention here is not to implement anything malicious {and I know about Trinity which is very useful}, but I just wanted a challenge and do it myself.). I have been working with win32 objects and was wondering if this functionality was already built in. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From n00m at narod.ru Fri Mar 16 01:49:03 2007 From: n00m at narod.ru (n00m) Date: 15 Mar 2007 22:49:03 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <7xtzwlkhq9.fsf@ruckus.brouhaha.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> Message-ID: <1174024143.049965.25710@l77g2000hsb.googlegroups.com> Steven, I ran this: import time, collections, itertools t = time.clock() q,w,e,r,sch = [],[],[],[],0 h = collections.defaultdict(itertools.repeat(0).next) f = open("D:/m4000.txt","rt") for o in range(int(f.readline())): row = map(int, f.readline().split()) q.append(row[0]) w.append(row[1]) e.append(row[2]) r.append(row[3]) f.close() for x in q: for y in w: h[x+y] += 1 for x in e: for y in r: sch += h[-(x + y)] q,w,e,r,h = None,None,None,None,None print sch print time.clock() - t ========= and it almost froze my PC... === but it was faster than my code on input file with 1000 rows: ====== 2.00864607094s VS 3.14631077413s From nagle at animats.com Tue Mar 20 15:45:15 2007 From: nagle at animats.com (John Nagle) Date: Tue, 20 Mar 2007 19:45:15 GMT Subject: Documentation for "str()" could use some adjustment - Unicode issue In-Reply-To: <1hv8tz5.l61xmz1mtprhiN%aleax@mac.com> References: <1hv8tz5.l61xmz1mtprhiN%aleax@mac.com> Message-ID: Alex Martelli wrote: > John Nagle wrote: > ... > >> The real problem is the published books on Python: >> >>"Learning Python", by Lutz and Ascher: >> "str(string) -- returns the string representation of any object." >> >>"Python in a Nutshell", by Martelli >> Doesn't really address the issue, but says that "print" calls >>"str" for conversions. >> >>Neither of these mentions that "str" is ASCII-only. > > > Are you looking at p. 109 of the 2nd edition of the Nutshell? No, I'm looking at the original edition from 2003. That was what Borders had in stock late last year. John Nagle From asandstrom at accesswave.ca Sat Mar 31 01:24:51 2007 From: asandstrom at accesswave.ca (Arved Sandstrom) Date: Sat, 31 Mar 2007 05:24:51 GMT Subject: What are OOP's Jargons and Complexities References: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> <460cca34$0$8723$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: "Mike Schilling" wrote in message news:SFbPh.10507$JZ3.490 at newssvr13.news.prodigy.net... > bugbear wrote: >> Er. How about >> >> public class test { >> public static void main(String[] args) { >> String a = "a string"; >> String b = "another one"; >> StringBuffer c = a + b; > > String c (etc.), that is. My answer, Mike. Since there was never any need for variables "a" and "b" to be separate, I'd just be blatting out System.out.println("a stringanother one"); as the solution to this particular problem. It's just a confuscated Hello World. AHS From aleax at mac.com Thu Mar 1 02:00:26 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 28 Feb 2007 23:00:26 -0800 Subject: How to Read Bytes from a file References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> Message-ID: <1hu9p0u.1rc19sp19r95zhN%aleax@mac.com> gregpinero at gmail.com wrote: > It seems like this would be easy but I'm drawing a blank. > > What I want to do is be able to open any file in binary mode, and read > in one byte (8 bits) at a time and then count the number of 1 bits in > that byte. > > I got as far as this but it is giving me strings and I'm not sure how > to accurately get to the byte/bit level. > > f1=file('somefile','rb') > while 1: > abyte=f1.read(1) You should probaby prepare before the loop a mapping from char to number of 1 bits in that char: m = {} for c in range(256): m[c] = countones(c) and then sum up the values of m[abyte] into a running total (break from the loop when 'not abyte', i.e. you're reading 0 bytes even though asking for 1 -- that tells you the fine is finished, remember to close it). A trivial way to do the countones function: def countones(x): assert x>=0 c = 0 while x: c += (x&1) x >>= 1 return c you just don't want to call it too often, whence the previous advice to call it just 256 times to prep a mapping. If you download and install gmpy you can use gmpy.popcount as a fast implementation of countones:-). Alex From gagsl-py2 at yahoo.com.ar Wed Mar 7 12:13:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 14:13:28 -0300 Subject: Python Source Code Beautifier References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> <1172700549.583792.41660@s48g2000cws.googlegroups.com> <45E8FADB.7000902@cosc.canterbury.ac.nz> <1rgq149m7oern$.1080aifmn5qo8$.dlg@40tude.net> <1fenbu7prg0bm.3q5rj5s6vex4$.dlg@40tude.net> Message-ID: En Wed, 07 Mar 2007 10:29:29 -0300, Alan Franzoni escribi?: > Il Tue, 06 Mar 2007 01:55:54 -0300, Gabriel Genellina ha scritto: > If we rely on duck typing, by the way, we may encounter two types > quacking > like ducks, flying like ducks, but in fact acting as slightly different > ducks. I should remember as well, when designing a container type that I > want to use in place of a list, to carefully craft an __iadd__ method > which > works just like the a list's own __iadd__ method; if I forget, I may > introduce a subtle error. I'm not sure of your concerns. If you want to provide your own container that mimics a list, there are a lot more things to consider than __iadd__ (See the UserList class or this ListMixin recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440656). __iadd__, in general, is not *required* to modify the instance in place (but should try to do that, if possible). After this code: b = a a += c you can't assert than a and b both refer to the *same* object, as before. If you need that, don't use += at all. (For a generic object, I mean. The built-in list "does the right thing", of course) -- Gabriel Genellina From pauld.prismm at comcast.net Fri Mar 16 19:58:32 2007 From: pauld.prismm at comcast.net (paul debrigida) Date: Fri, 16 Mar 2007 19:58:32 -0400 Subject: Obtaining Webpage Source with Python Message-ID: <000601c76827$00e32d50$fa64a8c0@MICROS1> hey bud this is ryan kaskel just wanted tuch base we have the same name little disapointed i did not come up on my google search ryan kaskel balt md search parkville high school lacrosse -------------- next part -------------- An HTML attachment was scrubbed... URL: From olsonas at gmail.com Wed Mar 14 16:48:49 2007 From: olsonas at gmail.com (Drew) Date: 14 Mar 2007 13:48:49 -0700 Subject: Converting a list to a dictionary In-Reply-To: <1173905016.752156.248140@n59g2000hsh.googlegroups.com> References: <1173902878.561018.244310@y80g2000hsf.googlegroups.com> <45f8583d$0$10407$426a34cc@news.free.fr> <1173904326.037621.10390@n76g2000hsh.googlegroups.com> <1173905016.752156.248140@n59g2000hsh.googlegroups.com> Message-ID: <1173905329.280910.24450@l75g2000hse.googlegroups.com> On Mar 14, 4:43 pm, "Samuel" wrote: > What this does is it maps the id to the object. In your case, you only > have one id. > > -Samuel This is interesting behavior, but may not be what the original poster intended. If I understand correctly, this means that if more than one object shares the same id, only one copy will be created in the dict. Is this correct? From bignose+hates-spam at benfinney.id.au Tue Mar 13 02:20:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 13 Mar 2007 17:20:42 +1100 Subject: Program __main__ function References: <1173760751.798442.300550@s48g2000cws.googlegroups.com> <87mz2hwuco.fsf_-_@benfinney.id.au> Message-ID: <87ird5wtol.fsf@benfinney.id.au> Ben Finney writes: > Now, when I write unit tests for my program (i.e. a Python module > designed to be run as a command), it can still be imported safely > into my unit tests, and all the code gets covered by test cases > except the three-line stanza at the end. All I need now is for Python to automatically execute a '__main__' function if the module name is '__main__' (which it seems the OP expected should happen), and unit test coverage could be 100% :-) > Htag.pl 0.0.23 - Simon Huggins Released under GPL > Copyright (C) 1999-2002 Project Purple. http://www.earth.li/projectpurple/ > > Got sigmatch == ^/home/bignose/\.sigs/news.*$ Er, okay. That was a bit strange. Sorry for the flubbed sigmonster. -- \ "I bet one legend that keeps recurring throughout history, in | `\ every culture, is the story of Popeye." -- Jack Handey | _o__) | Ben Finney From skip at pobox.com Sat Mar 24 15:26:11 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 24 Mar 2007 14:26:11 -0500 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174763412.409665.19870@l75g2000hse.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <1174763412.409665.19870@l75g2000hse.googlegroups.com> Message-ID: <17925.31571.833301.571700@montanaro.dyndns.org> bbxx789> Can you explain how that works? If you install python in bbxx789> /usr/local, doesn't that leave you with something like bbxx789> /usr/local/python? So what does putting usr/local/bin ahead of bbxx789> your other paths do? When you install with --prefix==/usr/local you will wind up with /usr/local/bin/python. There will also be a /usr/local/lib/pythonX.Y (with structure underneath it) containing all the Python and extension modules. Skip From http Thu Mar 8 16:25:46 2007 From: http (Paul Rubin) Date: 08 Mar 2007 13:25:46 -0800 Subject: multithreading concept References: <1170865166.423764.87050@s48g2000cws.googlegroups.com> <1173352667.089875.174620@q40g2000cwq.googlegroups.com> Message-ID: <7x4povv351.fsf@ruckus.brouhaha.com> "Paul Boddie" writes: > What makes all of the following not "Pythonic"...? > http://wiki.python.org/moin/ParallelProcessing I'd say mainly that they don't allow sharing data between processes except through expensive IPC mechanisms involving system calls. > I'm sure one could define "Pythonic" as being "you can write > code like you do now (but not like any of the ways encouraged by the > aforementioned solutions) and it just works over multiple processors/ > cores", but that's a view which is somewhat detached from the > practicalities (and favoured practices) of concurrent programming, > especially given the few guarantees Python would be able to provide to > make such a thing work effectively. Really, the existence of the GIL comes as an unpleasant surprise to progrmamers used to multi-threaded programming in other languages whose synchronization features outwardly look about the same as Python's. Somehow those other languages manage to use multiple CPU's based on those features, without needing a GIL. We are looking at a Python implementation wart, not "practicalities" inherent in the nature of concurrency. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Mar 27 01:34:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Mar 2007 07:34:48 +0200 Subject: about second parameter of signal handler func. References: Message-ID: <56ronoF2a9a19U1@mid.individual.net> Marco wrote: > In C, a signal handler function has only one parameter, that is > signal number. But in Python(import signal), a signal handler > function has two parameters, the first is signal number, the > second is "frame"? > > What is "frame", please? Did you bother using help()? >>> help(signal) [...] *** IMPORTANT NOTICE *** A signal handler function is called with two arguments: the first is the signal number, the second is the interrupted stack frame. Regards, Bj?rn -- BOFH excuse #253: We've run out of licenses From tismer at stackless.com Wed Mar 28 19:02:28 2007 From: tismer at stackless.com (Christian Tismer) Date: Thu, 29 Mar 2007 01:02:28 +0200 Subject: how can I clear a dictionary in python In-Reply-To: <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> Message-ID: <45951AAC-A959-48EE-B69B-0558FF2304F2@stackless.com> On 29.03.2007, at 00:48, Larry Bates wrote: > Marko.Cain.23 at gmail.com wrote: >> Hi, >> >> I create a dictionary like this >> myDict = {} >> >> and I add entry like this: >> myDict['a'] = 1 >> but how can I empty the whole dictionary? >> >> Thank you. >> > > just point myDict to an empty dictionary again > > myDict={} This is wrong and not answering the question. Creating a new dict does not change the dict. He wants to clear *this* dict, and maybe he cannot know how many other objects are referring to this dict. cheers -- chris ------------------------------------------------------------------ """pointless questions or useless answers - what do you like more""" From jjl at pobox.com Sat Mar 10 19:03:19 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 11 Mar 2007 00:03:19 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again References: <45eab67a@news.vo.lu> <3hDGh.5963$jx3.2552@newssvr25.news.prodigy.net> Message-ID: <87mz2kzlx0.fsf@pobox.com> John Nagle writes: [...] > Perl, PHP, C, C++, and Java don't have this particular > problem. Python stands alone, out in the cold. [...] I guess different people's experiences differ. I remember trying to install Java on a FreeBSD server a few years back. I recall no single software installation that has caused me anywhere near such pain as that one :-) Of course, FreeBSD is a minority thing compared with RedHat. John From bj_666 at gmx.net Wed Mar 21 05:42:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 21 Mar 2007 10:42:23 +0100 Subject: How to set SA_RESTART flag in Python References: Message-ID: In , Marco wrote: > I want to set SA_RESTART flag to restart a system-call. How to do > this in Python? You question seems to lack a little bit context. Are you talking about system calls into the Linux kernel? Ciao, Marc 'BlackJack' Rintsch From gabriel.hase at gmail.com Wed Mar 21 09:03:42 2007 From: gabriel.hase at gmail.com (killkolor) Date: 21 Mar 2007 06:03:42 -0700 Subject: replace illegal xml characters In-Reply-To: References: <1174464899.057656.177410@d57g2000hsg.googlegroups.com> Message-ID: <1174482222.951043.27070@y80g2000hsf.googlegroups.com> > Does InDesign export broken XML documents? What exactly is your problem? yes, unfortunately it does. it uses all possible unicode characters, though not all are alowed in valid xml (see link in the first post). in any way for my application i should be checking if the xml that comes in is valid and replace all non-valid characters. is there something out there to do this? From shawn.mcgrath at gmail.com Mon Mar 19 12:00:47 2007 From: shawn.mcgrath at gmail.com (Shawn McGrath) Date: 19 Mar 2007 09:00:47 -0700 Subject: Boost Python properties/getter functions for strings In-Reply-To: <1174312916.127830.303550@o5g2000hsb.googlegroups.com> References: <1174312916.127830.303550@o5g2000hsb.googlegroups.com> Message-ID: <1174320047.732767.101930@e65g2000hsc.googlegroups.com> I forgot to mention, getname is defined as: const std::string &Entity::getName() const; From python at rcn.com Sat Mar 10 03:39:44 2007 From: python at rcn.com (Raymond Hettinger) Date: 10 Mar 2007 00:39:44 -0800 Subject: number generator In-Reply-To: References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> Message-ID: <1173515984.515050.27400@n33g2000cwc.googlegroups.com> On Mar 9, 7:32 am, Marc 'BlackJack' Rintsch wrote: > In <1173453432.893222.308... at j27g2000cwj.googlegroups.com>, cesco wrote: > > Given two positive integers, N and M with N < M, I have to generate N > > positive integers such that sum(N)=M. No more constraints. > > Break it into subproblems. Generate a random number X from a suitable > range and you are left with one number, and the problem to generate (N-1) > random numbers that add up to (M-X). This approach skews the probabilities. The OP said for example with N=5 and M=50 that a possible solution is [3, 11, 7, 22, 7]. You're approach biases the probabilities toward solutions that have a large entry in the first position. To make the solutions equi-probable, a simple approach is to recursively enumerate all possibilities and then choose one of them with random.choice(). Raymond From inq1ltd at verizon.net Thu Mar 22 16:37:15 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Thu, 22 Mar 2007 16:37:15 -0400 Subject: What is the best way to upgrade python? In-Reply-To: References: <1173388393.052558.69270@s48g2000cws.googlegroups.com> Message-ID: <200703221637.15574.inq1ltd@verizon.net> On Thursday 22 March 2007 15:18, Facundo Batista wrote: > yinglcs at gmail.com wrote: > > i am using red hat enterprise 4. It has > > python 2.3 installed. What is the best way to > > upgrade to python 2.4? > > > > I think one way is to compile python 2.4 from > > the source, but I can't remove the old one > > since when i do 'rpm -e python', i get error > > like 'failed dependencies'. > > Install Py2.4 and actually start using it, are > two different animals. > > For example, I have installed Py2.4 and Py2.5 > in my laptop. They coexist, and there's no > problem about this. > > Telling all your installed applications to use > the newer, it's not so easy, mainly because you > don't have the power to test and change every > installed application. > > So let them be. Just install the new version, > and use it. > > Regards, > > -- > . Facundo > . > Blog: http://www.taniquetil.com.ar/plog/ > PyAr: http://www.python.org/ar/ I recently installed py 2.5 and I used the local user option. Now I build programs on 2.5 but I left the system with the original 2.4? since it worked just fine. Look in the instructions on how to build for local users and you 'll save yourself from encountering the unexpected. jim-on-linux http://www.inqvista.com From martinunsal at gmail.com Tue Mar 6 13:30:03 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 6 Mar 2007 10:30:03 -0800 Subject: Project organization and import In-Reply-To: References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> <45ec8f2c$0$29110$426a34cc@news.free.fr> <1173199320.094675.58350@p10g2000cwp.googlegroups.com> <1173201871.742845.84040@t69g2000cwt.googlegroups.com> Message-ID: <1173205801.346941.201060@8g2000cwh.googlegroups.com> On Mar 6, 9:34 am, "Chris Mellon" wrote: > It assumes that util.common is a module thats on the PYTHONPATH. Now we're getting somewhere. :) > The common way to ensure that this is the case is either to handle > util as a separate project, and install it into the system > site-packages just as you would any third party package, This breaks if you ever need to test more than one branch of the same code base. I use a release branch and a development branch. Only the release branch goes into site-packages, but obviously I do most of my work in the development branch. > or to have it > (and all your other application packages and modules) off a single > root which is where your your application "base" scripts live. This has SERIOUS scaling problems. > This, and other intra-package import issues are affected by the > relative/absolute import changes that were begun in Python 2.5, you > can read about them here:http://www.python.org/dev/peps/pep-0328/ Awesome! Thanks. I'll take a look. > Note that using relative imports to import a package that "happens" to > be share a common higher level directory would be frowned upon. What if it shares a common higher level directory by design? :) Relative imports aren't ideal, but I think in some cases it's better than relying on PYTHONPATH which is global state (an environment variable no less). Martin From paul at subsignal.org Fri Mar 16 10:51:32 2007 From: paul at subsignal.org (paul) Date: Fri, 16 Mar 2007 15:51:32 +0100 Subject: Mastering Python In-Reply-To: <1174052358.486071.163280@e65g2000hsc.googlegroups.com> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1174052358.486071.163280@e65g2000hsc.googlegroups.com> Message-ID: Paul McGuire schrieb: > What does Python have that C++ doesn't? > - The biggie: dynamic typing (sometimes called "duck typing"). > Dynamic typing is a huge simplifier for development: > . no variable declarations > . no method type signatures > . no interface definitions needed > . no templating for collections > . no method overloading by differing argument type signatures > ("Imagine there's no data types - I wonder if you can..."). What? No > static type-checking at compile time? Nope, not really. If your > method expects an object of type X, use it like an X. If it's not an > X, you may be surprised how often this is not a problem. But sometimes it is ;) Typical example: input and CGI/whatever. If one element is checked you'll get a string, if you select multiple (i.e. checkboxes) you'll get a list. Both support iteration Now if you iterate over the result: case 1, input -> "value1": for elem in input: #in real life we might validate here... print elem -> 'v' 'a' 'l' 'u' 'e' '1' case 2, input -> ["value1", "value2"] for elem in input: print elem -> "value1" "value2" cheers Paul Disclaimer: I like python and I write tests but i wish unittest had class/module level setUp()... From hitesh287 at gmail.com Mon Mar 5 11:45:25 2007 From: hitesh287 at gmail.com (Hitesh) Date: 5 Mar 2007 08:45:25 -0800 Subject: MS SQL Database connection In-Reply-To: References: <1173047639.166841.301030@h3g2000cwc.googlegroups.com> Message-ID: <1173113121.556667.81190@t69g2000cwt.googlegroups.com> On Mar 5, 4:44 am, Tim Golden wrote: > Hitesh wrote: > > Hi currently I am using DNS and ODBC to connect to MS SQL database. > > Is there any other non-dns way to connect? If I want to run my script > > from different server I first have to create the DNS in win2k3. > > Here are several ways to connect to an MSSQL database w/o > having to create "DNS" or anything else in win2k3 ;) > > There are other ways (the slightly stale MSSQL module > from Object Craft, for example, which still works fine > for Python <= 2.3). > > TJG > > > def adodbapi_connection (server, database, username, password): > # > #http://adodbapi.sf.net > # > import adodbapi > connectors = ["Provider=SQLOLEDB"] > connectors.append ("Data Source=%s" % server) > connectors.append ("Initial Catalog=%s" % database) > if username: > connectors.append ("User Id=%s" % username) > connectors.append ("Password=%s" % password) > else: > connectors.append("Integrated Security=SSPI") > return adodbapi.connect (";".join (connectors)) > > def pymssql_connection (server, database, username, password): > # > #http://pymssql.sf.net > # > import pymssql > if not username: > raise RuntimeError, "Unable to use NT authentication for pymssql" > return pymssql.connect (user=username, password=password, > host=server, database=database) > > def pyodbc_connection (server, database, username, password): > # > #http://pyodbc.sf.net > # > import pyodbc > connectors = ["Driver={SQL Server}"] > connectors.append ("Server=%s" % server) > connectors.append ("Database=%s" % database) > if username: > connectors.append ("UID=%s" % username) > connectors.append ("PWD=%s" % password) > else: > connectors.append ("TrustedConnection=Yes") > return pyodbc.connect (";".join (connectors)) > > Thank you. And I yes I meant DSN not DNS (my mistake, thank you for catching it ;) hj From jjl at pobox.com Fri Mar 30 20:11:24 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 31 Mar 2007 00:11:24 GMT Subject: very strange syntax errors References: Message-ID: <87mz1ui85v.fsf@pobox.com> hg writes: > Hi, > > I'v been facing some very strange errors lately: > > one example: > > def __init__(self): > .... > import my_info > some_text = my_info.T_SOME_TEXT > ^ syntax error > > > I manage to get rid of that one by moving the import on top of my file. > > Note: Python 2.4.1 under Windows > > > Any clue ? Do you have an encoding declaration in that file? IIRC 2.4.1 gave spurious syntax errors in some cases with files having coding declarations. John From sturlamolden at yahoo.no Thu Mar 15 18:29:37 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 15 Mar 2007 15:29:37 -0700 Subject: what are Python equivalent to MATLAB persistent or C++ static? In-Reply-To: <1173942572.130747.228410@l77g2000hsb.googlegroups.com> References: <1173942572.130747.228410@l77g2000hsb.googlegroups.com> Message-ID: <1173997776.913948.272270@n76g2000hsh.googlegroups.com> On Mar 15, 8:09 am, "dmitrey" wrote: > Thank you in advance, > Dmitrey First, "static" can mean at least three different things in C++: static int myvar1; void foobar() { static int myvar2; } class foobar { static int myvar3; } I assume you are thinking about the second case above - a static variable inside a function. You can achieve this by binding an attribute to the function, use a closure, or declare a class callable. def foobar1(): if not 'mystatic' in dir(foobar): foobar.mystatic = 0 foobar.mystatic += 1 return foobar.mystatic def foobar2(): mystatic = 0 def closure(): mystatic += 1 return mystatic return closure class foobar3: mystatic = 0 def __call__(): foobar.mystatic += 1 return foobar.mystatic Usage: for i in xrange(0,10): print foobar1() myclosure = foobar2() for i in xrange(0,10): print myclosure() myfoobar3 = foobar3() for i in xrange(0,10): print myfoobar3() From DustanGroups at gmail.com Sat Mar 17 12:31:01 2007 From: DustanGroups at gmail.com (Dustan) Date: 17 Mar 2007 09:31:01 -0700 Subject: Private data Message-ID: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> http://dustangroups.googlepages.com/privateattributesinpython This is something that I just threw together this morning, after a eureka moment. It's a way of creating private class attributes and static function variables (I'm not 100% sure if that's the correct terminology, but you get what I mean). I haven't tried to create private instance attributes, mainly because it would just be too difficult, and it would be awful syntax. I'm not considering actually using this, but I do have a couple questions about it. 1. Has anyone else ever come up with something like this? I can't imagine I'm the only person who's ever thought of this. 2. Is it possible to hack into something like this? ie, would it be possible to see and change these variables from client code (assuming the data manager has been properly removed from sight, as shown on the last line of class block TestPrivateClassAttributes)? To avoid utter confusion, you may want to look at TestPrivateClassAttributes before looking at the actual implementation of PrivateDataEngine. If you're still confused, feel free to ask what's going on here (and I'm open to suggestions on how to make it clearer). From sjdevnull at yahoo.com Thu Mar 15 12:47:19 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 Mar 2007 09:47:19 -0700 Subject: what are Python equivalent to MATLAB persistent or C++ static? In-Reply-To: References: <1173942572.130747.228410@l77g2000hsb.googlegroups.com> Message-ID: <1173977239.736622.46800@y80g2000hsf.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1173942572.130747.228410 at l77g2000hsb.googlegroups.com>, dmitrey wrote: > > > Thank you in advance, > > For what? Hint: Don't "hide" the question in the subject line. > > I don't know MATLAB's `persistent` but I know that ``static`` in C++ can > be used in different places with different meanings. > > It seems you are asking questions how to translate some constructs from > other languages 1:1 into Python. Without context this may lead you to > programming some other language in Python, resulting in fighting the > language because you don't use "pythonic" idioms to solve your problems. > > C++-static function's names on module level should start with an > underscore: > > def _i_am_not_meant_to_be_public(): > pass > > It's a naming convention for things that are considered internal. > > C++-static class members are class attributes in Python: > > class Spam(object): > i_am_a_class_attribute = 42 > > def __init__(self): > self.i_am_an_instance_attribute = 'Viking' > > And C++static local variables don't exist in Python. There are ways to > emulate them with mutable default arguments, but that's at least > debatable. Use a class instead. If you must, function attributes emulate static: def myfunc(): myfunc.foo += 1 return myfunc.foo myfunc.foo=0 #initialize the value near the function definition >>> print myfunc() 1 >>> print myfunc() 2 etc But it's usually a bad idea to use this. function attributes are better reserved for information about the function itself (similar to docstrings). From aspineux at gmail.com Sun Mar 18 08:40:40 2007 From: aspineux at gmail.com (aspineux) Date: 18 Mar 2007 05:40:40 -0700 Subject: Automagically log changes in table In-Reply-To: <1174188025.545923.272900@l77g2000hsb.googlegroups.com> References: <1174164187.257094.236020@l75g2000hse.googlegroups.com> <1174175976.156270.65830@e1g2000hsg.googlegroups.com> <1174188025.545923.272900@l77g2000hsb.googlegroups.com> Message-ID: <1174221640.893852.240810@l75g2000hse.googlegroups.com> On 18 mar, 04:20, "George Sakkis" wrote: > On Mar 17, 7:59 pm, "aspineux" wrote: > > > Hi > > > You can get this using "triggers" and "stored procedures". > > These are SQL engine dependent! This is available for long time with > > postgress and only from version 5 with mysql. > > This let you write SQL code (Procedure) that will be called when > > "trigged" by an event like inserting new row, updating rows, > > deleting .... > > I'd rather avoid triggers since I may have to deal with Mysql 4. Apart > from that, how can a trigger know the current user ? Because each user opening an web session will login to the SQL database using it's own login. That way you will be able to manage security at DB too. And the trigger will use the userid of the SQL session. > This information > is part of the context (e.g. an http request), not stored persistently > somewhere. It should be doable at the framework/orm level but I'm > rather green on Turbogears/SQLAlchemy. > > George Maybe it will be easier to manage this in your web application. it's not too dificulte to replace any UPDATE persone SET name = %{new_name}s WHERE persone_id=%{personeid} by something like UPDATE persone SET name = %{new_name}s, modified_by=%{user_id}s, modified_time=% {now}s WHERE persone_id=%{personeid} BR From kadarlakiran at yahoo.com Thu Mar 22 01:21:19 2007 From: kadarlakiran at yahoo.com (kadarla kiran kumar) Date: Wed, 21 Mar 2007 22:21:19 -0700 (PDT) Subject: copying only recent files from one machine to another Message-ID: <794394.60913.qm@web38815.mail.mud.yahoo.com> Hi Everybody, Iam trying to copy files from one machine to another over SFTP connection. For that Iam using sftp.get & sftp.put methods. Now, I have to copy only recently created/modified files,i.e, based on timestamps from remote machine to my machine. Is there any standard implementation for that in python/paramiko ? If not , can anyone suggest me the efficient method to implement the same. Thanks in Advance, Kiran Kumar --------------------------------- No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Mar 28 18:51:58 2007 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2007 15:51:58 -0700 Subject: how can I clear a dictionary in python References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> Message-ID: In article <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d at comcast.com>, Larry Bates wrote: >Marko.Cain.23 at gmail.com wrote: >> >> I create a dictionary like this >> myDict = {} >> >> and I add entry like this: >> myDict['a'] = 1 >> but how can I empty the whole dictionary? > >just point myDict to an empty dictionary again > >myDict={} Go back and read Christian's post, then post a followup explaning why his solution is better than yours. Your explanation should use id(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From marco at waven.com Tue Mar 13 00:18:38 2007 From: marco at waven.com (Marco) Date: Tue, 13 Mar 2007 12:18:38 +0800 Subject: how to set different TCP_KEEPALIVE parameters for different socket ? In-Reply-To: <5c62a320703122058s5a333e41h3b810241841beab3@mail.gmail.com> References: <5c62a320703122058s5a333e41h3b810241841beab3@mail.gmail.com> Message-ID: <5c62a320703122118w75b77e89m8004ef2ab57e9e73@mail.gmail.com> Oh, I see, sd.getsockopt(SOL_TCP, TCP_*) On 3/13/07, Marco wrote: > Hi, > > I can use sd.setsockopt() to enable the socket use TCP keepalive > feature, but how to set a different parameters(interval, probes and > time) for it? > Sure, I can modify /proc/sys/net/ipv4/tcp_* , but need root password > and will affect other program. > > Thank you! > > > -- > LinuX Power > -- LinuX Power From kyosohma at gmail.com Mon Mar 26 12:17:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 09:17:35 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> Message-ID: <1174925855.552135.228190@n59g2000hsh.googlegroups.com> On Mar 26, 10:51 am, "jp" wrote: > I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > I skip over these widgets when using the tab key? > > Thank you, > John I would probably write some custom event handling. Something that could tell it was a key-press event and not just an on-focus event. Then it would be a simple, if key-press == tab, put focus on next widget of interest. Something like that should work. Mike From steve at REMOVE.THIS.cybersource.com.au Wed Mar 21 12:23:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 03:23:55 +1100 Subject: Technical Answer - Protecting code in python References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> Message-ID: On Wed, 21 Mar 2007 06:36:16 -0700, flit wrote: > 1 - There is a way to make some program in python and protects it? I > am not talking about ultra hard-core protection, just a simple one > that will stop 90% script kiddies. Protect it from what? Viruses? Terrorists? The corrupt government? Your ex-wife cutting it up with scissors? People who want to copy it? People who will look at your code and laugh at you for being a bad programmer? Until you tell us what you are trying to protect against, your question is meaningless. Is your program valuable? Is it worth money? Then the 90% of script kiddies will just wait three days, and download the program off the Internet after the real hackers have broken your protection. If it is NOT valuable, then why on earth do you think people will put up with whatever "protection" you use? Why won't they just use another program? > 2 - If I put the code in web like a web service, how can I protect my > code from being ripped? There is a way to avoid someone using my site > and ripping the .py files? Don't make the .py files available on the web server. [penny drops] Hang on, you want us to believe that you're a serious computer programmer with a seriously valuable program that's worth "protecting", and you don't know that? I smell a troll. -- Steven. From cpblPublic at gmail.com Thu Mar 8 00:09:40 2007 From: cpblPublic at gmail.com (C Barr Leigh) Date: 7 Mar 2007 21:09:40 -0800 Subject: Bug in python!? persistent value of an optional parameter in function! In-Reply-To: <7xejo0bbpe.fsf@ruckus.brouhaha.com> References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> <7xfy8gqwof.fsf@ruckus.brouhaha.com> <7xejo0bbpe.fsf@ruckus.brouhaha.com> Message-ID: <1173330580.407435.288390@64g2000cwx.googlegroups.com> Oh, oops! Of course... :) A great and sensible feature if you're expecting it. Thanks very much, everyone, for the links and discussion! Chris From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 1 04:44:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 01 Mar 2007 10:44:48 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> <1172741018.978417.233160@v33g2000cwv.googlegroups.com> Message-ID: <54nlkgF21ft8aU3@mid.individual.net> Michele Simionato wrote: > On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch >> In <54msaoF21c6h... at mid.individual.net>, Bjoern Schliessmann >>> But what's it (__name__) good for? >> >> As objects don't know to which name they are bound, that's a good >> way to give some information in stack traces or when doing >> introspection. > > Also, the name is used by pickle to find the class of pickled > instances. Mh. I suspect there's also more to it than I see now, but this __name__ seems quite useless to me. What if I rebind the class' name after definition? Or is it really just for some manual introspection? If it is, it seems a bit of an overkill to me. >>> class Spam(object): ... pass ... >>> Ham = Spam >>> Spam = 0 >>> test = Ham() >>> test.__class__ >>> test.__class__.__name__ 'Spam' >>> Spam 0 >>> Regards, Bj?rn -- BOFH excuse #137: User was distributing pornography on server; system seized by FBI. From aleax at mac.com Sat Mar 3 11:23:53 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Mar 2007 08:23:53 -0800 Subject: print a ... z, A ... Z, "\n"' in Python References: Message-ID: <1hue4db.1ifwnsjmhm2pN%aleax@mac.com> js wrote: > HI guys, > > How do you write Perl's > > print a ... z, A ... Z, "\n"' in Python > > In Python? This specific one is easy, though this doesn't generalize: import string print string.lowercase + string.uppercase For the general case, there's no way to avoid calling chr and ord, because a string in Python doesn't have a "natural successor". So the only issue is how you prefer to hide those calls &c (in some class or function) and you already received suggestions on that. Alex From gagsl-py2 at yahoo.com.ar Thu Mar 15 16:14:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Mar 2007 17:14:19 -0300 Subject: Circular Class Logic References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> <1173921593.166607.240390@e65g2000hsc.googlegroups.com> <1173960067.782597.96840@e1g2000hsg.googlegroups.com> Message-ID: En Thu, 15 Mar 2007 09:01:07 -0300, escribi?: > I got it to work, but I had to add a check to see if the class > variable had been set.. > class Foo: > baz = None > def __init__(self): > if Foo.baz == None: > Foo.baz = True > initBaz() This is a different approach. You are using instance initialization (Foo.__init__) to finish class initialization. Foo.__init__ will be called each time you create a Foo instance; that's why you had to check if Foo.baz is None. (BTW, Foo.baz=True is unneeded). The only problem I can see is that the Foo class is not completely initialized until its first instance is created; this may not be a problem in your case. > What exactly is being accomplished by having the init function outside > of the class? If there is no check, wouldn't it just execute every > time an object is instantiated anyway? What I intended was different: ========== C:\TEMP>type foo.py class Foo: baz = None def __init__(self): pass def initFoo(): import baz Foo.baz = baz.Baz() initFoo() C:\TEMP>type bar.py import foo class Bar(foo.Foo): pass C:\TEMP>type baz.py import bar class Baz(bar.Bar): pass C:\TEMP>type test.py import foo,bar,baz print foo.Foo.baz f = foo.Foo() print f.baz b = bar.Bar() print b.baz print baz.Baz.baz C:\TEMP>python test.py ========== initFoo is only executed when Foo is imported the first time. Note that you can't do that if > I thought it was a good design, but now I'm not so sure. I'm > untrained, so often I dont know the right way to do things. As I > build this into the libraries, I'll keep an eye on how the code is > developing and go from there. Thanks for the help! Usually Python code is quite concise and straightforward; when I find myself writing things too convoluted, I know it's time to refactor/redesign. (Anyway some things remain not as simple as I'd like :( ) Perhaps you later find the need for a different/better way. -- Gabriel Genellina From claird at lairds.us Mon Mar 26 11:33:44 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 26 Mar 2007 15:33:44 +0000 Subject: call to function by text variable References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: In article , Steve Holden wrote: >Cameron Laird wrote: >> In article , >> Jan Schilleman wrote: >>> Hi, >>> >>> try this: >>> func = getattr(operations, ["Replace", "ChangeCase", "Move"][n]) >>> >>> HTH, >>> Jan >>> >>> "ianar?" schreef in bericht >>> news:1174862186.134912.117270 at p15g2000hsd.googlegroups.com... >>>> yeah the subject doesn't really make sense does it? >>>> >>>> anyway want I want to do is this: >>>> if n == 1: >>>> >>>> self.operations.insert(pos, operations.Replace.Panel(self, main)) >> . >> . >> . >> I think you meant "...[n - 1]" rather than "...[n]". >> >> I'm a tiny bit surprised no one has organized this in terms >> of a dictionary. I don't know, of course, how robust is the >> characterization of n as a small integer. Maybe >> >> lookup_table = { >> 0: "Replace", >> 1: "ChangeCase", >> 2: "Move"} >> >> captures the sentiment; maybe something else does it better. >> >Surely for this requirement the *only* advantage of a dictionary over a >list is its ability to index with arbitrary values and thereby avoid the >need to use [n-1]. Wouldn't it therefore be less perverse to use > > lookup_table = { > 1: "Replace", > 2: "ChangeCase", > 3: "Move"} > >Of course the dictionary would be a big win if the integer choice values >weren't a linear sequence. Otherwise using a list with a fixed offset is >likely to be quicker. . . . Ugh. Yes. Maybe your question, "Wouldn't it therefore be less perverse ...?", was rhetorical. I feel obliged to answer in public, though, rather than sending the private e-mail I originally wrote, because I want to leave no doubt in the minds of readers of this thread: what I wrote was wrong. Yes, Steve's lookup_table binding (or assignment) was what I had in mind all along, and entirely superior to what I mistakenly wrote; my thanks to him. He also elaborated the correct detail: "if the integer choice values weren't a linear sequence", or if they weren't even integers, or ..., then the dictionary suddenly becomes much more compelling. Incidentally, a fair amount of Python code that looks like if n == 1: ... elif n == 2: ... turns out, in my experience, to have been inherited from some other language in such a way that it turns out n is not even the most natural or expressive determinant. A fully idiomatic rewriting will have a table where the keys are more-humanly-readable strings, rather than small integers. From bh at intevation.de Fri Mar 2 12:31:43 2007 From: bh at intevation.de (Bernhard Herzog) Date: Fri, 02 Mar 2007 18:31:43 +0100 Subject: Dialog with a process via subprocess.Popen blocks forever References: <1172698063.670659.318340@k78g2000cwa.googlegroups.com> <1172770920.052040.33990@h3g2000cwc.googlegroups.com> Message-ID: bayer.justin at googlemail.com writes: > So, once I start the C Program from the shell, I immediately get its > output in my terminal. If I start it from a subprocess in python and > use python's sys.stdin/sys.stdout as the subprocess' stdout/stdin I > also get it immediately. If stdout is connected to a terminal, it's usually line buffered, so the buffer is flushed whenever a newline is written. > BUT If I use PIPE for both (so I can .write() on the stdin and .read() > from the subprocess' stdout stream (better: file descriptor)) reading > from the subprocess stdout blocks forever. If I write something onto > the subprocess' stdin that causes it to somehow proceed, I can read > from its stdout. When stdout is not connected to a terminal, it's usually fully buffered, so that nothing is actually written to the file until the buffer overflows or until it's explictly flushed. If you can modify the C program, you could force its stdout stream to be line buffered. Alternatively, you could call fflush on stdout whenever you're about to read from stdin. If you can't modify the C program you may have to resort to e.g. pseudo ttys to trick it into believing that its stdout is a terminal. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From nagle at animats.com Thu Mar 15 20:12:46 2007 From: nagle at animats.com (John Nagle) Date: Thu, 15 Mar 2007 17:12:46 -0700 Subject: "urlopen" not thread safe Message-ID: I was looking at the code for "urllib", and there's some undocumented "FTP cacheing" code in there that's not thread safe. The documentation for "urllib" Is there any good reason to keep that code in "urllib"? Unless something critical uses that undocumented feature, that code probably ought to come out. Comments? John Nagle From jstroud at mbi.ucla.edu Sun Mar 25 08:03:25 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 25 Mar 2007 12:03:25 GMT Subject: Tkinter Toplevel geometry In-Reply-To: <0dtNh.9164$JZ3.2879@newssvr13.news.prodigy.net> References: <1174803181.656189.303200@l77g2000hsb.googlegroups.com> <0dtNh.9164$JZ3.2879@newssvr13.news.prodigy.net> Message-ID: James Stroud wrote: > Chris wrote: >> Hi, >> >> If a user resizes a Toplevel window, or I set a Toplevel's geometry >> using the geometry() method*, is there any way to have the geometry >> reset to that required for all the widgets? >> >> I think I found what I'm looking for in tk itself: >> """ >> 13.3. How can I clear the geometry settings for a toplevel? >> If you want to have Tk resize your toplevel to what the toplevel >> requires (ie: the user might have resized it, or a widget was >> removed), use [wm geometry $toplevel]. >> """ >> [from http://tcl.sourceforge.net/faqs/tk/] >> >> >> >> * for instance, if I want to turn of Tkinter's automatic adjustment of >> the window to fit all the widgets by doing something like >> self.geometry(self.geometry()), is there any way to undo that? >> >> Thanks, >> Chris >> > > Hi Chris, > > I think you are on to something. The equivalent of > > [wm geometry $toplevel] > > in Tkinter would be > > sometop.geometry() > > Or, equivalently, > > sometop.wm_geometry() > > Or, calling the underlying tcl/tk interpreter directly > > sometop.tk.call('wm', 'geometry', str(sometop)) > > Which is redundant, but emphasizes the point: This does not resize the > widget as expected nor does it cause the window to resize upon adding > new packing slaves--at least for the X11 based Tkinter for mac via the > fink debian based package manager. > > Really wish things worked according to the docs a lot of the time or > that they weren't so poorly written. Perhaps they are implying that you > must pass parameters, however they do not explain how one might generate > said parameters to get the required size to which they allude. Terribly > disappointing. > > James After playing with this an inordinate amount of time, I found that one does need to supply parameters, namely the null parameter of an empty string. Try: sometop.geometry('') This repacks according to the widgets. Not quite clear from the miserable docs, is it? James From http Sat Mar 10 21:12:12 2007 From: http (Paul Rubin) Date: 10 Mar 2007 18:12:12 -0800 Subject: How to test if a key in a dictionary exists? References: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> <1173578899.046177.104890@j27g2000cwj.googlegroups.com> Message-ID: <7x6498le9v.fsf@ruckus.brouhaha.com> > if hist.has_key(outcome): > hist[outcome] += 1 # if key already exists, increment > else: > hist[outcome] = 1 # else create a new key You could write that: hist[outcome] = 1 + hist.get(outcome, 0) Or with Python 2.5 you could use hist = defaultdict(int) ... hist[outcome] += 1 # automatically initializes to 0 if outcome not found From steve at REMOVE.THIS.cybersource.com.au Mon Mar 26 19:30:58 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Mar 2007 09:30:58 +1000 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <4607fbf4$1@nntp.zianet.com> <1174929184.645992.61310@y66g2000hsf.googlegroups.com> <1174949636.284743.251680@n59g2000hsh.googlegroups.com> Message-ID: On Mon, 26 Mar 2007 15:53:56 -0700, sturlamolden wrote: > Python is a very high-level language. That means there are certain > things that put constraint on the attained speed. Most importantly: > keep the number of interpreter evals as scarce as possible. If you > make a for loop, the interpreter may evaluate the lines within the > loop several times. Languages like C, C++ and Java really teach you > bad habits when it comes to an interpreted language like Python. In > these languages, loops are almost free. In Python, they may be very > expensive as the interpreter is invoked multiple times. Jeez-Louise, this is why my blood boils when I read ignora^H^H^H^H misguided people referring to Python as "interpreted": it leads other people to imagine that Python is interpreting lines over and over and over again. Is the interpreter invoked multiple times in a for loop? Let's find out. Here is a function with a for loop: def looper(): x = 1 for i in range(1000000): print x x += i return x Let's look at the compiled code: >>> dis.dis(looper) 2 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (x) 3 6 SETUP_LOOP 35 (to 44) 9 LOAD_GLOBAL 0 (range) 12 LOAD_CONST 2 (1000000) 15 CALL_FUNCTION 1 18 GET_ITER >> 19 FOR_ITER 21 (to 43) 22 STORE_FAST 1 (i) 4 25 LOAD_FAST 0 (x) 28 PRINT_ITEM 29 PRINT_NEWLINE 5 30 LOAD_FAST 0 (x) 33 LOAD_FAST 1 (i) 36 INPLACE_ADD 37 STORE_FAST 0 (x) 40 JUMP_ABSOLUTE 19 >> 43 POP_BLOCK 6 >> 44 LOAD_FAST 0 (x) 47 RETURN_VALUE Certainly Python isn't interpreting the lines in the for loop one million times. It interprets them once, compiles them once, and executes them one million times. > But if you can > 'vectorize' the loop statement into a one-liner (or a few lines) using > slicing, list comprehensions or functional programming (e.g. the > lambda, map and filter intrinsics), the overhead will be very small. This is generally good advice because it moves the loop from moderately fast Python code to very fast C code, not because Python is interpreting each line over and over again. -- Steven. From gagsl-py2 at yahoo.com.ar Tue Mar 13 17:31:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Mar 2007 18:31:10 -0300 Subject: Iterating across a filtered list References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <1173813714.767225.164790@q40g2000cwq.googlegroups.com> <7xird5ndey.fsf@ruckus.brouhaha.com> <1173817193.179354.235790@p15g2000hsd.googlegroups.com> Message-ID: En Tue, 13 Mar 2007 17:19:53 -0300, Arnaud Delobelle escribi?: > On Mar 13, 7:36 pm, Paul Rubin wrote: >> >> The re library caches the compiled regexp, I think. > > That would surprise me. > How can re.search know that string.lower(search) is the same each > time? Or else there is something that I misunderstand. It does. py> import re py> x = re.compile("ijk") py> y = re.compile("ijk") py> x is y True Both, separate calls, returned identical results. You can show the cache: py> re._cache {(, '%(?:\\((?P.*?)\\))?(?P[-#0-9 +*.hlL]*?)[eEfFgGd iouxXcrs%]', 0): <_sre.SRE_Pattern object at 0x00A786A0>, (, 'ijk', 0): <_sre.SRE_Pattern object at 0x00ABB338>} -- Gabriel Genellina From nagle at animats.com Fri Mar 30 18:38:40 2007 From: nagle at animats.com (John Nagle) Date: Fri, 30 Mar 2007 15:38:40 -0700 Subject: Cheeseshop needs mirrors In-Reply-To: <460d874b$0$5746$afc38c87@news.optusnet.com.au> References: <1175238342.963086.234370@e65g2000hsc.googlegroups.com> <1175249588.897793.24450@o5g2000hsb.googlegroups.com> <460d874b$0$5746$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones wrote: > And of course I'll reiterate the same line I always do: the Cheese Shop was > set up by a volunteer, enhanced by some other volunteers and exactly > nothing more will get done unless more volunteers offer their time. Yup. That's why CPAN is so much better. Ook! John Nagle From lbates at websafe.com Thu Mar 29 09:16:26 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 29 Mar 2007 08:16:26 -0500 Subject: how can I clear a dictionary in python In-Reply-To: References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> Message-ID: Aahz wrote: > In article <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d at comcast.com>, > Larry Bates wrote: >> Marko.Cain.23 at gmail.com wrote: >>> I create a dictionary like this >>> myDict = {} >>> >>> and I add entry like this: >>> myDict['a'] = 1 >>> but how can I empty the whole dictionary? >> just point myDict to an empty dictionary again >> >> myDict={} > > Go back and read Christian's post, then post a followup explaning why his > solution is better than yours. Your explanation should use id(). I believe he (as many new to Python do) are mired in old programming thinking that variables "contain" things. As I'm sure you kno, variables point to things in Python. I don't believe that there are lots of other objects pointing to this dictionary. Perhaps the OP can clarify for us. If there aren't other objects pointing to this dictionary it would make NO sense to iterate over a dictionary and delete all the keys/values so I tried to read between the lines and answer what I believe the OP thought he was asking. BTW-I didn't see you posting an answer to what you thought was the "correct" question, just criticizing me for taking the time to answer what I perceived the OP was asking. -Larry From durumdara at gmail.com Fri Mar 30 04:14:37 2007 From: durumdara at gmail.com (Durumdara) Date: Fri, 30 Mar 2007 10:14:37 +0200 Subject: Is any way to split zip archive to sections? Message-ID: <9e384ef60703300114p534ec835wa707ce2292e1dfbb@mail.gmail.com> Hi! I want to create some backup archives with python (I want to write a backup application in Python). Some package managers (7z, arj, winzip) can create splitted archives (1 mega, 650, 700 mega, etc). Because I want to ftp these results to a ftp server, I want to split large volumes to 15 mb sections. Can I do it with any python wrapper automatically (like in Cobian), or I need to create the large volume, and next split it with another tool? Or anybody knows about a command line tool (like 7z, or arj) that can expand the splitted archive (and I can add files with them from Python one by one)? So what is the solution? Thanks for your help: dd -------------- next part -------------- An HTML attachment was scrubbed... URL: From irstas at gmail.com Sun Mar 25 05:00:27 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 25 Mar 2007 02:00:27 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: <1174803233.118069.234290@l75g2000hse.googlegroups.com> References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> Message-ID: <1174813227.275145.211000@o5g2000hsb.googlegroups.com> On Mar 25, 9:13 am, "7stud" wrote: > MyClass.someFunc > > Is there some other way to retrieve a user-defined function object > from a class other than using the class name or an instance? What Steven B. already said, MyClass.__dict__['someFunc'], is a different way than MyClass.someFunc that produces different results. Since the method is an attribute of a class, what other kinds of means are you expecting to be possible? You can use reflection to dig up MyClass-object from the module dictionary if referring to object or class by name in the code is something you want to get rid of. From skip at pobox.com Fri Mar 16 09:00:12 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 16 Mar 2007 08:00:12 -0500 Subject: CSV module and "fileobj" In-Reply-To: <1174042670.829441.286490@n59g2000hsh.googlegroups.com> References: <1174042670.829441.286490@n59g2000hsh.googlegroups.com> Message-ID: <17914.38108.680389.937374@montanaro.dyndns.org> Jon> If I have a CSV reader that's passed to a function, is it possible Jon> for that function to retrieve a reference to the "fileobj" like Jon> object that was passed to the reader's __init__? Nope, that isn't exposed from the C type. Skip From roland.hedberg at adm.umu.se Sun Mar 25 11:02:07 2007 From: roland.hedberg at adm.umu.se (Roland Hedberg) Date: Sun, 25 Mar 2007 17:02:07 +0200 Subject: Other classes in a module Message-ID: <46068EEF.6070000@adm.umu.se> Hi! Can an instance of a class in a module, in any simple way find out which other classes that exists in said module ? -- Roland From paddy3118 at googlemail.com Sat Mar 31 01:22:37 2007 From: paddy3118 at googlemail.com (Paddy) Date: 30 Mar 2007 22:22:37 -0700 Subject: Modal value of an array In-Reply-To: References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> <877it0u2h4.fsf@benfinney.id.au> <1hvpovd.1anin2by4gjl1N%aleax@mac.com> <1175208296.769865.186480@r56g2000hsd.googlegroups.com> Message-ID: <1175318557.079267.94740@b75g2000hsg.googlegroups.com> On Mar 30, 10:17 pm, "Gabriel Genellina" wrote: > En Thu, 29 Mar 2007 19:44:56 -0300, Paddy > escribi?: > > > On Mar 29, 8:49 am, a... at mac.com (Alex Martelli) wrote: > >> >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >> >>> max(foo, key=foo.count) > > >> 'spam' > > > This doesn't call foo.count for duplicate entries by keeping a cache > > >>>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >>>> def cachecount(x, cache={}): > > ... return cache.setdefault(x, foo.count(x)) > > Unfortunately it does, because all arguments are evaluated *before* a > function call, so you gain nothing. > > -- > Gabriel Genellina I had to experiment to find out what you meant but I finally got it. that call to foo.count in the setdefault is *always* called. Forgive my senility. - Paddy. From jjl at pobox.com Wed Mar 21 18:11:38 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 21 Mar 2007 22:11:38 GMT Subject: When is List Comprehension inappropriate? References: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> <1hv8wz8.19mj0kb1k9m2m8N%aleax@mac.com> Message-ID: <87wt1atffg.fsf@pobox.com> Steve Holden writes: > Alex Martelli wrote: > > BJ?rn Lindqvist wrote: > > ... > >> even2 = [(pos, col) for pos, col in iterimage(im, width, height, 2)] > > list(iterimage(etc etc)) > > is surely a better way to express identical semantics. More > > generally, > > [x for x in whatever] (whether x is a single name or gets peculiarly > > unpacked and repacked like here) is a good example of inappropriate LC, > > to get back to the question in the subject: list(whatever) is the "one > > obvious way" to perform the same task. > > > Clearly the comprehension you complain about is sub-optimal. > > The essential difference, however, is between > > [x for x in iterimage(im, width, height, 2)] > > and > > list(iterimage(im, width, height, 2)) > > I agree that the latter is the obvious way, but the difference isn't > as large as your leap makes it look - and we had to await the > invention of the generator expression for it to be a practical choice. What generator expression? I don't see a genexp in your examples. John From fabiofz at gmail.com Thu Mar 1 06:22:21 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 1 Mar 2007 08:22:21 -0300 Subject: Pydev 1.2.8 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.2.8 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code-analysis: when a compare statement is found out of a test scope, that's reported as a warning * Mark Occurrences: new option to choose whether strings and comments should be highlighted * Simple Completions: some keywords were removed from the default list (the 2-letter ones because they're barely worth it and those related to 'try', as there's already an assistant that creates 'try' blocks) * Rename refactoring / Mark Occurrences: matches in multi-line strings are now correct Release Highlights in Pydev: ---------------------------------------------- * Refactoring: integration of the PEPTIC refactoring engine * Package Explorer: many fixes (special thanks for Don Taylor for the bug reports) * Debugger: a number of small optimizations * Code-completion: works in emacs mode * Code-completion: added the possibility of auto-completing for all letter chars and '_' (so, it starts completing once you start writing) * Code-completion: code-completion for epydoc inside strings * Code-completion: assigns after global statement considered added to the global namespace * Code-completion: now works when a class is declared in a nested scope * Code-completion: if multiple assigns are found to some variable, the completion will be a merge of them * Code-completion: functions are analyzed for their return values for code-completion purposes * Code-completion: working on multi-line imports * Code-completion: can discover instance variables not declared in the class (in the scope where the class was instanced) * Auto-edit: adds 'self', 'cls' or no parameter based on the @clasmethod, @staticmethod declaration on previous line * Auto-edit: doesn't add 'self' if a method is declared in a method inner scope * Fix: BRM Refactoring: wrong column was being passed to the BRM refactoring engine * Code-folding: added for comments and strings * Fix: sometimes the 'create docstring' assistant was not recognizing method definitons What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Mar 8 04:24:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 06:24:30 -0300 Subject: Howto find dict members from a list of keys References: Message-ID: En Thu, 08 Mar 2007 05:37:48 -0300, Steven D'Aprano escribi?: > On Thu, 08 Mar 2007 05:26:22 -0300, Gabriel Genellina wrote: > >> found_dic_members = [d[key] for key in l] > > *self stares at the line of code* > > *self thinks about what he just posted* > > *self realises with acute embarrassment that he's jumped to conclusions > and completely misunderstood the Original Poster's question* > > Oops! I'll just be slinking away now... LOL! :) (...now! But when I saw your previous post, I had to check whether it was *me* who misunderstood the OP answering with a silly one-liner...) -- Gabriel Genellina From bj_666 at gmx.net Mon Mar 19 12:15:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 19 Mar 2007 17:15:18 +0100 Subject: check if files are the same on Windows References: <1174320587.618875.48290@y66g2000hsf.googlegroups.com> Message-ID: In <1174320587.618875.48290 at y66g2000hsf.googlegroups.com>, Beliavsky wrote: > [?] How should one check that files are the same in Python? The files > are plain text. Take a look at the `filecmp` module. Pay attention to the shallow argument of `filecmp.cmp()` and the default value! Ciao, Marc 'BlackJack' Rintsch From lobais at gmail.com Mon Mar 26 11:53:04 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Mon, 26 Mar 2007 17:53:04 +0200 Subject: Kill thread or at least socket.getaddrinfo Message-ID: Hi, I'm writing an application that connects to the internet. Something like this: for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) Now if the user press the cancel button, I'd like the connection to imidiatly stop. I run self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() Dunno if they are both nessesary. I normaly use only the first, but it makes no difference to use both. If python is at the actual connection in socket.socket( this work fine, but if python is at calling socket.getaddrinfo(, it doesn't stop. I also can't kill the thread, as it is afaik not a possibility in python. Is there any other way to do this? From arkanes at gmail.com Tue Mar 6 13:45:31 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 12:45:31 -0600 Subject: Project organization and import In-Reply-To: <1173205801.346941.201060@8g2000cwh.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <1173084337.538171.35530@c51g2000cwc.googlegroups.com> <1173111489.163974.89990@30g2000cwc.googlegroups.com> <45ec8f2c$0$29110$426a34cc@news.free.fr> <1173199320.094675.58350@p10g2000cwp.googlegroups.com> <1173201871.742845.84040@t69g2000cwt.googlegroups.com> <1173205801.346941.201060@8g2000cwh.googlegroups.com> Message-ID: <4866bea60703061045n1ff3ac12rb9f5ef3271ea1a59@mail.gmail.com> On 6 Mar 2007 10:30:03 -0800, Martin Unsal wrote: > On Mar 6, 9:34 am, "Chris Mellon" wrote: > > It assumes that util.common is a module thats on the PYTHONPATH. > > Now we're getting somewhere. :) > > > The common way to ensure that this is the case is either to handle > > util as a separate project, and install it into the system > > site-packages just as you would any third party package, > > This breaks if you ever need to test more than one branch of the same > code base. I use a release branch and a development branch. Only the > release branch goes into site-packages, but obviously I do most of my > work in the development branch. > Theres a number of solutions. They do involve manipulation of PYTHONPATH or creation of infrastructure, though. I find that I generally work "against" only one version of package at a time, so it's not any trouble for me to create a local directory that has all the version I'm working against. Testing infrastructure manipulates PYTHONPATH to ensure it's testing the version its supposed to. > > or to have it > > (and all your other application packages and modules) off a single > > root which is where your your application "base" scripts live. > > This has SERIOUS scaling problems. > If you have lots of modules used by lots of "things" it can be. Not necessarily though, it depends on how you package and deploy them. It's often the best solution to the above issue when it comes to testing, though. > > This, and other intra-package import issues are affected by the > > relative/absolute import changes that were begun in Python 2.5, you > > can read about them here:http://www.python.org/dev/peps/pep-0328/ > > Awesome! Thanks. I'll take a look. > > > Note that using relative imports to import a package that "happens" to > > be share a common higher level directory would be frowned upon. > > What if it shares a common higher level directory by design? :) > Then its a subpackage of a parent package. That's different than just walking up to wherever your did your RCS checkout. > Relative imports aren't ideal, but I think in some cases it's better > than relying on PYTHONPATH which is global state (an environment > variable no less). > Environment and manipulation of it is the job of the top level script/application/whatever. Modules/packages/whatever should rely on PYTHONPATH being sane. > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Tue Mar 27 02:47:26 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 27 Mar 2007 08:47:26 +0200 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: <009301c7703b$c8c0ac00$03000080@hendrik> "Diez B. Roggisch" wrote: > Nick Craig-Wood wrote: > > > Did anyone write a contextmanager implementing a timeout for > > python2.5? > > > > I'd love to be able to write something like > > > > with timeout(5.0) as exceeded: > > some_long_running_stuff() > > if exceeded: > > print "Oops - took too long!" > > > > And have it work reliably and in a cross platform way! > > Cross platform isn't the issue here - reliability though is. To put it > simple: can't be done that way. You could of course add a timer to the > python bytecode core, that would "jump back" to a stored savepoint or > something like that. > > But to make that work reliably, it has to be ensured that no sideeffects > occur while being in some_long_running_stuff. which doesn't only extend to > python itself, but also external modules and systems (file writing, network > communications...). Which can't be done, unless you use a time-machine. > Which I'd take as an personal insult, because in that rolled-back timeframe > I will be possibly proposing to my future wife or something... > how does the timed callback in the Tkinter stuff work - in my experience so far it seems that it does the timed callback quite reliably... probably has to do with the fact that the mainloop runs as a stand alone process, and that you set the timer up when you do the "after" call. so it probably means that to emulate that kind of thing you need a separate "thread" that is in a loop to monitor the timer's expiry, that somehow gains control from the "long running stuff" periodically... so Diez is probably right that the way to go is to put the timer in the python interpreter loop, as its the only thing around that you could more or less trust to run all the time. But then it will not read as nice as Nick's wish, but more like this: id = setup_callback(error_routine, timeout_in_milliseconds) long_running_stuff_that_can_block_on_IO(foo, bar, baz) cancel_callback(id) print "Hooray it worked !! " sys.exit() def error_routine(): print "toughies it took too long - your chocolate is toast" attempt_at_recovery_or_explanation(foo, bar, baz) Much more ugly. But would be useful to be able to do without messing with threads and GUI and imports. Could be hard to implement as the interpreter would have to be assured of getting control back periodically, so a ticker interrupt routine is called for - begins to sound more like a kernel function to me. Isn't there something available that could be got at via ctypes? - Hendrik From bjourne at gmail.com Thu Mar 1 06:15:21 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 1 Mar 2007 12:15:21 +0100 Subject: class declaration shortcut In-Reply-To: <1172699617.628947.118110@m58g2000cwm.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <7o-dndyPgY_db3jYnZ2dnUVZ_t2tnZ2d@comcast.com> <1172699617.628947.118110@m58g2000cwm.googlegroups.com> Message-ID: <740c3aec0703010315g49993d77y90e383ebcec408ab@mail.gmail.com> On 28 Feb 2007 13:53:37 -0800, Luis M. Gonz?lez wrote: > Hmmm... not really. > The code above is supposed to be a shorter way of writing this: > > class Person: > def __init__(self, name, birthday, children): > self.name = name > self.birthday = birthday > self.children = children > > So the purpose of this question is finding a way to emulate this with > a single line and minimal typing. I believe this is what you are looking for: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 olle = attrdict(name = "Olle", birthday = date(2222, 12, 1), children = 329) print olle.name, olle.birthday, olle.children It is not identical to the Ruby recipe, but is IMHO better. Being able to instantiate objects on the fly, without having to explicitly declare the class, is a big advantage. -- mvh Bj?rn From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 19 08:31:25 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 13:31:25 +0100 Subject: Private data In-Reply-To: <1174298781.038887.29330@b75g2000hsg.googlegroups.com> References: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> <45fe5335$0$14570$426a74cc@news.free.fr> <1174298781.038887.29330@b75g2000hsg.googlegroups.com> Message-ID: <45fe829c$0$16064$426a74cc@news.free.fr> Dustan a ?crit : > On Mar 19, 4:09 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Dustan a ?crit : >> >>> http://dustangroups.googlepages.com/privateattributesinpython >>> This is something that I just threw together this morning, after a >>> eureka moment. It's a way of creating private class attributes (snip) >>> 1. Has anyone else ever come up with something like this? I can't >>> imagine I'm the only person who's ever thought of this. >> With something like trying to forcefit access restriction in Python ? >> Nope, you're not the first one here. I've not seen anyone using such a >> thing in any of the projects I've worked on/with yet. > > You ignored certain parts of my post, like "I'm not considering > actually using this, but I do have a couple questions about it"; I > assume that means you're not even going to begin to attempt to answer > my queries. Likewise, you ignored a similar message on the page I > linked to. I already knew about everything you told me. > > With all this active ignoring, I get the feeling you're not even > trying to respond to my questions. So why respond in the first place? > Were you trying to be hostile? > > Because I can't see any other intent > for your post. I didn't missed the "I'm not considering actually using this" part, but I missed the note on the page - and I apologize if you felt offended by my remarks, which were effectivly a bit on the reactive side. Still there was an implied question : *why* trying to implement access restriction in Python ? From steven.potter at gmail.com Mon Mar 12 20:34:11 2007 From: steven.potter at gmail.com (Steve Potter) Date: 12 Mar 2007 17:34:11 -0700 Subject: attaching Tkinter Listbox to python list object Message-ID: <1173746051.180729.97350@h3g2000cwc.googlegroups.com> I am trying to find some method of attaching a Listbox object to a list object so as the contents of the list are changed the contents of the Listbox will be updated to match. I have found a few references to something like this in this old post http://groups.google.com/group/comp.lang.python/browse_thread/thread/3a6fe7534c812f55/43f201ab53cfdbf7 as well as here http://effbot.org/zone/wck-4.htm . It just seems that there should be some way of achieving this. The only this I can think of is create a subclass of list that deletes and then refills the Listbox every time that the list changes, but this seems very in efficient. Any ideas? Steve From john.pye at gmail.com Wed Mar 21 02:35:09 2007 From: john.pye at gmail.com (John Pye) Date: 20 Mar 2007 23:35:09 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> <1174453085.748142.48700@y80g2000hsf.googlegroups.com> Message-ID: <1174458909.732321.101590@n59g2000hsh.googlegroups.com> Gabriel, if you think you can make an example that works, that would be great. I'm afraid I feel a bit out of my depth and don't have much confidence in this idea. JP From mahs at telcopartners.com Fri Mar 16 01:11:40 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 15 Mar 2007 23:11:40 -0600 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> Message-ID: n00m wrote: > http://www.spoj.pl/problems/SUMFOUR/ > > 3 > 0 0 0 0 > 0 0 0 0 > -1 -1 1 1 > Answer for this input data is 33. > > My solution for the problem is > ====================================================================== > > import time > t = time.clock() > > q,w,e,r,sch,h = [],[],[],[],0,{} > > f = open("D:/m4000.txt","rt") > > n = int(f.readline()) > > for o in range(n): > row = map(long, f.readline().split()) > q.append(row[0]) > w.append(row[1]) > e.append(row[2]) > r.append(row[3]) > > f.close() > > for x in q: > for y in w: > if h.has_key(x+y): > h[x+y] += 1 > else: > h[x+y] = 1 > > for x in e: > for y in r: > sch += h.get(-(x+y),0) > > q,w,e,r,h = None,None,None,None,None > > print sch > print time.clock() - t > > =============================================================== > > Alas it gets "time limit exceeded". > On my home PC (1.6 GHz, 512 MB RAM) and for 4000 input rows it > executes ~1.5 min. > Any ideas to speed it up say 10 times? Or the problem only for C-like > langs? > Perhaps a bit faster using slicing to get the lists and avoiding dict.get: def sumfour(src): l = map(int, src.split()) dct={} s=0 A, B, C, D = l[1::4], l[2::4], l[3::4], l[4::4] for a in A: for b in B: if a+b in dct: dct[a+b] += 1 else: dct[a+b] = 1 for c in C: for d in D: if -c-d in dct: s+= dct[-c-d] return s if __name__ == '__main__': import sys print sumfour(sys.stdin.read()) Michael From kyosohma at gmail.com Mon Mar 19 15:04:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Mar 2007 12:04:09 -0700 Subject: Choosing Python In-Reply-To: References: Message-ID: <1174331049.460684.174950@l77g2000hsb.googlegroups.com> On Mar 19, 1:52 pm, "Sells, Fred" wrote: > glad to hear it. Those of us who would like to introduce it in reluctant > schools elsewhere could benefit from a post-semester evaluation, including > student comments and some sample, running projects. > > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.... at python.org > > [mailto:python-list-bounces+frsells=adventistcare.... at python.org]On > Behalf Of adawo... at sbcglobal.net > Sent: Sunday, March 18, 2007 9:22 PM > To: python-l... at python.org > Subject: Choosing Python > > The choice is made. The school where I teach has finally > made its decision to teach Python first. For several years, > we have been teaching Java first, and before that, C++. > > I introduced Python in one of my courses and got a lot of > flak from some of the other faculty. I also introduced Ruby, > and got even more flak. In my course, the students loved > Python for its simplicity, its power, and its flexibility. > > It is clear that Python is not the ultimate, one-size-fits-all > language. No language is. However, for a beginner's > language it is nearly ideal. Further, it is a great language > for a wide range of serious programming problems. > > For large-scale, safety-critical software, I still prefer Eiffel > or Ada. Java could vanish tomorrow and, with Python > and Ruby available, no one would miss Java at all. As for > C++, for any serious software systems, it should always be > the language of last resort. C++, as an object-oriented > assembler, is pretty much its own virus. > > Already, students are turning in really good projects in Python, > and some in Ruby. Not all the professors are on-board with > this decision, but in time I think they will be. > > Richard Riehle > > --http://mail.python.org/mailman/listinfo/python-list What would be really cool is to mix in the whole C/C++ extension paradigm...or IPython/Jython in a second semester class. That way the students could get into more real-world language mixes, which most developers have to deal with. We run COBOL, Python, PHP, and some truly awful VBA here. I wish I could have learned Python to being with, but it would have needed to have been supplemented with some of the other lower-level languages as well. Mike From esj at harvee.org Fri Mar 23 18:34:31 2007 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 23 Mar 2007 18:34:31 -0400 Subject: fine grain logging cotrol In-Reply-To: References: Message-ID: Peter Otten wrote: > Eric S. Johansson wrote: > > Here is yet another revision of my example then: it's making more and more sense although I don't quite follow 'property' quite yet. But I see that get_logger is invoked prior to the __logger.info call. I was looking at how to implement one of my other requirements (conditional based on a predicate) and I see that I could use a filter. I've experimented a little but come up empty. This is what I changed: class filter_test (logging.Filter): test_names = { "Felis.alpha" : True, "Catus.alpha" : False, } def ___init__ (self, name): """simple filter test """ self.name = name def filter(self, record): """test and forget """ return test_names.has_key(self.name) and test_names[self.name] class LoggedType(type): def __new__(mcl, name, bases, classdict): def get_logger(self): tag = "%s.%s" % (name,sys._getframe(1).f_code.co_name) lgr = logging.getLogger(tag) lgr.addFilter(filter_test) return lgr classdict["_%s__logger" % name] = property(get_logger) return type.__new__(mcl, name, bases, classdict) It's probably real obvious but I keep getting a: File "C:\Python24\lib\logging\__init__.py", line 539, in filter if not f.filter(record): TypeError: unbound method filter() must be called with filter_test instance as first argument (got LogRecord instance instead) I'm puzzled that I thought I was adding the filter object at the right point in time with addFilter. I wouldn't be surprised if I was totally off base but I'd be interested in figuring out how I went off the rails so I can fill in the knowledge. ---eric From steven.bethard at gmail.com Fri Mar 16 13:15:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 16 Mar 2007 11:15:39 -0600 Subject: getopt or optparse options/arguments wrapping? In-Reply-To: <1174048469.334735.185750@l77g2000hsb.googlegroups.com> References: <1174048469.334735.185750@l77g2000hsb.googlegroups.com> Message-ID: <_9OdneVkFJIhTWfYnZ2dnUVZ_vWtnZ2d@comcast.com> Rocky Zhou wrote: > I wonder is there any way to make the wrapper program can wrap options > && arguments for the the subprocess/command the wrapper will > execute? by getopt or optparse module? [snip] > I need this because I now have finished a fs_backup script written in > python, it will execute tar && find to complete full and > differentiating/incremental backup for the file system level files, > and their restoring. This script will do different things by the > command line arguments, and execute find/tar in different ways, but > for being more flexible, I want some options of tar/find can also been > specified from the command line directly, and the script just transmit > those to tar/find simply. I'm not clear on exactly what it is you want. Are you trying to do something like:: fs_backup --foo --bar x y z --tar-foo --tar-bar tx ty tz where ``--foo --bar x y z`` gets handled by your command and ``--tar-foo --tar-bar tx ty tz`` gets passed on through to the tar command? STeVe From Eugene.Antimirov at portaone.com Mon Mar 19 13:33:03 2007 From: Eugene.Antimirov at portaone.com (Eugene Antimirov) Date: Mon, 19 Mar 2007 19:33:03 +0200 Subject: pyosd question Message-ID: <45FEC94F.80608@portaone.com> Small script used to work, by last week I noticed that it simply hangs up. Can someone run this code on his own python and tell me about results? Help me please. import time import pyosd import re default_font="-adobe-helvetica-medium-r-*-*-24-*" interval = 2 temp_led_number = pyosd.osd(default_font, colour='#038b06', timeout=1,pos=pyosd.POS_BOT,offset=40,shadow=1,align=pyosd.ALIGN_CENTER) def display(): # Here it will stay forever temp_led_number.display('123', pyosd.TYPE_STRING) # Never reach this line :( print "Yeah!" while 1: display() time.sleep(interval) -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Engineer support at portaone.com From matthew.garman at gmail.com Mon Mar 26 11:10:03 2007 From: matthew.garman at gmail.com (Matt Garman) Date: Mon, 26 Mar 2007 09:10:03 -0600 Subject: Python object overhead? In-Reply-To: <56ja46F28lpp9U1@mid.individual.net> References: <56ja46F28lpp9U1@mid.individual.net> Message-ID: On 3/23/07, Bjoern Schliessmann wrote: > "one blank line" == "EOF"? That's strange. Intended? In my case, I know my input data doesn't have any blank lines. However, I'm glad you (and others) clarified the issue, because I wasn't aware of the better methods for checking for EOF. > > Example 2: read lines into objects: > > # begin readobjects.py > > import sys, time > > class FileRecord: > > def __init__(self, line): > > self.line = line > > What's this class intended to do? Store a line :) I just wanted to post two runnable examples. So the above class's real intention is just to be a (contrived) example. In the program I actually wrote, my class structure was a bit more interesting. After storing the input line, I'd then call split("|") (to tokenize the line). Each token would then be assigned to an member variable. Some of the member variables turned into ints or floats as well. My input data had three record types; all had a few common attributes. So I created a parent class and three child classes. Also, many folks have suggested operating on only one line at a time (i.e. not storing the whole data set). Unfortunately, I'm constantly "looking" forward and backward in the record set while I process the data (i.e., to process any particular record, I sometimes need to know the whole contents of the file). (This is purchased proprietary vendor data that needs to be converted into our own internal format.) Finally, for what it's worth: the total run time memory requirements of my program is roughly 20x the datafile size. A 200MB file literally requires 4GB of RAM to effectively process. Note that, in addition to the class structure I defined above, I also create two caches of all the data (two dicts with different keys from the collection of objects). This is necessary to ensure the program runs in a semi-reasonable amount of time. Thanks to all for your input and suggestions. I received many more responses than I expected! Matt From kf9150 at gmail.com Fri Mar 30 12:21:08 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: 30 Mar 2007 09:21:08 -0700 Subject: Library for windows ini-files ? In-Reply-To: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> References: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> Message-ID: <1175271668.888450.124160@e65g2000hsc.googlegroups.com> On Mar 30, 1:26 am, stef wrote: > hello, > > is there a Python library for easy reading and writing windows ini-files ? > > thanks, > Stef Mientki Maybe check this out? http://www.voidspace.org.uk/python/configobj.html From Graham.Dumpleton at gmail.com Wed Mar 14 17:31:04 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 14 Mar 2007 14:31:04 -0700 Subject: merits of Lisp vs Python In-Reply-To: <87odmvinhf.fsf@pobox.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> <1173581125.663707.5810@s48g2000cws.googlegroups.com> <87odmvinhf.fsf@pobox.com> Message-ID: <1173907864.802954.66820@n59g2000hsh.googlegroups.com> On Mar 15, 7:22 am, j... at pobox.com (John J. Lee) wrote: > "Graham Dumpleton" writes: > > On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: > [...] > > >mod_pythonrelies on an unsupported feature of Python, namely > > > multiple interpreters --> risk of more pain with C extensions. > > > As usual, those bashing up onmod_pythontend not to really know what > > they are talking about. :-( > > > Although multiple Python interpreters cannot be manipulated directly > > from within a Python script, they can from the Python C API and it is > > very much a feature of Python and has been for a long time. > > I didn't dispute that multiple interpreters are a feature of Python. > I said that they are an unsupported feature -- at least, Martin > v. Loewis says they're "just broken", which is close enough for me: > > http://groups.google.co.uk/group/comp.lang.python/browse_thread/threa... > > """ > In any case, it looks like that the "multiple interpreters" feature of > Python is just broken. > """ For mod_python at least, the issues described there do not present as a problem because in mod_python sub interpreters are never destroyed while the process is running. Thus as far as the implementation of mod_python goes it is fine to key off the pointer to the interpreter as one knows interpreters will never go away. In the more general case I can see that it may be an issue for some small percentage of C extension modules which may want to cache information per interpreter. This though would only be the case if they wanted to exclusively hold everything directly within the C code space. Although it would perceivably slow access down, there is nothing to stop such a module instantiating its own pseudo module within the context of a sub interpreter using PyImport_AddModule(). This Python module could then be used to hold objects created by PyCObject_FromVoidPtr() with access later being had by using PyCObject_AsVoidPtr() after having looked up the object in the module. As necessary, when creating these objects, the C extension module can associate a cleanup function to be called when the object is destroyed by virtue of the sub interpreter being destroyed. Thus the C extension module would be able to cope with sub interpreters coming an going. So, more work is required and some may be concerned about efficiency and that a user may screw with the cached data from Python code, but it is possible to have per interpreter information with a C extension module. > [...]> Even so, to get such a C extension module working in the context of > >mod_pythonsimply means tellingmod_pythonto run that particular > > application in the first interpreter instance by specifying the > >mod_pythondirective: > > > PythonInterpreter main_interpreter > > [...] > > Is it possible to askmod_pythonto start separate processes to serve > requests, rather than "separate" interpreters? We couldn't see a way. Within the context of Apache it is possible to write modules which could spawn off a separate daemon process to which requests could later be passed for processing. An example of this included with Apache is something like mod_cgid. Other examples of modules which allow requests to be farmed off to separate processes, although they work a bit differently, are mod_fastcgi, mod_scgi and mod_proxy_ajp. To do something similar with mod_python isn't really practical because of the way it hooks into more than just the response handling phase of Apache. This concept though is being investigated for some version of mod_wsgi after the initial version has been released. When implemented, it would allow mod_wsgi to either handle WSGI applications in the same style as mod_python within the Apache child processes, or optionally farm the request off to a separate process running either as the same user as Apache or a different user, in the same style as mod_fastcgi and mod_scgi. The difference with mod_wsgi would be that it would be one self contained module all managed from Apache and would not require a separate executable or daemon process to Apache to be run to which it would communicate with as the separate daemon processes would ultimately just be a fork of the Apache parent process and be running code from the Apache module itself. Also the application scripts would be exactly the same no matter which mode it was running in so no need to modify them in any special way to run under the separate process. Graham From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Mar 2 15:22:45 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Mar 2007 21:22:45 +0100 Subject: Sorting strings containing special characters (german 'Umlaute') References: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> <54r2c4F21fssbU1@mid.individual.net> Message-ID: <54rfclF22ck5iU2@mid.individual.net> Robin Becker wrote: > Bj?rn, in one of our projects we are sorting in javascript in > several languages English, German, Scandinavian languages, > Japanese; from somewhere (I cannot actually remember) we got this > sort spelling function for scandic languages > > a > .replace(/\u00C4/g,'A~') //A umlaut > .replace(/\u00e4/g,'a~') //a umlaut > .replace(/\u00D6/g,'O~') //O umlaut > .replace(/\u00f6/g,'o~') //o umlaut > .replace(/\u00DC/g,'U~') //U umlaut > .replace(/\u00fc/g,'u~') //u umlaut > .replace(/\u00C5/g,'A~~') //A ring > .replace(/\u00e5/g,'a~~'); //a ring > > does this actually make sense? If I'm not mistaken, this would sort all umlauts after the "pure" vowels. This is, according to , used in Austria. If you can't understand german, the rules given there in section "Einsortierungsregeln" (roughly: ordering rules) translate as follows: "X und Y sind gleich": "X equals Y" "X kommt nach Y": "X comes after Y" Regards&HTH, Bj?rn -- BOFH excuse #146: Communications satellite used by the military for star wars. From gagsl-py2 at yahoo.com.ar Mon Mar 19 01:07:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 02:07:02 -0300 Subject: class objects, method objects, function objects References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> Message-ID: En Mon, 19 Mar 2007 01:38:37 -0300, 7stud escribi?: > But the last part of the passage makes no sense to me: > ------ > When the method object is called with an argument list, it is unpacked > again, a new argument list is constructed from the instance object and > the original argument list, and the function object is called with > this new argument list. > ------ > Can anyone interpret that for me? Calling a.foo(x,y) means that, after fetching foo from a, a new argument list must be constructed containing 3 items: the instance a (self), x and y. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sat Mar 3 18:46:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 04 Mar 2007 10:46:13 +1100 Subject: pop method question References: <7xd53qxdb2.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 03 Mar 2007 23:22:10 +0000, James Stroud wrote: >> To my mind, having to supply a key to dict.pop makes it rather pointless. >> >> > > > I've used it in something like this and found it worthwhile: > > for akey in dict1: > if some_condition(akey): > dict2[akey] = dict2.pop(akey) Surely that's a no-op? You pop the value, than add it back again. Or do you mean dict2[akey] = dict1.pop(akey)? If so, are you sure that works? When I try it, I get "RuntimeError: dictionary changed size during iteration". You would need to take a copy of the keys and iterate over that. for key in dict1.keys(): if some_condition(key): dict2[key] = dict1.pop(key) -- Steven. From harry.g.george at boeing.com Tue Mar 27 06:20:23 2007 From: harry.g.george at boeing.com (Harry George) Date: Tue, 27 Mar 2007 10:20:23 GMT Subject: Help in Placing Object in Memory References: <1175006005.782360.233620@b75g2000hsg.googlegroups.com> Message-ID: "Clement" writes: > I am newbie to Python...... i want to know something.......... > > can i place an object in disk instead of placing in Main Memory...? > > If possible, can you please explain with some scripts...? > > can two python script share a common object....? > For the CPU to use the object, it needs to be in RAM. But it is possible to save the RAM image onto disk, and then bring it back later. The common approach is called "pickling", though there are several variants on this: http://docs.python.org/lib/persistence.html -- Harry George PLM Engineering Architecture From knipknap at gmail.com Sat Mar 10 13:52:45 2007 From: knipknap at gmail.com (Samuel) Date: 10 Mar 2007 10:52:45 -0800 Subject: CGI handler: Retrieving POST and GET at the same time Message-ID: <1173552765.277146.273730@t69g2000cwt.googlegroups.com> Hi, I have the following form:
and would like to retrieve both fields, "one" and "two". However, the following does not work: form_data = cgi.FieldStorage() for key in form_data: print key + ":", form_data[key].value It prints out: two: 2 How can I retrieve the GET variables in that context? -Samuel From bdesth.quelquechose at free.quelquepart.fr Thu Mar 1 15:45:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Mar 2007 21:45:55 +0100 Subject: Questions about app design - OOP with python classes In-Reply-To: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> Message-ID: <45e733aa$0$25247$426a74cc@news.free.fr> adriancico at gmail.com a ?crit : > Hi > > I am working on a python app, an outliner(a window with a TreeCtrl > on the > left to select a document, and a RichTextBox at the right to edit the > current > doc). > > I am familiarized with OOP concepts and terms but I lack practical > experience > , so any comment/tip/pointer to docs will be welcome. > > So far, I have created a separated class for each important > element of my app > - the main Frame (cFrmMain) > - the TreeCtrl > - the TextCtrl at the right > - a cDocument class that contains the entire file with all > docs > and manages creation/deletion/saving to disk, etc > - classes for the toolbar, the menubar, etc As a side note : hungarian notation is usually considered bad form here. Look here for usual naming conventions: http://www.python.org/dev/peps/pep-0008/ > With this design, pretty much everything is encapsulated in it > respective > class. However, that means that the main program logic is in the Frame > class. What do you call "main program logic" exactly ? >>From there, it instantiates the other classes and is responsable of > the > communication between them. > > For example, the user deletes a node on the Tree, this raises an > event > on cFrmMain (the main Frame class). In the event handler, cFrmMain > notifies > cDocument that a node (and the associated text) has been deleted so > the master > file is modified accordingly. Ok. > The problem is, I have been implementing some funcionalities to > test this > design, I have less than a dozen operations implemented and cFrmMain > has grown > more than acceptable, starting to get confusing. Ok. > This design feels "not quite right" to me, Looks "almost right" to me !-) Using the main frame as a mediator between the different widgets is a well-known design pattern, named - suprisingly - mediator. The motivation is that it avoid each and every widget to know about the existence of every other widget. You may want to read about this pattern - but note that most litterature about design patterns is expressed in terms of statically typed languages (Java, C++ etc), and that dynamic languages like Python usually don't need that much boilerplate and complication (IOW : try to understand the pattern itself, not to blindly apply it). What's your looking for IMHO is the "controller" part - the one that glue together the "view" (main frame and all it's widgets) and the "model" (mostly, your document). Here again, googling for "model/view/controller" (MVC) may be a good idea. > I've been considering > allowing > the different classes to know of the existence of each other and pass > messages > between them. I would lose encapsulation (I think), At least this would introduce too much coupling between these classes. Note that there's nothing Python-specific in your question. But since comp.object is one of the worst places on earth to ask questions about OO... From nick at craig-wood.com Tue Mar 27 01:34:45 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 27 Mar 2007 00:34:45 -0500 Subject: Sending ECHO_REQUEST (pinging) with python References: Message-ID: Jean-Paul Calderone wrote: > On Mon, 26 Mar 2007 16:50:33 +0200, Thomas Dybdahl Ahle wrote: > >Den Mon, 26 Mar 2007 06:30:04 -0500 skrev Nick Craig-Wood: > >> Under linux the only priviledge you need is CAP_NET_RAW. It is possible > >> to give this to a process - a bit of searching with google will show you > >> how! > > > >How, I did google, but I wasn't able to find any way to do this in > >python.. > > You need a sendmsg wrapper (there are several, none in the stdlib), then > you need a privileged process which is willing to give you the privilege. > > It's pretty inconvenient. You start a user process with an extra capability using want using libcap and the execcap and sucap tools. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From deets at nospam.web.de Tue Mar 13 19:08:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Mar 2007 00:08:10 +0100 Subject: help!! *extra* tricky web page to extract data from... In-Reply-To: <7x1wjskbs7.fsf@ruckus.brouhaha.com> References: <1173819262.288501.66350@n76g2000hsh.googlegroups.com> <55ojorF26c25jU1@mid.uni-berlin.de> <55oli1F25u2dmU1@mid.uni-berlin.de> <7xmz2gbx6r.fsf@ruckus.brouhaha.com> <55omooF25ll0vU1@mid.uni-berlin.de> <7x1wjskbs7.fsf@ruckus.brouhaha.com> Message-ID: <55op6uF24n2biU1@mid.uni-berlin.de> Paul Rubin schrieb: > "Diez B. Roggisch" writes: >> Nice idea, but not really helpful in the end. Besides the rather nasty >> parts of the DOMs that make JS programming the PITA it is, I think the >> whole event-based stuff makes this basically impossible. > > Obviously the Python interface would need ways to send events into the > DOM, simulating timer ticks, mouse clicks, and so forth, just like > urllib in a sense simulates a user navigating a browser. Obviously this wouldn't really help, as you can't predict what a website actually wants which events, in possibly which order. Especially if the site does not _want_ to be scrapable- think of a simple "click on the images in the order of the numbers shown on them" captcha. Most time it's easier to sniff the http stream & grab the data directly. Diez From inq1ltd at verizon.net Sat Mar 17 15:43:14 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Sat, 17 Mar 2007 15:43:14 -0400 Subject: SQLite3, data not found In-Reply-To: References: <200703161755.58549.inq1ltd@verizon.net> Message-ID: <200703171543.14452.inq1ltd@verizon.net> On Saturday 17 March 2007 13:51, John Nagle wrote: > jim-on-linux wrote: > > On Friday 16 March 2007 18:23, Jerry Hill wrote: > >>On 3/16/07, jim-on-linux > >> > > > > wrote: > >>>Below, the first select produces results > >>> but, after closing then re-opening the > >>> database the select produces an empty list. > >>> Anyone know the reason ?? > >> > >>When you first open a connection, you > >>implicitly begin a transaction. You need to > >>call con.commit() before you close the > >>connection, or your transaction will be > >> rolled back when you close() it. If don't > >> want to bother with transaction handling, > >> you can turn it off when you open the > >> connection, like this: con = > >> sqlite3.connect('myData', > >>isolation_level=None) > >> > >>See the Python Database API 2.0 PEP for more > >>details about the behavior required of DB-API > >>2.0 compliant interfaces: > >>http://www.python.org/dev/peps/pep-0249/ > >> > >>-- > >>Jerry > > > > Thanks, this saves a lot of con.commit > > action. And the website is valuable. > > > > jim-on-linux > > Don't turn off atomic transactions, use > them. Otherwise, two copies of your program > running at the same time will probably not do > what you want. Just call "commit" at the end of > each transaction. > > John Nagle Thanks I appreciate the help. jim-on-linux From bbxx789_05ss at yahoo.com Sun Mar 18 13:15:42 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Mar 2007 10:15:42 -0700 Subject: Finding the insertion point in a list In-Reply-To: <7xbqir9d05.fsf@ruckus.brouhaha.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <7xird0bom3.fsf@ruckus.brouhaha.com> <7xfy845q24.fsf@ruckus.brouhaha.com> <7xbqir9d05.fsf@ruckus.brouhaha.com> Message-ID: <1174238142.658049.13380@e65g2000hsc.googlegroups.com> On Mar 18, 2:23 am, Paul Rubin wrote: > Steve Holden writes: > > > max(i for i,t in enumerate(x) if t <= y) > > > Those are actually pretty direct. > > > How about a solution (like the bisect one suggested almost as soon as > > this thread started) that doesn't iterate over the whole list. > > Here's a Haskell-inspired one: > > len(list(itertools.takewhile(lambda t: y > t, x))) > Can you explain how list() works in that statement. I looked up takewhile() and it returns an iterator that will automatically stop at the insertion point? So does list() do an internal comprehension with the iterator? From millerdev at gmail.com Fri Mar 9 17:57:58 2007 From: millerdev at gmail.com (Daniel Miller) Date: Fri, 09 Mar 2007 17:57:58 -0500 Subject: Hamburg Pythoneers Monthly Meeting: Wed, Apr 11 In-Reply-To: References: Message-ID: <45F1E676.1090502@gmail.com> Hello Helge, Which "AOPython" module will be covered during the meeting? Is it this one: http://www.openpolitics.com/pieces/archives/001710.html If that's not the one then you can stop reading now :)... But if that's the one you'll be highlighting then I'd be interested to hear what people think of it. I wrote that module, but I wasn't aware that anyone was using it. I wrote it as an exercise to learn about Python callables (functions, methods, etc.). I believe I did use it in a real project once to apply declarative exception handling and logging. I would love to know what others are using it for. Thanks, Daniel Miller Helge Stahlmann wrote: > +++++ Hamburg Python User Group April Meeting +++++ > > I am pleased to announce our next user group meeting: > > Wednesday, April 11, 2007 at 7:00pm > > Location: DDD Design GmbH, Jarrestrasse 46, 22303 Hamburg. > > Session highlight: Aspect-oriented programming with AOPython > > RSVP now at http://python.meetup.com/179/calendar/5549826/ > > If you're interested in learning more, please visit our website at > meetup.com: http://python.meetup.com/179/ > > > Additional links: > > RSS Newsfeed: > feed://www.meetup.com/rss/g/python/179/new/ > > Group Calendar RSS: > feed://python.meetup.com/179/calendar/rss/The+Hamburg+Python+User+Group/ > > iCal: > webcal://python.meetup.com/179/calendar/ical/The+Hamburg+Python+User > +Group/ > > > +++++ Hamburg Python User Group - Treffen im April +++++ > > Ich freue mich, an dieser Stelle unser n?chstes Meeting ank?ndigen zu > d?rfen: > > Mittwoch, 11. April 2007 um 19 Uhr > > Veranstaltungsort: DDD Design GmbH, Jarrestrasse 46, 22303 Hamburg. > > Highlight: Aspektorientierte Programmierung mit AOPython > > Anmeldungen werden unter > http://python.meetup.com/179/calendar/5549826/ entgegengenommen. > > Weitere Informationen finden sich auf unserer Webseite bei meetup.com: > http://python.meetup.com/179/ > > > Weitere Links: > > RSS Newsfeed: > feed://www.meetup.com/rss/g/python/179/new/ > > Gruppen Kalender RSS: > feed://python.meetup.com/179/calendar/rss/The+Hamburg+Python+User+Group/ > > iCal: > webcal://python.meetup.com/179/calendar/ical/The+Hamburg+Python+User > +Group/ From Joshua.R.English at gmail.com Mon Mar 5 12:55:09 2007 From: Joshua.R.English at gmail.com (Joshua.R.English at gmail.com) Date: 5 Mar 2007 09:55:09 -0800 Subject: Newbie question In-Reply-To: References: Message-ID: <1173117307.283564.22270@30g2000cwc.googlegroups.com> On Mar 5, 9:03 am, Stargaming wrote: > Tommy Grav schrieb: > > For this case, there are list comprehensions (or map, but you shouldn't > use it any longer): I didn't see anything in the docs about this. Is map going away or is it considered un-Pythonic now? Josh From __peter__ at web.de Sun Mar 18 09:35:35 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 Mar 2007 14:35:35 +0100 Subject: [Help]UnicodeDecodeError References: <1174224026.501145.19360@y66g2000hsf.googlegroups.com> Message-ID: Karl wrote: > error msg: > Mod_python error: "PythonHandler mod_python.publisher" > > Traceback (most recent call last): > > File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line > 299, in HandlerDispatch > result = object(req) > > File "/usr/lib/python2.3/site-packages/mod_python/publisher.py", > line 136, in handler > result = util.apply_fs_data(object, req.form, req=req) > > File "/usr/lib/python2.3/site-packages/mod_python/util.py", line > 361, in apply_fs_data > return object(**args) > > File "/var/www/html/sky.py", line 38, in main > sresult = sresult.decode('zh-hk').encode('utf_8') > > UnicodeDecodeError: 'big5hkscs' codec can't decode bytes in position > 958-959: illegal multibyte sequence > > > Wt can I do, since there is some characters, is there any solutions to > solve it??? Other than requiring valid input? You can choose a more lenient decoding strategy, e. g.: sresult = sresult.decode('zh-hk', "replace") >>> help(s.decode) Help on built-in function decode: decode(...) S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors. Peter From duncan.booth at invalid.invalid Mon Mar 19 16:23:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2007 20:23:05 GMT Subject: class objects, method objects, function objects References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> <1174324902.778062.104610@b75g2000hsg.googlegroups.com> Message-ID: "7stud" wrote: > When the method object is called with an > argument list, > > x.g("GvR") ==> I think I'm both "referencing an instance attribute" > and calling the method object with an argument list > > it(the method object) is unpacked again, a new argument list is > constructed from the instance object and the original argument list, > and the function object is called with this new argument list. It may help you to understand if you consider the two parts separately. There is no linkage between 'referencing an instance attribute' and 'calling the method object'. You can rewrite the code as: method = x.g method("GvR") and it works in exactly the same way. First you reference the attribute 'x.g', which looks up MyClass.g (an unbound method) and calls MyClass.g.__get__(x, MyClass) which creates a new bound method. Then you call the bound method passing "GvR" as the first positional argument: so a single element tuple is created for the argument list. The bound method object unpacks and repacks the tuple to give the two-tuple (self, "GvR") which it then passes to the original function. From paul.rudin at ntlworld.com Mon Mar 19 14:05:23 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Mon, 19 Mar 2007 18:05:23 +0000 Subject: PythonCard or Dabo? References: Message-ID: <87lkht3y8s.fsf@rudin.co.uk> Kevin Walzer writes: > I'm curious to know what others think of these two frameworks for > building wxPython apps. > > PythonCard has been around longer, but its development seems to have > slowed. The last release, 0.8.2, has been out for quite awhile now. > > Dabo is newer and seems to have gathered a lot of buzz. > > Anyone try both? What's your preference and why? Is one more robust > than the other? > Incidentally, there's also boa constructor, which at least has the best name of the three :) From jgodoy at gmail.com Sun Mar 11 22:47:45 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 11 Mar 2007 23:47:45 -0300 Subject: setuptools and code.google.com (was Re: Signed zeros: is this a bug?) References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <7xy7m3tqq8.fsf@ruckus.brouhaha.com> <1173653364.059431.19990@v33g2000cwv.googlegroups.com> <7xps7f5ptp.fsf@ruckus.brouhaha.com> <1hutrb3.e1sbu5kvxk8nN%aleax@mac.com> <87odmznrbf.fsf@gmail.com> <1hutsxr.3pcc7j1w12q1oN%aleax@mac.com> Message-ID: <87fy8bnpny.fsf_-_@gmail.com> aleax at mac.com (Alex Martelli) writes: > I'm not familiar with setuptools, what exactly is it looking for? > > If it's looking for stuff to download it should start at > > http://code.google.com/p/gmpy/downloads/list > > (but what does it want -- the sources' zipfile, or some binary, and in > what format and with what naming convention?) -- I'll be glad to edit > the URL for gmpy at cheeseshop if some setuptools expert can explain > these subtleties... thanks for pointing out that there's a problem > btw!-) Thanks for caring ;-) It looks for several things: eggs (for the Python version it is being used), zipfiles and tarballs (I dunno if it looks for more things). If it finds, for example, gmpy-1.0.2-py2.4.egg it won't install here 'cause I use Python 2.5 and then it will continue searching for gmpy-1.0.2-py2.5.egg or an alternative format that can be used. The last resort is the tarball / zip with the sources so that the package can be rebuilt. Probably other people that are more experienced with it can help more. I'm more an end user of it and I know the essential for my needs. I just pointed out because setuptools helps a lot on obtaining a package and installing it (even if there's some building needed before installing). Sorry for not being able to help more. With regards to the hyperlink, I believe that if the link on Pypi was to the URL above it would be easier. Another alternative is a link at the first page. And, of course, the last alternative is teaching setuptools how to work with code.google.com -- if it doesn't already know -- as it learnt how to work with SourceForge and its "random" mirrors. I don't know how to write that code, though. Be seeing you, -- Jorge Godoy From inq1ltd at verizon.net Wed Mar 21 21:39:42 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Wed, 21 Mar 2007 21:39:42 -0400 Subject: the second of nested buttons using textvariable remains void! In-Reply-To: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> References: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> Message-ID: <200703212139.42807.inq1ltd@verizon.net> On Wednesday 21 March 2007 20:11, Samkos wrote: > Hi there, > > I am fighting with a problem I intended to > believe trivial that I could not solve yet! > > I am trying to have a button with a variable > text, that pops up another button with a > variable text when pressed. > > I did that with the following program in > Python, but the second button remains always > void!!! is it related to the textvariable > parameters? > > If any of you had a clue, please don't > hesitate! > > in advance, many thanks > > Samuel > > #----------------------- program 2 buttons.py > -------------------------- > > from Tkinter import * > > > def go(event): > root = Tk() > > s1=StringVar() > s1.set("s1") > label1 = Label(root, textvariable=s1) > label1.pack(side=LEFT) > > root.mainloop() > > > > root = Tk() > > s0=StringVar() > s0.set("s0") > label0 = Label(root, textvariable=s0) > label0.pack(side=LEFT) > > > root.bind("",go) > > root.mainloop() try this; def go(): root = Tk() root.config(bg= 'yellow') s1=StringVar() blabel1 = Button(root, textvariable=s1, width = 10, height = 2, command = next) blabel1.pack() root.bind("", vbind) s1.set('click_s1') def vbind(event): next() def next(): second = Toplevel() s0=StringVar() s0.set("click_s0") blabel0 = Button(second, textvariable=s0, command = second.destroy, width = 10, height = 2) blabel0.pack() if __name__ == '__main__' : go() mainloop() jim-on-linux http://inqvista.com From lew at nospam.lewscanon.com Thu Mar 22 08:45:50 2007 From: lew at nospam.lewscanon.com (Lew) Date: Thu, 22 Mar 2007 08:45:50 -0400 Subject: On Java's Interface (the meaning of interface in computer programing) In-Reply-To: <1174557840.338374.25990@d57g2000hsg.googlegroups.com> References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> <1174557840.338374.25990@d57g2000hsg.googlegroups.com> Message-ID: <57idnf5DTKfj55_bnZ2dnUVZ_uzinZ2d@comcast.com> Jim Burton wrote: > Or you could stop feeding the trolls. People need to stop saying that. The original post was a detailed if incorrect exposition of Java information. How in the world do you rate that trollish? I have absolutely no reason to rate the OP as a troll or their post as trollish. -- Lew From JHoover at fbi.gov Mon Mar 12 15:39:58 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Mon, 12 Mar 2007 15:39:58 -0400 Subject: Watching a file another app is writing In-Reply-To: References: Message-ID: Vishal Bhargava wrote: > What kind of file is it? CSV? It's a hand history file generated by an online poker client, thus it probably keeps it's data pretty much to itself otherwise, and in any case I'm not a Windows programmer so I probably don't have the stomach to get very deep into its process communication mechanisms. > > It occurs to me under Unix you could perhaps get your first program to write > to a "named pipe", which you 2nd program could read from. See > > http://en.wikipedia.org/wiki/Named_pipe From gregpinero at gmail.com Thu Mar 1 10:58:45 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 1 Mar 2007 07:58:45 -0800 Subject: How to Read Bytes from a file In-Reply-To: <1172757183.819978.219440@v33g2000cwv.googlegroups.com> References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1172757183.819978.219440@v33g2000cwv.googlegroups.com> Message-ID: <1172764725.827624.298180@j27g2000cwj.googlegroups.com> On Mar 1, 8:53 am, "Bart Ogryczak" wrote: > On Mar 1, 7:52 am, "gregpin... at gmail.com" > wrote: > > > It seems like this would be easy but I'm drawing a blank. > > > What I want to do is be able to open any file in binary mode, and read > > in one byte (8 bits) at a time and then count the number of 1 bits in > > that byte. > > > I got as far as this but it is giving me strings and I'm not sure how > > to accurately get to the byte/bit level. > > > f1=file('somefile','rb') > > while 1: > > abyte=f1.read(1) > > import struct > buf = open('somefile','rb').read() > count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+ > (x&64>0)+(x&128>0) > byteOnes = map(count1,struct.unpack('B'*len(buf),buf)) > > byteOnes[n] is number is number of ones in byte n. This solution looks nice, but how does it work? I'm guessing struct.unpack will provide me with 8 bit bytes (will this work on any system?) How does count1 work exactly? Thanks for the help. -Greg From beliavsky at aol.com Mon Mar 5 08:55:28 2007 From: beliavsky at aol.com (Beliavsky) Date: 5 Mar 2007 05:55:28 -0800 Subject: Python stock market analysis tools? In-Reply-To: <1173073290.907489.101150@t69g2000cwt.googlegroups.com> References: <1173066776.884126.86810@64g2000cwx.googlegroups.com> <1173073290.907489.101150@t69g2000cwt.googlegroups.com> Message-ID: <1173102924.803537.89930@c51g2000cwc.googlegroups.com> On Mar 5, 12:41 am, "Raymond Hettinger" wrote: > On Mar 4, 7:52 pm, "Mudcat" wrote: > > > I have done a bit of searching and can't seem to find a stock market > > tool written in Python that is active. Anybody know of any? I'm trying > > not to re-create the wheel here. > > What kind of tool do you want? Getting quotes is the easy part: > > import urllib > symbols = 'ibm jpm msft nok'.split() > quotes = urllib.urlopen( 'http://finance.yahoo.com/d/quotes.csv?s='+ > '+'.join(symbols) + '&f=l1&e=.csv').read().split() > print dict(zip(symbols, quotes)) > > The hard part is raising capital and deciding what to buy, sell, or > hold. Yes, and a discussion of investment approaches would be off-topic. Unfortunately, newsgroups such as misc.invest.stocks are dominated by spam -- the moderated newsgroup misc.invest.financial-plan is better. Some research says that "mean variance portfolio optimization" can give good results. I discussed this in a message http://groups.google.com/group/misc.invest.financial-plan/msg/3b9d13f3d399050c?dmode=source Newsgroups: misc.invest.financial-plan From: beliavsky at aol.com Date: Mon, 26 Feb 2007 12:47:25 -0600 Local: Mon, Feb 26 2007 1:47 pm Subject: Re: Portfolio Optimization Software? To implement this approach, a needed input is the covariance matrix of returns, which requires historical stock prices, which one can obtain using "Python quote grabber" http://www.openvest.org/Databases/ovpyq . For expected returns -- hmmm. One of the papers I cited found that assuming equal expected returns of all stocks can give reasonable results. Then one needs a "quadratic programming" solver, which appears to be handled by the CVXOPT Python package. If someone implements the approach in Python, I'd be happy to hear about it. There is a "backtest" package in R (open source stats package callable from Python) http://cran.r-project.org/src/contrib/Descriptions/backtest.html "for exploring portfolio-based hypotheses about financial instruments (stocks, bonds, swaps, options, et cetera)." From s.mientki at id.umcn.nl Mon Mar 19 06:14:12 2007 From: s.mientki at id.umcn.nl (stef) Date: Mon, 19 Mar 2007 11:14:12 +0100 Subject: from maple to python + numpy/scipy In-Reply-To: References: Message-ID: Daniel Nogradi wrote: > I'm just getting started with numpy/scipy and first would like to get > a view of what it can do and what it can't. The main idea is to move > from maple to python and the first thing that poped up is the fact > that maple is very convenient for both formal manipulations and exact > integer calculations. For instance if a matrix has integer entries and > the eigenvalues are integers maple can find these exactly. > > Can numpy/scipy do this? Or the eigenvalues will always be floating > point numbers? it might be better to ask this question on the scipy newsgroup SciPy Users List cheers, Stef Mientki From gagsl-py2 at yahoo.com.ar Fri Mar 9 20:44:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 22:44:15 -0300 Subject: Python-list Digest, Vol 42, Issue 117 References: <45F1D33F.1050909@optonline.net> Message-ID: En Fri, 09 Mar 2007 18:35:59 -0300, Bart Willems escribi?: > I'm sorry, but what's wrong with: > radix = [ [] ] * 256 http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects -- Gabriel Genellina From michael at jedimindworks.com Sat Mar 24 22:35:10 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 24 Mar 2007 21:35:10 -0500 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174758927.095854.167030@e65g2000hsc.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> <1174758927.095854.167030@e65g2000hsc.googlegroups.com> Message-ID: On Mar 24, 2007, at 12:55 PM, 7stud wrote: > In addition, the download notes for the stand alone MacPython 2.5 > install say that there aren't as many modules for 2.5 as there are for > the 2.4, which is something you may want to consider. There aren't as many pre-built modules for 2.5 at the MacPython site. That's not to say you can't easily build your own, mind you -- assuming you've got developer tools installed. regards, Michael --- A clever person solves a problem. A wise person avoids it. -Albert Einstein From john106henry at hotmail.com Thu Mar 1 18:10:26 2007 From: john106henry at hotmail.com (John Henry) Date: 1 Mar 2007 15:10:26 -0800 Subject: Matplotlib axes label Message-ID: <1172790626.088267.303150@j27g2000cwj.googlegroups.com> I've been asking this question at the matplotlib user list and never gotten an answer. I am hoping that there are matplotlib users here that can help. My problem with matplotlib's way of handling axes label is illustrated by this example: http://www.scipy.org/Cookbook/Matplotlib/MulticoloredLine Notice that the y-axis goes from (-1.1, 1.1) but the first label is at -1.0. I really don't like that because when I read values off the graph, I have to keep reminding myself that the origin is at -1.1. This may seem trivial but if you have to think, walk, chew gums at the same time you're reading the graph, it gets annoying - particularly if you have to read lots of these graphs. Is there a way to force the label to start at -1.1 instead of -1.0? Thanks, From Gerald.Klix at klix.ch Tue Mar 20 12:26:40 2007 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Tue, 20 Mar 2007 17:26:40 +0100 Subject: Wanted: a python24 package for Python 2.3 In-Reply-To: <1174406681.405930.237930@e1g2000hsg.googlegroups.com> References: <45FFFEB6.2080403@pytex.org> <1174406681.405930.237930@e1g2000hsg.googlegroups.com> Message-ID: <46000B40.3080504@klix.ch> Hi, You can't import subproces from future, only syntactic and semantic changes that will become standard feature in future python version can be activated that way. You can copy the subprocess module from python 2.4 somewhere where it will be found from python 2.3. At least subporcess is importable after that: --- snip --- klix at vesuv6:~/ttt> cp -av /usr/local/lib/python2.4/subprocess.py . ?/usr/local/lib/python2.4/subprocess.py? -> ?./subprocess.py? klix at vesuv6:~/ttt> python2.3 Python 2.3.3 (#1, Jun 29 2004, 14:43:40) [GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> --- snip --- HTH, Gerald kyosohma at gmail.com schrieb: > On Mar 20, 10:33 am, Jonathan Fine wrote: > >>Hello >> >>My problem is that I want a Python 2.4 module on >>a server that is running Python 2.3. I definitely >>want to use the 2.4 module, and I don't want to >>require the server to move to Python 2.4. >> >>More exactly, I am using subprocess, which is >>new in Python 2.4. What I am writing is something >>like >>=== >>from subprocess import Popen >>=== >> >>This will fail in Python 2.3, in which case I >>would like to write something like >>=== >>try: >> from subprocess import Popen >>else ImportError: >> from somewhere_else import Popen >>=== >> >>Put this way, it is clear (to me) that somewhere_else >>should be python24. >> >>In other words, I'm asking for a python24 package that >>contains all (or most) of the modules that are new to >>Python 2.4. >> >>I've looked around a bit, and it seems that this >>formulation of the solution is new. I wonder if >>anyone else has encountered this problem, or has >>comments on my solution. >> >>-- >>Jonathan > > > You might be able to use the "from future import SomeModule" syntax to > accomplish this, but I am not sure. Other than that, I would just > recommend using the os.popen calls that are native to 2.3 > > Mike > From s.mientki at id.umcn.nl Fri Mar 30 08:55:43 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 30 Mar 2007 14:55:43 +0200 Subject: Library for windows ini-files ? In-Reply-To: References: <1b387$460cf3fd$83aef404$10944@news2.tudelft.nl> Message-ID: <8e1f6$460d08cf$83aef404$17326@news2.tudelft.nl> Laurent Pointal wrote: > stef a ?crit : > >> hello, >> >> is there a Python library for easy reading and writing windows ini-files ? >> > > http://docs.python.org/lib/module-ConfigParser.html > > A+ > > Laurent. > thanks Laurent, that seems to be what I was looking for. cheers, Stef From rhc28 at cornell.edu Fri Mar 2 12:07:13 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Fri, 2 Mar 2007 12:07:13 -0500 Subject: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs. In-Reply-To: <1172579296.156674.203150@j27g2000cwj.googlegroups.com> References: <2ff9b$45db652f$d443bb3a$29705@news.speedlinq.nl> <1172579296.156674.203150@j27g2000cwj.googlegroups.com> Message-ID: Mike, Yes, that is a pretty fair description of our support for symbolics using Python's own inheritance. Our ModelSpec classes provide only an elementary form of inheritance, polymorphism and type checking. We hope to expand our existing support for hybrid/DAE systems at the level of our ModelSpec model-building tools. All ideas and code contributions are welcome! Cheers, Rob From andmarti at gmail.com Mon Mar 19 01:12:39 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Mon, 19 Mar 2007 02:12:39 -0300 Subject: struct.pack returns nothing Message-ID: <20070319051239.GA8214@lacordilleraandina.com.ar> If I build a strict with: import struct print struck.pack ('i', 1) it returns a '\n'. What's wrong with it??? :( -- Andr?s M. --------------------------------------------- From irstas at gmail.com Mon Mar 26 12:50:20 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 26 Mar 2007 09:50:20 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: <1174925704.394888.18170@d57g2000hsg.googlegroups.com> References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> <1174813227.275145.211000@o5g2000hsb.googlegroups.com> <1174854156.298431.68150@n59g2000hsh.googlegroups.com> <1174925704.394888.18170@d57g2000hsg.googlegroups.com> Message-ID: <1174927820.575669.101990@p15g2000hsd.googlegroups.com> On Mar 26, 7:15 pm, "7stud" wrote: > On Mar 25, 3:09 pm, Steven Bethard wrote: > > > Here's another way of looking at it:: > > > >>> class Test(object): > > ... pass > > ... > > >>> def greet(): > > ... print 'Hello' > > ... > >>> Test.greet = greet > >>> Test.greet > > > > Interesting. After playing around with that example a bit and finally > thinking I understood bound v. unbound, I found what appears to be an > anomaly: > ------------ > class Test(object): > pass > > def greet(x): > print "hello" > > Test.func = greet > print Test.func > > t = Test() > print t.func > > def sayBye(x): > print "bye" > > t.bye = sayBye > print t.bye > ------------output: > > > > > > Why doesn't t.bye cause a method object to be created? Because that would be bad and unexpected behaviour. I might want to store callback functions to an object as attributes. It wouldn't make sense for the functions to be bound to the container object when I'd access them. Of course, "Test.func = greet; print Test.func" is also "unexpected behaviour" as Test.func is not same as Test.__dict__['func']. But it's unexpected in a good way, because it facilitates the way classes are usually used. The whole point of the magic is to make common idioms simple. From taurelin at gmail.com Fri Mar 9 11:53:48 2007 From: taurelin at gmail.com (Arne Jamtgaard) Date: 9 Mar 2007 08:53:48 -0800 Subject: Problem with new Vista and os.system Message-ID: <1173459228.574405.213280@h3g2000cwc.googlegroups.com> I'm getting myself set up on a new Vista box at work, and one of my old scripts has stopped working. Specifically, all calls to os.system return a -1. Whatever action I was asking os.system to run does not take place. Is this a Vista thing, or perhaps just a wonky setting in my environment. Oh, python 2.5. Arne From aleax at mac.com Fri Mar 23 10:47:04 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 23 Mar 2007 07:47:04 -0700 Subject: Idiom for running compiled python scripts? References: Message-ID: <1hvf41r.136f636r1ft4cN%aleax@mac.com> Mark wrote: ... > so I could just do a "python_compile_and_run myscript.py" and it would > do what I want, i.e. run myscript.pyc if available and valid, generate > and run it if necessary. You can use python -c 'import myscript; myscript.main()' and variations thereon. Alex From rewire at gmail.com Wed Mar 14 08:45:35 2007 From: rewire at gmail.com (Divya) Date: 14 Mar 2007 05:45:35 -0700 Subject: IronPython and COM Interface Message-ID: <1173876334.993319.34430@n59g2000hsh.googlegroups.com> Hello, I'm new to IronPython and COM so please bear with me. I have a COM interface provided to me. I need to implement this interface and pass it to a method as a way of implementing 'callbacks'. However it appears that the methods of my interface object are never called. As a alternative, I implemented the interface in C# and then extended the C# class in IronPython. However, on running the code, methods of my C# class rather than the IronPython class are being called. Can anyone advise? Is this possible in IronPython? The code is listed below. Regards, Divya --------------------------- import time import clr clr.AddReference('Interop.MBTCOMLib.dll') clr.AddReference('Interop.MBTORDERSLib.dll') clr.AddReference('Interop.MBTQUOTELib.dll') import MBTCOMLib import MBTORDERSLib import MBTQUOTELib demo_user='user' demo_pass='pass' demo_host=9 class MBEvents(MBTQUOTELib.IMbtQuotesNotify): def __init__(self): MBTQUOTELib.IMbtQuotesNotify.__init__(self) def OnLevel2Data(data): print 'OnLevel2Data' def OnOptionsData(self, data): print 'OnOptionsData' def OnQuoteData(self, data): print 'OnQuoteData' def OnTSData(self, data): print 'OnTSData' class MB: def __init__(self): self.conn = MBTCOMLib.MbtComMgrClass() #self.conn.EnableSplash(False) self.orders = self.conn.OrderClient self.quotes = self.conn.Quotes self.events = MBEvents() def login(self, host=demo_host, user=demo_user, passwd=demo_pass): self.conn.DoLogin(host, user, passwd, '') print self.quotes.RemoteAddress, self.quotes.RemotePort self.quotes.AdviseSymbol(self.events, 'EUR/USD', 1|2|3|4) From proteusguy at gmail.com Mon Mar 19 05:30:54 2007 From: proteusguy at gmail.com (proteusguy at gmail.com) Date: 19 Mar 2007 02:30:54 -0700 Subject: keyword arguments for xml-rpc Message-ID: <1174296653.983861.47630@o5g2000hsb.googlegroups.com> I've just noticed that I can't seem to use keyword arguments for xml-rpc requests even though the protocol itself encodes parameter names, types, and values when it sends the xml across the network. This becomes a bit problematic for me because I want to store some XML- RPC method dispatch signatures in a database and can't easily guarantee parameter order when I load it so being able to pass a dictionary of name/value pairs greatly eases the development effort and helps assure correct methods get invoked. Is this a limitation of the SimpleXMLRPCServer, the xmlrpclib.ServerProxy, or something completely different? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Mar 2 15:13:02 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Mar 2007 21:13:02 +0100 Subject: Sort with extra variables References: Message-ID: <54reqdF22ck5iU1@mid.individual.net> Thomas Dybdahl Ahle wrote: > However I'd really like not to use the lambda, as it slows down > the code. Did you check how much the slowdown is? Regards, Bj?rn -- BOFH excuse #65: system needs to be rebooted From pecora at anvil.nrl.navy.mil Sat Mar 10 12:16:19 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sat, 10 Mar 2007 12:16:19 -0500 Subject: Is this right? Multiple imports of same module. References: Message-ID: In article , Dennis Lee Bieber wrote: > > Expected behavior if you 1) understand how Python variable binding > works, and 2) that "from <> import *" is equivalent to > > import <> > name1 = <>.name1 > name2 = <>.name2 > > IOWs, one is creating local names that are bound to the objects > inside the imported module. If, subsequently, one does > > name2 = 123 > > one has UNbound the connection to <>.name2 and rebound the local name to > the integer object 123. Whereas > > <>.name2 = 123 > > says "go into the module <>, and rebind its 'name2' to the integer > object 123"; since you "went inside" to do the rebinding, any other code > that also uses the <>.name2 reference will see the change inside <>. Ah! (light bulb goes on) Yes, I get it. Thanks. No more from ** import *. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From savalon at ukr.net Wed Mar 21 04:12:01 2007 From: savalon at ukr.net (Orin) Date: Wed, 21 Mar 2007 10:12:01 +0200 Subject: coverage.py problem In-Reply-To: <17919.4374.192994.456090@montanaro.dyndns.org> Message-ID: Thank you very much. Just reading the comments on that url, I found the reason of my problem. It was here: --- coverage.py +++ coverage.py @@ -464,6 +464,8 @@ def collect(self): cache_dir, local = os.path.split(self.cache) + if not cache_dir: #this two strings was upsent + cache_dir = "." for file in os.listdir(cache_dir): if not file.startswith(local): continue With best regards, Orin From steve at REMOVEME.cybersource.com.au Tue Mar 27 23:00:33 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Mar 2007 13:00:33 +1000 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174916449.171929.138950@n76g2000hsh.googlegroups.com> <46095e24$1@nntp.zianet.com> Message-ID: On Tue, 27 Mar 2007 12:11:01 -0600, Erik Johnson wrote: > But seriously... I'm not a language or architecture guru. Is there any > real difference between a JVM and an interpreter? I mean, I have some > general feel that bytecode is a lower-level, more direct and more efficient > thing to be interpreting that Java or Python source, but at the bottom > level, you are still running an interpreter which is going to be > (significantly?) more inefficient than executing native machine instructions > directly on the CPU, right? Thirty (or more?) years ago, the differences between compilers and interpreters was fairly large. Interpreters would scan the source code of each and every line. If you had a loop, each line in the loop would be parsed each time around the loop. Despite 30+ years of progress, that's still the model that many (most?) people have in their head when they think of "interpreted language". That's why "interpreted" is the Kiss of Death to anyone interested in speed -- whether true or not. def if_(): # interpreted function exec 'x = 0' exec """for i in range(100): exec 'x += i'""" return x def cf(): # compiled function x = 0 for i in range(100): x += i return x >>> timeit.Timer('cf()', 'from __main__ import cf').repeat(3, 1000) [0.054703950881958008, 0.038740158081054688, 0.041306018829345703] >>> timeit.Timer('if_()', 'from __main__ import if_').repeat(3, 1000) [16.228797912597656, 16.261317014694214, 15.885524034500122] But these days, and probably for the last decade at least, the nice neat lines between "compiled" and "interpreted" is much fuzzier. So-called interpreted languages don't parse the source code every time it is run. They compile to byte-code, which is interpreted in a virtual machine in the same way that compiled code is interpreted in a real machine. Even that distinction isn't necessarily cut and dried. On modern CPUs, machine code itself can be implemented in a mini-language, which naturally is interpreted by an interpreter built into the CPU. The "real" machine on the CPU is likely to itself include "virtual" machines, up to and including entire emulators of other CPUs. (Note: for each and every generalization I have made, there are almost certainly exceptions. I think that just supports my contention that the generalizations about "compiled" and "interpreted" languages are more misleading than useful.) > Why is Python able to automatically compile source into bytecode on the > fly (when needed) but Java still forces you to do so explicitly? That probably has more to do with different programming models than different technologies. I'm sure somebody could build an interactive complier/interpreter for Java like Python's. If nobody has, it is probably more to do with nobody seeing the need of such than because it can't be done. I suspect that the advantages of an interactive system are much less for languages like Java that have static type declarations. > I don't mean to bash Java - I think it has it's place as well, but I > mean to note that Java is very carefully marketed whereas Python's image is > not managed by a major, international corporation. Exactly. And that's why I think it does Python no favours at all to keep emphasising the interpreter over the compiler. It gives too many people the wrong idea. -- Steven D'Aprano From john.pye at gmail.com Wed Mar 21 23:09:51 2007 From: john.pye at gmail.com (John Pye) Date: 21 Mar 2007 20:09:51 -0700 Subject: splitting perl-style find/replace regexp using python In-Reply-To: References: <1172741100.414936.269460@q2g2000cwa.googlegroups.com> Message-ID: <1174532991.858501.290610@e1g2000hsg.googlegroups.com> Thanks all for your suggestions on this. The 'splitter' idea was particularly good, not something I'd thought of. Sorry for my late reply. From skip at pobox.com Wed Mar 21 09:49:33 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 21 Mar 2007 08:49:33 -0500 Subject: Garbage collection In-Reply-To: References: Message-ID: <17921.14317.94569.747087@montanaro.dyndns.org> Tom> I suspect I may be missing something vital here, but Python's Tom> garbage collection doesn't seem to work as I expect it to. Here's Tom> a small test program which shows the problem on python 2.4 and 2.5: Tom> (at this point, Python is using 15MB) >>> a = range(int(1e7)) >>> a = None >>> import gc >>> gc.collect() 0 Tom> (at this point, Python is using 252MB) Tom> Is there something I've forgotten to do? Why is Python still using Tom> such a lot of memory? You haven't forgotten to do anything. Your attempts at freeing memory are being thwarted (in part, at least) by Python's int free list. I believe the int free list remains after the 10M individual ints' refcounts drop to zero. The large storage for the list is grabbed in one gulp and thus mmap()d I believe, so it is reclaimed by being munmap()d, hence the drop from 320+MB to 250+MB. I haven't looked at the int free list or obmalloc implementations in awhile, but if the free list does return any of its memory to the system it probably just calls the free() library function. Whether or not the system actually reclaims any memory from your process is dependent on the details of the malloc/free implementation's details. That is, the behavior is outside Python's control. Skip From tinaweb at bestemselv.com Mon Mar 26 02:27:19 2007 From: tinaweb at bestemselv.com (Tina I) Date: Mon, 26 Mar 2007 08:27:19 +0200 Subject: __init__.py In-Reply-To: References: Message-ID: Tina I wrote: > When looking at other peoples code (to learn from it) I keep seeing an > empty file named "__init__.py". What's the purpose of this? > > Thanks > Tina Duh! Never mind... found it. Kinda neat actually :) T From Robert.Katic at gmail.com Sun Mar 4 13:06:07 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 4 Mar 2007 10:06:07 -0800 Subject: class attrdict In-Reply-To: <1hufw45.os60h3bkuqh9N%aleax@mac.com> References: <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1173009806.383478.50230@i80g2000cwc.googlegroups.com> <1hufw45.os60h3bkuqh9N%aleax@mac.com> Message-ID: <1173031567.734026.292940@30g2000cwc.googlegroups.com> class Namespace(object): def __init__(self, __ns=None, **kwargs): if __ns is None: #if no dictionary is given self.__dict__ = kwargs #then use kwargs without copying or creating new dict else: assert len(kwargs) == 0 self.__dict__ = __ns #else use dictionary without copyng #additional methods for JS like object (ONLY FOR DEMONSTRATION) def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): setattr(self, name, value) def __delitem__(self, name): delattr(self, name) def __iter__(self): return iter(self.__dict__) def __contains__(self, name): return hasattr(self, name) From rhc28 at cornell.edu Mon Mar 5 22:17:54 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Mon, 5 Mar 2007 22:17:54 -0500 Subject: ANN: PyDSTool now compatible with numpy 1.0.1, scipy 0.5.2 and 64-bit CPUs. In-Reply-To: <1173135681.180640.209810@30g2000cwc.googlegroups.com> References: <2ff9b$45db652f$d443bb3a$29705@news.speedlinq.nl> <1172579296.156674.203150@j27g2000cwj.googlegroups.com> <1173135681.180640.209810@30g2000cwc.googlegroups.com> Message-ID: This kind of comment comes up often, so I think it's worth spelling out a response that will persist on the web and can appear in our FAQ. I have a different and admittedly limited view of hybrid systems as part of dynamical systems theory. In principle, I would love to have time to write an interface to something like Modelica, but PyDSTool isn't intended as an industrial-scale simulation package: it is intended for applied dynamical systems research involving small systems that people want to analyze with tools like bifurcation theory and parameter estimation. I also want to switch components in and out of a model with minimum overhead as part of model estimation and parameter estimation routines that remain an open research area. Partly for this reason I don't want to start depending on large external packages, most features of which people may never be needed. Given my present purposes the overhead of writing an interface is a demanding sink of my time when basic (essentially prototype) tools suffice in the short term. That is also why I am not planning a graphical UI at this time. (The related DsTool and XPP packages already have GUIs.) I appreciate the idea of outsourcing to take advantage of good work in areas such as yours. I hope to step up to that bar later on as part of an ongoing research project connected to me, which involves studying the mechanisms of locomotion in insects. There are other mechanical simulation packages that I would like to interface to (most are commercial), but on close inspection it turns out there's a lot of very technical issues involved -- although at least modelica is open source! Sorry to be taking a short-term view here (I try to avoid that), but we're just a couple of guys trying to concentrate on our day jobs... Rob From jan.m.danielsson at gmail.com Tue Mar 27 09:30:38 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 27 Mar 2007 15:30:38 +0200 Subject: Modules & positive surprises Message-ID: <46091c7e$1@griseus.its.uu.se> Hello all, Although I have encountered many modules that have impressed me with regards to what they can actually do -- too be perfectly honest, it's very rare that I become impressed by the _interfaces_ to the modules. Using a new module is normally, with my - admittedly - limited experience, a pain. It's not just about reading the reference material, and then just use it. You have to figure out how the developer who wrote the module was thinking. Often there's a (more or less) natural way to do things, and unfortunately that's not how module developers do it. It's not a major issue to me personally, since the important part is that the module can perform its function. But then there are a few modules that I just love to use, because they are so "clean" from interface to function. Among them I can't help mentioning optparse. Yesterday I found another module which I fell in love with: Python Cryptography Toolkit (http://www.amk.ca/python/writing/pycrypt/). It's just so ... elegant, and functional. -- Kind regards, Jan Danielsson From paddy3118 at googlemail.com Thu Mar 29 18:44:56 2007 From: paddy3118 at googlemail.com (Paddy) Date: 29 Mar 2007 15:44:56 -0700 Subject: Modal value of an array In-Reply-To: <1hvpovd.1anin2by4gjl1N%aleax@mac.com> References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> <877it0u2h4.fsf@benfinney.id.au> <1hvpovd.1anin2by4gjl1N%aleax@mac.com> Message-ID: <1175208296.769865.186480@r56g2000hsd.googlegroups.com> On Mar 29, 8:49 am, a... at mac.com (Alex Martelli) wrote: > Ben Finney wrote: > > ... > > > That's not the only case though. What do you expect to be returned for > > an input of ["eggs", "beans", "beans", "eggs", "spam"] ? > > > Assuming you want *a* mode value, and any one will do (e.g. any of > > "spam", "eggs" or "beans" is okay), I'd write it this way as a first > > guess: > > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > > >>> counts = [(foo.count(val), val) for val in set(foo)] > > >>> counts > > [(2, 'eggs'), (1, 'beans'), (4, 'spam')] > > >>> sorted(counts)[-1] > > (4, 'spam') > > >>> sorted(counts)[-1][1] > > 'spam' > > A bit more directly: > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >>> max(foo, key=foo.count) > > 'spam' > > Alex This doesn't call foo.count for duplicate entries by keeping a cache >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] >>> def cachecount(x, cache={}): ... return cache.setdefault(x, foo.count(x)) ... >>> max(foo, key=cachecount) 'spam' >>> cachecount.func_defaults ({'eggs': 2, 'beans': 1, 'spam': 4},) >>> - Paddy. From http Wed Mar 14 11:50:55 2007 From: http (Paul Rubin) Date: 14 Mar 2007 07:50:55 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> <1173515984.515050.27400@n33g2000cwc.googlegroups.com> <1173861843.878008.83090@p15g2000hsd.googlegroups.com> Message-ID: <7xps7bbz8g.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > Since people are posting their solutions now (originally only hints > were provided for the homework problem), here's mine: > > def genpool(n, m): > if n == 1: > yield [m] > else: > for i in xrange(1, m): > for rest in genpool(n-1, m-i): > yield rest + [i] > > import random > print random.choice(list(genpool(n=4, m=20))) This generates a lot of the partitions more than once, with possibly unequal probability. From jstroud at mbi.ucla.edu Mon Mar 19 05:16:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 19 Mar 2007 09:16:43 GMT Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> Message-ID: <%xsLh.14400$FG1.1735@newssvr27.news.prodigy.net> momobear wrote: > hi, I am puzzled about how to determine whether an object is > initilized in one class, anyone could give me any instructions? > here is an example code: > > class coffee: > def boil(self): > self.temp = 80 > > a = coffer() > if a.temp > 60: > print "it's boiled" > > in C++ language we must initilized a variable first, so there is no > such problem, but in python if we don't invoke a.boil(), we will not > get self.temp to be initilized, any way to determine if it's initilzed > before self.temp be used. > I think you might be looking for hasattr: class coffee: def boil(self): if hasattr(self, 'temp') and self.temp > 60: print "Its boilt, yo." else: self.temp = 80 Other ways to do this are try/except: class coffee: def boil(self): try: if self.temp > 60: print "Its bizzle, yo." return except AttributeError: pass self.temp = 80 Which is not so good in my opinion because it takes too much typing and makes your fingers hurt at the very tips. A fun way is with dict.setdefault which might actually be cleanest, but you loose testing the precondition for the print: class coffee: def boil(self): if self.__dict__.setdefault('temp', 80) > 60: print "Its bizzle m'wizzle." py> c = coffee() py> c.temp Traceback (most recent call last): File "", line 1, in AttributeError: coffee instance has no attribute 'temp' py> c.boil() Its bizzle m'wizzle. py> c.temp 80 Of course, the idea is that, in classes, you will be intimately aware of the attributes of your class via __init__, as others have mentioned, so you should never really resort to any of the above. James From scuba.margie at gmail.com Thu Mar 22 23:45:27 2007 From: scuba.margie at gmail.com (scuba.margie at gmail.com) Date: 22 Mar 2007 20:45:27 -0700 Subject: Cool new website Message-ID: <1174621527.601045.166590@n76g2000hsh.googlegroups.com> Brand new site. Loads of great stuff Free membership and full access Check out Yapooh! http://www.yapooh.org From public21 at lakeweb.com Sat Mar 10 15:23:27 2007 From: public21 at lakeweb.com (Dan Bloomquist) Date: Sat, 10 Mar 2007 20:23:27 GMT Subject: Phase change material ... In-Reply-To: <1173554707.826932.246100@30g2000cwc.googlegroups.com> References: <1173405474.489111.139350@p10g2000cwp.googlegroups.com> <1173554707.826932.246100@30g2000cwc.googlegroups.com> Message-ID: <3tEIh.4571$B25.683@news01.roc.ny> thermate at india.com wrote: > On Mar 8, 5:57 pm, "martinl" wrote: > >>Hi All, >>I'm looking for a substance that does a phase change at between 60 and >>100 C. >> >>I need something with a high heat capacity so that when it cools >>through the phase change, it stays at the freezing temperature for as >>long as possible. >> >>Also it needs to be non toxic since it will be handled. >> >>Any thoughts? I settled for hurricane wax. (IGI-1260). But that, because I felt it would suit my application, domestic heating. I have 3 thousand pounds of the stuff. > If you want to arrest the temperature of your system using phase > transformation, you probably need good thermal conductivity of the > phase change material. My biggest concern as I build the heat exchangers. Here is a photo at a previous state. http://lakeweb.com/boiler/tubes.jpg The tubes on the left are for steam condensation. I didn't think I would need to cover the volume that well with them because the wax will melt around them and convection currents will distribute the heat. But the heat sink tubing, (two rows on the right), are double and much longer with back and forth winding. When all the tubing is in there will be much vertical support, brazed, half inch EMT. The coefficient of expansion for wax is up there and I don't want the solid wax building on the tubes to sag the copper. And, more surface area for the exchanger. I had thought of running FEA on this but would have downloaded free software. I figured I lack the skill to make the time invested work out. The average distance from far points to the heat exchanger will be some 3-4 inches. And, the heat will be moved out on the scale of hours. The only time I could see having trouble is on the very coldest nights and having to bring the house back up to temperature in the morning. The contingency plan for that is I load the boiler with some wood in the evening and it autostarts very early in the morning for those coldest nights. Best, Dan. From bj_666 at gmx.net Sat Mar 3 03:10:14 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 03 Mar 2007 09:10:14 +0100 Subject: Perl and Python, a practical side-by-side example. References: <45e8c931$0$8646$426a34cc@news.free.fr> <54sl5dF21mn73U1@mid.individual.net> Message-ID: In <54sl5dF21mn73U1 at mid.individual.net>, Bjoern Schliessmann wrote: > Bruno Desthuilliers wrote: >> Shawn Milo a ?crit : > >>> if recs.has_key(piid) is False: >> >> 'is' is the identity operator - practically, in CPython, it >> compares memory addresses. You *dont* want to use it here. > > It's recommended to use "is None"; why not "is False"? Are there > multiple False instances or is False generated somehow? Before `True` and `False` existed many people defined them as aliases to 1 and 0. And of course there are *many* other objects that can be used in a boolean context of an ``if`` statement for testing "trueness" and "falseness". Ciao, Marc 'BlackJack' Rintsch From larry.bates at websafe.com Fri Mar 30 11:55:08 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 30 Mar 2007 10:55:08 -0500 Subject: Inserting '-' character in front of all numbers in a string In-Reply-To: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> Message-ID: <460D32DC.4060104@websafe.com> kevinliu23 wrote: > Hey guys, > > I want to be able to insert a '-' character in front of all numeric > values in a string. I want to insert the '-' character to use in > conjunction with the getopt.getopt() function. > > Rigt now, I'm implementing a menu system where users will be able to > select a set of options like "2a 3ab" which corresponds to menu > choices. However, with getopt.getopt(), it'll only return what I want > if I input -2a -3ab as my string. I don't want the user have to insert > a '-' character in front of all their choices, so I was thinking of > accepting the string input first, then adding in the '-' character > myself. > > So my qusetion is, how do I change: > > "2a 3ab" into "-2a -3ab". > > Regular expressions? :/ > s="2a 3b" s="-%s -%s"% tuple(s.split()) -Larry From jjl at pobox.com Sat Mar 24 11:16:37 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 24 Mar 2007 15:16:37 GMT Subject: [JOB] Sr. Python Developer, Northern VA References: <87aby59dy1.fsf@pobox.com> Message-ID: <87wt167jts.fsf@pobox.com> Anton Vredegoor writes: > John J. Lee wrote: [...] > > but I'm sure you appreciate the point -- if you're hiring employees, > > being fairly risk-averse is probably quite rational. > > So when we really mean business, you're back to static typing? I'm not wedded to dynamic typing, as it happens. Of course, if I were, I would have to take it as a metaphor for all of life ;-) [...] > Well, on my next leisurely stroll along the river side, I will > consciously enjoy the freedom of currently having no job instead of > the usual "I'm lucky I have no kids to worry about", just to humor you! Bastard :-) John From gagsl-py2 at yahoo.com.ar Thu Mar 29 15:45:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 29 Mar 2007 16:45:08 -0300 Subject: Question about details of __import__ References: <20070329104233.2129d267@opal.pathscale.com> <20070329115654.5455dd96@opal.pathscale.com> Message-ID: En Thu, 29 Mar 2007 15:56:54 -0300, Mitko Haralanov escribi?: >> You may check if this is the case, looking at sys.modules > > I did look at sys.modules but I wasn't sure what to look for. There was > a log module in the list but what else should I look for? If you think that Python got confused and has two duplicate modules, try to find them in sys.modules. Perhaps under the names 'log' and 'xxx.log' Or, using print, try to see *when* your global variable is reset to None. -- Gabriel Genellina From jgodoy at gmail.com Wed Mar 14 21:08:48 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 14 Mar 2007 22:08:48 -0300 Subject: merits of Lisp vs Python References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> <1173581125.663707.5810@s48g2000cws.googlegroups.com> <87odmvinhf.fsf@pobox.com> <871wjrs4vo.fsf@pobox.com> Message-ID: <87ps7bz527.fsf@gmail.com> jjl at pobox.com (John J. Lee) writes: > John Nagle writes: > >> John J. Lee wrote: >> > "Graham Dumpleton" writes: >> > >> >>On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: >> >> > Is it possible to ask mod_python to start separate processes to serve >> > requests, rather than "separate" interpreters? We couldn't see a way. >> >> That's what CGI does. > > I meant long running processes, as I hoped was obvious from context... Maybe FastCGI should help, then. It can run "forever" after a request has finished so it is suitable for long running processes. -- Jorge Godoy From lbates at websafe.com Tue Mar 13 18:50:37 2007 From: lbates at websafe.com (Larry Bates) Date: Tue, 13 Mar 2007 17:50:37 -0500 Subject: Problem I have with a while loop/boolean/or In-Reply-To: <1173825244.368771.273720@e1g2000hsg.googlegroups.com> References: <1173825244.368771.273720@e1g2000hsg.googlegroups.com> Message-ID: israphelr at googlemail.com wrote: > Hi all. > > I have a problem with some code :( > > ----------- > > hint = raw_input("\nAre you stuck? y/n: ") > hint = hint.lower() > > while (hint != 'n') or (hint != 'y'): > hint = raw_input("Please specify a valid choice: ") > > --------------------------------------------- > > so everytime I run the program, and enter my choice as y or n, I'm > told to 'Please Specify a valid Choice Again' and can't get out of the > loop. > > > > ----------- > > hint = raw_input("\nAre you stuck? y/n: ") > hint = hint.lower() > > while (hint != 'n'): > hint = raw_input("Please specify a valid choice: ") > > --------------------------------------------- > > As for here when I enter n, I can leave the while loop. > > Anyway I can't put my finger on this, so I'd be real grateful if > someone could tell me what I've done wrong. Thanks. > (I have a guy feeling it's something really silly I'm overlooking...) > Your if test is wrong. If hint='n' hint !='n' is False hint !='y' is True False or True equals True I think you want something like: hint = raw_input("\nAre you stuck? y/n: ") hint = hint.lower() while hint not in ['y', 'n']: hint = raw_input("Please specify a valid choice: ") -Larry From robert.kern at gmail.com Tue Mar 13 23:20:05 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 13 Mar 2007 22:20:05 -0500 Subject: Questions on migrating from Numeric/Scipy to Numpy In-Reply-To: <1173841694.932998.290390@d57g2000hsg.googlegroups.com> References: <1173835370.353415.8000@e1g2000hsg.googlegroups.com> <1173841694.932998.290390@d57g2000hsg.googlegroups.com> Message-ID: vj wrote: >> Note that the mask needs to be a bool array. > >>>> mask = zeros(5) >>>> mask = zeros(5, numpy.int8) >>>> mask[1] = True >>>> mask[2] = True >>>> a = zeros(5) >>>> a[mask] = [100, 200] >>>> a > array([ 100., 100., 0., 0., 0.]) > > I found this strange. It should just give an error if you try to use a > mask array of non booleans. No, it simply does something different. Boolean arrays apply as a mask. Integer arrays apply as indices into the array. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From eddie at holyrood.ed.ac.uk Mon Mar 26 07:00:07 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 26 Mar 2007 11:00:07 +0000 (UTC) Subject: Need help to learn Python References: Message-ID: "wesley chun" writes: >with that said, i would still like to state that the book's target >audience is for people who know how to program but need to pick up >Python as quickly as possible. the "theory" that's in the book is >really more explanation of how the Python interpreter works, >especially the relationship between objects and memory management. >the goal is to give you enough of an understanding of how Python works >"under the covers" that you will write very effective code, even as a >beginner to the language. Worked for me. The 1/e was the easiest intro to a language I've ever read. (I don't suppose you fancy doing one for Ruby :) Eddie From bignose+hates-spam at benfinney.id.au Tue Mar 27 23:41:23 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 Mar 2007 13:41:23 +1000 Subject: PyPy 1.0: JIT compilers for free and more References: Message-ID: <87abxym3vg.fsf@benfinney.id.au> Carl Friedrich Bolz writes: > ========================================== > PyPy 1.0: JIT compilers for free and more > ========================================== > > Welcome to the PyPy 1.0 release - a milestone integrating the > results of four years of research, engineering, management and > sprinting efforts, concluding the 28 months phase of EU co-funding! Fabulous! Congratulations to all who contributed to getting PyPy to this significant milestone. Here's to all the cool new things people will be doing with PyPy! -- \ "If nothing changes, everything will remain the same." -- | `\ Barne's Law | _o__) | Ben Finney From michele.simionato at gmail.com Mon Mar 12 12:35:20 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Mar 2007 09:35:20 -0700 Subject: nonlinear interpolation In-Reply-To: <7x7itm8m02.fsf@ruckus.brouhaha.com> References: <1173713333.615789.287070@v33g2000cwv.googlegroups.com> <7x7itm8m02.fsf@ruckus.brouhaha.com> Message-ID: <1173717319.977458.323280@q40g2000cwq.googlegroups.com> On Mar 12, 5:28 pm, Paul Rubin wrote: > "Michele Simionato" writes: > > Any pointer would be well received :) > > Dunno about those libs but it helps to understand the mathematical > options. Numerical Recipes by Teukolsky et al has understandable, > cookbook-like advice about this stuff. I'm told that true numerics > gurus scoff at it but it's at least a start. No, I know about Numerical Recipes, I want an already-made solution. For instance I found one here http://dirac.cnrs-orleans.fr/ScientificPython/ScientificPythonManual/Scientific.Functions.LeastSquares-module.html but I wonder if I should use numpy or something else, since I am not following the progresses in numerical Python these days. P.S. sorry for the multiple post, google tricked me. From steve at holdenweb.com Fri Mar 16 10:04:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 16 Mar 2007 10:04:50 -0400 Subject: String formatting with fixed width In-Reply-To: References: Message-ID: Steve Holden wrote: > Alexander Eisenhuth wrote: >> Hello alltogether, >> >> is it possible to format stings with fixed width of let's say 7 character. T >> need a floating point with 3 chars before dot, padded with ' ' and 3 chars after >> dot, padded with '0'. >> >> Followingh is my approach >> >>> f = 21.1 >> >>> s = "%.03f" % f >> >>> s >> '21.100' >> >> But there are missing ' '. How can I get that? (For bigger numbers than 999 they >> might be cut: 1021 -> 021) >> > >>> def f(x): > ... return "%7.3f" % (x % 1000.0) > ... > >>> for x in (9.9, 99.9, 999.9, 9999.9): > ... print f(x) > ... > 9.900 > 99.900 > 999.900 > 999.900 > >>> > ... but (unfortunately?): >>> f(-9999.99) ' 0.010' >>> You don't say what you want to do about negative numbers, so this may or may not be significant. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From spedrosa at gmail.com Thu Mar 8 11:11:57 2007 From: spedrosa at gmail.com (Stephen Eilert) Date: 8 Mar 2007 08:11:57 -0800 Subject: merits of Lisp vs Python In-Reply-To: <8KPHh.5712$M65.2750@newssvr21.news.prodigy.net> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <7mOHh.3099$h73.2536@newsfe12.lga> <8KPHh.5712$M65.2750@newssvr21.news.prodigy.net> Message-ID: <1173370317.438703.116790@v33g2000cwv.googlegroups.com> On Mar 8, 5:23 am, John Nagle wrote: > Brian Adkins wrote: > > Ken Tilton wrote: > > >> John Nagle wrote: > > Turns out John is having quite a tough time with Python web hosting (the > > thread has split off to a c.l.p only fork), so I'm going to cut him some > > slack. Maybe with some lovin' we can woo him over to c.l.l ;) > > Been there, done that. I've actually used an original refrigerator > sized Symbolics LISP machine. > > I tend to think of Python as a LISP with infix syntax. > We have a better handle on what to put in a dynamic language now, and > Python does a good job in that direction. I'm happy with the > language; it's the integration with external components that isn't > working. > > John Nagle OMG! And I thought the thread was dead! Necromancers! Run!!! From bjourne at gmail.com Fri Mar 9 05:59:24 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 9 Mar 2007 11:59:24 +0100 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: <1173436274.346506.200920@q40g2000cwq.googlegroups.com> References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <1173436274.346506.200920@q40g2000cwq.googlegroups.com> Message-ID: <740c3aec0703090259k5253ac90r459269c5ea19e4e9@mail.gmail.com> On 9 Mar 2007 02:31:14 -0800, dbhbarton at googlemail.com wrote: > Thanks for the thoughts. > > > This could be implemented without new syntax: just make your editor > > recognize some special comments, and apply the highlighting to the > > following block. By example, > > > > # XXX Remove this when FuruFaifa is fixed to always provide > > # XXX the names in the same order > > names.sort() > > names.reverse() > > Yes I recognise that we can use existing comments for this purpose, > and if I was suitably gifted I guess I could try to make the IDE > recognise these 'special comments', and maybe even work out what block > they're meant to apply to. Of course I'll still argue that the WIP > character would be a more elegant, speedy and versatile alternative. But you are overloading the ? character for a purpose which it totally was not meant for. What the character means really depends on what person you are asking. To me, it means that what precedes it is something someone or something does not know and wants to know the answer to. To me, it really does not mean that what follows it is work in progress. Even if I could intuitively tell that a question mark represents a work in progress, that information is not very useful. Similarly to the "under construction" animated gifs that were popular on the web in the mid 90-ties, the symbol does not convey any useful information. WHY is it a work in progress? Is there something wrong with it? ?def foobar(): do stuff The question mark does not leave me any the wiser. Now if you replace that question mark with a comment: # foobar() is buggy because it throws weird exceptions when x = 42. def foobar(): do stuff That gives me some useful information. -- mvh Bj?rn From vorner at ucw.cz Mon Mar 26 05:24:34 2007 From: vorner at ucw.cz (Michal 'vorner' Vaner) Date: Mon, 26 Mar 2007 11:24:34 +0200 Subject: Sending ECHO_REQUEST (pinging) with python In-Reply-To: References: Message-ID: <20070326092434.GA24995@tarantula.kolej.mff.cuni.cz> On Mon, Mar 26, 2007 at 08:30:16AM +0200, Thomas Dybdahl Ahle wrote: > Hi, I've writing a python application in which I'd like to have a small > "ping label", to always tell the current ping time to the server. > > It seems however that I have to be root to send those imcp packages, but > I guess there must be a workaround since I can easily use the "ping" > command as ordinary user. > > Do anybody know how to do this in python? You need root for that and the ping command is allowed to have them by suid bit. You can execute ping from inside python and use ping as is, if you need. -- This is a terroristic email. It will explode in 10 minutes, if you do not close it in the meantime. Michal "vorner" Vaner -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From newsgroups at nospam.nowire.org Sat Mar 31 08:53:11 2007 From: newsgroups at nospam.nowire.org (=?UTF-8?B?VGhvbWFzIEtyw7xnZXI=?=) Date: Sat, 31 Mar 2007 14:53:11 +0200 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: References: Message-ID: Rehceb Rotkiv schrieb: > can I sort a multidimensional array in Python by multiple sort keys? A > litte code sample would be nice! You can pass a function as argument to the sort method of a list. The function should take two arguments and return -1, 0 or 1 as comparison result. Just like the cmp function. This will objects in list obj_lst by their id attributes: def sorter(a, b): return cmp(a.id, b.id) obj_lst.sort(sorter) Thomas From ogerchikov at gmail.com Sat Mar 24 00:45:38 2007 From: ogerchikov at gmail.com (ogerchikov at gmail.com) Date: 23 Mar 2007 21:45:38 -0700 Subject: How can I tell when the threads that I spawn are done in python Message-ID: <1174711538.875033.215320@d57g2000hsg.googlegroups.com> Hi, In my python scripts, I create thread likes this: // for example threadCount is 10 for j in range(int(threadCount)): t = MyThread() t.start() // wait all the threads are done doSomething() My question is how can i tell when all the threads are done before I call doSomething()? Thank you. From robert.kern at gmail.com Thu Mar 22 15:37:06 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 22 Mar 2007 14:37:06 -0500 Subject: design question: generator object with other attributes In-Reply-To: References: Message-ID: Alan Isaac wrote: > Essentially I want a generator that I can query about > its characteristics. (E.g., a random number generator > that I want to be able to ask about is distributional > parameters.) > > I am thinking of a class that wraps a generator. > An object of this class will have a ``next`` method that simply > returns the value the object get by calling the wrapped > generator. You will probably also need to define def __iter__(self): return self if I remember correctly. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gtcopeland at gmail.com Wed Mar 7 09:39:05 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 7 Mar 2007 06:39:05 -0800 Subject: Why does SocketServer default allow_reuse_address = false? In-Reply-To: <45e3668e$0$16385$88260bb3@free.teranews.com> References: <45e3668e$0$16385$88260bb3@free.teranews.com> Message-ID: <1173278345.027948.94700@j27g2000cwj.googlegroups.com> On Feb 26, 5:54 pm, "Joshua J. Kugler" wrote: > Considering that UNIX Network Programming, Vol 1 (by W. Richard Stevens) > recommends "_All_ TCP servers should specify [SO_REUSEADDR] to allow the > server to be restarted [if there are clients connected]," and that > self.allow_reuse_address = False makes restarting a server a pain if there > were connected clients, why does SocketServer default allow_reuse_address > to False? It's kind of bemusing to subclass ThreadingTCPServer just to > change one variable that arguably should have been True in the first place. > > Is there some history to this of which I'm not aware? Is there a good > reason for it to default to false? > Yes, it is there for a good reason. Security is the primary focus of that option. If you enable that option, rogue applications can assume service processing under a number of server failure conditions. In other words, start your rogue, crash the primary service, and you now have a rogue service running. Even periodic checks will show the server is still running. Under a number of other configurations, it is also possible for the rogue service to simply start and usurp some types of IP traffic on certain OSs which would otherwise be delivered to your real server. Contrary to the book, blindly enabling SO_REUSEADDR is a very, very bad idea unless you completely understand the problem domain. I'm sure Stevens' does understand so it makes for a good choice for him. On the other hand, most people don't understand the implications so it makes for a very, very poor move from a security perspective. Long story short, it is not a bug. It is a feature. The proper default is that of the OS, which is to ensure SO_REUSEADDR is disabled unless you absoluetely understand what you're buying by enabling it. Greg From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 8 03:05:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 08 Mar 2007 09:05:42 +0100 Subject: catching exceptions from an except: block In-Reply-To: <1173319364.288542.252370@j27g2000cwj.googlegroups.com> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <45EF260C.6000205@websafe.com> <1173304097.821562.75060@t69g2000cwt.googlegroups.com> <45ef3b80$0$18249$426a34cc@news.free.fr> <1173319364.288542.252370@j27g2000cwj.googlegroups.com> Message-ID: <45efc3b4$0$6082$426a74cc@news.free.fr> MonkeeSage a ?crit : > On Mar 7, 4:58 pm, Bruno Desthuilliers > wrote: >> except_retry: # the missing(???) keyword you're after > > What is 'except_retry'? A totally imaginary statement that would do what the OP is looking for. > To the OP, with the loop and the callables you could also break out of > the loop when the condition is met and use the else condition to raise > the exception. > > def test(arg): > for f in int, float, str, hex: > try: > return f(arg) > break # breaks on f==str You don't need to break here since you're returning. > except: > pass > else: > raise ValueError # remove str above to see this From anil.karadag at gmail.com Fri Mar 16 16:13:34 2007 From: anil.karadag at gmail.com (=?ISO-8859-9?Q?ANIL_KARADA=D0?=) Date: Fri, 16 Mar 2007 22:13:34 +0200 Subject: python global variable error Message-ID: hi, i made a program in python but received global name error. the program code; serverhost = '127.0.0.1' serverport = 2000 BUFSIZ = 1024 addr = (serverhost,serverport) if str(sys.argv).find("-s") == -1: cs = socket(AF_INET, SOCK_STREAM,0) # create a TCP socket cs.connect(addr) key=1 main() else: serversock = socket(AF_INET, SOCK_STREAM) # create a TCP socket serversock.bind(addr) serversock.listen(2) key=2 print 'waiting for connection?' while 1: clientsock, addr = serversock.accept() print '?connected from:', addr,clientsock main() serversock.close() what is difference cs and clientsock? i use cs in main() function or others, but don't use clientsock not call from main() " data = clientsock.recv(BUFSIZ) NameError: global name 'clientsock' is not defined " i am sorry, i little know english -------------- next part -------------- An HTML attachment was scrubbed... URL: From jezonthenet at yahoo.com Tue Mar 13 02:13:37 2007 From: jezonthenet at yahoo.com (jezzzz .) Date: Mon, 12 Mar 2007 23:13:37 -0700 (PDT) Subject: Starting Python... some questions Message-ID: <845401.48808.qm@web58115.mail.re3.yahoo.com> Jordan, Thinker, Steven, Thanks for your responses. Makes more sense now! I can run my program from the console. I added the self parameter to the the chassis_id function, however I now have a problem and question regarding encoding MAC addresses for a struct. What string format am I supposed to use? Also, I think I will get rid of Scapy in my small program. Any references I can use to easily send (no need to receive) a packet with a Layer 1 and 2 only? (i.e. only Ethernet and LLDP - no need for IP, UDP, TCP etc. I wish to create something like Ethernet | LLDP msg1 | LLDP msg2 | ... | LLDP msgn) Thanks! This is what I got now: #!/usr/bin/python import scapy import struct class lldp_class: def __init__(self): self.chassis_id_tlv = None def chassis_id(self, subtype, chassis_info): if subtype == 4: chassis_data = struct.pack("!B",chassis_info) subtype_data = struct.pack("!B",subtype) self.chassis_id_tlv = subtype_data + chassis_data def __main__(): p = lldp_class() p.chassis_id(4, "01:80:C2:00:00:0E") payload = p.chassis_id_tlv ether = scapy.Ether(dst="01:02:03:04:05:06") fullpayload = ether + payload sendp(fullpayload) __main__() ____________________________________________________________________________________ Expecting? Get great news right away with email Auto-Check. Try the Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html From paddy3118 at googlemail.com Fri Mar 30 01:53:57 2007 From: paddy3118 at googlemail.com (Paddy) Date: 29 Mar 2007 22:53:57 -0700 Subject: Modal value of an array In-Reply-To: <1hvr34h.12c953hpq7pavN%aleax@mac.com> References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> <877it0u2h4.fsf@benfinney.id.au> <1hvpovd.1anin2by4gjl1N%aleax@mac.com> <1175208296.769865.186480@r56g2000hsd.googlegroups.com> <1hvr34h.12c953hpq7pavN%aleax@mac.com> Message-ID: <1175234036.941266.112960@e65g2000hsc.googlegroups.com> On Mar 30, 2:58 am, a... at mac.com (Alex Martelli) wrote: > Paddy wrote: > > ... > > > > > > A bit more directly: > > > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > > > >>> max(foo, key=foo.count) > > > > 'spam' > > > > Alex > > > This doesn't call foo.count for duplicate entries by keeping a cache > > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > > >>> def cachecount(x, cache={}): > > ... return cache.setdefault(x, foo.count(x)) > > ... > > >>> max(foo, key=cachecount) > > 'spam' > > >>> cachecount.func_defaults > > ({'eggs': 2, 'beans': 1, 'spam': 4},) > > If you're willing to do that much extra coding to save some work (while > still being O(N squared)), then the further small extra needed to be > O(N) starts looking good: > > counts = collections.defaultdict(int) > for item in foo: counts[item] += 1 > max(foo, key=counts.get) > > Alex Yeh, My first answer is like that but I had to play around with your original to try and 'fix' the idea in my head - it might be useful someday. :-) - Paddy. From PrikrylP at skil.cz Fri Mar 16 02:45:53 2007 From: PrikrylP at skil.cz (Petr Prikryl) Date: Fri, 16 Mar 2007 07:45:53 +0100 Subject: problem with str() Message-ID: "Alex Martelli" wrote > Steve Holden wrote: > ... > > >> Get yourself a stuffed bear, and next time you have this kind of problem > > >> spend a few minutes explaining to the bear exactly how your program > > >> can't possibly be wrong. Works like a charm. > > > > > > A rubber ducky works much better for that, btw -- more easily washable > > > than a stuffed bear, for example. > > > > > But stuffed bears are so much more knowledgeable about the minutiae of > > software design. > > And yet, the key to Python's strength is duck typing -- if you can teach > the duck to type, you've got it made. ... and then (gradually) rather unrealistic communication dream called "Babylonian fish" can be replaced by slighly more realistic programmers dream called "Python language with natural language processing when programming" (buzzword DuckPython). From mark at mailinator.com Sat Mar 24 01:07:42 2007 From: mark at mailinator.com (Mark) Date: 24 Mar 2007 05:07:42 GMT Subject: Idiom for running compiled python scripts? References: <1hvf41r.136f636r1ft4cN%aleax@mac.com> Message-ID: On Fri, 23 Mar 2007 07:47:04 -0700, Alex Martelli wrote: > You can use > > python -c 'import myscript; myscript.main()' > > and variations thereon. Hmmm, after all that, this seems to be close to what I was looking for. Thanks Alex. Didn't find anything about this in your cookbook! (I'm just starting reading it whole - best way to really learn the language I think). So the general purpose invoking bash script e.g. "runpy" is merely something like: ################################################################# #!/bin/bash if [ $# -lt 1 ]; then echo "usage: `basename $0` script.py [script args ..]" exit 1 fi PROG=$1 DIR=`dirname $PROG` MOD=`basename $PROG` MOD=${MOD%.py} shift exec python -c "import sys; \ sys.argv[0] = \"$PROG\"; \ sys.path.append(\"$DIR\"); \ import $MOD; $MOD.main()" $@ ################################################################# So I timed "~/bin/myscript.py myargs" against "runpy ~/bin/myscript.py myargs" but got only maybe a couple of millisec improvement (using a 1000 line myscript.py which just immediately exits - to try and push the advantage!). So I agree - the ends do not justify the means here and I'll just execute myscript.py directly. Still not sure why python does not provide this as a "python --compile_and_run myscript.py" option though?! ;) From lbrooks at MIT.EDU Thu Mar 15 23:34:35 2007 From: lbrooks at MIT.EDU (Lane Brooks) Date: Thu, 15 Mar 2007 23:34:35 -0400 Subject: Import Error with embedded python Message-ID: <45FA104B.3050400@mit.edu> When I run a particular python script from an embedded interpreter, I get the following ImportError: File "di.py", line 14, in load from xml.dom.ext.reader import Sax2 File "/usr/lib64/python2.4/site-packages/_xmlplus/dom/ext/reader/__init__.py", line 14, in ? import string, urllib2, urlparse, cStringIO, os File "/usr/lib64/python2.4/urllib2.py", line 90, in ? import base64 File "/usr/lib64/python2.4/base64.py", line 9, in ? import struct ImportError: /usr/lib64/python2.4/lib-dynload/structmodule.so: undefined symbol: PyExc_TypeError However, running the same script from the command line does not produce this error. Any ideas as to what I need to do to get the embedded interpreter setup to not produce this error? The platform is Linux x86_64. Thanks, Lane From jackdied at jackdied.com Wed Mar 7 20:42:45 2007 From: jackdied at jackdied.com (Jack Diederich) Date: Wed, 7 Mar 2007 20:42:45 -0500 Subject: Descriptor/Decorator challenge In-Reply-To: <1173210288.178790.233730@64g2000cwx.googlegroups.com> References: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> <1173105492.632821.326810@n33g2000cwc.googlegroups.com> <1173121140.087027.214600@h3g2000cwc.googlegroups.com> <1173210288.178790.233730@64g2000cwx.googlegroups.com> Message-ID: <20070308014245.GG18179@performancedrivers.com> On Tue, Mar 06, 2007 at 11:44:48AM -0800, Arnaud Delobelle wrote: > On 5 Mar, 18:59, "Arnaud Delobelle" wrote: > [snip] > > Well in fact I couldn't help but try to improve it a bit. Objects now > > don't need a callerclass attribute, instead all necessary info is > > stored in a global __callerclass__. Bits that didn't work now do. > > OK that wasn't really thought through. Because I changed the design > mid-way through writing it __callerclass__ wasn't doing the right > thing. I've sorted the issues I could see and made it (hopefully) > thread-safe. I'm not going to pollute this list again with my code so > I've put it at the following address: > > http://marooned.org.uk/local.py > I fooled around with this a bit and even when using different techniques than Arnaud (namely stack inspection and/or class decorators) it ends up looking the same. In order to pull this off you need to 1) mark the localmethods as special (@localmethod works here) 2) mark all non-localmethods as not special (metaclasses, class decorators, or module-level stack inspection) 3) keep track of the call stack (can be implemented as part of #1 and #2 but adds overhead regardless) Double underscore names take care of #1 at compile time and by definition anything not name-manged falls into the non-special class of #2. After that the special/non-special calls are given different names so the native call semantics take care of the call stack for you. With some bytecode manipulation it should be possible to fake the same name mangling by using just @localmethod decorators and adding some overhead to always checking the current class (eg A.m() for the function am()) and falling back on doing the normal call of self.m(). This could be made more exact by doing inspection after the fact with any of metaclasses/class decorators/module inspection because then we could inspect what is a @localmethod and what isn't all the way through the class tree. I could be wrong on the byte-hack part as I've only recently learned to read the chicken bones that are byte codes (thanks to PyCon sprints I got to spend time picking python-devs's brains over burritos). It seem plausible if fragile. -Jack From Ognjen at mailshack.com Sat Mar 10 09:27:04 2007 From: Ognjen at mailshack.com (Ognjen Bezanov) Date: Sat, 10 Mar 2007 14:27:04 +0000 Subject: Help controlling CDROM from python Message-ID: <45F2C038.40601@mailshack.com> Hello, I am trying to control a CD-ROM drive using python. The code I use is shown below. > import CDROM > from fcntl import ioctl > import os > > > class Device: > > CDdevice="" > CDfd = None > > def __init__(self,name): > self.CDdevice = name #we get a device name when module loaded > > if self.CDdevice == "": > print "No device specified" > sys.exit(-1) > self.openCD() > > def openCD(self): > > try: > self.CDfd = open(self.CDdevice, 'r') #open the device and return filedescriptor > > except(OSError,IOError): #if there is an OS or IO Error (usually indicates nodisk) > print "Device Error, Halting.... (usually means drive or disk not found)" > sys.exit(-1) > def unlockCD(self): > return self.sendCDcommand(CDROM.CDROM_LOCKDOOR,0) > def ejectCD(self): > self.unlockCD() #we need to unlock the CD tray before we try to eject, otherwise we get an IO Error (#5) > return self.sendCDcommand(CDROM.CDROMEJECT) > > def sendCDcommand(self,command,argument=''): > return ioctl(self.CDfd,command,argument) > The code that calls the class is a follows: > import CD_Bindings > > CD = CD_Bindings.Device("/dev/cdrom") > > print CD.ejectCD() This works great, but only when there is a disk inside, otherwise we get an error. My issue is that I need to be able to eject the CDROM tray even if there is no disk inside. This is possible because other programs (like the linux "eject" command) can do it. Its just a question of how it is done in python. So I'm posting here in the hope someone can tell me. Thanks, Ognjen From cedb816 at yahoo.com Tue Mar 6 00:08:03 2007 From: cedb816 at yahoo.com (ce) Date: 5 Mar 2007 21:08:03 -0800 Subject: Islam, the Religion of Ease In-Reply-To: <1173155233.348048.220690@n33g2000cwc.googlegroups.com> References: <1173155233.348048.220690@n33g2000cwc.googlegroups.com> Message-ID: <1173157683.610018.305860@n33g2000cwc.googlegroups.com> On Mar 6, 12:27 pm, lovelyd... at hotmail.com wrote: > Excuse me!! > Would you stop for a moment?! > O...man...Haven't you thought-one day- about yourself ? > Who has made it? > Have you seen a design which hasn't a designer ?! > Have you seen a wonderful,delicate work without a worker ?! > It's you and the whole universe!.. > Who has made them all ?!! > You know who ?.. It's "ALLAH",prise be to him. > Just think for a moment. > How are you going to be after death ?! > Can you believe that this exact system of the universe and all of > these great creation will end in in nothing...just after death! > Have you thought, for a second, How to save your soul from Allah's > punishment?! > Haven't you thought about what is the right religion?! > Read ... and think deeply before you answer.. > It is religion of Islam. > It is the religion that Mohammad-peace upon him- the last prophet, had > been sent by. > It is the religion that the right Bible- which is not distorted-has > preached. > Just have a look at The Bible of (Bernaba). > Don't be emstional. > Be rational and judge.. > Just look..listen...compare..and then judge and say your word. > We advise you visiting :http://www.islam-guide.comhttp://www.thetruereligion.orghttp://www.beconvinced.comhttp://www.plaintruth.orghttp://english.islamway.comhttp://www.todayislam.comhttp://www.prophetmuhammed.orghttp://www.islamtoday.net/english/http://www.islamunveiled.orghttp://www.islamic-knowledge.com Yah, this has so much to do with python.. python is the language of ease too! I am muslim too by the way, but i dont' think this is a proper way to let ppl know about our religion, buddy! have any other opinion! From ms at cerenity.org Thu Mar 22 13:12:34 2007 From: ms at cerenity.org (Michael) Date: Thu, 22 Mar 2007 17:12:34 +0000 Subject: Kamaelia & Google's Summer of Code 2007 Message-ID: <4602b76c$0$8731$ed2619ec@ptn-nntp-reader02.plus.net> Hi, We're (BBC Research) participating in Google's Summer of Code as a mentor organisation again, and I thought it worth spreading some extra publicity where I think there might be some interested people. (I perhaps should've sent this sooner!) * What's Google Summer of Code? (I suspect most people here know :) Essentially Google are paying students to work on open source projects and being mentored in those projects, producing useful code and learning useful skills. Google's aim is to increase the number of people bitten by the open source bug :-) * How is BBC Research/ Kamaelia involved? Like last year we're a mentor organisation, Kamaelia is the open source project that project applications are invited for. It's aim is to make highly concurrent systems natural to create and simple to maintain. (given a choice of forces the we choose the latter) We seem to be having some success in this and have a number of systems we've built using Kamaelia. Kamaelia is primarily focussed around building networked, multimedia systems, tools and applications, since that's generally our problem domain, however Kamaelia is a generic component framework & toolset. Our project ideas and guidance page is here: * http://kamaelia.sourceforge.net/SummerOfCode2007 However, we're also interested other ideas beyond that, especially systems that use Kamaelia that can act as exemplars. To give an idea of potential scope, a list of components can be found here: * http://kamaelia.sourceforge.net/Components * Who can Apply ? You need to be a student now, or in september enrolled at a university degree course or similar level of institution/degree. * When is the deadline ? Monday midnight. * Url? http://code.google.com/soc/ Please feel free to forward this to any students or student groups you would find this interesting ! :-) Regards, Michael. -- Michael Sparks, Senior Research Engineer, BBC Research, Technology Group michael.sparks at rd.bbc.co.uk, Kamaelia Project Lead, http://kamaelia.sf.net/ From arnodel at googlemail.com Tue Mar 13 16:19:53 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 13 Mar 2007 13:19:53 -0700 Subject: Iterating across a filtered list In-Reply-To: <7xird5ndey.fsf@ruckus.brouhaha.com> References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <1173813714.767225.164790@q40g2000cwq.googlegroups.com> <7xird5ndey.fsf@ruckus.brouhaha.com> Message-ID: <1173817193.179354.235790@p15g2000hsd.googlegroups.com> On Mar 13, 7:36 pm, Paul Rubin wrote: > "Arnaud Delobelle" writes: > > in the for loop. Moreover you recalculate the regexp for each element > > of the list. > > The re library caches the compiled regexp, I think. That would surprise me. How can re.search know that string.lower(search) is the same each time? Or else there is something that I misunderstand. Moreover: In [49]: from timeit import Timer In [50]: Timer('for i in range(1000): search("abcdefghijk")', 'import re; search=re.compile("ijk").search').timeit(100) Out[50]: 0.36964607238769531 In [51]: Timer('for i in range(1000): re.search("ijk", "abcdefghijk")', 'import re; search=re.compile("ijk").search').timeit(100) Out[51]: 1.4777300357818604 -- Arnaud From john106henry at hotmail.com Fri Mar 9 16:58:09 2007 From: john106henry at hotmail.com (John Henry) Date: 9 Mar 2007 13:58:09 -0800 Subject: floating point rounding In-Reply-To: References: Message-ID: <1173477489.186292.167530@c51g2000cwc.googlegroups.com> On Mar 9, 5:45 am, hg wrote: > hg wrote: > > Hi, > > > Here is my issue: > > > f = 1.5 * 0.01 > > f > >>> 0.014999999999999999 > > '%f' % f > >>>'0.015000' > > > But I really want to get 0.02 as a result ... is there a way out ? > > > Thanks, > > > hg > > round Or more precisely: round(0.014999999999999999,2) if that's what you wish to do. From steve at REMOVE.THIS.cybersource.com.au Tue Mar 20 08:37:24 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 20 Mar 2007 23:37:24 +1100 Subject: any ways to judge whether an object is initilized or not in a class References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <1174293300.034362.282460@l75g2000hse.googlegroups.com> <45ffa91e$0$2136$426a74cc@news.free.fr> Message-ID: On Tue, 20 Mar 2007 10:28:10 +0100, Bruno Desthuilliers complained about classic classes: >> What's wrong with old-style classes? > > Almost everything. That's rather an exaggeration, don't you think? They have methods, and inheritance, and attributes, all the critical features of classes, and work perfectly well even if they don't support the more advanced features. >> - Documentation on old style classes is more extensive. > > Since new-style classes are backward compatible with old-style ones, Then "almost everything" is wrong with new style classes too? *wink* > almost all the old-style classes documentation applies to new-style ones > as well. Everything else is quite well documented too: > http://www.python.org/doc/newstyle/ On that very page, the first sentence says: "Unfortunately, new-style classes have not yet been integrated into Python's standard documention." complete with spelling mistake. >> On the minus side: >> >> - Properties don't work as you expect them too. > > properties don't work. Period. Properties rely on the descriptor > protocol, which only works with new-style classes. Non-data descriptors (e.g. properties with only a getter) work fine. It is only data descriptors (those with both a getter and a setter) that don't work correctly. > - no metaclasses Metaclasses worked all the way back in Python 1.5, although they were painful and brain-exploding. http://www.python.org/doc/essays/metaclasses > - no classmethod Guido's own documentation for classmethods and staticmethods uses classic classes. See http://www.python.org/download/releases/2.2.3/descrintro/#staticmethods But don't just take his word for it, try it for yourself *wink* -- Steven From dbhbarton at googlemail.com Fri Mar 9 04:14:46 2007 From: dbhbarton at googlemail.com (dbhbarton at googlemail.com) Date: 9 Mar 2007 01:14:46 -0800 Subject: 2 new comment-like characters in Python to aid development? Message-ID: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> Had a thought that's grown on me. No idea if it's original or not- too inexperienced in programming- but I guess there's no harm floating it out there. Python wins big on readability, and there's no doubt that context- dependent text formatting in IDEs (keywords, strings, comments etc) is a massive help too, therefore benefitting development and maintenance. This idea is in a similar vein, especially for when scripts grow large. What if 2 new 'special' comment-like characters were added to Python?: 1. The WIP (Work In Progress) comment: A '?' placed in the preceding whitespace of a line as a means of quickly highlighting a line or block of code for special attention. The interpreter simply ignores these characters, and executes the code as if each WIP character wasn't there. The value-added comes from how IDEs can exploit this to color the line or code block (in a customisable fashion as with other context-dependent IDE formatting). Thus... ?a=6 #This line gets highlighted. ?class MyClass: #This entire class gets highlighted. def __init__(self): self.val=3 ?def MyFn(): #This entire function gets highlighted. return 'x' ?for each in range(9): #This entire block gets highlighted. print each Simply delete the ? and the associated highlighting vanishes immediately. Indeed if the interpreter can tolerate one '?' then perhaps it can also allow '??' and '???', letting the IDE color each differently for some additional flexibility. Applications... Lets you highlight / un-highlight entire blocks with a single keystroke: to record which part of a long script you're working on, or which part needs development or optimization. IDEs could add additional functionality if they chose: options to remove all wip comments, or step through them, or even to automatically add WIP comments (to highlight syntax errors, potentially infinite loops, or rate-limiting code blocks, perhaps?) 2. The HALT comment: A '!' at the start of a line, indicating the end of the script proper. The interpreter would register this one, and ignore everything after it, a bit like a sys.exit() call but also stopping it from picking syntax errors after the HALT. IDEs could then 'grey out' (or 'yellow out' or whatever) all following characters, including later HALT comments. Applications... Lets you mask / unmask the tailing parts of a py script with a single keystroke: potentially quite useful during the writing / testing phase of coding when you might not want to run the whole thing, or as another means of adding extensive comments to the end of a file. Could also be rather handy in 'tutorial scripts' and the like... E.g... # Welcome to my Python Tutorial Script my_string="Hello World" print my_string ! # Everything after this '!' is ignored and greyed out for now, but when you're ready to move on to the next part of the tutorial script just delete the '!' and run it again. my_list=list(my_string) print my_list ! # <-- delete '!' when ready, etc etc my_list_reversed=my_list[::-1] print my_list_reversed As far as I can see, neither of these would break backwards compatibility and, like the @ decorator, if you don't like it, you wouldn't have to use it. I don't know enough about the guts of Python to say much about ease of implementation, but it doesn't seem like it would be too hard. Personally I'd use these a lot, but I'm a rank amateur so maybe I just don't develop code properly. That's it. Useful? Pointless? Dangerous? Stupid? Dave. From gagsl-py2 at yahoo.com.ar Fri Mar 23 04:00:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 05:00:29 -0300 Subject: Question regarding __new__ References: <20070322171952.121530d7@localhost> Message-ID: En Thu, 22 Mar 2007 13:19:52 -0300, Frank Benkstein escribi?: > Yet [1] says: "[...] some rules for __new__: [...] If you return an > object of a different class, its __init__ method will be called." That was true at that time (2.2 initial), but not now. See http://www.python.org/sf/537450 Revision 26220 - Modified Sat Apr 6 01:05:01 2002 UTC (4 years, 11 months ago) by gvanrossum - Changed new-style class instantiation so that when C's __new__ method returns something that's not a C instance, its __init__ is not called. [SF bug #537450] The documentation should be updated to reflect this change. > Am I missing something? Is this documented somewhere else? See http://docs.python.org/ref/customization.html > Also it > would be nice if someone could point me to the function that implements > this in C. I didn't find anything in object.c or typeobject.c. It's in typeobject.c, function type_call -- Gabriel Genellina From bbbart at inGen.be Sun Mar 4 04:14:22 2007 From: bbbart at inGen.be (Bart Van Loon) Date: Sun, 4 Mar 2007 14:14:22 +0500 Subject: portable Python ifconfig References: Message-ID: It was Sun, 4 Mar 2007 14:09:20 +0500, when Bart Van Loon wrote: > It was Sun, 4 Mar 2007 02:38:58 +0500, when Bart Van Loon wrote: >> Hi all, >> >> I'm looking for a portable (FreeBSD and Linux) way of getting typical >> ifconfig information into Python. > > After lots of trial and error (I'm proficient in C at all), I puzzled err... I'm NOT proficient in c at all :-) -- groetjes, BBBart Hobbes : How is the diorama coming along? Calvin : I'm almost finished. Hobbes : I don't see the roadrunner. Weren't you going to put one in? Calvin : See the cotton balls I glued down? Hobbes : Yeah? Calvin : The roadrunner just ran out of the scene leaving behind clouds of dust! From mail at microcorp.co.za Thu Mar 1 00:54:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 1 Mar 2007 07:54:24 +0200 Subject: Dialog with a process via subprocess.Popen blocks forever References: <1172698063.670659.318340@k78g2000cwa.googlegroups.com> Message-ID: <022201c75bca$1f390360$03000080@hendrik> wrote: > Is it possible to read to and write to the std streams of a > subprocess? What am I doing wrong? I think this problem lies deeper - there has been a lot of complaints about blocking and data getting stuck in pipes and sockets... I have noticed that the Python file objects seem to be inherently half duplex, but I am not sure if it is python or the underlying OS. (Suse 10 in my case) You can fix it by unblocking using the fcntl module, but then all your accesses have to be in try - except clauses. It may be worth making some sort of FAQ on this subject, as it appears from time to time. The standard advice has been to use file.flush() after file.write(), but if you are threading and have called file.read(n), then the flushing does not help - this is why I say that the file object seems to be inherently half duplex. It makes perfect sense, of course, if the file is a real disk file, as you have to finish the read before you can move the heads to do the write- but for pipes, sockets and RS-232 serial lines it does not make so much sense. Does anybody know where it comes from - Python, the various OSses, or C? - Hendrik From bbxx789_05ss at yahoo.com Sun Mar 25 16:22:36 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 25 Mar 2007 13:22:36 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: <1174813227.275145.211000@o5g2000hsb.googlegroups.com> References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> <1174813227.275145.211000@o5g2000hsb.googlegroups.com> Message-ID: <1174854156.298431.68150@n59g2000hsh.googlegroups.com> On Mar 25, 3:00 am, irs... at gmail.com wrote: > On Mar 25, 9:13 am, "7stud" wrote: > > > MyClass.someFunc > > > Is there some other way to retrieve a user-defined function object > > from a class other than using the class name or an instance? > > What Steven B. already said, MyClass.__dict__['someFunc'], is a > different way than MyClass.someFunc that produces different results. That doesn't seem to fit what GvR was talking about. From this example: class Test(object): def greet(): print "Hello" methObj = Test.__dict__["greet"] print methObj.im_self I get this output: Traceback (most recent call last): File "test1.py", line 7, in ? print methObj.im_self AttributeError: 'function' object has no attribute 'im_self' So it doesn't look like a method object gets created when you retrieve a function from a class like that. Compare to: class Test(object): def greet(): print "Hello" methObj = Test.greet print methObj.im_self output: None > Since the method is an attribute of a class, what other kinds of means > are you expecting to be possible? > I'm just wondering why in this description: ---- When a user-defined method object is created by retrieving a user- defined function object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its im_self attribute is the instance, and the method object is said to be bound. ----- GvR didn't explicitly mention using the class name to retrieve the function object in the first sentence. It seems to imply there are other ways to retrieve the function object from the class that cause a method object to be created. From john106henry at hotmail.com Mon Mar 19 14:30:32 2007 From: john106henry at hotmail.com (John Henry) Date: 19 Mar 2007 11:30:32 -0700 Subject: PythonCard thoughts In-Reply-To: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> References: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> Message-ID: <1174329032.236378.161150@e65g2000hsc.googlegroups.com> On Mar 19, 5:08 am, "king kikapu" wrote: > Hi to all folks here, > > i downloaded and "playing" with PythonCard and i just want to share my > thoughts so maybe we can discuss a little about it. > I was used to wxGlade before and i think PythonCard is even better. > I like the separate implementation of GUI and Code that PythonCard > provides, i also like the "binding system" so you can bind functions > to events and have them executed at runtime. > I also like that it does not force you to use sizers and all that > stuff and that you can freely place your components on the form and > set their exact position just with the mouse. > > The only "problem" i see with this design is that by that separation > of Gui/Code, you loose the intellisense that (ex. PyDev) some editors/ > plugins can provide because in the .py file nothing is indicating > that , for example, the btnDoWork is a Button object. > This force you to remember many properties and switch back and forth > between your code and the wxPython help file. This is not the case for > wxGlade because all boilerplate code is in the same file (for good and > for bad) and PyDev (and others too) can "understand" for which kind of > objects we are talking about and so can display -and thus help us- > with their properties. > > Apart from that, everything else is great. > > Any opinions/suggestion on all this ? (If I understand your question correctly) There is no restirction on what you call your objects. For instance, I do call all of my buttons btnSomeThing, and so forth. If you use the codeEditor that comes with Pythoncard, you can easily see which method goes with what control. (And yes, I wish there are more developers drawn to Pythoncard too - it's such a nice package). From facundo at taniquetil.com.ar Wed Mar 14 08:54:38 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 14 Mar 2007 12:54:38 +0000 (UTC) Subject: i can`t get python working on the command line (linux) References: <6e24a8e80703130804y7a88f1b0wf7ed30e98d6a35f7@mail.gmail.com> Message-ID: Mark wrote: > and i`ve put it in tel.py (just the same as in the sample) than chmod > it to 777 (just to make sure it isn`t a permission issue) and than i > run it with: ./tel.py > now this is the error that i get: > > Traceback (most recent call last): > File "./tel.py", line 12, in > for line in open(argv[1], 'r').readlines(): > IndexError: list index out of range Your Python is installed fine. The problem is that you're accesing argv[1], which would be the first argument after the program in the command line, and you're executing your program without any parameters. All you need to do is read the error message, they help, ;) Try executing your program with something like ./tel.py myfile.txt where, of course, myfile.txt is some file you have around... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From bignose+hates-spam at benfinney.id.au Tue Mar 20 18:10:37 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 21 Mar 2007 09:10:37 +1100 Subject: help - Module needs access to another module References: <1174398386.976864.109350@p15g2000hsd.googlegroups.com> <56a7j9F28bl1sU2@mid.uni-berlin.de> <1174400041.278036.183940@p15g2000hsd.googlegroups.com> Message-ID: <87odmn5zxe.fsf@benfinney.id.au> "abcd" writes: > On Mar 20, 9:58 am, "Diez B. Roggisch" wrote: > > http://docs.python.org/tut/node8.html > > got it, thanks. Now that you've got that one part of the tutorial, please do *the whole thing*. Start from the beginning, run each example and watch what it does. Experiment with it until you understand what's going on, then move on. Repeat until done. You'll possibly see a bunch of things you have already learned, but you *will* cover a lot of gaps in your knowledge that you don't even know exist. -- \ "People always ask me, 'Where were you when Kennedy was shot?' | `\ Well, I don't have an alibi." -- Emo Philips | _o__) | Ben Finney From sebast.weber at wanadoo.fr Sun Mar 4 06:18:14 2007 From: sebast.weber at wanadoo.fr (=?iso-8859-1?q?WEBER_S=E9bastien?=) Date: 04 Mar 2007 11:18:14 GMT Subject: SAMBA-PYTHON ??? Message-ID: <45eaaaf6$0$21150$7a628cd7@news.club-internet.fr> Hello, (I'm french and I speak english like a spanish cow : sorry.) Does someone know how to use the samba-python tdb.so module ? I've been looking for information about this on Google for 3 days and I've found not a word. The only functions I can use are 'open()' and 'first_key()' : not enough. Thank's. SW. From Afro.Systems at gmail.com Tue Mar 13 06:42:41 2007 From: Afro.Systems at gmail.com (Tzury) Date: 13 Mar 2007 03:42:41 -0700 Subject: Setting System Date And Time Message-ID: <1173782561.405032.85910@s48g2000cws.googlegroups.com> Is it possible to modify the Systems' Date and Time with python? From parker at hiredatum.demon.co.uk Tue Mar 6 02:13:07 2007 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Tue, 6 Mar 2007 07:13:07 +0000 Subject: Graphviz Python Binding for Python 2.5 on Windows? References: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> <45eca530$0$27390$ba4acef3@news.orange.fr> <1173160979.344083.91030@n33g2000cwc.googlegroups.com> Message-ID: In message <1173160979.344083.91030 at n33g2000cwc.googlegroups.com>, Alex Li writes >Thanks Michel, I will give it a try. > >Alex > > > You could simply generate the .dot files from python and do os.startfile on the dot file (which is what I do because it is remarkably easy!) Regards -- Ian Parker From psdasilvaX at esotericaX.ptX Fri Mar 23 10:41:04 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 23 Mar 2007 14:41:04 +0000 Subject: Still the __new__ hell ... In-Reply-To: References: <1174167360.522350@jubilee.claranet.pt> <45fe7f46$0$2138$426a74cc@news.free.fr> <1174337519.926611@jubilee.claranet.pt> <46010e1a$0$2347$426a74cc@news.free.fr> Message-ID: <1174674720.953469@jubilee.claranet.pt> Gabriel Genellina escreveu: > En Wed, 21 Mar 2007 07:51:32 -0300, Bruno Desthuilliers > escribi?: > >> Paulo da Silva a ?crit : >>> As a relatively inexperient >>> in python, how could I know that a 'string' is an instance of >>> basestring? >> >> By reading this newsgroup ?-) > > Or asking Python itself: > >>>> type("any string").mro() > [, , ] > > --Gabriel Genellina > Good! ;-) Paulo From gagsl-py2 at yahoo.com.ar Tue Mar 20 22:16:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 Mar 2007 23:16:56 -0300 Subject: generating stats from stdout on a regular interval References: <1174441516.876016.19360@y66g2000hsf.googlegroups.com> Message-ID: En Tue, 20 Mar 2007 22:45:16 -0300, russ escribi?: > Very new to Python - but excited to see what is possible - it sounds > very suitable for a project of mine I need a little help with. > > I've got an executable which writes out data to stdout in a CSV sort > of format - I'd like to grab the data from stdout and create stats > from it at a regular interval, i.e. every 10 min. Probably push the > stats out to a CSV file. > > The popen2 module can read the stdout just like a file, and the csv > module can handle the reading / writing. How do I go about > 'processing' the stdout every 10 min? The executable is continuously writting data to stdout, right? So your code will likely be reading that output inside a loop - just check using time.time() if the desired interval has elapsed. Maybe you'd prefer using the subprocess module instead of popen2. -- Gabriel Genellina From mikael at isy.liu.se Wed Mar 14 06:02:05 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 14 Mar 2007 11:02:05 +0100 Subject: Communicating with a DLL under Linux In-Reply-To: <45F6D87B.4070407@isy.liu.se> References: <45F6D87B.4070407@isy.liu.se> Message-ID: <45F7C81D.5020503@isy.liu.se> Thanks for all the responces, both on and off list. So, I should forget about the DLL, and if I intend to connect the thing to a Linux computer, I'll have to develop the code myself for communicating with it over USB. Fair enough. I might even try that. I've done some surfing since yesterday. Why do I always do that after asking stupid questions in public? It turns out that a Nicolas Sutre has already ported the thing to Linux: http://linuxk8055.free.fr/ Velleman links to his solution from their product page http://www.velleman.be/ot/en/product/view/?id=351346 which might mean something. Nicolas solution is only 250 lines of C code. It #includes a usb.h, so I guess a lot of its functionality is hidden there. It seems structured enough, so I might be able to find some inspiration there. I guess I have some reading to do before I can decide if I shall do this. Anyway, thanks once again for the responces. Not completely in dispair... /MiO From irstas at gmail.com Mon Mar 26 08:48:38 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 26 Mar 2007 05:48:38 -0700 Subject: with timeout(...): In-Reply-To: <56prsrF2am4a1U1@mid.uni-berlin.de> References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: <1174913318.298278.222300@l77g2000hsb.googlegroups.com> On Mar 26, 3:16 pm, "Diez B. Roggisch" wrote: > But to make that work reliably, it has to be ensured that no sideeffects > occur while being in some_long_running_stuff. which doesn't only extend to > python itself, but also external modules and systems (file writing, network > communications...). Which can't be done, unless you use a time-machine. Hey hey, isn't the Python mantra that we're all adults here? It'd be the programmers responsibility to use only code that has no side effects. I certainly can ensure that no side-effects occur in the following code: 1+2. I didn't even need a time machine to do that :P Or the primitive could be implemented so that Python throws a TimeoutException at the earliest opportunity. Then one could write except-blocks which deal with rolling back any undesirable side effects. (I'm not saying such timeout feature could be implemented in Python, but it could be made by modifying the CPython implementation) From gagsl-py2 at yahoo.com.ar Thu Mar 1 07:40:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Mar 2007 09:40:37 -0300 Subject: urlDecode() References: <1172706706.152350.56390@z35g2000cwz.googlegroups.com> <1172713540.467763.98810@t69g2000cwt.googlegroups.com> Message-ID: En Wed, 28 Feb 2007 22:45:40 -0300, gert escribi?: > import re > > def htc(m): > return chr(int(m.group(1),16)) > > def urldecode(url): > rex=re.compile('%([0-9a-hA-H][0-9a-hA-H])',re.M) > return rex.sub(htc,url) > > if __name__ == '__main__': > print urldecode('adasasdasd%20asdasdasdas') > > Ok thats it enough googeling around i make one my self :) You reinvented urllib.unquote -- Gabriel Genellina From hardcoded.software at gmail.com Wed Mar 7 19:34:27 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 7 Mar 2007 16:34:27 -0800 Subject: Flatten a two-level list --> one liner? In-Reply-To: References: Message-ID: <1173314066.947751.258930@v33g2000cwv.googlegroups.com> On Mar 7, 7:14 pm, "Sergio Correia" wrote: > Hi, > > I'm looking for an easy way to flatten a two level list like this > > spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] > > Into something like > eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > There are *no* special cases (no empty sub-lists). > > I have found two ways: > > 1) Accumulator > eggs = [] > for x in eggs: > eggs.extend(x) > > 2) Reduce > eggs = reduce(lambda x, y: x+y, spam) > > I feel the 1st way is too cumbersome (three lines), and although I > like the 2nd way (except for the lambda part), I understand reduce is > discouraged by Guido so I want to know if there is a "Better Way"(TM) > ? > > Any ideas? > > Thanks, > Sergio > > PS: Why does `sum` works only with numbers? A search in the python group should get you all the details you need. Quick answer: "sum(eggs, [])", but the "correct" way is to have a flatten() function, with those 3 lines. From bj_666 at gmx.net Mon Mar 26 14:01:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 26 Mar 2007 20:01:58 +0200 Subject: how to abort on syntax errors References: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: In <46080186$0$14151$b45e6eb0 at senator-bedfellow.mit.edu>, Josh wrote: > I have a lot of except Exception, e statements in my code, which poses some > problems. One of the biggest is whenever I refactor even the triviallest > thing in my code. > > I would like python to abort, almost as if it were a compile-time error, > whenever it cannot find a function, or if I introduced a syntax error. But, > instead, it merrily proceeds on its way. > > Is there some idiom that you use in situations like these? Just don't use so many ``except Exception:`` constructs that obviously swallow exceptions they shouldn't swallow. Ciao, Marc 'BlackJack' Rintsch From skip at pobox.com Tue Mar 13 08:41:59 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 13 Mar 2007 07:41:59 -0500 Subject: Request for a change in the csv module. In-Reply-To: <1173785251.78605@jubilee.claranet.pt> References: <1173741982.944813@jubilee.claranet.pt> <1173744248.195944.245550@t69g2000cwt.googlegroups.com> <1173747644.616698@jubilee.claranet.pt> <55n53lF25s78sU1@mid.uni-berlin.de> <1173785251.78605@jubilee.claranet.pt> Message-ID: <17910.39959.548972.889847@montanaro.dyndns.org> Paulo> That is not the point. The problem is to have things generalized. Well, perhaps. One of the goals of the csv module was to do things the way Excel does things. Ideally, that would include formatting elements with locale sensitivity. I've been working on a csv module in Python, so I decided to try the locale.format() calls in its writerow implementation. A number of test cases broke as a result because apparently locale.format doesn't do its job quite the same way Excel does. I don't think pushing the locale-sensitive formatting down into the csv module is going to be a panacea. Skip From mark at freelance-developer.com Sat Mar 3 11:56:07 2007 From: mark at freelance-developer.com (Mark Nenadov) Date: Sat, 03 Mar 2007 11:56:07 -0500 Subject: Randomizing in Python References: <1172940368.958826.273260@j27g2000cwj.googlegroups.com> Message-ID: On Sat, 03 Mar 2007 08:46:09 -0800, andre.ditador9999 at gmail.com wrote: > I want to randomize a certain calculation in Python but haven't > figured it out yet. To explain what i mean, I' m going to use an > example: > I want to get the numbers to do a random > experience database for a game. What would be necessary to do so? Look into the random module (http://docs.python.org/lib/module-random.html) random.choice selects a random item out of a sequence random.shuffle shuffles a sequence randomly random.random gives a random floating point number -- Mark Nenadov -> skype: marknenadov, web: http://www.marknenadov.com -> "Relying on the government to protect your privacy is like asking a peeping tom to install your window blinds." -- John Perry Barlow From me at mylife.com Tue Mar 27 14:23:05 2007 From: me at mylife.com (Jason B) Date: Tue, 27 Mar 2007 18:23:05 GMT Subject: 16bit RGB with Image module References: Message-ID: Well I kept screwing around and funny thing, this works: import sys, Image if len(sys.argv) == 2: print "\nReading: "+sys.argv[1] image_file = open(sys.argv[1], "rb") pixel_data = image_file.read() im = Image.fromstring("RGB", (326, 325), pixel_data, "raw", "BGR;16") im.show() Although I have no idea *why* it works, other than the fact that I'm now using the correct number of bits per pixel. :) Anyone have thoughts on this? Thanks! J "Jason B" wrote in message news:hcdOh.9548$JZ3.7651 at newssvr13.news.prodigy.net... > Hi all, > > I'm still new to all of this, but I'm trying to do something here that > *seems* like it should be pretty simple. All I want to do is take an > array of pixel data from a file (no header data or anything, just pixel > data) in RGB565 format and save it off to a bitmap file - or display it, > in the case below: > > import sys, Image > > if len(sys.argv) == 2: > print "\nReading: "+sys.argv[1] > image_file = open(sys.argv[1], "rb") > pixel_data = image_file.read() > > im = Image.fromstring("RGB", (326, 325), pixel_data) > im.show() > > When run, I get: > > ValueError: not enough image data > > Which I'm pretty sure is because it's expecting a 24bit image. Of course > if I tune down the width and height or change the format to B&W ("L") then > it *does* display an image, the B&W one even having recognizable features, > just not the right one. :( > > I've read through the documentation a thousand times trying to understand > the raw decoder and plugins, etc. but I still can't figure this out... > > Any help is greatly appreciated! > > Thanks, > J > From aahz at pythoncraft.com Tue Mar 20 16:48:08 2007 From: aahz at pythoncraft.com (Aahz) Date: 20 Mar 2007 13:48:08 -0700 Subject: any ways to judge whether an object is initilized or not in a class References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <45ffa91e$0$2136$426a74cc@news.free.fr> <4600476b$0$752$426a74cc@news.free.fr> Message-ID: In article <4600476b$0$752$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > >Not officially yet, true. But come on, it's been 6 (six) years since >type unification, and it has always been obvious (to me at least) that >the new object model was to replace the 'classic' one. ...in Python 3.0. Anything else you believe is strictly a product of your imagination. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From nagle at animats.com Sat Mar 17 01:42:12 2007 From: nagle at animats.com (John Nagle) Date: Fri, 16 Mar 2007 22:42:12 -0700 Subject: mySQLdb versus platform problem In-Reply-To: <45FB13EF.2050706@jessikat.plus.net> References: <45FB13EF.2050706@jessikat.plus.net> Message-ID: Robin Becker wrote: > John Nagle wrote: > >> Try: >> >> db=MySQLdb.connect(host='appx',db='sc_0',user='user',passwd='secret', >> use_unicode=True, charset = "utf8") >> >> The distinction is that "use_unicode" tells Python to convert to Unicode, >> but Python doesn't know the MySQL table type. 'charset="utf8"' tells >> MySQL to do the conversion to UTF8, which can be reliably converted >> to Unicode. >> >> John Nagle >> >> ....... > > > OK that seems to help. However, my database has tables with different > encodings. Does MySQLdb ignore the table encoding? That would be a bit > lame. MySQLdb, the client, doesn't know the table encoding. The server end does. > Also it still doesn't explain the different behaviours between unix & > win32 (or perhaps different defaults are somehow magically decided upon). The default encoding is an environment thing. It comes, somehow, from the locale your system thinks it is in. > -things were so much easier when bytes were bytes-ly yrs- > Robin Becker So convert the database to Unicode/UTF-8 and have everything be consistent. MySQL 5 can do that dynamically with an ALTER TABLE statement. John Nagle From DustanGroups at gmail.com Mon Mar 12 09:01:43 2007 From: DustanGroups at gmail.com (Dustan) Date: 12 Mar 2007 06:01:43 -0700 Subject: New to Python In-Reply-To: References: <55kmslF249ihcU1@mid.uni-berlin.de> Message-ID: <1173704503.459048.310560@t69g2000cwt.googlegroups.com> On Mar 12, 5:07 am, "Alberto Monteiro" wrote: > I wrote: > > >> Hi, I am new to Python, how stupid can be the questions I ask? > > >> For example, how can I add (mathematically) two tuples? > >> x = (1,2) > >> y = (3,4) > >> How can I get z = (1 + 3, 2 + 4) ? > > Wow, I really didn't expect that my silly little newbie question > would get so many _different_ answers! > > What is the best way to get documentation about the functions > and classes of python? I tried to google, but usually I can just > find the __doc__ of the objects, without examples or anything that > can help me use it. > > Alberto Monteiro Refer to this as a reference: http://docs.python.org/ It includes a tutorial and documentation on the functions and classes in all the global modules, as well as builtin functions (http:// docs.python.org/lib/built-in-funcs.html) and syntax. If you have prior experience with programming, you may be able to learn python from the tutorial, but otherwise, I would highly recommend you get a good book for beginners on python (http://wiki.python.org/moin/PythonBooks); there's plenty of them out there. From snakepit.rattlesnakes at gmail.com Fri Mar 9 07:36:40 2007 From: snakepit.rattlesnakes at gmail.com (Joydeep Mitra) Date: Fri, 9 Mar 2007 18:06:40 +0530 Subject: MPI in python? Message-ID: <972566ff0703090436w3d99d2d6hdf76b58a9eebe2b9@mail.gmail.com> Hi guys, I am a relatively new user of python. I wanted to know what are the minimum requirements (modules, etc) are required for paralleliing python programs on a multiproc linux cluster. Is there a tutorial that explains the MPI syntax in python with examples? Thanking in advance, Joydeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Wed Mar 14 15:07:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Mar 2007 15:07:09 -0400 Subject: os.path.basename() - only Windows OR *nix? In-Reply-To: <45F843AD.6050509@gmx.net> References: <45F843AD.6050509@gmx.net> Message-ID: Thomas Ploch wrote: > Hello, > > I have a cgi script that handles fileuploads from windows and *nix > machines. i need os.path.basename(filename) to get the pure filename. > > For *nix, thats not a problem, but for windows, it always returns the > full path: > > > > #/usr/bin/env python > > import cgi, os > import cgitb; cgitb.enable() > > form = cgi.FieldStorage() > filename = os.path.basename(form['uploadfile'].filename) > > print 'Content-Type: text/html\n\n' > print filename > > > > ----------------- > > For 'C:\text\text.txt', the output is 'C:\text\text.txt', which should > be 'text.txt', the same happens for 'C:\\text\\text.txt'. I think its > the escapes that makes python not splitting it. All Unix style paths get > converted the right way. > > Is there an easy way around this, or do I really have to write a parser > including _all_ Python escapes? > > Thomas First of all you should clarify your thinking about this issue. The problem isn't with os.path.basename (which assumes that paths are given for the local filestore architecture), the problem is that you are failing to correctly pre-condition your data. It's nothing to do with Python escapes - they are only relevant when you are writing string literals in Python. Pay no attention to the way the strings are printed - the Windows client is sending you a single backslash character for each path separator in its filename. You can check this using the len() function on the returned string. Clearly if form['uploadfile'] is returning the client's path information you do have to remove that somehow before further processing, which also means you need to deduce what the client architecture is to correctly remove path data. Of course this also leaves open the question "what does a Mac client return?", and you might want to cater for that also. I suspect you will also find that there are at least some circumstances under which a Unix browser will also include path information. I presume you are looking to use the same filename that the user provided on the client? Does this mean that each user's files are stored in different directories? Otherwise it's not always a good idea to use filenames provided by the user for files on the server anyway. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From richard.leland at gmail.com Wed Mar 7 06:42:49 2007 From: richard.leland at gmail.com (leland) Date: 7 Mar 2007 03:42:49 -0800 Subject: re-point mod_python - is it possible? In-Reply-To: <1173243624.574888.258390@h3g2000cwc.googlegroups.com> References: <1173240491.770637.27440@t69g2000cwt.googlegroups.com> <1173243624.574888.258390@h3g2000cwc.googlegroups.com> Message-ID: <1173267769.255639.118290@p10g2000cwp.googlegroups.com> great explaination - thanks graham! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 14 05:28:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 14 Mar 2007 10:28:38 +0100 Subject: Iterating across a filtered list In-Reply-To: <1173818667.789785.111220@d57g2000hsg.googlegroups.com> References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <7xveh5nfwz.fsf@ruckus.brouhaha.com> <1173812047.578137.223430@j27g2000cwj.googlegroups.com> <7xmz2hndh0.fsf@ruckus.brouhaha.com> <45f70709$0$5892$426a34cc@news.free.fr> <1173818667.789785.111220@d57g2000hsg.googlegroups.com> Message-ID: <45f7c030$0$6505$426a74cc@news.free.fr> Arnaud Delobelle a ?crit : > On Mar 13, 8:53 pm, Bruno Desthuilliers > wrote: >> Paul Rubin a ?crit : > > [snip] > >>> Iterators like that are a new Python feature >> List comps are not that new (2.0 or 2.1 ?): >> print "\n".join([contact for name, contact in contacts.items() \ >> if search.match(name)]) > > You can write this, but: > * it is difficult to argue that it is more readable than Paul's (or > my) 'imperative' version; I personnaly find it more readable. To me, it tells what, not how. > * it has no obvious performance benefit, No. >>> and they have >>> some annoying characteristics, like the way they mutate when you touch >>> them. >> While sequences are iterables, all iterables are not sequences. Know >> what you use, and you'll be fine. > > ...And know when to use for statements :) Don't worry, I still use them when appropriate. From knipknap at gmail.com Sat Mar 17 19:54:29 2007 From: knipknap at gmail.com (Samuel) Date: 17 Mar 2007 16:54:29 -0700 Subject: MIME Magic In-Reply-To: <87fy834fdm.fsf@gmail.com> References: <1174172570.473458.215460@y80g2000hsf.googlegroups.com> <87fy834fdm.fsf@gmail.com> Message-ID: <1174175669.774906.225530@l77g2000hsb.googlegroups.com> On Mar 18, 12:30 am, Jorge Godoy wrote: > I'd start by taking a look at "file"'s code. :-) > > The thing is being able to identify the signatures of several different types > of files. Here's some help for you:http://www.garykessler.net/library/file_sigs.html > > And here's an example of an authoritative source for that table:http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html Actually, I am looking for an existing solution because I do not want to write it from scratch... I hope I am not out of options. -Samuel From steve at REMOVEME.cybersource.com.au Tue Mar 13 21:14:49 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 14 Mar 2007 12:14:49 +1100 Subject: number generator References: Message-ID: On Tue, 13 Mar 2007 17:53:41 -0700, Dick Moores wrote: > At 05:47 PM 3/10/2007, Paul Rubin wrote: > >>The fencepost method still seems to be simplest: >> >> t = sorted(random.sample(xrange(1,50), 4)) >> print [(j-i) for i,j in zip([0]+t, t+[50])] > > ================================= > M = 50 > N = 4 > def sumRndIntRubin(M, N): > import random > t = sorted(random.sample(xrange(1,M), N-1)) > lst = [(j-i) for i,j in zip([0]+t, t+[M])] > > print t > print t + [M] > print [0] + t > print lst > print sum(lst) > > sumRndIntRubin(M, N) > ==================================== > [6, 20, 31] > [6, 20, 31, 50] > [0, 6, 20, 31] > [6, 14, 11, 19] > 50 > > I understand what zip() and random.sample() are doing, and the above > helps me get inside the fencepost method, but I don't understand WHY > it works, or how in the world anyone could have devised it. It is > truly magical to me! Me too. Although Alex Martelli's algorithm: map([random.randrange(5) for i in xrange(45)].count, xrange(5)) (each value needs adjusting up by one) really boggles my brain. I'm going to have to think about that. > BTW I did see this in this thread, "Suppose you have a fixed > telegraph pole at N and a fixed telegraph pole at M, and you're given > 5 more telegraph poles..." (Gerard Flanagan), but even now I can't > take it anywhere. I guess I'm just a dim bulb. (I thought I was a > fairly smart guy until I took up Python.) Consider the distance between each paid of consecutive poles. The sum of the distances must add up to the distance from the first to the last, and if there are two fixed poles plus five in between, there are five distances. Hence five (random) distances which sum to the required total. -- Steven D'Aprano From codecraig at gmail.com Fri Mar 9 15:24:27 2007 From: codecraig at gmail.com (abcd) Date: 9 Mar 2007 12:24:27 -0800 Subject: Are Lists thread safe? In-Reply-To: <1173469804.756713.41700@q40g2000cwq.googlegroups.com> References: <1173467014.510693.60330@30g2000cwc.googlegroups.com> <1173469137.897102.298120@p10g2000cwp.googlegroups.com> <1173469517.797876.262330@t69g2000cwt.googlegroups.com> <1173469804.756713.41700@q40g2000cwq.googlegroups.com> Message-ID: <1173471867.603306.135860@q40g2000cwq.googlegroups.com> On Mar 9, 2:50 pm, "abcd" wrote: > I guess this might be overkill then... > > class MyList(list): > def __init__(self): > self.l = threading.Lock() > > def append(self, val): > try: > self.l.acquire() > list.append(self, val) > finally: > if self.l.locked(): > self.l.release() > > ....performing the same locking/unlocking for the other methods (i.e. > remove, extend, etc). comments? From iltchevi at gmail.com Sun Mar 11 18:39:08 2007 From: iltchevi at gmail.com (ici) Date: 11 Mar 2007 15:39:08 -0700 Subject: a better solution for GUI in python In-Reply-To: <1173611016.810735.70700@30g2000cwc.googlegroups.com> References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> Message-ID: <1173652748.128071.87250@j27g2000cwj.googlegroups.com> On Mar 11, 1:03 pm, "ce" wrote: > Hi, > > My company is using python currently for our website. We need to > develop a GUI front-end for our ERP that would be portable (Windows > and Linux). > > My question is which solution would be better for the GUI (and easier > to implement)? I knew there are something like wxidgets, QT and pyGTK? > actually we will need some complicated stuff in the GUI and yet I > don't know much about GUI programming. > > Any recommendation guys? http://pythoncard.sourceforge.net/ - Debugger, visual editor(resource editor) , one place event handlers like on_Object_Command, uses wxPython but easy than VB. From fumanchu at amor.org Sat Mar 10 15:57:23 2007 From: fumanchu at amor.org (fumanchu) Date: 10 Mar 2007 12:57:23 -0800 Subject: Database module & multithreading In-Reply-To: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> Message-ID: <1173560243.069846.307160@q40g2000cwq.googlegroups.com> On Mar 10, 6:14 am, "jupiter" wrote: > Just one quick question... Which database module > should I use when I want to use multi threading > as my application requires lots of data from > internet ???? I also want this database module > to be fast, simple n efficient, in any case > multi threading capabilities are # 1 requirement. Any discussion of multithreaded database access should also address isolation levels and locking scenarios. Have a look at the bottom of http://projects.amor.org/docs/dejavu/1.5.0RC1/storage.html#comparison ... especially the footnotes. Note that Firebird and SQLite immediately raise errors on locking conflicts, so you need to write your own retry mechanisms. SQLServer and MySQL, in contrast, have their own (configurable) timeout settings. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From john.pye at gmail.com Wed Mar 21 00:30:34 2007 From: john.pye at gmail.com (John Pye) Date: 20 Mar 2007 21:30:34 -0700 Subject: How to receive a FILE* from Python under MinGW? In-Reply-To: References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> Message-ID: <1174451434.910082.231900@b75g2000hsg.googlegroups.com> On Mar 21, 3:15 pm, "Gabriel Genellina" wrote: > En Wed, 21 Mar 2007 00:46:03 -0300, John Pye > escribi?: > > > This is not an option for me, as I want to pass the > > FILE* from Python and all the way into into a existing shared-library > > code. I can't change the latter; it must work ok with standard fprintf > > (etc) functions. > > You can get the file descriptor from the Python file object using its > fileno() method. The file descriptor lives at the OS level, so it's safe > to pass around. You can regenerate a new FILE struct (using the other > runtime library) with fdopen. > > -- > Gabriel Genellina Hi Gabriel Are you sure about this? My understanding is that 'fileno' is just a FILE* cast to an integer. So it's a pointer to something (check out stdio.h to see what it points to). Problem is (AFAICT) that Python 2.4 uses a different version of the C runtime DLL (MSVCRT*.DLL) to that which MinGW links against. And it turns out that the different C runtime libraries have incompatible implementations of the FILE struct. And therefore if you try to pass a FILE* (fileno?) from Python to MinGW you will get a segfault. If there is more to your suggestion that I'm not seeing, please clarify. Have you tried this with MinGW actually? Cheers JP From johnpenk7 at yahoo.com Tue Mar 27 08:55:39 2007 From: johnpenk7 at yahoo.com (jp) Date: 27 Mar 2007 05:55:39 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> <1174925855.552135.228190@n59g2000hsh.googlegroups.com> <1174926471.899631.228810@e65g2000hsc.googlegroups.com> <1174926951.133085.294900@l75g2000hse.googlegroups.com> Message-ID: <1175000139.216317.22670@p77g2000hsh.googlegroups.com> On Mar 26, 5:41 pm, John McMonagle wrote: > jp wrote: > >>> On Mar 26, 10:51 am, "jp" wrote: > >>>> I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > >>>> I skip over these widgets when using the tab key? > >>>> Thank you, > >>>> John > > What version of Pmw are you using ? Tabbing between widgets works fine > on my system (Pmw 1.2, tk 8.4, KDE) > > I can change the focus behaviour by using the takefocus option. You > were on the right track, you just did it wrong (see code below): > > ######################################################################## > from Tkinter import * > import Pmw > > root = Tk() > entry = Pmw.EntryField(root, labelpos=W, value="", label_text='Name:') > entry.grid(row=1) > entry.component('entry').configure(takefocus=0) > > Button(root,text='test1').grid(row=2) > Button(root,text='test2').grid(row=3) > Button(root,text='test3').grid(row=4) > > root.mainloop() > ######################################################################### > > Regards, > > John Thank you for pointing out my error, John and James. I had the syntax of the command messed up. Using the following does cause the field to be skipped when tabbing: entry.component('entry').configure(takefocus=0) John From aleax at mac.com Tue Mar 20 01:29:54 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 19 Mar 2007 22:29:54 -0700 Subject: Documentation for "str()" could use some adjustment - Unicode issue References: Message-ID: <1hv8tz5.l61xmz1mtprhiN%aleax@mac.com> John Nagle wrote: ... > The real problem is the published books on Python: > > "Learning Python", by Lutz and Ascher: > "str(string) -- returns the string representation of any object." > > "Python in a Nutshell", by Martelli > Doesn't really address the issue, but says that "print" calls > "str" for conversions. > > Neither of these mentions that "str" is ASCII-only. Are you looking at p. 109 of the 2nd edition of the Nutshell? That's where looking for str will eventually lead you. The word "ASCII" is nowhere in sight in this page (because it's only true if you don't change the default encoding, so saying "str is ASCII-only" would be a lie -- now THAT kind of disinformation WOULD be a "real problem" in a "published book on Python") but right after the documentation for __str__ you see that for __unicode__ which explains their respective roles (returning plain-string types and unicode strings respectively). Unicode is documented on page 198 ff, where you will clearly see that: """ Python uses a default encoding, normally 'ascii'. """ followed by pointers to modules and functions connected with changing that default, and a recommendation to avoid doing that and why. I therefore dispute your contention that "Python in a Nutshell" ``doesn't really address the issue", as well as your other contention that "the real problem is" my book (I won't speak for Lutz and Ascher). If you disagree, feel free to open an errata on O'Reilly's page devoted to my book (and/or to the one by Lutz and Ascher); I will of course do my best to strongly rebut your provably-false contentions, if it's my book you choose to attack (I use the word advisedly, because it's easy to see that you're not interested in offering constructive criticism and suggestions -- it would have been obvious to open an errata, had you been thus interested -- but only in picking a public fight about this). Alex From michele.simionato at gmail.com Mon Mar 26 09:40:51 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Mar 2007 06:40:51 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174916451.809708.253720@p15g2000hsd.googlegroups.com> On Mar 26, 9:20 am, "Noma... at gmail.com" wrote: > OK... > I've been told that Both Fortran and Python are easy to read, and are > quite useful in creating scientific apps for the number crunching, but > then Python is a tad slower than Fortran because of its a high level > language nature, so what are the advantages of using Python for > creating number crunching apps over Fortran?? > Thanks > Chris The standard way is to perform the number crunching in Fortran and to use Python as glue. See for instance the scipy project, which includes the f2py bridge. Michele Simionato From steve at REMOVEME.cybersource.com.au Thu Mar 22 23:03:12 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Mar 2007 14:03:12 +1100 Subject: Idiom for running compiled python scripts? References: Message-ID: On Fri, 23 Mar 2007 01:01:15 +0000, Mark wrote: > So given the lack of response it seems that there is probably no such > idiom and that I should not be concerned by the inefficiency inherent in > running .py scripts directly? > > I did some time tests and sure, the speed gain is slight, but it is a > gain none the less. Since you've done these tests already, perhaps you can tell us what gain you actually got? Here's a test I did: [steve at apple ~]$ time python script.py the result is 166166000 real 0m0.555s user 0m0.470s sys 0m0.011s [steve at apple ~]$ time python script.pyc the result is 166166000 real 0m0.540s user 0m0.456s sys 0m0.011s That gives me an absolute gain of 15ms which is a percentage gain of about 3%. But don't forget the time it takes you to type the extra "c" at the end of the script, even with filename completion. The average human reaction time is something between 200 and 270 milliseconds, so unless you're saving at least 200ms, typing that extra "c" at the end actually wastes time. Of course you have to type the "c". You're not deleting the source files away are you? *wink* -- Steven D'Aprano From gabriel.hase at gmail.com Fri Mar 23 09:08:21 2007 From: gabriel.hase at gmail.com (killkolor) Date: 23 Mar 2007 06:08:21 -0700 Subject: "finally" for unit test In-Reply-To: References: <1174648739.464811.7150@y80g2000hsf.googlegroups.com> Message-ID: <1174655301.114220.4260@e65g2000hsc.googlegroups.com> I went with the TestCase.setUp() function. Thanks a lot! From jjl at pobox.com Sun Mar 25 18:29:03 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 25 Mar 2007 22:29:03 GMT Subject: A better webpage filter References: Message-ID: <87ps6x2c07.fsf@pobox.com> Anton Vredegoor writes: [...] > Most web pages I visit lately are taking so much room for ads (even > with adblocker installed) that the mere 20 columns of text that are > available for reading are slowing me down unacceptably. I have tried [...] http://webcleaner.sourceforge.net/ Not actually tried it myself, though did browse some of the code once or twice -- does some clever stuff. Lots of other Python-implemented HTTP proxies, some of which are relevant (though AFAIK all less sophisticated than webcleaner), are listed on Alan Kennedy's nice page here: http://xhaus.com/alan/python/proxies.html A surprising amount of diversity there. John From facundo at taniquetil.com.ar Thu Mar 22 15:18:37 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 22 Mar 2007 19:18:37 +0000 (UTC) Subject: What is the best way to upgrade python? References: <1173388393.052558.69270@s48g2000cws.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > i am using red hat enterprise 4. It has python 2.3 installed. What is > the best way to upgrade to python 2.4? > > I think one way is to compile python 2.4 from the source, but I can't > remove the old one since when i do 'rpm -e python', i get error like > 'failed dependencies'. Install Py2.4 and actually start using it, are two different animals. For example, I have installed Py2.4 and Py2.5 in my laptop. They coexist, and there's no problem about this. Telling all your installed applications to use the newer, it's not so easy, mainly because you don't have the power to test and change every installed application. So let them be. Just install the new version, and use it. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From mail at microcorp.co.za Sat Mar 10 03:48:22 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 10 Mar 2007 10:48:22 +0200 Subject: Need help with a string plz! (newbie) References: <1173475520.292989.239200@p10g2000cwp.googlegroups.com><12v3ksihos7uj7a@corp.supernews.com><1173477047.467568.298090@p10g2000cwp.googlegroups.com><2ZqdnZCruccLRWzYnZ2dnUVZ_rqhnZ2d@comcast.com> <1173488215.913014.130190@h3g2000cwc.googlegroups.com> Message-ID: <01f501c762f1$48bc7860$03000080@hendrik> wrote: > Oh, thanks for the advice then. And as for Grant..look forward to > seeing more of your posts. YOW! - some recognition at last! - Hendrik From bignose+hates-spam at benfinney.id.au Sun Mar 4 01:37:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 04 Mar 2007 17:37:27 +1100 Subject: Non Sequitur References: <1172968335.511875.255750@p10g2000cwp.googlegroups.com> <1172979629.812957.156820@i80g2000cwc.googlegroups.com> <_ftGh.8984$tD2.396@newsread1.news.pas.earthlink.net> Message-ID: <87lkid1plk.fsf_-_@benfinney.id.au> Dennis Lee Bieber writes: > """ > I before E > Except after C > Or when sounded as A > As in Neighbor and Weigh > """ Yes, like the "A" sound in "weird" or "ceiling". -- \ "Most people don't realize that large pieces of coral, which | `\ have been painted brown and attached to the skull by common | _o__) wood screws, can make a child look like a deer." -- Jack Handey | Ben Finney From jjl at pobox.com Sat Mar 24 11:15:21 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 24 Mar 2007 15:15:21 GMT Subject: [JOB] Sr. Python Developer, Northern VA References: <87aby59dy1.fsf@pobox.com> Message-ID: <871wje8ygd.fsf@pobox.com> Chuck Rhode writes: > John J. Lee wrote this on Thu, 22 Mar 2007 21:16:13 +0000. My reply is > below. > > > I sympathise but conventional wisdom (which surely has a lot of > > truth in it) is that employers are not faced with the problem of > > minimising false negatives (failing to hire when they should have > > hired). They are faced with the problem of minimising false > > positives (hiring when they should not have hired). That's a gross > > simplification of course, but I'm sure you appreciate the point -- > > if you're hiring employees, being fairly risk-averse is probably > > quite rational. > > ... so what's this we hear of employers' (in the US) being so starved > for talent that they're willing to bring in young men from overseas > with 3.5 kids and 1.5 wives? I honestly don't follow the connection between my statements about the way things are and the ethical (?) position you appear to be pushing. Please don't take offence when I ask you not to bother to elaborate, though. John From beliavsky at aol.com Mon Mar 19 12:09:47 2007 From: beliavsky at aol.com (Beliavsky) Date: 19 Mar 2007 09:09:47 -0700 Subject: check if files are the same on Windows Message-ID: <1174320587.618875.48290@y66g2000hsf.googlegroups.com> A crude way to check if two files are the same on Windows is to look at the output of the "fc" function of cmd.exe, for example def files_same(f1,f2): cmnd = "fc " + f1 + " " + f2 return ("no differences" in popen(cmnd).read()) This is needlessly slow, because one can stop comparing two files after the first difference is detected. How should one check that files are the same in Python? The files are plain text. From aleax at mac.com Tue Mar 6 10:37:46 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 6 Mar 2007 07:37:46 -0800 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <45ec933a$0$15549$426a34cc@news.free.fr> <1huivd7.7l18eh1paqp0aN%aleax@mac.com> <1173167838.173634.62810@c51g2000cwc.googlegroups.com> Message-ID: <1hujkde.1ukd1ix1easo5cN%aleax@mac.com> Martin Unsal wrote: > On Mar 5, 10:06 pm, a... at mac.com (Alex Martelli) wrote: > > My favorite way of working: add a test (or a limited set of tests) for > > the new or changed feature, run it, check that it fails, change the > > code, rerun the test, check that the test now runs, rerun all tests to > > see that nothing broke, add and run more tests to make sure the new code > > is excellently covered, rinse, repeat. Occasionally, to ensure the code > > stays clean, stop to refactor, rerunning tests as I go. > > From the way you describe your workflow, it sounds like you spend very > little time working interactively in the interpreter. Is that the case > or have I misunderstood? I often do have an interpreter open in its own window, to help me find out something or other, but you're correct that it isn't where I "work"; I want all tests to be automated and repeatable, after all, so they're better written as their own scripts and run in the test-framework. I used to use a lot of doctests (often produced by copy and paste from an interactive interpreter session), but these days I lean more and more towards unittest and derivatives thereof. Sometimes, when I don't immediately understand why a test is failing (or, at times, why it's unexpectedly succeeding _before_ I have implemented the feature it's supposed to test!-), I stick a pdb.set_trace() call at the right spot to "look around" (and find out how to fix the test and/or the code) -- I used to use "print" a lot for such exploration, but the interactive interpreter started by pdb is often handier (I can look at as many pieces of data as I need to find out about the problem). I still prefer to run the test[s] within the test framework, getting interactive only at the point where I want to be, rather than running the tests from within pdb to "set breakpoints" manually -- not a big deal either way, I guess. Alex From soyouthinkimgonnalikethis at hotmail.com Sat Mar 31 09:38:53 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 31 Mar 2007 09:38:53 -0400 Subject: os.system questions In-Reply-To: Message-ID: Oops! The problem isn't in the os.system call. It's in the fact that I don't call the function. That is, I write a script called "test.py" with a function in it called "freshReboot". Now, how do I call that function from test.py? That is, how do I write a cron event such that "freshReboot" actually gets called when I run test.py? TIA, Eric >From: "Eric Price" >To: khemkaamit at gmail.com >CC: python-list at python.org >Subject: Re: os.system questions >Date: Sat, 31 Mar 2007 09:33:03 -0400 > >Great! That seems to work fine: > >#!/usr/local/bin/python >import re, os > >def freshReboot(): > up = os.popen('uptime').readlines() > up = up[0] > if re.search('day|hour', up): > pass > else: > tup = re.split('min', up) > first = tup[0] > n = len(first) > char = first[n-3:n-2] > if re.match(' ', char): > os.system("/usr/local/etc/rc.d/zz_mysql_starter_script.sh") > >However, I don't see evidence that the os.system call at the end actually >executes said script. The reason for this screwy script is because MySQL >doesn't set the proper environment on boot and that screws up my Zope >instances. So, I'll cron this script to run every 6 mins. If the server has >been up less than 10 mins, this script will run. So, I rebooted the server >and ran the script. But it didn't execute the os.system script at the end! >If I run this from the python prompt instead: > >import re, os > >def a(): > up = os.popen('uptime').readlines() > up = up[0] > up = " 7:25AM up 2 mins, 1 user, load averages: 2.42, 1.01, 0.41" > if re.search('day|hour', up): > pass > else: > tup = re.split('min', up) > first = tup[0] > n = len(first) > char = first[n-3:n-2] > if re.match(' ', char): > print "gotcha!" > >it prints "gocha!" Now, that substitution for the "up" var is what I got as >output from the "uptime" command at the shell prompt. So, obviously, it >should be running the script! What am I doing wrong? >TIA, >Eric > >_________________________________________________________________ >Watch free concerts with Pink, Rod Stewart, Oasis and more. Visit MSN >Presents today. >http://music.msn.com/presents?icid=ncmsnpresentstagline&ocid=T002MSN03A07001 > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ 5.5%* 30 year fixed mortgage rate. Good credit refinance. Up to 5 free quotes - *Terms https://www2.nextag.com/goto.jsp?product=100000035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h2a5d&s=4056&p=5117&disc=y&vers=910 From PrikrylP at skil.cz Wed Mar 14 09:38:15 2007 From: PrikrylP at skil.cz (Petr Prikryl) Date: Wed, 14 Mar 2007 14:38:15 +0100 Subject: Q: Cteni unicode retezcu ze souboru UTF-8 s BOM? Message-ID: Ahoj v?eci, Tak n?jak prakticky poprv? se dost?v?m k tomu, jak p?e??st unicode ?et?zce ze souboru, kter? je ulo?en ve form?tu UTF-8 se signaturou na za??tku (BOM). N?jak se mi neda??. M?m takov?to soubor.txt v UTF-8 s BOM ===================================== Prvn? ??dek. Druh? ??dek. T?et? ??dek. P???ern? ?lu?ou?k? k?? ?p?l ??belsk? ?dy. ===================================== ... a pust?m skript ===================================== import codecs f = codecs.open('soubor.txt', 'r', 'utf-8') for line in f: print repr(line) print line[1:] f.close() ===================================== V?sledek vypad? takto ===================================== C:\tmp>python a.py u'\ufeffPrvn\xed \u0159\xe1dek.\r\n' Prvn? ??dek. u'Druh\xfd \u0159\xe1dek.\r\n' ruh? ??dek. u'T\u0159et\xed \u0159\xe1dek.\r\n' ?et? ??dek. u'P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy.\r\n' ???ern? ?lu?ou?k? k?? ?p?l ??belsk? ?dy. ===================================== V?imn?te si, ?e na prvn?m ??dku je \ufeff, co? je Byte Order Mark, kter? se tam v?bec nem? objevit. Jev? se mi to jako chyba. Na v?ech ??dc?ch z?m?rn? nevypisuji printem prvn? znak, proto?e u toho prvn?ho ??dku to krachne (co? je pochopiteln?). ?e?il n?kdo n?co podobn?ho? Mus? se BOM ukous?vat ve vlastn? re?ii? D?ky, pepr From mark.dufour at gmail.com Mon Mar 26 10:09:26 2007 From: mark.dufour at gmail.com (mark.dufour at gmail.com) Date: 26 Mar 2007 07:09:26 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174158002.730076.22720@y80g2000hsf.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> <1174024633.431427.236920@y66g2000hsf.googlegroups.com> <7xslc5k9cc.fsf@ruckus.brouhaha.com> <1174158002.730076.22720@y80g2000hsf.googlegroups.com> Message-ID: <1174918166.654117.307670@p77g2000hsh.googlegroups.com> > FWIW, the original program can also be compiled with Shed Skin (http:// > mark.dufour.googlepages.com), an experimental (static-)Python-to-C++ > compiler, resulting in a speedup of about 8 times for a single test > with 500 tuples. here's a slightly modified version that works with > Shed Skin CVS at least: after optimizing dicts a bit for Shedskin 0.0.21 (http:// mark.dufour.googlepages.com), the speedup for this program is now about 16.5 times for the same test. Thanks, Mark Dufour (Shed Skin author - send me bug reports!) From steve at holdenweb.com Thu Mar 22 08:51:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 08:51:51 -0400 Subject: fine grain logging cotrol In-Reply-To: References: Message-ID: Eric S. Johansson wrote: > I need to to be able to conditionally log based on the method the log > statement is in and one other factor like a log level. in order to do > so, I need to be able to automatically find out the name of the method > and its class but I haven't found out how to do that yet. > > for example, > > class catus(Felis): > def Siamese_cat( yowl, purr, demand_food): > > ... > log("state of litter box %s"% litter_box.smell, level = 1) > > > If the table of methods logged contains "catus.Siamese_cat", then I > would expect to see the output of the log statements in a log file. If > not then I wouldn't see anything in the log. > > Has somebody done this already? Is it even possible to do without > manually adding the class and method information for every log statement? > > a related question is using signals for reloading configurations etc. I > have to find any good examples of how to use signals to cause a > long-running process to reload external data. Any good pointers? > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From aleax at mac.com Sun Mar 18 13:33:13 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 18 Mar 2007 10:33:13 -0700 Subject: Finding the insertion point in a list References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <7xird0bom3.fsf@ruckus.brouhaha.com> <7xfy845q24.fsf@ruckus.brouhaha.com> <7xbqir9d05.fsf@ruckus.brouhaha.com> <1174238142.658049.13380@e65g2000hsc.googlegroups.com> Message-ID: <1hv62l6.yav5zjodogp9N%aleax@mac.com> 7stud wrote: > On Mar 18, 2:23 am, Paul Rubin wrote: > > Steve Holden writes: > > > > max(i for i,t in enumerate(x) if t <= y) > > > > Those are actually pretty direct. > > > > > How about a solution (like the bisect one suggested almost as soon as > > > this thread started) that doesn't iterate over the whole list. > > > > Here's a Haskell-inspired one: > > > > len(list(itertools.takewhile(lambda t: y > t, x))) > > Can you explain how list() works in that statement. I looked up > takewhile() and it returns an iterator that will automatically stop at > the insertion point? So does list() do an internal comprehension with > the iterator? Any call to list(iterator) works roughly as follows: def likelist(iterator): result = [] while True: try: result.append(iterator.next()) except StopIteration: return result Alex From melirizarry at gmail.com Thu Mar 1 09:05:17 2007 From: melirizarry at gmail.com (Mel) Date: 1 Mar 2007 06:05:17 -0800 Subject: How do I Color a QTableView row in PyQt4 In-Reply-To: <29fbf$45e61974$54d1d767$18593@news.chello.no> References: <1172685355.820708.149990@q2g2000cwa.googlegroups.com> <29fbf$45e61974$54d1d767$18593@news.chello.no> Message-ID: <1172757917.160687.228650@z35g2000cwz.googlegroups.com> On Feb 28, 5:08 pm, David Boddie wrote: > On Wednesday 28 February 2007 18:55, Mel wrote: > > > > > I am currently porting an SQL centered Visual Basic application to run > > on Linux, Python, and Qt4. Currently I am stumped on changing row > > colors in the QTableView widget. My test code is based on code from > > the PyQt4 examples and looks like this: > > > *** Start Code *** > > > import sys > > from PyQt4 import QtCore, QtGui, QtSql > > > import connection > > > class CustomSqlModel(QtSql.QSqlQueryModel): > > def data(self, index, role): > > value = QtSql.QSqlQueryModel.data(self, index, role) > > if value.isValid() and role == QtCore.Qt.DisplayRole: > > if index.column() == 0: > > return QtCore.QVariant(value.toString().prepend("#")) > > elif index.column() == 2: > > return QtCore.QVariant(value.toString().toUpper()) > > if role == QtCore.Qt.TextColorRole and index.column() == 1: > > return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue)) > > return value > > [Snipping the rest of the code to keep this post short.] > > > Column 18 in the table shows a number from 1 to 3. I would like to > > change the color of the row based on the value in column 18 but I have > > not been able to find any resources that show me how. Can anyone lend > > a hand? > > It's interesting to see that you subclassed QSqlQueryModel instead of > using a custom delegate to display the data. It's usually recommended > that you subclass QItemDelegate if you want to customize the way items > are represented, but you can also customize the model if you want. > > What you can do is to check to see if the requested role is the > Qt.BackgroundRole and, if so, query the base class for the data in > column 18 in the same row. Then you can supply a different colour > (as a brush, actually) depending on the value you obtained. > > if role == QtCore.Qt.BackgroundRole: > # Get the data from column 18. > column18_data = index.sibling(index.row(), 18).data() > # The data is stored in a QVariant, so we unpack it. > integer_value = column18_data.toInt()[0] # just the value > # Look up the associated color in a dictionary which you > # have already defined, and return it. > color = self.colors.get(integer_value, self.default_color) > return QtCore.QVariant(QtGui.QBrush(color)) > > You might also find the following pages useful: > > http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html#ItemDataRol...http://doc.trolltech.com/4.2/model-view-model.html > > Good luck! > > David Thanks David, that did work as I had hoped. I just need to work on the colors a bit and make them more appealing. Here is my final code that works for the custom Sql Model. class CustomSqlModel(QtSql.QSqlQueryModel): def data(self, index, role): value = QtSql.QSqlQueryModel.data(self, index, role) if value.isValid() and role == QtCore.Qt.DisplayRole: if index.column() == 0: return QtCore.QVariant(value.toString().prepend("#")) elif index.column() == 2: return QtCore.QVariant(value.toString().toUpper()) if role == QtCore.Qt.TextColorRole and index.column() == 1: return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue)) if role == QtCore.Qt.BackgroundRole: # Get the data from column 18. column18_data = index.sibling(index.row(), 18).data() # The data is stored in a QVariant, so we unpack it. integer_value = column18_data.toInt()[0] # just the value # Look up the associated color in a dictionary which you # have already defined, and return it. if integer_value == 1: return QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.red))) if integer_value == 2: return QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.yellow))) if integer_value == 3: return QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.green))) return value Mel From gregpinero at gmail.com Fri Mar 9 15:22:02 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 9 Mar 2007 12:22:02 -0800 Subject: How to Start a (thread?) and Leave Message-ID: <1173471722.668943.126700@h3g2000cwc.googlegroups.com> Here's my situation, would you folks be so kind as to reccomend an approach? I have a small Python CGI script running as an intranet app. One of the things the script needs to do is allow users to save invoices. This is a process that takes about 60 seconds once the user submits the order from the web app. Ideally I'd like the CGI script to kick off a process to save the invoice but not wait until it's finished to render the page. What's the best way to do this, a thread, call a separate program from os.system, something else? Thanks in advance for the help. -Greg From gagsl-py2 at yahoo.com.ar Fri Mar 9 16:13:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 18:13:43 -0300 Subject: C++ and Python References: <1173420288.646573.327340@h3g2000cwc.googlegroups.com> Message-ID: En Fri, 09 Mar 2007 05:28:54 -0300, hg escribi?: > Mandus wrote: >> 8 Mar 2007 22:04:48 -0800 skrev bressert at gmail.com: >>> I'm considering about generating some Python Bindings for C++ >>> libraries. What are considered the best tools for doing something like >>> this? I know that there are SWIG, SIP, Boost.Python, and GCC_XML. >> >> We are doing this quite extensively at work, and have found that in the >> long run SWIG is the best solution. OMMV, but if you ask me, the answer >> is SWIG. > > Why do you think it is better than ctypes ? I won't say SWIG is better than anything, but how would you use ctypes to create an instance of a class with several levels of inheritance, and then invoke a virtual method? You have to mangle all the names (not too bad, can be done in Python following the rules) but you also need to find the right function pointer in the virtual method table; and that can't be done without processing the source code (at least the .h) in order to know the layout and ordering of the methods. Let alone inline functions, templates and #define macros. -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Mon Mar 5 16:54:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Mar 2007 22:54:39 +0100 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> Message-ID: <45ec89a4$0$2349$426a74cc@news.free.fr> Adam Atlas a ?crit : (snip) > If you make a ZIP archive of > this and run it through Squisher, you'll get a single .pyc file which > can be imported by any Python installation anywhere just like any > other module, without requiring users to install any supporting > mechanisms (like setuptools), setuptools offers *much* more than a convenient way to package source code. From greg at cosc.canterbury.ac.nz Tue Mar 13 20:01:37 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 14 Mar 2007 13:01:37 +1300 Subject: number generator In-Reply-To: References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <55fbgjF2492skU1@mid.individual.net> <1173573654.009953.266280@30g2000cwc.googlegroups.com> <7xbqj01u9c.fsf@ruckus.brouhaha.com> <01f501c7653e$1ee8cee0$03000080@hendrik> Message-ID: <55osfiF25uqm7U1@mid.individual.net> Gabriel Genellina wrote: > The 5th number is not "random". More precisely, the fifth number is not *independent* of the others. You can't have five independent random numbers that sum to 50; only four independent numbers plus a dependent one. -- Greg From yinglcs at gmail.com Sun Mar 11 14:48:45 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 11 Mar 2007 11:48:45 -0700 Subject: Need help in using mod_python In-Reply-To: <45f43bf9$0$31995$426a74cc@news.free.fr> References: <1173560794.835409.34400@v33g2000cwv.googlegroups.com> <45f43bf9$0$31995$426a74cc@news.free.fr> Message-ID: <1173638925.764275.78690@n33g2000cwc.googlegroups.com> On Mar 11, 1:02 pm, Bruno Desthuilliers wrote: > ying... at gmail.com a ?crit : > > > > > Hi, > > > I am trying to setup Apache with Trac which uses mod_python. I get the > > following error: > > > assert have_pysqlite > 0 > > > And I have verify this via command line as well, that seem no > > problem. > > (snip) > > What do you get using tracd (the standalone server) ? I am using apache with mod_python. I have done a sanity check with command prompt, it can find 'pysqlite', But when I access Trac using Apache (via mod_python), it somehow can't find 'pysqlite' and gives me an error. So my question is how python command prompt loads library differently from mod_python? # python Python 2.3.4 (#1, Feb 2 2005, 11:44:49) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import trac.db.sqlite_backend >>> trac.db.sqlite_backend._ver (3, 3, 13) >>> trac.db.sqlite_backend.have_pysqlite 2 >>> trac.db.sqlite_backend.sqlite.version '2.3.3' From khemkaamit at gmail.com Tue Mar 13 01:52:08 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 13 Mar 2007 11:22:08 +0530 Subject: converting epoch time to string (and vice versa) In-Reply-To: <45F639AA.1040209@al.com.au> References: <45F639AA.1040209@al.com.au> Message-ID: <1360b7230703122252n58825188n1a9b7ae66b59c989@mail.gmail.com> On 3/13/07, Astan Chee wrote: > Hi, > I have a string in this format "DD/MM/YYY" for example: > tdate = "18/01/1990" > and Im trying to convert this to epoch time, can anyone help? import calendar t = map(int,tdate.split('/')) epochs = calendar.timegm((t[2], t[1], t[0], 0, 0, 0)) > Im also trying to convert that epoch time to the string format > previously. Can anyone help this one too? import time time.ctime(epochs) cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From Leo.Kislov at gmail.com Sun Mar 18 16:50:19 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 18 Mar 2007 13:50:19 -0700 Subject: lock problem In-Reply-To: References: <1174026699.143415.69940@n59g2000hsh.googlegroups.com> <1174034766.213528.164170@e65g2000hsc.googlegroups.com> Message-ID: <1174251019.868625.81650@y80g2000hsf.googlegroups.com> On Mar 16, 3:08 pm, Ritesh Raj Sarraf wrote: > Leo Kislov wrote: > > But you miss the fact that there is only one environment per process. > > Maybe there's a confusion. > The environment variable that I'm setting has noting to do with ldapsearch. I > use the environment variable as a filename to which ldapsearch can redirect its > output. And that I do is because the output can be huge and useless. > Then I do some pattern matching on that file and filter my data and then delete > it. > > If you think I still am missing something important, request you to describe it. Imagine this timeline: os.environ['__kabc_ldap'] = '/tmp/tmp1' os.environ['__kabc_ldap'] = '/tmp/tmp2' launch ldapsearch (output goes to '/tmp/tmp2') launch ldapsearch (output goes to '/tmp/tmp2' over output from ldapsearch launched from thread1) Seems like that's what is happening to your program. -- Leo From maxsteel at gmail.com Fri Mar 30 15:19:33 2007 From: maxsteel at gmail.com (Max Steel) Date: Fri, 30 Mar 2007 14:19:33 -0500 Subject: New to Python - Easy way to open a text file References: <1175270675.296617.83380@e65g2000hsc.googlegroups.com> Message-ID: Hmm.. maybe it'd help if I explained that I'm playing with edna http://edna.sourceforge.net/ I'll play with this simple code: f = open(r'pathToFile) for line in f: # do something with the line of text such as print it. f.close() and this one from Skip: f = open(plainfiles.href, "r") print f.read() and see if I can make a go of it.. I think it's the template portion that is mixing me up.. the template is what's used to create the look of the html on the edna server. Thanks to all who replied so quickly, much appreciated! .\\ax "Marc 'BlackJack' Rintsch" wrote in message news:pan.2007.03.30.16.39.12.89800 at gmx.net... > In <1175270675.296617.83380 at e65g2000hsc.googlegroups.com>, kyosohma wrote: > >> I'm not familiar with ezt formats, however reading a text file is a >> breeze. > > This sentence doesn't match the code that follow. It's really simpler > than that ``while`` loop. > >> f = open(r'pathToFile') >> while True: >> line = f.readline() >> if not line: break >> # do something with the line of text such as print it. >> >> f.close() > > f = open(r'pathToFile) > for line in f: > # do something with the line of text such as print it. > f.close() > > Ciao, > Marc 'BlackJack' Rintsch From __peter__ at web.de Thu Mar 1 06:10:09 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Mar 2007 12:10:09 +0100 Subject: splitting perl-style find/replace regexp using python References: <1172741100.414936.269460@q2g2000cwa.googlegroups.com> Message-ID: John Pye wrote: > Is there an easy and general way that I can split these perl-style > find-and-replace expressions into something I can use with Python, eg > re.sub('search','replace',str) ? Another candidate: >>> re.compile(r"(?:/((?:\\.|[^/])*))").findall(r"/abc\\/def\/ghi//jkl") ['abc\\\\', 'def\\/ghi', '', 'jkl'] Peter From grflanagan at yahoo.co.uk Tue Mar 6 05:03:33 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 6 Mar 2007 02:03:33 -0800 Subject: Any module to parse httpd.conf? Message-ID: <1173175413.679940.310750@p10g2000cwp.googlegroups.com> Hello, Does anyone know of an existing module to parse httpd.conf files? Thanks. From gagsl-py2 at yahoo.com.ar Wed Mar 7 04:40:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Mar 2007 06:40:28 -0300 Subject: How to check whether file is open or not References: <1173245313.037991.89380@s48g2000cws.googlegroups.com> Message-ID: En Wed, 07 Mar 2007 02:28:33 -0300, Ros escribi?: > There are 10 files in the folder. I wish to process all the files one > by one. But if the files are open or some processing is going on them > then I do not want to disturb that process. In that case I would > ignore processing that particular file and move to next file. > > How can I check whether the file is open or not? > > I tried os.stat and os.access but I am not getting the expected > results. > Also I checked in IO exceptions, IO error handler doesnt raise any > error if the file is open. > There are some options to check but they are platform dependent (works > only with unix) This works only on Windows: You can use the _sopen function (from the C runtime library), which takes additional flags for specifying file sharing. See http://msdn2.microsoft.com/en-us/library/aa273350(VS.60).aspx _sopen with _SH_DENYRW will fail if the file is already open by the same or another process. Try to open the file using this flag: if _sopen succeeds (does not return -1) the file was not already open (remember to close it as soon as possible!); if _sopen fails (returns -1) it was already open. Using the ctypes module (included with Python 2.5; you can download and install it for previous versions) you can call that function easily: py> from ctypes import * py> crt = cdll.msvcrt py> _sopen = crt._sopen py> _sopen.argtypes = (c_char_p, c_int, c_int, c_int) py> _SH_DENYRW = 0x10 # from py> h = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0) py> h 3 py> h2 = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0) py> h2 -1 py> _close = crt._close py> _close(h) 0 py> h2 = _sopen("C:\\1.txt", 0, _SH_DENYRW, 0) py> h2 3 py> _close(h2) 0 Note: You said "But if the files are open or some processing is going on them then I do not want to disturb that process.". There exist a (small) risk of disturbing the other process: if it tries to open the file just after you opened it, but before you close it, the operation will fail. It is a tiny window, but might happen... Surely there are other ways - some programs can report all processes having a certain file opened, by example, but I don't know how to do that. -- Gabriel Genellina From kyosohma at gmail.com Thu Mar 29 10:14:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 29 Mar 2007 07:14:49 -0700 Subject: Finding User Profile path In-Reply-To: References: <1175116080.934888.171450@n76g2000hsh.googlegroups.com> <1175173141.277735.192020@o5g2000hsb.googlegroups.com> <1175175904.199745.81460@y80g2000hsf.googlegroups.com> Message-ID: <1175177689.254125.250390@b75g2000hsg.googlegroups.com> On Mar 29, 9:05 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > On Mar 29, 8:23 am, Tim Golden wrote: > >> kyoso... at gmail.com wrote: > >>> One of my co-workers thought I could do > >>> something like this: > >>> c = wmi.WMI() > >>> for i in c.Win32_UserAccount(Name=user): > >>> # Get user paths somehow. > >>> I messed around with that, but I think he was mistaken. It has lots of > >>> good info, but not what I need. > >>> I apologize for not being specific. I will look at those win32net > >>> functions. > >>> Mike > >> Might depend on what you mean by "profile" but would the > >> users' homeDirectory/homeDrive active directory attributes > >> or the profilePath be of use here? If so, they're fairly > >> easy to get hold of. > > >> TJG > > > Yes. It's the homeDirectory as you say. Once again the IT community's > > use of multiple terms for the same thing has bitten me. > > I take it you're OK for getting things out of AD? > > TJG Actually no. Our organization does not use Active Directory. In fact, the server I need to query happens to be an NT 4.0 box. We do have a Win2k Server, but it is for specialized services. Mike From psdasilvaX at esotericaX.ptX Fri Mar 23 14:37:50 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 23 Mar 2007 18:37:50 +0000 Subject: Join strings - very simple Q. Message-ID: <1174675011.244339@jubilee.claranet.pt> Hi! I was told in this NG that string is obsolet. I should use str methods. So, how do I join a list of strings delimited by a given char, let's say ','? Old way: l=['a','b','c'] jl=string.join(l,',') New way? Thanks Paulo From garrickp at gmail.com Wed Mar 7 17:07:51 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 7 Mar 2007 14:07:51 -0800 Subject: catching exceptions from an except: block In-Reply-To: <1173305065.041154.41660@j27g2000cwj.googlegroups.com> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <45EF260C.6000205@websafe.com> <1173304097.821562.75060@t69g2000cwt.googlegroups.com> <1173305065.041154.41660@j27g2000cwj.googlegroups.com> Message-ID: <1173305271.294806.37470@n33g2000cwc.googlegroups.com> On Mar 7, 3:04 pm, garri... at gmail.com wrote: > On Mar 7, 2:48 pm, "Arnaud Delobelle" wrote: > > > > > > > I'm not really thinking about this situation so let me clarify. Here > > is a simple concrete example, taking the following for the functions > > a,b,c I mention in my original post. > > - a=int > > - b=float > > - c=complex > > - x is a string > > This means I want to convert x to an int if possible, otherwise a > > float, otherwise a complex, otherwise raise CantDoIt. > > > I can do: > > > for f in int, float, complex: > > try: > > return f(x) > > except ValueError: > > continue > > raise CantDoIt > > > But if the three things I want to do are not callable objects but > > chunks of code this method is awkward because you have to create > > functions simply in order to be able to loop over them (this is whay I > > was talking about 'abusing loop constructs'). Besides I am not happy > > with the other two idioms I can think of. > > > -- > > Arnaud > > Wouldn't it be easier to do: > > if isinstance(x, int): > # do something > elif isinstance(x, float)t: > # do something > elif isinstance(x, complex): > # do something > else: > raise CantDoIt > > or, > > i = [int, float, complex] > for f in i: > if isinstance(x, f): > return x > else: > raise CantDoIt I so missed the point of this. Not my day. Please ignore my post. From chimalus at gmail.com Fri Mar 30 13:20:49 2007 From: chimalus at gmail.com (jd) Date: 30 Mar 2007 10:20:49 -0700 Subject: clean up html document created by Word Message-ID: <1175275249.200620.76590@o5g2000hsb.googlegroups.com> I am looking for python code (working or sample code) that can take an html document created by Microsoft Word and clean it up (if you've never had to look at a Word-generated html document, consider yourself lucky ;-) Alternatively, if you know of a non-python solution, I'd like to hear about it. Thanks... -- jeff From lucastorri at gmail.com Mon Mar 12 11:15:10 2007 From: lucastorri at gmail.com (Lucas Torri) Date: Mon, 12 Mar 2007 12:15:10 -0300 Subject: backslashes in lists In-Reply-To: References: Message-ID: I don't know how ugly this look like, but { print str(alist).replace('\\\\', '\\') } works... On 3/12/07, Fabio Gomes wrote: > > Yes, Luca. > > I noticed that printing the list item will show the string as expected. > But I need to print the entire list in the script I'm writing and doing > that, the list will will be repr()'ed. Is there any way to print the entire > list without being parsed by repr()? > > > > ------------------------------ > Date: Mon, 12 Mar 2007 12:00:19 -0300 > From: lucastorri at gmail.com > To: flgoms at hotmail.com > Subject: Re: backslashes in lists > CC: python-list at python.org > > The backslash is a key to enter especial characters, like breakline: '\n' > > There is two backslashes cause of this especial condition of this char, > but if you try print the specific string you will see that only one > backslash remain: > > print alist[2] > > On 3/12/07, *Fabio Gomes* wrote: > > Hi list, > > I'm trying to use a string with backslashes in a list. But Python parses > strings in lists with repr(). > > > >>> alist = ['a', 'b', 'c:\some\path'] > >>> alist > ['a', 'b', 'c:\\some\\path'] > >>> print alist > ['a', 'b', 'c:\\some\\path'] > > > I already tried str() and raw (r) but it didn't work. All I want is to > keep a single backslash in the string since it is a path information. > > Can anyone help me, please? > > Thank you. > > ------------------------------ > O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na > Web e sua rede amigos. Confira! > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > ------------------------------ > Busque em qualquer p?gina da Web com alta prote??o. Obtenha o Windows Live > Toolbar GRATUITO ainda hoje! Experimente agora! > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From goodTweetieBird at hotmail.com Wed Mar 21 14:33:52 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 21 Mar 2007 11:33:52 -0700 Subject: Technical Answer - Protecting code in python In-Reply-To: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> Message-ID: <1174502032.402958.213090@y66g2000hsf.googlegroups.com> On Mar 21, 8:36 am, "flit" wrote: > Hello All, > > I have a hard question, every time I look for this answer its get out > from the technical domain and goes on in the moral/social domain. > First, I live in third world with bad gov., bad education, bad police > and a lot of taxes and bills to pay, and yes I live in a democratic > "state" (corrupt, but democratic). > So please, don't try to convince me about the social / economical / > open source / give to all / be open / all people are honest until > prove contrary / dance with the rabbits... > Remember I need to pay bills and security. > Now the technical question: > > 1 - There is a way to make some program in python and protects it? I > am not talking about ultra hard-core protection, just a simple one > that will stop 90% script kiddies. > > 2 - If I put the code in web like a web service, how can I protect my > code from being ripped? There is a way to avoid someone using my site > and ripping the .py files? > > Thanks and sorry for the introduction Maybe an application for php. Then any html visible is not source but result of execution of php. From duncan.booth at invalid.invalid Thu Mar 15 17:23:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Mar 2007 21:23:48 GMT Subject: dict.items() vs dict.iteritems and similar questions References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <1173955724.284863.97340@y80g2000hsf.googlegroups.com> <1hv0bc4.4o7cz81m7dokrN%aleax@mac.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In , skip wrote: > >> Are you sure? There's no guarantee that an iterator will terminate: >> >> len(list(itertools.cycle(range(10)))) > > You have infinite memory? ;-) Strangely, Skip's example is exactly the one I tested before posting my claim that it would terminate. From psdasilvaX at esotericaX.ptX Fri Mar 9 15:15:44 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 09 Mar 2007 20:15:44 +0000 Subject: bisect on a list of lists Message-ID: <1173471342.957772@iceman.esoterica.pt> Hi! What is the best way to have something like the bisect_left method on a list of lists being the comparision based on an specified arbitrary i_th element of each list element? Is there, for lists, something equivalent to the __cmp__ function for classes? Thanks. From aleax at mac.com Sun Mar 11 23:07:19 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 11 Mar 2007 20:07:19 -0700 Subject: setuptools and code.google.com References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <7xy7m3tqq8.fsf@ruckus.brouhaha.com> <1173653364.059431.19990@v33g2000cwv.googlegroups.com> <7xps7f5ptp.fsf@ruckus.brouhaha.com> <1hutrb3.e1sbu5kvxk8nN%aleax@mac.com> <87odmznrbf.fsf@gmail.com> <1hutsxr.3pcc7j1w12q1oN%aleax@mac.com> <87fy8bnpny.fsf_-_@gmail.com> Message-ID: <1hutu78.816hpgmmhn8jN%aleax@mac.com> Jorge Godoy wrote: ... > > these subtleties... thanks for pointing out that there's a problem > > btw!-) > > Thanks for caring ;-) Hey, I'd just love to make it as easy as possible to get gmpy -- that's why I (shudder!-) even build and upload Windows installers... > It looks for several things: eggs (for the Python version it is being used), > zipfiles and tarballs (I dunno if it looks for more things). > > If it finds, for example, gmpy-1.0.2-py2.4.egg it won't install here 'cause I > use Python 2.5 and then it will continue searching for gmpy-1.0.2-py2.5.egg or > an alternative format that can be used. The last resort is the tarball / zip > with the sources so that the package can be rebuilt. OK, the .zip file IS there -- I don't know how to build .egg ones but of course I could study up on it -- can you suggest a URL? To be usable on Windows w/o effort, the packaged format must contain a .pyd (and, on Mac, a .so, etc). Can a .egg deal w/that? I need to find out w/certainty, because once I've uploaded a file w/a certain name I can't change the name, nor the contents -- the URLs on code.google.com are meant to be permanent... > Probably other people that are more experienced with it can help more. I'm > more an end user of it and I know the essential for my needs. > > I just pointed out because setuptools helps a lot on obtaining a package and > installing it (even if there's some building needed before installing). OK, but since most Windows users don't have a suitable C compiler, and many Mac ones never bother installing the C compiler that comes with their OS DVDs, if I'm to make things easy I definitely need to pack up binaries. How do I pack binaries (for dynamic link libraries) that need to be very different on Win, Mac, various Linux distros...? > Sorry for not being able to help more. > > > With regards to the hyperlink, I believe that if the link on Pypi was to the > URL above it would be easier. Another alternative is a link at the first > page. And, of course, the last alternative is teaching setuptools how to work > with code.google.com -- if it doesn't already know -- as it learnt how to work > with SourceForge and its "random" mirrors. I don't know how to write that > code, though. Me neither, knowing near to nothing about setuptools (I'm not even a user of it...). Let's hope some expert does speak up -- I can't just freely experiment with uploads and the like... Alex From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 15 07:36:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 15 Mar 2007 12:36:19 +0100 Subject: print and softspace in python In-Reply-To: <1173888776.475236.81720@d57g2000hsg.googlegroups.com> References: <1173888776.475236.81720@d57g2000hsg.googlegroups.com> Message-ID: <45f92f90$0$32298$426a74cc@news.free.fr> Phoe6 a ?crit : > print and softspace in python > In python, whenever you use >>>print statement Drop the '>>>' part. It's just the default Python shell prompt. > it will append a > newline by default. If you don't want newline to be appended, you got > use a comma at the end (>>>print 10,) > When, you have a list of characters and want them to be printed > together a string using a for loop, Why would one use a for loop to do so ? This is inefficient (even in C - it's mostly a system limitation). If you have a list of characters (actually, a list of one-character strings - there's no 'char' type in Python) and want to print it as a string, then first turn that list into a string, then print it: >>> list1=['a','b','c'] >>> print "".join(list1) HTH From jon+usenet at unequivocal.co.uk Wed Mar 7 12:43:32 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 7 Mar 2007 17:43:32 GMT Subject: Recommended FastCGI module? References: Message-ID: In article , John Nagle wrote: > Jon Ribbens wrote: >>> The "JonPy" version: >>> http://jonpy.sourceforge.net/fcgi.html >>> Last revised in 2004. >> >> I'd recommend my one, but it's just possible I'm not impartial ;-) > > Does it work with current Pythons? (2.4, 2.5)? I'm mainly > concerned about the abandonware problem with some of them. Yes, I use it myself in my day job, where we have recently upgraded to Python 2.5. jonpy itself hasn't been revised for a while because there have been no revisions I felt necessary. There may be a new version released in the next couple of months, but there won't be any major changes. From kyosohma at gmail.com Wed Mar 21 09:16:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 21 Mar 2007 06:16:10 -0700 Subject: Exceptions and unicode messages In-Reply-To: References: Message-ID: <1174482970.148046.291160@p15g2000hsd.googlegroups.com> On Mar 21, 6:03 am, Tuomas wrote: > This works: > >>> raise StandardError(u'Wrong type') > Traceback (most recent call last): > File "", line 1, in ? > StandardError: Wrong type > > but don't in Finnish: > >>> raise StandardError(u'V??r? tyyppi') > Traceback (most recent call last): > File "", line 1, in ? > StandardError>>> > >>> > > Any solution in Python? > > TV When I do this, mine says "StandardError: " on both Python 2.4 and 2.5. I tried setting them to unicode, but that didn't help. One way around this may be to subclass the errors you want and do some custom processing that way. Mike From bdesth.quelquechose at free.quelquepart.fr Wed Mar 14 16:52:14 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 14 Mar 2007 21:52:14 +0100 Subject: Converting a list to a dictionary In-Reply-To: <1173902878.561018.244310@y80g2000hsf.googlegroups.com> References: <1173902878.561018.244310@y80g2000hsf.googlegroups.com> Message-ID: <45f8583d$0$10407$426a34cc@news.free.fr> Samuel a ?crit : > Hi, > > is there a short version for this? > > res_dict = {} > for resource in res_list: > res_dict[resource.get_id()] = resource > > This does not work: > > res_dict = dict([r.get_id(), r for r in res_list]) res_dict = dict((r.get_id(), r) for r in res_list) or if you have to be compatible with older python versions: res_dict = dict([(r.get_id(), r) for r in res_list]) HTH From rds1226 at sh163.net Thu Mar 8 20:11:26 2007 From: rds1226 at sh163.net (John) Date: Thu, 8 Mar 2007 20:11:26 -0500 Subject: any better code to initalize a list of lists? Message-ID: For my code of radix sort, I need to initialize 256 buckets. My code looks a little clumsy: radix=[[]] for i in range(255): radix.append([]) any better code to initalize this list? From bdesth.quelquechose at free.quelquepart.fr Wed Mar 14 16:47:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 14 Mar 2007 21:47:10 +0100 Subject: os.path.basename() - only Windows OR *nix? In-Reply-To: References: Message-ID: <45f8570f$0$10407$426a34cc@news.free.fr> Thomas Ploch a ?crit : > Hello, > > I have a cgi script that handles fileuploads from windows and *nix > machines. i need os.path.basename(filename) to get the pure filename. > > For *nix, thats not a problem, but for windows, it always returns the > full path: > > > > #/usr/bin/env python > > import cgi, os > import cgitb; cgitb.enable() > > form = cgi.FieldStorage() > filename = os.path.basename(form['uploadfile'].filename) > > print 'Content-Type: text/html\n\n' > print filename > > > > ----------------- > > For 'C:\text\text.txt', the output is 'C:\text\text.txt', which should > be 'text.txt', the same happens for 'C:\\text\\text.txt'. I think its > the escapes that makes python not splitting it. All Unix style paths get > converted the right way. Let me guess : your cgi script is running on *n*x ?-) > Is there an easy way around this, Probably. >>> fnames = "C:\\dir\\data.ext", "/dir/data.txt", "dir:data" >>> import ntpath, posixpath, macpath >>> def basename(filename): ... for m in ntpath, posixpath, macpath: ... if m.sep in filename: ... return m.basename(filename) ... else: ... # XXX ... raise SomeException('could not do the job') ... >>> for f in fnames: ... print f, basename(f) ... C:\dir\data.ext data.ext /dir/data.txt data.txt dir:data data >>> Might need some improvements, but you get the idea... HTH From chris.lasher at gmail.com Tue Mar 27 15:50:37 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 27 Mar 2007 12:50:37 -0700 Subject: PDB does not allow jumping to first statement? In-Reply-To: <1174989571.857680.318720@o5g2000hsb.googlegroups.com> References: <1174946787.291632.154690@n59g2000hsh.googlegroups.com> <1174989571.857680.318720@o5g2000hsb.googlegroups.com> Message-ID: <1175025037.464283.260680@e65g2000hsc.googlegroups.com> On Mar 27, 5:59 am, "rocky.bernst... at gmail.com" wrote: > I tried on GNU/Linux and Python versions 2.4 and 2.5 and get the same > behavior. Best as I can tell, it looks like a bug in Python. pdb, > pydb, rpdb2 all handle the "jump" command by changing the frame > f_lineno value. When the corresponding code pointer has offset 0 (or > equivalently and more simlply as you put it, is the first statement) > this doesn't seem to work properly. But this also implies that all you > need to do is add something as the first statement. A docstring > comment, e.g. > "this is what my program does..." > comes to mind :-) I started implementing this, but it's a hack. Looks like it's time for me to file a bug report! > Lastly, I'll mention that I what most folks want to do is not jump to > the beginning of the program but rather *restart* it. The difference > here as applied to your example is seen in the way variables (e.g. a, > b, and c) are handled. In a "restart", those names would go back to > being undefined and referring to them before assigning to them would > cause a NameError exception. With "jump", they retain their existing > values. In the case I was working with, I really did want to "jump" and retain the values, rather than restart and clear those values. Just as an aside, Rocky, I really like your ShowMeDo on pydb. Thanks for making that. (For those who haven't seen it, check out the "Introducing the pydb Debugger" at ) From MonkeeSage at gmail.com Sat Mar 3 21:06:11 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Mar 2007 18:06:11 -0800 Subject: class attrdict In-Reply-To: <1hueupp.1dcf9wl17pyf2bN%aleax@mac.com> References: <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1172895832.352834.313300@p10g2000cwp.googlegroups.com> <1hud90j.zf49afwqrk0bN%aleax@mac.com> <45e9b753$0$8983$4c368faf@roadrunner.com> <1huecz7.1thcn0b1j64biiN%aleax@mac.com> <1172960883.340892.183850@31g2000cwt.googlegroups.com> <1hueupp.1dcf9wl17pyf2bN%aleax@mac.com> Message-ID: <1172973970.929910.111000@s48g2000cws.googlegroups.com> On Mar 3, 7:54 pm, a... at mac.com (Alex Martelli) wrote: > Besides missing the warning in the __init__, this also has pretty weird > behavior whenever subject to a .pop, .update, .setdefault, del of either > item or attr, etc, etc: the attributes and items "get out of sync" (and, > catching each and every mutating-method to keep the separate dicts of > items and attrs in perfect sync is somewhat of a nightmare). Good points. There are many complexities involved, and little actual gain. Saving three or four chars isn't worth all the trouble. I hadn't fully thought-out the situation. Regards, Jordan From email at christoph-haas.de Thu Mar 15 11:15:42 2007 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 15 Mar 2007 16:15:42 +0100 Subject: Multiline code - trailing slash usage In-Reply-To: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> References: <1173970632.192949.236050@p15g2000hsd.googlegroups.com> Message-ID: <200703151615.42919.email@christoph-haas.de> On Thursday 15 March 2007 15:57, abcd wrote: > When do I need to use a trailing slash to separate code over multiple > lines. > > For example: > > x = "hello world, this is my multiline " + \ > "string!!!!" Needed. Although you can omit the "+". > x = {'name' : \ > 'bob'} Not needed because you are inside the curly brackets {} and it's clear where the statement ends. > Do I need to use the "\" in the above examples? When do i need to use > it? Cheers Christoph From kyosohma at gmail.com Tue Mar 20 10:44:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Mar 2007 07:44:56 -0700 Subject: How to send In-Reply-To: References: Message-ID: <1174401896.743804.31350@o5g2000hsb.googlegroups.com> On Mar 20, 7:21 am, "Admir Saric" wrote: > Hi, > > i have created an application in pygtk. The application creates files with > its own file type and extensions and saves them. I would like to extend the > application to be able to send these files over WLAN. I would use the > application in my Nokia 770 Internet tablet and send the files from one > tablet to the other. Does anybody know how to make python application send > files over the WLAN. > > Best regards > Admir > > _________________________________________________________________ > Schlagerfeber p? MSN!http://festival.msn.se/ Probably the easiest way to do this would be to use either the socket module or the smtp module Sockets: http://www.amk.ca/python/howto/sockets/ http://www.quepublishing.com/articles/article.asp?p=686162&rl=1 SMTP: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243 You could even do FTP: http://snippets.dzone.com/posts/show/711 Good luck! Mike From __peter__ at web.de Sun Mar 25 05:58:00 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Mar 2007 11:58:00 +0200 Subject: Class factory functions References: Message-ID: Steven D'Aprano wrote: > Here's a simple class-factory function that returns a sub-class of the > old-style class it is passed. > > def verbosify_oclass(klass): > """Returns a verbose sub-class of old-style klass.""" > class VClass(klass): > def __init__(self, *args, **kwargs): > print "Calling initializer __init__ ..." > klass.__init__(self, *args, **kwargs) > return VClass > > > Here it is in action: > >>>> class Parrot: > ... def __init__(self, colour): self.colour = colour > ... >>>> VParrot = verbosify_oclass(Parrot) >>>> bird = VParrot('red') > Calling initializer __init__ ... >>>> bird.colour > 'red' > > > Here's an equivalent for new-style classes. It uses super() because I > understand that super() is preferred to calling the super-class by name. > > > def verbosify_nclass(klass): > """Returns a verbose sub-class of new-style klass.""" > class VClass(klass): > def __new__(cls, *args, **kwargs): > print "Calling constructor __new__ ..." > return super(klass, cls).__new__(cls, *args, **kwargs) > def __init__(self, *args, **kwargs): > print "Calling initializer __init__ ..." > super(klass, self).__init__(*args, **kwargs) > return VClass > > > > But it doesn't work: > >>>> vint = verbosify_nclass(int) >>>> vint(42) > Calling constructor __new__ ... > Traceback (most recent call last): > File "", line 1, in > File "", line 6, in __new__ > TypeError: object.__new__(VClass) is not safe, use int.__new__() > > > What am I doing wrong? Why would you skip VClass in the super() calls? This should work: def verbosify_nclass(klass): """Returns a verbose sub-class of new-style klass.""" class VClass(klass): def __new__(cls, *args, **kwargs): print "Calling constructor __new__ ..." return super(VClass, cls).__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): print "Calling initializer __init__ ..." super(VClass, self).__init__(*args, **kwargs) return VClass Peer From tundra at tundraware.com Fri Mar 23 01:53:22 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Fri, 23 Mar 2007 00:53:22 -0500 Subject: How can I check if the listdir result a directory? In-Reply-To: <1174628417.345912.91410@l75g2000hse.googlegroups.com> References: <1174628417.345912.91410@l75g2000hse.googlegroups.com> Message-ID: Plissken.s at gmail.com wrote: > I have the following code which list out all the files/directories > under the current directory. > > But how can I find out if 'f' is a directory? > > for f in os.listdir("."): > // how can I check if 'f' a directory? > Try os.path.isdir() -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From brad at allendev.com Sat Mar 10 11:01:20 2007 From: brad at allendev.com (Brad Allen) Date: Sat, 10 Mar 2007 10:01:20 -0600 Subject: [python-advocacy] A Pythonic Way to Measure and Improve Your Programming Skills? In-Reply-To: <45F14D7E.3060707@taupro.com> References: <45F14D7E.3060707@taupro.com> Message-ID: At 6:05 AM -0600 3/9/07, Jeff Rush wrote: >Prior to PyCon I'd been thinking about some kind of campaign, service or >documents, that I call "So you think you know Python...". My initial idea was >for use by Python programmers, who are honest with themselves, to have a way >to measure their knowledge. A interactive Python skills test could be useful, fun, and popular, if designed well. There are a lot of Python programmers who are serious about honing their skills, and enjoy doing so. Building a good interactive test is a big project; I hope we can get community buy-in and participation for this idea. I'll volunteer to be a tester, and to help with brainstorming ideas for content. At 6:05 AM -0600 3/9/07, Jeff Rush wrote: >I've been carefully watching Crunchy, about which a talk was given at PyCon, >for writing tutorials that, with its "doctests" feature, could be used to >propose tests that pass and require a candidate to write an acceptable >program. Crunchy has great possibilities, especially if we can find a good way to use it on the web instead of requiring a download to run locally. However, there is an obvious security problem with giving web users access to a Python interpreter on the web server. When I discussed this problem with Michael Bernstein at PyCon he suggested the idea of creating a "chroot jail" for each web session which could run the Python interpreter in a secure sandbox. That might be easier than giving each session a whole virtual server. Are there any experienced sysadmins reading this who know of a practical way solve this problem so we can have Crunchy tutorials on the web? From dd55 at cornell.edu Wed Mar 14 17:07:51 2007 From: dd55 at cornell.edu (Darren Dale) Date: Wed, 14 Mar 2007 17:07:51 -0400 Subject: string formatting: engineering notation References: Message-ID: Steve Holden wrote: > Darren Dale wrote: >> Does anyone know if it is possible to represent a number as a string with >> engineering notation (like scientific notation, but with 10 raised to >> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the >> decimal.Decimal class, but repeatedly instantiating Decimals is >> inefficient for my application (matplotlib plotting library). If it is >> not currently possible, do you think the python devs would be receptive >> to including support for engineering notation in future releases? >> > How close is this: > > >>> "%.3e" % 3.14159 > '3.142e+00' >>> "%.3e" % 31415.9 '3.142e+04' What I am looking for is '31.4159e+03' Darren From bdesth.quelquechose at free.quelquepart.fr Thu Mar 22 16:06:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 22 Mar 2007 21:06:32 +0100 Subject: My MVC critique In-Reply-To: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> References: <1174573765.410866.56510@y66g2000hsf.googlegroups.com> Message-ID: <4602d943$0$7444$426a74cc@news.free.fr> scott.w.white at gmail.com a ?crit : (snip) > What MVC does not emphasis is the separation of the data access layer, Why should it ? Smalltalk is not only a language, it's a complete environment that provides automatic persistency. (snip some more OT stuff) And what's your question about Python, exactly ? From MonkeeSage at gmail.com Thu Mar 1 14:27:50 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Mar 2007 11:27:50 -0800 Subject: xml minidom redundant children?? In-Reply-To: <54omjoF21oduuU1@mid.uni-berlin.de> References: <1172774813.293437.108250@v33g2000cwv.googlegroups.com> <54omjoF21oduuU1@mid.uni-berlin.de> Message-ID: <1172777270.294820.10220@n33g2000cwc.googlegroups.com> On Mar 1, 12:46 pm, bkamr... at gmail.com wrote: > As a newbie, I'm trying to simply parse a xml file using minidom, but > I don't know why I get some extra children(?). I don't know what is > wrong in xml file, but I've tried different xml files, still same > problem. Most simply, if you need to stick with xml.dom.minidom; just check the nodeType and make sure its not 3 (textNode): from xml.dom import minidom doc = minidom.parse(fileTest) for item in doc.documentElement.childNodes: if not item.nodeType == 3: print item.nodeName Regards, Jordan From bbxx789_05ss at yahoo.com Mon Mar 19 00:38:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Mar 2007 21:38:37 -0700 Subject: class objects, method objects, function objects Message-ID: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> Hi, I'm trying to figure out what this passage from GvR's tutorial means: ------- Class definitions, like function definitions (def statements) must be executed before they have any effect.... When a class definition is entered, a new namespace is created... When a class definition is left normally (via the end), a class object is created. If you still don't understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn't a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. ----------- Here is my diagram of the above: class object ---------------------------------------- | class MyClass: | | def __init__(self): | | self.name = "GvR" | | def sayHi(self): | | print "Hello " + self.name | |________________________________________| x = MyClass() x.sayHi() #the "class search" begins which initiates the #creation of the method object: method object instance object ----------------- -------------- | ptr1 ----------|--------> |x = MyClass() | | ptr2 | |______________| | | | |___|_____________| | | V function object --------------------------------- | def sayHi(self): print "hello" | |_________________________________| But the last part of the passage makes no sense to me: ------ When the method object is called with an argument list, it is unpacked again, a new argument list is constructed from the instance object and the original argument list, and the function object is called with this new argument list. ------ Can anyone interpret that for me? From martinunsal at gmail.com Tue Mar 6 12:55:23 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 6 Mar 2007 09:55:23 -0800 Subject: Project organization and import In-Reply-To: References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <45ec9ba3$0$2333$426a34cc@news.free.fr> <1173167617.207318.22400@h3g2000cwc.googlegroups.com> <45ed41f7$0$21515$426a74cc@news.free.fr> <1173198244.092412.17400@n33g2000cwc.googlegroups.com> Message-ID: <1173203718.520489.161040@t69g2000cwt.googlegroups.com> On Mar 6, 9:46 am, Dennis Lee Bieber wrote: > The only usage I've ever made of "reload()" has been during > interactive debugging: Modify the module, then reload it at the > interactive prompt so I could create an instance of the modified code, > and manually manipulate it. That's exactly what I want to do. That's exactly what I'm having trouble with. Martin From kyosohma at gmail.com Mon Mar 26 12:27:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 09:27:51 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: <1174925855.552135.228190@n59g2000hsh.googlegroups.com> References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> <1174925855.552135.228190@n59g2000hsh.googlegroups.com> Message-ID: <1174926471.899631.228810@e65g2000hsc.googlegroups.com> On Mar 26, 11:17 am, kyoso... at gmail.com wrote: > On Mar 26, 10:51 am, "jp" wrote: > > > I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > > I skip over these widgets when using the tab key? > > > Thank you, > > John > > I would probably write some custom event handling. Something that > could tell it was a key-press event and not just an on-focus event. > Then it would be a simple, if key-press == tab, put focus on next > widget of interest. Something like that should work. > > Mike I looked in my Tkinter book, and it says that if the widget has the "takefocus" option set to true, the widget is placed in the tab group and will get focus when they are tabbed to. I assume that this means if you set the PMW widgets' "takefocus" option to false, they will be skipped over since they won't be in the tab group. Mike From irmen.NOSPAM at xs4all.nl Sun Mar 11 07:36:42 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 11 Mar 2007 12:36:42 +0100 Subject: distributed queue? In-Reply-To: <7xwt1olnlx.fsf_-_@ruckus.brouhaha.com> References: <7xwt1olnlx.fsf_-_@ruckus.brouhaha.com> Message-ID: <45f3e9ca$0$79139$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > Does anyone have an implementation of a distributed queue? I.e. I > have a long running computation f(x) and I'd like to be able to > evaluate it (for different values of x) on a bunch of different > computers simultaneously, the usual "worker thread" pattern except > distributed across a network. I guess this is pretty easy to write > with a centralized socket listener that dispatches requests through a > Queue to multiple threads on the same machine, each talking > synchronously to a server socket. I wonder if something like it > already exists. I see a little bit of discussion in the newsgroup > archive but no obvious pointers to code. > > Thanks. Pyro (http://pyro.sf.net) contains 2 examples that do just this. One is a distributed merge sort / md5 "cracker", the other is distributed prime factorization of a set of numbers. --Irmen From bbxx789_05ss at yahoo.com Tue Mar 20 11:27:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 20 Mar 2007 08:27:59 -0700 Subject: class objects, method objects, function objects In-Reply-To: References: <1174279117.490381.229370@y66g2000hsf.googlegroups.com> <1174324902.778062.104610@b75g2000hsg.googlegroups.com> Message-ID: <1174404479.942013.136150@e1g2000hsg.googlegroups.com> Thanks Duncan and Dennis. From supervau at gmail.com Sat Mar 10 16:17:11 2007 From: supervau at gmail.com (Frank) Date: 10 Mar 2007 13:17:11 -0800 Subject: How to test if a key in a dictionary exists? Message-ID: <1173561430.910888.25700@q40g2000cwq.googlegroups.com> Hi, does anyone know how one can test if, e.g., a dictionary 'name' has a key called 'name_key'? This would be possible: keys_of_names = names.keys() L = len(keys_of_names) for i in range(L): if keys_of_names[i] == name_key: print 'found' But certainly not efficient. I would expect there is something like: name.is_key(name_key) I appreciate your help! Frank From bearophileHUGS at lycos.com Tue Mar 27 07:31:41 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Mar 2007 04:31:41 -0700 Subject: plot dendrogram with python In-Reply-To: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> References: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> Message-ID: <1174995101.750777.117860@b75g2000hsg.googlegroups.com> Frank: > does anyone know if there is a way to plot a dendrogram with python. > Pylab or matplotlib do not provide such a function. An ASCII solution: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/139422 Some graphics: http://plone.org/products/phylogenetictree http://www.bioinformatics.org/mavric/ Bye, bearophile From dbhbarton at googlemail.com Fri Mar 9 09:56:46 2007 From: dbhbarton at googlemail.com (dbhbarton at googlemail.com) Date: 9 Mar 2007 06:56:46 -0800 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: <55d9ehF24cdi0U1@mid.uni-berlin.de> References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <1173436274.346506.200920@q40g2000cwq.googlegroups.com> <55cs24F23meg4U1@mid.individual.net> <1173438105.600342.243200@n33g2000cwc.googlegroups.com> <55d34sF24ijrdU1@mid.individual.net> <1173448114.905480.47200@h3g2000cwc.googlegroups.com> <55d7t9F240tp2U1@mid.uni-berlin.de> <1173449933.926669.90810@n33g2000cwc.googlegroups.com> <55d9ehF24cdi0U1@mid.uni-berlin.de> Message-ID: <1173452206.029944.255750@j27g2000cwj.googlegroups.com> > > I'm sorry I don't follow your logic. Meaningless to the interpreter, > > yes, meaningless to the IDE or to me, no. I "_can't_ profit from these > > conveniences"? Why ever not? > > Exactly, the ? is meaningless to the language itself, it's only a comment > sign - ... > ... it has nothing to do with _python_ the language, so it doesn't > belong there. But # is 'only a comment sign' as well, and equally meaningless to the interpreter. But it's still part of the language, very very useful and I profit from its existence every day. > But for python itself, it has no meaning whatsoever, and would just be a > character to overread, introducing visual clutter. If you can highlight an entire block with a single character, won't there be _less_ visual clutter than the current way of achieving the same effect with # comments? > So - if you want that feature, patch your editor of choice to deal with that > comments, make them added and removed with a key stroke, whatever - be my > guest. Would if I could! > Besides, I don't see how "quick highlighting of text" is something that > needs to be persisted anyway - if it is quick, hightlight it within the > editor until the file is closed. If not, it might be well worth a comment > anyway why you think it needs special attention. What we're talking about here is a form of 'alternate commenting style'. With the IDE's cooperation it'd work on whole blocks at once, it would highlight without disrupting the code concerned (at least the way I'm envisaging it), it would be versatile (could probably be used for as big a variety of purposes as the # comment), and yes, it'd be persistent, which is how it would be different from any IDE-based highlighting. I think that'd be most useful. You don't. So far nobody else here does either, and I've not persuaded anybody differently. Fair enough! dave From lbates at websafe.com Wed Mar 14 20:17:12 2007 From: lbates at websafe.com (Larry Bates) Date: Wed, 14 Mar 2007 19:17:12 -0500 Subject: Python COM called from VB/Delphi Message-ID: <3KidnaXVSJHiDWXYnZ2dnUVZ_vGinZ2d@comcast.com> I have a rather large Python class that I've converted to a COM object. I can dispatch (using either Python or VB) and call the methods perfectly. Now a new client wants to call it from Delphi. Can anyone out there give me any pointers on how that would be done. Are there any "gotchas" about the way arguments or return values would need to be different for Delphi. I have NO Delphi experience so I'm completely lost. Secondly, I need a callback function in VB (progress meter) that I can pass to Python COM object to show progress of https: uploads. I've tried a bunch of different things, but am getting nowhere. Anybody know how to accomplish this? I need a class that has start(), progress(total, count), complete() methods that is called from my Python COM object. I got one working in Python by using win32's win32com.server.util.wrap/unwrap functions but the VB one has got me stumped. Thanks in advance for any assistance. Regards, Larry From tjreedy at udel.edu Wed Mar 21 16:11:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Mar 2007 16:11:45 -0400 Subject: Printing __doc__ References: <1174506426.108098.243940@d57g2000hsg.googlegroups.com> Message-ID: "gtb" wrote in message news:1174506426.108098.243940 at d57g2000hsg.googlegroups.com... | Greetings, | | Don't know the daily limit for dumb questions so I will ask one or | more. | | In a function I can use the statement n = | sys._getframe().f_code.co_name to get the name of the current | function. Given that I can get the name how can I print the __doc__ | string? I cant use the following, it will tell me to bugger off as the | string has no such attribute. | | def spam(self): | n = sys._getframe().f_code.co_name | print n.__doc__ #Wrong | print __doc__ #No good either | #.... The docstring you are looking for is attached to the *function* object as .__doc__ and .func_doc. Frame.f_code is a *code* object. It has a boilerplate doc string, but not the one you want. As near as I can tell, frames do not keep references to the func object but only the code object, which is all it needs to run the code. I believe tracebacks use co_filename and co_name to find the text of a function. You could try to parse out the doc string from there. Terry Jan Reedy From kavithapython at yahoo.co.in Thu Mar 8 08:10:14 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Thu, 8 Mar 2007 13:10:14 +0000 (GMT) Subject: writing dictionary to file Message-ID: <527332.20009.qm@web7805.mail.in.yahoo.com> Hi, I have 'n' number of dictionaries with the same name but different values ( DorC means debit or credit) some={'DorC':'D', 'amount':200,'name':'xxx'} some={'DorC':'C', 'amount':200,'name':'xxx'} some={'DorC':'D', 'amount':300,'name':'yyy'} some={'DorC':'C', 'amount':500,'name':'yyy'} some={'DorC':'D', 'amount':700,'name':zzz} some={'DorC':'C', 'amount':900,'name':zzz} and so on,,, if the credit and debit is not equal for a person, then i would like to open a file and write it in the following format: name:yyy debit:300 credit:500 name:zzz debit:700 credit:900 can anyone help me??? kavitha --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From franz.steinhaeusler at gmx.at Thu Mar 1 02:52:43 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Thu, 01 Mar 2007 08:52:43 +0100 Subject: Python Source Code Beautifier References: Message-ID: Hello, thanks. pythontidy (with maybe some patches could be useful) not directly related but: pyflakes looks quite interesting too. and I try out (again) pylint and pychecker or a combination of these could bring good results, I assume. ;) From laurent.pointal at limsi.fr Fri Mar 30 03:59:21 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 30 Mar 2007 09:59:21 +0200 Subject: Game programming for kids: looking for open source 2D game development kit In-Reply-To: References: Message-ID: Max Kubierschky a ?crit : > Hello, > > I'm planning to give a game programming course for kids of mixed age. > For this, I am looking for an open source 2D game development kit. > I am also willing to participate in the development of the development kit. > > Features I'd like to see > - Possibility to construct simple games via drag and drop without > programming > - Integration into an IDE > - Based on Java or Python > Pluses: > - Good Tutorial > - German documentation With Python: * pygame + build your drag'n drop features * if you like 3D, vpython. http://www.pygame.org/ http://www.vpython.org/ From sudharani4fun at yahoo.com Wed Mar 7 03:35:50 2007 From: sudharani4fun at yahoo.com (sudha madhuri) Date: 7 Mar 2007 00:35:50 -0800 Subject: Videos inside(adult-fun-romantic-love-movies-songs)singles-profiles-chating-mails-earn money ! Message-ID: <1173256550.541680.176410@8g2000cwh.googlegroups.com> Videos inside(adult-fun-romantic-love-movies-songs)singles-profiles- chating-mails-earn money ! http://tinyurl.com/yr28hh India's largest social network place-Many people with good profiles. chating-videos-messages-mails-contest-parttime earning-unlimited fun-1 stop for everything signup and get fun http://tinyurl.com/yr28hh From steve at holdenweb.com Sun Mar 25 18:48:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 25 Mar 2007 18:48:19 -0400 Subject: call to function by text variable In-Reply-To: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: <4606FC33.7050906@holdenweb.com> ianar? wrote: > yeah the subject doesn't really make sense does it? > > anyway want I want to do is this: > if n == 1: > > self.operations.insert(pos, operations.Replace.Panel(self, main)) > > elif n == 2: > > self.operations.insert(pos, operations.ChangeCase.Panel(self, > main)) > > elif n == 3: > > self.operations.insert(pos, operations.Move.Panel(self, main)) > > As you can see all the different functions have the same variables, so > it would be easier if I could just make a list and use that. > > like this: > > > list = ["Replace", "ChangeCase", "Move"] > textVariable = list[n] > self.operations.insert(pos, operations.[textVariable].Panel(self, > main)) > > Is something sort of like that possible? > Indeed. You don't need to use textual names (though for that you can investigate "getattr()) - the following, naturally, is untested: ops = [operations.Replace, operations.ChangeCase, operations.Move ] self.operations.insert(pos, ops[n-1].Panel(self, main) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From Leo.Kislov at gmail.com Tue Mar 27 01:05:45 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 26 Mar 2007 22:05:45 -0700 Subject: shutil.copy Problem In-Reply-To: References: Message-ID: <1174971945.069767.93590@r56g2000hsd.googlegroups.com> On Mar 26, 8:10 pm, David Nicolson wrote: > Hi, > > I wasn't exactly sure where to send this, I don't know if it is a bug > in Python or not. This is rare, but it has occurred a few times and > seems to be reproducible for those who experience it. > > Examine this code: > >>> try: > >>> shutil.copy("/file.xml","/Volumes/External/file.xml") > >>> except Exception, err: > >>> print sys.exc_info()[0] > >>> print err > > This is the output: > exceptions.UnicodeDecodeError > 'ascii' codec can't decode byte 0xd6 in position 26: ordinal not in > range(128)] > > What could the possible cause of this be? Show us traceback, without it I doubt anyone can help. > Shouldn't shutil simply be > reading and writing the bytes and not character decoding them? Yes, shutil.copy copies content verbatim. -- Leo From mwilson at the-wire.com Sun Mar 18 14:30:04 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 18 Mar 2007 14:30:04 -0400 Subject: How to get the previous line in a file? In-Reply-To: <155468.56172.qm@web58905.mail.re1.yahoo.com> References: <155468.56172.qm@web58905.mail.re1.yahoo.com> Message-ID: Qilong Ren wrote: > Hi, Shane, > > Thanks for fast reply. > > What I used is : > for line in open(FILE): > > I don't want to store all lines in a list because sometimes the file is very large. We need to store the value of the previous line in a variable. Is that right? Almost. Strictly, we need to bind a name to the object holding the previous value, so we can refer to that object later. :) From bdesth.quelquechose at free.quelquepart.fr Thu Mar 8 18:49:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 09 Mar 2007 00:49:42 +0100 Subject: Where to "import"? In-Reply-To: <1173393063.705376@jubilee.claranet.pt> References: <1173379952.901004@iceman.esoterica.pt> <45f068a2$0$18256$426a74cc@news.free.fr> <1173393063.705376@jubilee.claranet.pt> Message-ID: <45f09905$0$28886$426a34cc@news.free.fr> Paulo da Silva a ?crit : > Bruno Desthuilliers escreveu: > >>Paulo da Silva a ?crit : > > ... > > >>>c.py >>> class c: >> >> class C(object): >> >>1/ better to stick to naming conventions (class names in CamelCase) > > Ok. Thanks. FWIW: http://www.python.org/dev/peps/pep-0008/ >>2/ do yourself a favor: use new-style classes > > I still have python 2.4.3 (The gentoo current version). new-style classes came with Python 2.2.1 IIRC. > I didn't find this in my tutorial. Would you please enlight me > a bit about this (class C(object))? Inheriting from the builtin class 'object' (or from any other new-style class) makes your class a new-style class. new-style classes have much more features than old-style ones. Like support for properties (computed attributes). old-style classes are still here mainly for compatibility with old code. While there not yet officially deprecated, you can consider them as such. > Or just point me out some doc > to read about. http://www.python.org/doc/newstyle/ HTH From gagsl-py2 at yahoo.com.ar Thu Mar 8 23:27:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 01:27:32 -0300 Subject: Where to "import"? References: <1173379952.901004@iceman.esoterica.pt> <45f068a2$0$18256$426a74cc@news.free.fr> <1173393063.705376@jubilee.claranet.pt> <45f09905$0$28886$426a34cc@news.free.fr> <1173413376.191416.30990@s48g2000cws.googlegroups.com> Message-ID: En Fri, 09 Mar 2007 01:09:36 -0300, MonkeeSage escribi?: >> FWIW:http://www.python.org/dev/peps/pep-0008/ > > By my reading, PEP8 doesn't specify CamelCase as preferred over the > other styles it mentions. non_camel_case is also considered good > style, as I understand (and is used all over the standard library). Class names should be CamelCase. Read it again, and notice the difference between a "Descriptive" section and a "Prescriptive" one. -- Gabriel Genellina From kyosohma at gmail.com Fri Mar 23 09:20:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Mar 2007 06:20:15 -0700 Subject: Need help to learn Python In-Reply-To: <1174626206.083519.294730@y66g2000hsf.googlegroups.com> References: <1174626206.083519.294730@y66g2000hsf.googlegroups.com> Message-ID: <1174656015.099363.35330@e65g2000hsc.googlegroups.com> On Mar 23, 12:03 am, "PythonBiter" wrote: > Hi everyone, > > I'm very new in this Group as well Python language. I want to learn > Python. So could you please advice me, and guide me how can i become > master in Python ! > > Thanks, > Partha If you need books for a beginner in Python, go with "Python Programming for the Absolute Beginner" by Dawson, or "Python Programming: An Introduction to Computer Science" by Zelle. Core Python Programming is mostly theory and very little code. It's good for reference and digging deeper into the language, if you don't mind some screwy grammatical errors here and there. Programming Python 3rd Ed (by Lutz) has lots of code to dig into, but I would say it is for intermediate to advanced users. It also contains many practical useful scripts in it. Mike From MonkeeSage at gmail.com Sun Mar 11 00:22:34 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 10 Mar 2007 21:22:34 -0800 Subject: minimum age to learn python (a.k.a graphical vs text languages) In-Reply-To: References: Message-ID: <1173590554.510996.118150@30g2000cwc.googlegroups.com> " "first person shooter" programming language " OMG! Thank's freakin awsome, lol!!! From nagle at animats.com Wed Mar 7 12:15:16 2007 From: nagle at animats.com (John Nagle) Date: Wed, 07 Mar 2007 17:15:16 GMT Subject: Recommended FastCGI module? In-Reply-To: References: Message-ID: Jon Ribbens wrote: > In article , John Nagle wrote: > >> The "JonPy" version: >> http://jonpy.sourceforge.net/fcgi.html >> Last revised in 2004. > > > I'd recommend my one, but it's just possible I'm not impartial ;-) Does it work with current Pythons? (2.4, 2.5)? I'm mainly concerned about the abandonware problem with some of them. John Nagle From mlacunza at gmail.com Mon Mar 19 09:38:22 2007 From: mlacunza at gmail.com (Mario Lacunza) Date: Mon, 19 Mar 2007 08:38:22 -0500 Subject: Report options... Message-ID: <1174311502.5260.2.camel@laptop> > Hello, > > Right now Im migrating an VB6+Crystal report+Word App to Python+wxPython > +Reportlab+??? > > The VB system work with Word, creating some patterns (title, foot prints, > etc) and users maybe could insert some new text and Form fields (like parameters) to personalize the > output, connecting this fields with an recordset retrieve from a DB. > > I dont want to use any external tool for this taks (OpenOffice+pyUno is > my last chance) > > Any suggestion? > > Thanks! > > Mi configuracion/My config: > > Ubuntu Edgy Eft 6.10 > Linux Kernel 2.6.17-11-386 > Gnome 2.16.1 > Python 2.4.4c1 > wxPython 2.8.1.1 Unicode > Python IDE: Ulipad 3.6 > Database: Firebird 2.0 Superserver > > -- > Saludos / Best regards > > Mario Lacunza V?squez > Desarrollador de Software - Webmaster > Linux Registered User #439179 > Desarrollador 2 Estrellas VS2005 > > Website : http://mlacunzav[DOT]cogia[DOT]net > Email : mlacunza[AT]gmail.com / mario_lacunza[AT]yahoo.es > Blog : http://mlacunza.blogspot.com > Lima - Peru From lojicdotcomNOSPAM at gmail.com Thu Mar 8 00:12:46 2007 From: lojicdotcomNOSPAM at gmail.com (Brian Adkins) Date: Thu, 08 Mar 2007 00:12:46 -0500 Subject: merits of Lisp vs Python In-Reply-To: <1173329966.266070.283130@8g2000cwh.googlegroups.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> Message-ID: alex23 wrote: > John Nagle wrote: >> Hosting providers and distro >> makers aren't concerned over whether Python works. They >> care if C, C++, Java, PHP, and Perl work, but not Python or LISP. >> Ask them. > > Do you have any real experience with recent linux distros? Or with any > _real_ hosting providers? > > Because what you've said is clearly not true. Just because the > situation isn't as easy _for you_ as you would like, doesn't mean that > Python is being ignored to the extent you're trying to claim. > > -alex23 > alex23 - please don't feed the trolls. From duncan.booth at invalid.invalid Thu Mar 22 05:58:19 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Mar 2007 09:58:19 GMT Subject: parsing tables with beautiful soup? References: <1174499030.042369.312350@n76g2000hsh.googlegroups.com> <1174500627.339029.65590@n76g2000hsh.googlegroups.com> Message-ID: "cjl" wrote: > This works: > > for row in soup.find("table",{"class": "class_name"}): > for cell in row: > print cell.contents[0] > > Is there a better way to do this? > It may work for the page you are testing against, but it wouldn't work if your page contained valid HTML. You are assuming that the TR elements are direct children of the TABLE, but HTML requires that the TR elements appear inside THEAD, TBODY or TFOOT elements, so if anyone ever corrects the html your code will break. Something like this (untested) ought to work and be reasonably robust: table = soup.find("table",{"class": "class_name"}) for row in table.findAll("tr"): for cell in row.findAll("td"): print cell.findAll(text=True) From kw at codebykevin.com Fri Mar 30 16:37:29 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 30 Mar 2007 16:37:29 -0400 Subject: Tkinter menu question--how to pass arguments In-Reply-To: <1175285826.971400.321470@y80g2000hsf.googlegroups.com> References: <85c10$460d65c8$4275d90a$19337@FUSE.NET> <1175285826.971400.321470@y80g2000hsf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Mar 30, 2:32 pm, Kevin Walzer wrote: >> I'm having difficulty structuring a Tkinter menu entry. Here is the >> command in question: >> >> self.finkmenu.add_command(label='Update List of Packages', >> command=self.authorizeCommand(self.scanPackages)) >> >> When I start my program, it crashes because it's trying to run the >> command self.authorizeCommand. The reason I'm structuring it in this >> fashion is that this command takes another command as an argument--in >> this case, self.ScanPackages. >> >> The basic structure of the program is that the self.authorizeCommand >> function pops up a dialog box for a password; it then feeds the password >> to the function that it takes as an argument, i.e. self.scanPackages. >> >> I tried setting up the menu entry without the additional parameter, i.e. >> command=self.authorizeCommand, but then when I try to run the command >> from the menu, it complains there are not enough arguments. >> Unsurprising, since self.authorizeCommand takes another function name as >> an argument. >> >> How can I structure the menu item to reflect the correct number of >> arguments without it trying to execute the command? >> >> -- >> Kevin Walzer >> Code by Kevinhttp://www.codebykevin.com > > There are various ways to accomplish this. The 2 most popular that I > am aware of are using a helper function or lambda. > > using a lambda: > > command=(lambda:self.authorizeCommand(self.scanPackages)) > > > using a handler (i.e. indirection layer): > > def func(): > self.authorizeCommand(self.scanPackages) > > self.finkmenu.add_command(label='Update List of > Packages',command=func) > > > Both of these are talked about in detail in "Programming Python 3rd > Ed" by Lutz. I found that helpful for me. Of course, I decided to stop > using Tkinter and switched to wxPython. Hope this gets you going > though. > > Mike > lambda does the trick--thanks. I have the Lutz book but overlooked that part. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From skip at pobox.com Fri Mar 23 07:32:05 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 23 Mar 2007 06:32:05 -0500 Subject: "finally" for unit test In-Reply-To: <1174648739.464811.7150@y80g2000hsf.googlegroups.com> References: <1174648739.464811.7150@y80g2000hsf.googlegroups.com> Message-ID: <17923.47797.932315.33614@montanaro.dyndns.org> gabriel> Is there something like a finally for unittest functions? TestCase instances have setUp() and tearDown() methods: http://docs.python.org/dev/lib/testcase-objects.html Skip From eight02645999 at yahoo.com Tue Mar 20 00:49:13 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 19 Mar 2007 21:49:13 -0700 Subject: an enumerate question In-Reply-To: References: <1174354730.832021.263940@p15g2000hsd.googlegroups.com> <7xr6rkr8gw.fsf@ruckus.brouhaha.com> <1174356075.710324.321150@b75g2000hsg.googlegroups.com> Message-ID: <1174366153.314933.327200@y80g2000hsf.googlegroups.com> On Mar 20, 11:00 am, Steven Bethard wrote: > eight02645... at yahoo.com wrote: > > for n,l in enumerate(open("file")): > > print n,l # this prints current line > > print next line in this current iteration of the loop. > > Depends what you want to happen when you request "next". If you want to > renumber the lines, you can call .next() on the iterator:: > > >>> open('temp.txt', 'w').write('1\n2\n3\n4\n5\n6\n7\n') > >>> lines_iter = open('temp.txt') > >>> for i, line in enumerate(lines_iter): > ... print 'LINE %i, %r %r' % (i, line, lines_iter.next()) > ... > LINE 0, '1\n' '2\n' > LINE 1, '3\n' '4\n' > LINE 2, '5\n' '6\n' > Traceback (most recent call last): > File "", line 2, in > StopIteration > > If you want to peek ahead without removing the line from the iterator, > check out this recipe:: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 > > Which allows code like:: > > >>> lines_iter = peekable(open('temp.txt')) > >>> for i, line in enumerate(lines_iter): > ... print 'LINE %i, %r %r' % (i, line, lines_iter.peek()) > ... > LINE 0, '1\n' '2\n' > LINE 1, '2\n' '3\n' > LINE 2, '3\n' '4\n' > LINE 3, '4\n' '5\n' > LINE 4, '5\n' '6\n' > LINE 5, '6\n' '7\n' > Traceback (most recent call last): > ... > StopIteration > > (Note that the recipe doesn't try to catch the StopIteration, but if you > want that suppressed, it should be a pretty simple change.) > > STeVe thanks, lines_iter.next() is what i need at the moment. From marco at waven.com Mon Mar 26 21:58:29 2007 From: marco at waven.com (Marco) Date: Tue, 27 Mar 2007 09:58:29 +0800 Subject: about second parameter of signal handler func. Message-ID: <5c62a320703261858k79352a38o63b1627c913e529d@mail.gmail.com> Hi, In C, a signal handler function has only one parameter, that is signal number. But in Python(import signal), a signal handler function has two parameters, the first is signal number, the second is "frame"? What is "frame", please? Thank you! -- LinuX Power From steve at holdenweb.com Wed Mar 14 12:45:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Mar 2007 12:45:07 -0400 Subject: most complete xml package for Python? In-Reply-To: <1173887937.251026.175260@y66g2000hsf.googlegroups.com> References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> <45F811A3.1050208@web.de> <1173887937.251026.175260@y66g2000hsf.googlegroups.com> Message-ID: Paul Boddie wrote: > On 14 Mar, 16:15, Stefan Behnel wrote: >> metaperl wrote: >>> Without even checking them all out, I'm thinking the Amara XML Toolkit >>> must be the most feature-packed. >> Please check out lxml before you post FUD like this. >> >> http://codespeak.net/lxml/ > > Calm down, Stefan! The inquirer must have got the impression of > Amara's superiority from somewhere; all you need to do is to discover > which resource gave that impression and balance the situation out. In > any case, it's an opinion: there's no fear involved, and the only > uncertainty and doubt are in the inquirer's mind, which I suppose is > why they posted the inquiry. > Although the phrase "without even checking them all out" hardly lends credence to the OP's assertion of Amara's superiority, and does tend to support a hypothesis involving some ulterior motive (or would if less ingenuously done). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From nick at craig-wood.com Thu Mar 29 07:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 29 Mar 2007 06:30:04 -0500 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: Hendrik van Rooyen wrote: > "Nick Craig-Wood" wrote: > > > Well, yes there are different levels of potential reliability with > > different implementation strategies for each! > > Gadzooks! Foiled again by the horses for courses argument. > > ; - ) ;-) I'd like there to be something which works well enough for day to day use. Ie doesn't ever wreck the internals of python. It could have some caveats like "may not timeout during C functions which haven't released the GIL" and that would still make it very useable. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jjl at pobox.com Wed Mar 14 16:22:47 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 14 Mar 2007 20:22:47 GMT Subject: merits of Lisp vs Python References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> <1173581125.663707.5810@s48g2000cws.googlegroups.com> Message-ID: <87odmvinhf.fsf@pobox.com> "Graham Dumpleton" writes: > On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: [...] > > mod_python relies on an unsupported feature of Python, namely > > multiple interpreters --> risk of more pain with C extensions. > > As usual, those bashing up on mod_python tend not to really know what > they are talking about. :-( > > Although multiple Python interpreters cannot be manipulated directly > from within a Python script, they can from the Python C API and it is > very much a feature of Python and has been for a long time. I didn't dispute that multiple interpreters are a feature of Python. I said that they are an unsupported feature -- at least, Martin v. Loewis says they're "just broken", which is close enough for me: http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/1ba97b5e088eb171/674accc133afbc96?rnum=2#674accc133afbc96 """ In any case, it looks like that the "multiple interpreters" feature of Python is just broken. """ [...] > Even so, to get such a C extension module working in the context of > mod_python simply means telling mod_python to run that particular > application in the first interpreter instance by specifying the > mod_python directive: > > PythonInterpreter main_interpreter [...] Is it possible to ask mod_python to start separate processes to serve requests, rather than "separate" interpreters? We couldn't see a way. John From aleax at mac.com Sun Mar 18 19:34:25 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 18 Mar 2007 16:34:25 -0700 Subject: fifo queue References: <1174257160.540073.113380@b75g2000hsg.googlegroups.com> <7x3b42rwq9.fsf@ruckus.brouhaha.com> Message-ID: <1hv6jbh.39z9b71mdku7uN%aleax@mac.com> Paul Rubin wrote: > Unless the queue is really large, just use the pop operation to get > stuff off the top of the queue. That causes O(n) operations but it > should be fast if n is small. > > class queue(list): > push = append > def pop(self): > return list.pop(self,0) > > should do about what you wrote. If it IS large, then: import collections class queue(collections.deque): push = collections.deque.append pop = collections.deque.popleft could be even better. Alex From steve at REMOVE.THIS.cybersource.com.au Tue Mar 6 08:04:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 07 Mar 2007 00:04:51 +1100 Subject: Good handling of input data (was Re: Newbie question) References: <45EC579A.8090602@websafe.com> Message-ID: On Tue, 06 Mar 2007 05:57:43 -0500, Tommy Grav wrote: > So how would you handle this type of error handling? > My main problem is that occasionally there is an entry > in the list that is a string: > > 0.9834 134.4933 78.009 run11 27 How do you want to deal with such an occasional string? What do you expect the code to do? The way I see it, if you're expecting five floats, and you get four floats and a string, that's an error. Do you ignore the entire line, or replace the string with zero, or what? > Again I would like to avoid having to individually parse the 3 floats, > while still easily handling the string, but a list comprehension will > not work as far as I can tell. Is there a module that handles this > type of flat ascii tables? Something like: > > (x,y,z,id,n) = ParseFile("float","float","float","string","int") > > would be great, and I guess > > (x,y,z,id,n) = PaseFile2("%f %f %f %s %d") > > would be even better. How about this? def parse_line(line, types): items = line.split() return [t(s) for (t, s) in zip(types, items)] >>> line = " 4.5 6.7 23 -1 fred 7.9 " >>> parse_line(line, (float, float, int, int, str, float)) [4.5, 6.7000000000000002, 23, -1, 'fred', 7.9000000000000004] -- Steven. From exarkun at divmod.com Thu Mar 1 15:08:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Mar 2007 15:08:39 -0500 Subject: GIS Shape file upload to FTP server In-Reply-To: <14A2A120D369B6469BB154B2D2DC34D206F1EC12@EXCHVS01.ad.sfwmd.gov> Message-ID: <20070301200839.17852.1570987901.divmod.quotient.1490@ohm> On Thu, 1 Mar 2007 14:58:11 -0500, "Ahmed, Shakir" wrote: >HI Group, > >As I am very new in python field so this question might be very silly to >you but if I get any help is highly appreciated. > >Problem: > >I wrote a python script which is working fine to upload files to the ftp >server but the problem is it is reducing the actual size after >transferring. I need to upload a GIS Shape file to the ftp server but >want to keep the same size and format. Any idea or help is highly >appreciated. > > > [snip] >ffile = open('c:/test/wuppnt.shp', 'r') Perhaps the problem is that you did not open the file in binary mode here? Jean-Paul From bill.mill at gmail.com Wed Mar 14 23:41:54 2007 From: bill.mill at gmail.com (Bill Mill) Date: 14 Mar 2007 20:41:54 -0700 Subject: windows blinds In-Reply-To: References: Message-ID: <1173930114.349677.268150@y80g2000hsf.googlegroups.com> On Mar 14, 4:58 pm, lled wrote: > i am new to python and wanted to know > could i use it to write a programme so when i double click on a windoz > window it collapses (like in linux)? You probably could, but you would basically be writing C, because you're going to need to use the Win32 API. As for how to use the win32 API, you could try asking on comp.os.ms- windows.programmer.win32 ( http://groups.google.com/group/comp.os.ms-windows.programmer.win32/topics?lnk=srg ), because that's some fiendish stuff. -Bill Mill bill.mill at gmail.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 26 05:36:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 26 Mar 2007 11:36:38 +0200 Subject: Python object overhead? In-Reply-To: References: Message-ID: <46079426$0$3272$426a74cc@news.free.fr> Matt Garman a ?crit : > I'm trying to use Python to work with large pipe ('|') delimited data > files. Looks like a job for the csv module (in the standard lib). > The files range in size from 25 MB to 200 MB. > > Since each line corresponds to a record, what I'm trying to do is > create an object from each record. However, it seems that doing this > causes the memory overhead to go up two or three times. > > See the two examples below: running each on the same input file > results in 3x the memory usage for Example 2. (Memory usage is > checked using top.) Just for the record, *everything* in Python is an object - so the problem is not about 'using objects'. Now Of course, a complex object might eat up more space than a simple one... Python has 2 simple types for structured data : tuples (like database rows), and dicts (associative arrays). You can use the csv module to parse a csv-like format into either tuples or dicts. If you want to save memory, tuples may be the best choice. > This happens for both Python 2.4.3 on Gentoo Linux (64bit) and Python > 2.3.4 on CentOS 4.4 (64bit). > > Is this "just the way it is" or am I overlooking something obvious? What are you doing with your records ? Do you *really* need to keep the whole list in memory ? Else you can just work line by line: source = open(sys.argv[1]) for line in source: do_something_with(line) source.close() This will avoid building a huge in-memory list. While we're at it, your snippets are definitively unpythonic and overcomplicated: (snip) > filedata = list() > file = open(sys.argv[1]) > while True: > line = file.readline() > if len(line) == 0: break # EOF > filedata.append(line) > file.close() (snip) filedata = open(sys.argv[1]).readlines()) > Example 2: read lines into objects: > # begin readobjects.py > import sys, time > class FileRecord: class FileRecord(object): > def __init__(self, line): > self.line = line If this is your real code, I don't see any reason why this should eat up 3 times more space than the original version. > records = list() > file = open(sys.argv[1]) > while True: > line = file.readline() > if len(line) == 0: break # EOF > rec = FileRecord(line) > records.append(rec) > file.close() records = map(FileRecord, open(sys.argv[1]).readlines())) From jstroud at mbi.ucla.edu Wed Mar 21 20:18:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 21 Mar 2007 17:18:57 -0700 Subject: the second of nested buttons using textvariable remains void! In-Reply-To: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> References: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> Message-ID: Samkos wrote: > Hi there, > > I am fighting with a problem I intended to believe trivial that > I could not solve yet! > > I am trying to have a button with a variable text, that > pops up another button with a variable text when pressed. > > I did that with the following program in Python, but the > second button remains always void!!! is it related to > the textvariable parameters? > > If any of you had a clue, please don't hesitate! > > in advance, many thanks > > Samuel > > #----------------------- program 2 buttons.py > -------------------------- > > from Tkinter import * > > > def go(event): > root = Tk() > > s1=StringVar() > s1.set("s1") > label1 = Label(root, textvariable=s1) > label1.pack(side=LEFT) > > root.mainloop() > > > > root = Tk() > > s0=StringVar() > s0.set("s0") > label0 = Label(root, textvariable=s0) > label0.pack(side=LEFT) > > > root.bind("",go) > > root.mainloop() > You have instantiated Tk twice which causes these kind of problems. If you want a window in go(), use Toplevel instead of Tk (and "mainloop" is not needed in go()). I.e.: def go(event): not_root = Toplevel() s1=StringVar() s1.set("s1") label1 = Label(not_root, textvariable=s1) label1.pack(side=LEFT) James From john106henry at hotmail.com Fri Mar 2 01:07:19 2007 From: john106henry at hotmail.com (John Henry) Date: 1 Mar 2007 22:07:19 -0800 Subject: Matplotlib axes label In-Reply-To: <1172814815.385543.180040@j27g2000cwj.googlegroups.com> References: <1172790626.088267.303150@j27g2000cwj.googlegroups.com> <1172814815.385543.180040@j27g2000cwj.googlegroups.com> Message-ID: <1172815638.950663.198040@t69g2000cwt.googlegroups.com> On Mar 1, 9:53 pm, attn.steven.... at gmail.com wrote: > On Mar 1, 3:10 pm, "John Henry" wrote: > > > I've been asking this question at the matplotlib user list and never > > gotten an answer. I am hoping that there are matplotlib users here > > that can help. > > > My problem with matplotlib's way of handling axes label is illustrated > > by this example: > > >http://www.scipy.org/Cookbook/Matplotlib/MulticoloredLine > > > Notice that the y-axis goes from (-1.1, 1.1) but the first label is at > > -1.0. > > (snipped) > > > Is there a way to force the label to start at -1.1 instead of -1.0? > > > Thanks, > > You can try adjusting the labels and ticks > using matplotlib.ticker. > > To the example you cited, one can add > > from matplotlib.ticker import MultipleLocator, FormatStrFormatter > > # ... > > minorLocator = MultipleLocator(0.1) > minorFormattor = FormatStrFormatter('%0.1f') > ax.yaxis.set_minor_locator(minorLocator) > ax.yaxis.set_minor_formatter(minorFormattor) > > show() > > -- > Hope this helps, > Steven Thank you for the response. Yes, adding those lines did work. But what exactly is going on here? Why would adding these two lines works? Thanks, From adamgarstang at googlemail.com Sun Mar 4 08:45:20 2007 From: adamgarstang at googlemail.com (Adam) Date: 4 Mar 2007 05:45:20 -0800 Subject: Where I could find older python releases ? In-Reply-To: References: Message-ID: <1173015920.085918.71760@s48g2000cws.googlegroups.com> Sorry jumped the gun a little there. Is this what you are looking for? http://codespeak.net/download/py/py-0.9.0.zip From steve at REMOVE.THIS.cybersource.com.au Tue Mar 6 16:56:28 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 07 Mar 2007 08:56:28 +1100 Subject: Getting external IP address References: <1173206863_18689@sp6iad.superfeed.net> Message-ID: On Tue, 06 Mar 2007 14:40:37 -0500, Sergio Correia wrote: > The above suggestions seem nice, but I find this one easier: [snip] Thanks to everybody who replied, that's great. -- Steven. From mike.klaas at gmail.com Wed Mar 28 00:34:09 2007 From: mike.klaas at gmail.com (Klaas) Date: 27 Mar 2007 21:34:09 -0700 Subject: with timeout(...): In-Reply-To: <7xodme724p.fsf@ruckus.brouhaha.com> References: <56prsrF2am4a1U1@mid.uni-berlin.de> <7xodme724p.fsf@ruckus.brouhaha.com> Message-ID: <1175056449.483895.14760@e65g2000hsc.googlegroups.com> On Mar 27, 3:28 pm, Paul Rubin wrote: > Nick Craig-Wood writes: > > It could be made to work I'm sure by getting the interpreter to check > > for timeouts every few hundred bytecodes (like it does for thread > > switching). > > Is there some reason not to use sigalarm for this? * doesn't work with threads * requires global state/handler * cross-platform? -Mike From lovelydiab at hotmail.com Thu Mar 29 10:36:21 2007 From: lovelydiab at hotmail.com (moslim) Date: 29 Mar 2007 07:36:21 -0700 Subject: Islam, the Religion of Ease Message-ID: <1175178981.676137.156340@n59g2000hsh.googlegroups.com> Excuse me!! Would you stop for a moment?! O...man...Haven't you thought-one day- about yourself ? Who has made it? Have you seen a design which hasn't a designer ?! Have you seen a wonderful,delicate work without a worker ?! It's you and the whole universe!.. Who has made them all ?!! You know who ?.. It's "ALLAH",prise be to him. Just think for a moment. How are you going to be after death ?! Can you believe that this exact system of the universe and all of these great creation will end in in nothing...just after death! Have you thought, for a second, How to save your soul from Allah's punishment?! Haven't you thought about what is the right religion?! Read ... and think deeply before you answer.. It is religion of Islam. It is the religion that Mohammad-peace upon him- the last prophet, had been sent by. It is the religion that the right Bible- which is not distorted-has preached. Just have a look at The Bible of (Bernaba). Don't be emstional. Be rational and judge.. Just look..listen...compare..and then judge and say your word. We advise you visiting : http://www.islam-guide.com http://www.thetruereligion.org http://www.beconvinced.com http://www.plaintruth.org http://english.islamway.com http://www.todayislam.com http://www.prophetmuhammed.org http://www.islamtoday.net/english/ http://www.islamunveiled.org http://www.islamic-knowledge.com We willingly recive any inquries at the e-mail : muslim5 at hotmail.com From gagsl-py2 at yahoo.com.ar Sat Mar 10 01:25:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Mar 2007 03:25:18 -0300 Subject: __init__ in subclass of tuple References: Message-ID: En Sat, 10 Mar 2007 02:36:41 -0300, Alan Isaac escribi?: > I am probably confused about immutable types. > But for now my questions boil down to these two: > > - what does ``tuple.__init__`` do? Nothing. tuple.__init__ does not even exist, as tuples are immutable, they are fully initialized with __new__ (the actual constructor) > - what is the signature of ``tuple.__init__``? Already said; it does not exist. > These questions are stimulated by > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303439 > Looking at that, what fails if I leave out the following line? :: > > tuple.__init__(self) > > For exaple, if I try:: > > class Test1(tuple): > def __init__(self,seq): > pass > > I seem to get a perfectly usable tuple. > What initialization is missing? Nothing! > Next, the signature question. > I'm guessing the signature is something like > tuple.__init__(self, *args, **kwargs) > with nothing done with anything but self. > As a trivial illustrative example:: > > class Test2(tuple): > def __init__(self,seq): > tuple.__init__(self, "foo", "bar") > > seems to cause no objections. And does nothing; the tuple is already constructed (try with "print self" before the tuple.__init__ call). (That recipe is a bit old, anyway, I think that tuples *never* have used __init__) Better look for other "named tuples"/"record"/"struct" recipes on the CookBook. The signature is like you said, but it's not a tuple method, it's an object method instead: py> tuple.__init__ The only important thing is that it says: of 'object' objects, not: of 'tuple' objects. Compare with: py> tuple.__len__ > One last question: where should I have looked > to answer these questions? Uhm... Python Language Reference, section 3.4.1 Python/C API Reference Manual, section 10.3, Type objects. The C source code, object.c Or asking here :) -- Gabriel Genellina From MonkeeSage at gmail.com Thu Mar 8 23:17:48 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 8 Mar 2007 20:17:48 -0800 Subject: Where to "import"? In-Reply-To: <1173413376.191416.30990@s48g2000cws.googlegroups.com> References: <1173379952.901004@iceman.esoterica.pt> <45f068a2$0$18256$426a74cc@news.free.fr> <1173393063.705376@jubilee.claranet.pt> <45f09905$0$28886$426a34cc@news.free.fr> <1173413376.191416.30990@s48g2000cws.googlegroups.com> Message-ID: <1173413868.239390.45330@s48g2000cws.googlegroups.com> Disregard my last message, I'm stupid. I totally missed that Bruno was talking about classname. Bruno is exactly right. From steve at holdenweb.com Wed Mar 21 22:05:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 21 Mar 2007 22:05:01 -0400 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: <1174528562.192439.84480@l77g2000hsb.googlegroups.com> References: <1174528562.192439.84480@l77g2000hsb.googlegroups.com> Message-ID: Virgil Dupras wrote: > On Mar 21, 9:24 pm, Steve Holden wrote: >> Marcin Ciura wrote: >>> Steven D'Aprano wrote: >>>>>>> x, y, z = 1, 2, 3 >>>>>>> x = y = z >>>>>>> x, y, z >>>> (3, 3, 3) >>>> I certainly wouldn't expect to get (2, 3, 3). >>> Neither would I. I must have expressed myself not clearly enough. >>> Currently >>> x = y = z >>> is roughly equivalent to >>> x = z >>> y = z >>> I propose to change it to >>> y = z >>> x = z >>> Cheers, >>> Marcin >> The difference being ... ? >> -- >> Steve Holden +44 150 684 7255 +1 800 494 3119 >> Holden Web LLC/Ltd http://www.holdenweb.com >> Skype: holdenweb http://del.icio.us/steve.holden >> Recent Ramblings http://holdenweb.blogspot.com > > I think I see what Marcin means. The 'node' is changed too fast in the > chain, and next is assigned to 'nextnode' instead of being assigned to > node. > >>>> class Node: > ... pass > ... >>>> node = Node() >>>> nextnode = Node() >>>> backup_node = node >>>> node = node.next = nextnode >>>> node.next is node > True >>>> hasattr(backup_node,'next') > False > So we should take the already well-defined semantics of assignment and change them because it seems more obvious to J. Random User? I think I might be a little concerned about potential code breakage there. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From aleax at mac.com Wed Mar 14 10:12:54 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Mar 2007 07:12:54 -0700 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <1hut8e8.g1jy3a1hj5hobN%aleax@mac.com> <1173865162.313406.245740@b75g2000hsg.googlegroups.com> Message-ID: <1huyelp.s2ysob1dom8lfN%aleax@mac.com> Raymond Hettinger wrote: > [Alex Martelli] > > map([random.randrange(5) for i in xrange(45)].count, xrange(5)) > > > > i.e., this gives 5 integers (each between 0 and 45 included) summing to > > 45 -- add 1 to each of them to get the desired result. > > This is a really nice approach. Besides being fast, it is not too > hard to see that it is correct. > > FWIW, here's a variant with a count using the new defaultdict: > > n, m = 5, 45 > bag = collections.defaultdict(int) > for i in xrange(m): > bag[random.randrange(n)] += 1 > ans = [bag[k] for k in range(n)] Neat -- and you can use 1+bag[k] in the LC to adjust the results if needed, of course. Alex From MonkeeSage at gmail.com Thu Mar 1 11:43:59 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Mar 2007 08:43:59 -0800 Subject: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple) In-Reply-To: <1172746956.836438.53470@p10g2000cwp.googlegroups.com> References: <87slcqvskr.fsf@benfinney.id.au> <54ms6fF21c6h3U2@mid.individual.net> <1172727871.032664.165240@j27g2000cwj.googlegroups.com> <1172746956.836438.53470@p10g2000cwp.googlegroups.com> Message-ID: <1172767439.049062.193900@h3g2000cwc.googlegroups.com> On Mar 1, 5:02 am, bearophileH... at lycos.com wrote: > I don't know Ruby, but I think it allows such purposes with a freezing > function. In ruby all objects can be frozen (freeze is a method on Object, from which all other objects derive), not just Arrays (Arrays == lists in python; ruby has no built-in container equiv. to tuple). But that's more of an implementation detail rather than anthing to do with the structure/semantics of a certain type of object (e.g., a String can be frozen, a Hash can be frozen, &c). Regards, Jordan From esj at harvee.org Sat Mar 24 16:50:47 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 24 Mar 2007 16:50:47 -0400 Subject: fine grain logging cotrol In-Reply-To: References: <_P1Nh.15765$tD2.11562@newsread1.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > On Sat, 24 Mar 2007 11:29:34 -0400, "Eric S. Johansson" > declaimed the following in comp.lang.python: > > >> yes. here is the code that fails. I don't understand why the unbound >> method. what is really weird is that when I singlestep through the >> code, it never seems to call filter_test. it is like the method never >> existed. >> > Among other things -- the init is never called... You have too many > _ on it. Second, I suspect you needed to overload getLogger -- there is > no code, that I could see that would /invoke/ a get_logger method. get_logger does get called as part of the metaclass magic. I don't understand it well enough to explain but a debugger reveals some. for example, stepping through get_logger, I hit the first two statements but after executing getLogger, I end up at logger.info. this leads me to believe that __new__ runs at the start of every method invocation (not just at object creation). I obviously need to read more on the topic. I am really puzzled that get_logger never makes past getLogger but hopefully insight will arrive. From sgeiger at ncee.net Wed Mar 14 12:54:55 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 14 Mar 2007 11:54:55 -0500 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: <1173886227.609832.170540@l75g2000hse.googlegroups.com> References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> Message-ID: <45F828DF.1020701@ncee.net> # Just by looking at the output, it seems pretty obvious that xrange would be more memory effcient for large ranges: print "With range():",range(100,200) print print "With xrange():",xrange(100,200) d = {1:2,2:3,3:4} d.items() d.iteritems() # I have been curious to use Pysizer (which requires patching Python) to demonstrate the difference. Drew wrote: > When is it appropriate to use dict.items() vs dict.iteritems. Both > seem to work for something like: > > for key,val in mydict.items(): > print key,val > > for key,val in mydict.iteritems(): > print key,val > > Also, when is it appropriate to use range() vs xrange(). From my > understanding, xrange() essentially gives you an iterator across a > range, so it should be used when iterating. Should you only use > range() when want to physically store the range as a list? > > Thanks, > Drew > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From jura.grozni at gmail.com Thu Mar 1 08:15:41 2007 From: jura.grozni at gmail.com (azrael) Date: 1 Mar 2007 05:15:41 -0800 Subject: pattern matching Message-ID: <1172754941.682697.122580@v33g2000cwv.googlegroups.com> can someone give me good links for pattern matching in images using python From researchbase at gmail.com Tue Mar 13 03:15:55 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Tue, 13 Mar 2007 12:45:55 +0530 Subject: help developing an editor to view openoffice files. Message-ID: hello, right now I am involved on doing a very important accessibility work. as many people may or may not know that I am a visually handicap person and work a lot on accessibility. the main issue at hand is to create an accessible editor for open office. there are a lot of things remaining on that front. so right now I am trying to find out a temporary work around by creating a simple accessible editor (with wxpython) for viewing and editing open office files. I know there must be python libraries that can open/ save .odt files because it is an open standard any ways. but I am trying to work out a kind of a program where those files can also be displayed in a text area with all the formatting. probably one way of doing it is to use some thing like a rich text editor and allow the file to be converted to rtf from odt for viewing and back again to odt when the user wishes to save it. another way I find is to actually find out if there is a odt text box that can display these files as they are. viewing the contents of the files in an editable way is most important. any suggestions? regards. Krishnakant. From spamtrap at dot-app.org Fri Mar 23 18:30:05 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Fri, 23 Mar 2007 18:30:05 -0400 Subject: On Java's Interface (the meaning of interface in computer programing) References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> <1174557840.338374.25990@d57g2000hsg.googlegroups.com> <57idnfxDTKdi5J_bnZ2dnUVZ_uzinZ2d@comcast.com> Message-ID: Lew writes: > But if Xah were being trollish, why didn't they jump on my response > and call me names? Xah never replies to the threads he starts. At least, I've never known him to do so. > I still think that analysis of the original post is a useful exercise > to learn Java. Maybe so - I don't know enough Java to comment on that. But there's nothing useful to cross-posting the original to a fistful of non-Java lists. > The more subtle Xah or other > minions of Satan get in their presentations, the more interesting the > forensic exercise to dig out the truth. The truth is that Xah wants to start an argument. He cross-posts for that reason, so that the "forensic exercise" you're speaking of then becomes an argument among proponents of the various languages about which language is closer to the "truth". Don't take my word for it though - check Google Groups. You'll find he's been doing this for a long time. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From gandalf at designaproduct.biz Mon Mar 12 16:02:35 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 12 Mar 2007 21:02:35 +0100 Subject: Find the path of a running .py program Message-ID: <45F5B1DB.1030105@designaproduct.biz> Hi All! There was a thread here, more than a month ago. It was about finding the path of a .py file. I suggested os.abspath(__file__). Others told that sys.argv[0] is better. I was not sure why I did not like that solution. Now I ran into the problem again, and I now I remember what is the problem with that. For windows service applications, it does not work. The running program will be pythonservice.exe. Usually we want to know where the python program (.py sources) are. So, if you ever write a windows service in Python, make sure that you os.chdir to the correct directory before you do anything else. Original thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d1a674a2d42741ee/9763b5a8ab48b0a0?lnk=st&q=python+__file__+gandalf+argv&rnum=2&hl=hu#9763b5a8ab48b0a0 Here is a snippet that helped me to overcome the problem: import sys,os os.chdir(os.path.split(__file__)[0]) keywords: windows, service, startup directory, startup folder, path of a .py program I hope this comment will help others in the future. Cheers, Laszlo From lobais at gmail.com Fri Mar 2 18:08:19 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Sat, 03 Mar 2007 00:08:19 +0100 Subject: Sort with extra variables References: <7xlkifh1lw.fsf@ruckus.brouhaha.com> Message-ID: Den Fri, 02 Mar 2007 11:44:27 -0800 skrev Paul Rubin: > Thomas Dybdahl Ahle writes: >> Do you have any ideas how I can sort these moves the fastest? > > One idea: if you're using alpha-beta pruning, maybe you can use > something like heapq instead of sorting, since a lot of the time you > only have to look at the first few moves (ordered best-first). Do you mean that I add my moves something like this? from heapq import heappush, heappop heap = [] for move in genAll(): heappush(heap, (-getMoveValue (board, table, ply, move), move)) And then use heappop(heap) in the alphabeta loop? I don't know much of heap queues, but it actually looks very smart. From gagsl-py2 at yahoo.com.ar Thu Mar 8 20:03:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 22:03:59 -0300 Subject: property syntax References: <1173346452.096798.215970@t69g2000cwt.googlegroups.com> <1173351878.314596.252030@30g2000cwc.googlegroups.com> Message-ID: En Thu, 08 Mar 2007 08:04:38 -0300, escribi?: > Gabriel Genellina: >> You miss this common way, that does not depend on metaclasses, >> nor base classes, nor custom decorators... > > My purpose was to discuss a new syntax. The other stuff is mostly for > reference, to show that lot of (some) people has tried to find > alternative solutions to a problem they feel. Nex syntax has many disadvantages, so you should come with a greater analysis of what would be the gain. Maybe these comments are applicable here: http://mail.python.org/pipermail/python-dev/2007-February/071061.html and http://mail.python.org/pipermail/python-dev/2007-February/071123.html (sorry, a long thread, and two subject lines, that's why I had to post two references) I think this thread belongs to python-ideas instead. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 21 13:03:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 21 Mar 2007 18:03:58 +0100 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) In-Reply-To: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> References: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Message-ID: <46016562$0$27815$426a74cc@news.free.fr> dmitrey a ?crit : > Hi all, > I looked to the PEPs & didn't find a proposition to remove brackets & > commas for to make Python func call syntax caml- or tcl- like: instead > of > result = myfun(param1, myfun2(param5, param8), param3) > just make possible using > result = myfun param1 (myfun2 param5 param8) param3 > > it would reduce length of code lines Not by a noticeable amount > and make them more readable, I guess it's a matter of personal taste, experience with other languages and whatnot, but as far a I'm concerned, I find the actual syntax more readable - I don't have to think twice to know that it's a function call and what are the params. Also, and FWIW, in Python, the parens are the call operator. Given that a function may return another function, how would you handle the following case: result = my_hof(foo, bar)(baaz) And while where at it, since Python functions are first class objects, how would you handle this other case: def somefunc(arg): return 2 * arg alias = somefunc # some code here result = alias(42) > + no > needs to write annoing charecters. Could it be that these 'annoying characters' have a good reason to be here ? Strange as it might be, Python has not been built randomly. > Maybe it will require more work than I suppose, Probably, yes. > but anyway I think it worth. So try to solve the above problems and come back here with an example working implementation. > + it will not yield incompabilities with previous Python versions. Hmmm. I would not bet my life on this... From facundo at taniquetil.com.ar Wed Mar 14 14:01:00 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 14 Mar 2007 18:01:00 +0000 (UTC) Subject: Python & Oracle Message-ID: Hi! I need to connect to Oracle. I found this binding, http://www.zope.org/Members/matt/dco2 that is the recommended in the Python page. But that page seems a bit confuse to me. In the upper right corner says that the last release is PreRelease 1, from 2001-11-15. At the bottom, however, it says that 1.3 beta was released 2003-02-10, and is a development version (the last stable is 1.2, from 2002-10-02), four and a half years ago. The question is: is this connector the recommended one? it's aged because it's stable and no more changes are necessary, or it just dead? Works Ok? Thank you!! Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From johannes.wollard at gmail.com Tue Mar 6 07:48:43 2007 From: johannes.wollard at gmail.com (Johannes Woolard) Date: 6 Mar 2007 04:48:43 -0800 Subject: Interface Implementation in Python In-Reply-To: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> References: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> Message-ID: <1173185323.053052.45140@n33g2000cwc.googlegroups.com> 'Lo, I think I know what you're asking: > I would like to know the interface concept in Python.How the > Interface is defined and implemented in Python?. I assume you're talking about the what Java calls an interface - and the simple answer is that we don't have an equivalent in Python. This is because in the Python system of classes, interface inheritance would be unenforceable (because methods can be arbitrarily added at runtime). > How to access the interface fromn Client? I'm not completely sure what you mean here... client class, client of some protocol? Assuming you mean the client class, my answer above should suffice (and if not then I am completely missing the question). Regards, Johannes Woolard From mail at microcorp.co.za Wed Mar 14 03:35:59 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 14 Mar 2007 09:35:59 +0200 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com><55fbgjF2492skU1@mid.individual.net><1173573654.009953.266280@30g2000cwc.googlegroups.com><7xbqj01u9c.fsf@ruckus.brouhaha.com> <45f75596.0@entanet> Message-ID: <020701c7660c$b3417280$03000080@hendrik> "Duncan Smith" wrote: > Yes, if the generating processes yield numbers from different > probability mass functions. You could simply look at the likelihood > ratio. Otherwise, the likelihood ratio will be 1. > I was thinking about the same random number generator being used in the two disparate ways. - Hendrik From test.07 at gmail.com Thu Mar 8 22:38:55 2007 From: test.07 at gmail.com (test.07 at gmail.com) Date: 8 Mar 2007 19:38:55 -0800 Subject: Python threading In-Reply-To: References: <1173374702.195390.90550@s48g2000cws.googlegroups.com> Message-ID: <1173411535.336766.39230@q40g2000cwq.googlegroups.com> On Mar 8, 6:15 pm, "Gabriel Genellina" wrote: > En Thu, 08 Mar 2007 14:25:02 -0300, escribi?: > All threads share the same memory space, there is not a "per-thread" > memory allocator, if that's what you are thinking. > Perhaps you hold a reference to some objects in the Thread object? Or you > still keep the Thread object itself? That is what I was thinking. A per-thread memory allocator of some sort. What I need is run a lot of commands from a COM object that can be run independently. There commands leak memory, so when the command finishes, the memory consumption jumps to 800MBs or so. Which begs the question, if I initialize the COM object in a separate thread and run the command, does finishing the thread clean up any and all memory the thread used or not. The output of each thread would actually be a file on disk, therefore there is no need to pass any data between the threads and the main program. > > I did try the pythoncom.CoUnitialize() to release memory, but it > > doesn't seem to work (it does work about 30-45 seconds after the > > command is run). > > I don't understand what you say here. > What means "it doesn't seem to work" and "it does work 30 seconds after"? pythoncom.CoUninitialize(), if I am not mistaken, releases a COM object (and therefore the memory it uses I assume). When the command is run (in PythonWin for example), the memory is not released but persists for quite a while. Using my watch and the Task Manager in Windows I can see that the memory is released approximately 30 seconds AFTER I run the pythoncom.CoUninitialize() command is run. > What memory do you want to release "right away"? The memory I want to release is the memory the COM object used (the one initialized with the win32com Dispatch command). The "right-away" is not much of an issue, but if I can release it before I run each command from the COM object that leaks memory, it would be nice. Running upwards to 800MBs of RAM for one 500 line python script seems a little bit too much for me. Thank you for your reply Gabriel. If you have any more input, I would greatly appreciate it. From jzgoda at o2.usun.pl Sat Mar 31 06:41:46 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 31 Mar 2007 12:41:46 +0200 Subject: Long way around UnicodeDecodeError, or 'ascii' codec can't decode byte In-Reply-To: <1175314508.766924.38830@d57g2000hsg.googlegroups.com> References: <1175142370.740773.190400@e65g2000hsc.googlegroups.com> <1175172787.832055.223350@n76g2000hsh.googlegroups.com> <1175314508.766924.38830@d57g2000hsg.googlegroups.com> Message-ID: Oleg Parashchenko napisa?(a): >>> I spent two hours fixing it, and I hope it's done. The solution is one >>> of the ugliest hack I ever written, but it solves the pain. The full >>> story and the code is in my blog: >>> http://uucode.com/blog/2007/03/23/shut-up-you-dummy-7-bit-python/ >> Calling sys.setdefaultencoding might not even help in this case, and >> the consensus is that it may be harmful to your code's portability >> [1]. > > Yes, but I think UTF-8 is now everywhere. No, it is not. Your own system is "not ready for UTF-8", as you stated somewhere in this blog entry. How can you expect everybody else's system being utf-8, while "you are not ready for transition"? It would be better if you write your programs in encoding-agnostic way, using byte streams only for input and output (yes, printing a debug statement on terminal *is* a kind of producing the output). An, oh, you cann't encode/decode text not knowing the encoding... -- Jarek Zgoda http://jpa.berlios.de/ From tjreedy at udel.edu Mon Mar 5 13:32:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 Mar 2007 13:32:39 -0500 Subject: Help Deciphering Code References: <3671C2002ECC9149B2B5509290F533A678FA30@fiscex.FISCHERINTERNATIONAL.COM> Message-ID: "Bryan Leber" wrote in message news:3671C2002ECC9149B2B5509290F533A678FA30 at fiscex.FISCHERINTERNATIONAL.COM... I am learning python and I am having to make some changes on an existing python script. What happens is that one scripts creates an xml document that looks like this: >> "IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/component/profile >>> ProfileUtil.java".split() ['IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/component/profile', 'ProfileUtil.java'] If the ' ' were a '/' instead, then the os.path module has a function for splitting off the last component, the file name. Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Thu Mar 8 03:26:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 05:26:22 -0300 Subject: Howto find dict members from a list of keys References: Message-ID: En Thu, 08 Mar 2007 05:20:20 -0300, Alexander Eisenhuth escribi?: > what algo do you use, when you want to find the dict values from d, with > members > of l. Following example: > > >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10} > >>> l = [7,8] > >>> found_dic_members = > >>> print found_dict_members > [8,9] found_dic_members = [d[key] for key in l] -- Gabriel Genellina From nagle at animats.com Fri Mar 30 17:58:46 2007 From: nagle at animats.com (John Nagle) Date: Fri, 30 Mar 2007 21:58:46 GMT Subject: Inserting '-' character in front of all numbers in a string In-Reply-To: <1175290917.509860.224250@o5g2000hsb.googlegroups.com> References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> <1175290917.509860.224250@o5g2000hsb.googlegroups.com> Message-ID: Paul McGuire wrote: > On Mar 30, 2:09 pm, Michael Bentley wrote: > >>On Mar 30, 2007, at 10:38 AM, kevinliu23 wrote: >> >> >> >> >> >> >>>I want to be able to insert a '-' character in front of all numeric >>>values in a string. I want to insert the '-' character to use in >>>conjunction with the getopt.getopt() function. ' '.join(map(lambda x: '-' + x, s.split())) assuming that you just want to put a "-" in front of each field, regardless of its content. John Nagle From paul at boddie.org.uk Fri Mar 2 15:28:13 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Mar 2007 12:28:13 -0800 Subject: is it bug or feature in xml.dom.minidom? In-Reply-To: References: Message-ID: <1172867293.638995.324830@31g2000cwt.googlegroups.com> Maksim Kasimov wrote: > Hi, i'm faced with such a problem when i use xml.dom.minidom: > > to append all child nodes from "doc" in "_requ" to "doc" in "_resp", i do the following: > > _requ = minidom.parseString("OneTwo") > _resp = minidom.parseString("") Note that these are different documents - this is important later on. > iSourseTag = _requ.getElementsByTagName('doc')[0] > iTargetTag = _resp.getElementsByTagName('doc')[0] > > > # it prints me that there are two child nodes > for iChild in iSourseTag.childNodes: > print iChild.toxml() Seems alright. > # when i walk elements, only first iteration was made > # and iSourseTag.childNodes now have only one element instead of two > for iChild in iSourseTag.childNodes: > iTargetTag.appendChild(iChild) But since you're taking a node from one document to add it to another, you should instead use importNode to make that node importable into the target document: for iChild in iSourseTag.childNodes: # 1 or True should cause a deep copy iNewChild = _resp.importNode(iChild, 1) iTargetTag.appendChild(iNewChild) > # it prints me that there is only one child node > for iChild in iSourseTag.childNodes: > print iChild.toxml() That's probably because you've "stolen" the node from its document in order to add it to the target document - something which is possibly an artifact of the minidom implementation. > i'm not sure, whether i append child nodes in properly way, but IMHO it looks like a bug. That minidom does not refuse to let you "move" nodes in this way could be debated as being a bug or not, but the correct way of copying nodes is to use importNode. > My question is how to avoid the "iSourseTag" changes while iterate its nodes? > > And, of course, how to append all child nodes to "iTargetTag"? These questions are hopefully answered above. Paul From johnpenk7 at yahoo.com Mon Mar 26 12:27:57 2007 From: johnpenk7 at yahoo.com (jp) Date: 26 Mar 2007 09:27:57 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: <1174925855.552135.228190@n59g2000hsh.googlegroups.com> References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> <1174925855.552135.228190@n59g2000hsh.googlegroups.com> Message-ID: <1174926477.816452.208900@y80g2000hsf.googlegroups.com> On Mar 26, 11:17 am, kyoso... at gmail.com wrote: > On Mar 26, 10:51 am, "jp" wrote: > > > I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > > I skip over these widgets when using the tab key? > > > Thank you, > > John > > I would probably write some custom event handling. Something that > could tell it was a key-press event and not just an on-focus event. > Then it would be a simple, if key-press == tab, put focus on next > widget of interest. Something like that should work. > > Mike Isn't there just a simple configuration option to disable the tab key? Like the takfocus option with Tkinter widgets? From steve at REMOVE.THIS.cybersource.com.au Fri Mar 30 09:01:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 30 Mar 2007 23:01:43 +1000 Subject: which methods to use? References: <1175126969.200404.24370@e65g2000hsc.googlegroups.com> <1175130991.799268.311470@n59g2000hsh.googlegroups.com> Message-ID: On Thu, 29 Mar 2007 14:55:04 -0300, Gabriel Genellina wrote: > En Thu, 29 Mar 2007 01:56:15 -0300, Steven D'Aprano > escribi?: > >> By the way, "id(obj) == id(another_object)" is just a long way of writing >> "obj is another_object". > > Just as a side note: that's not true, testing by id() only works if both > objects are alive at the same time. Correction noted. > py> id(object()) == id(object()) > True > py> object() is object() > False That's weird. How on earth does that happen? > So using the `is` operator is the only safe way to test for identity. But if an object can be garbage collected before the is operator does the comparison, how can that be safe? -- Steven. From steve at REMOVE.THIS.cybersource.com.au Sat Mar 3 19:32:48 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 04 Mar 2007 11:32:48 +1100 Subject: Problem with returning prime number in a simple calculation program References: <1172964996.193310.251650@j27g2000cwj.googlegroups.com> Message-ID: On Sat, 03 Mar 2007 15:36:36 -0800, QHorizon wrote: > Hello, I'm new to Python (I've learned everything up to iterators so > far) and fairly new to Programming. This would be my first real > program: > > #Coordinate Geometry (The whole program is not shown) > > import math > import sys > > print "Welcome to the Coordinate Geometry Calculator!" > print "Type 'terms' for a list of commands" > > def main(): [snip big boring series of if...elif... statements] You're eventually going to run into a run time recursion error if you run that for long enough. Can you see why? A better way to do a command loop is something like this: def bad_command(): # called when the user enters an unrecognized command print "Unknown command, please try again" class QuitException(Exception): # used for exiting the loop pass def main(): # Make a "dispatch table" that maps the name of a command # (as typed by the user) with a function to call. dispatcher = {'slope': do_slope, 'primes': do_primes, 'quit': do_quit, # ... and more here } try: # loop forever (until we jump out of it) while True: cmd = get_command_from_user() # you have to write get_command_from_user yourself func = dispatcher.get(cmd, bad_command) result = func() print result except QuitException: print "Goodbye, come again soon!" Now you just need to define your individual functions do_slope, do_primes, etc. The only "special" one is do_quit. def do_quit(): raise QuitException Now let's look at the do_primes function. (You call it "prime".) > def prime(): > num = input("Number ") That's a good way to have malicious users do really, really really bad things to your PC. Safer is to do this: num = int(raw_input("Number ")) > i = num - 1 > divcounter = 0 > while i > 1: > if num % i != 0: > divcounter += 1 > i -= 1 That's an inefficient algorithm, if it even works. I'm not sure that it works, and I'm too lazy to find out :) > if divcounter == num - 2: > print num, "is a prime number" > else: > print num, "is not a prime number" This will only work if divcounter happens to equal the original number less two. If it equals something else, nothing will be printed. Here's a simple algorithm to check if a number is prime. # Warning: untested. def do_primes(): num = int(raw_input("Number ") if num <= 1: return "%n is not prime" % num if num == 2: return "%n is prime" % num elif num % 2 == 0: # even numbers other than 2 aren't prime return "%n is not prime" % num for i in range(3, num, 2): if num % i == 0: return "%n is not prime" % num return "%n is prime" % num Now, this is deliberately not an efficient algorithm. There are things you can do to make it more efficient, or you can re-write it completely. The thing to remember is, don't PRINT the result, RETURN it. Your do_primes() function should only calculate the result, and pass that result up to the main loop for printing (or writing to a text file, or emailing, or whatever). Have fun! -- Steven. From aleax at mac.com Thu Mar 15 23:03:54 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 15 Mar 2007 20:03:54 -0700 Subject: problem with str() References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> <1173992205.985657.167970@y66g2000hsf.googlegroups.com> Message-ID: <1hv191c.1bj9j73fp25ldN%aleax@mac.com> Steve Holden wrote: > 7stud wrote: > > Sheesh! You would think that after looking at every inch of the code > > for way too many hours, at some point that would have poked me in the > > eye. > > > > Thanks all. > > > Get yourself a stuffed bear, and next time you have this kind of problem > spend a few minutes explaining to the bear exactly how your program > can't possibly be wrong. Works like a charm. A rubber ducky works much better for that, btw -- more easily washable than a stuffed bear, for example. Alex From michele.simionato at gmail.com Thu Mar 1 04:23:39 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Mar 2007 01:23:39 -0800 Subject: class declaration shortcut In-Reply-To: References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> Message-ID: <1172741018.978417.233160@v33g2000cwv.googlegroups.com> On Mar 1, 9:40 am, Marc 'BlackJack' Rintsch wrote: > In <54msaoF21c6h... at mid.individual.net>, Bjoern Schliessmann wrote: > > > But what's it (__name__) good for? > > As objects don't know to which name they are bound, that's a good way to > give some information in stack traces or when doing introspection. Also, the name is used by pickle to find the class of pickled instances. Michele Simionato From ianare at gmail.com Sun Mar 25 19:01:50 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 25 Mar 2007 16:01:50 -0700 Subject: call to function by text variable In-Reply-To: References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: <1174863710.576989.235290@o5g2000hsb.googlegroups.com> Cool now I can run it through the translator. ops = (_("Directory"), _("Replace"), _("ChangeCase"), _("Move"), _("Swap"), _("Insert"), _("ChangeLength")) self.operations.insert(pos, getattr(operations, ops[n]).Panel(self, main)) Thanks guys! From jgodoy at gmail.com Tue Mar 6 17:41:49 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Tue, 06 Mar 2007 19:41:49 -0300 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> <1173203395.649560.249930@p10g2000cwp.googlegroups.com> Message-ID: <87d53mataq.fsf@gmail.com> "Martin Unsal" writes: > On Mar 6, 9:19 am, "Chris Mellon" wrote: >> You do? Or do you only have trouble because you don't like using "from >> foo import Foo" because you need to do more work to reload such an >> import? > > More work, like rewriting __import__ and reload??? :) > > There's a point where you should blame the language, not the > programmer. Are you saying I'm lazy just because I don't want to mess > with __import__? I *never* messed with __import__. And one of my systems has more than 15 packages, with an average of 7 more subpackages plus __init__.py... Why do you need messing with __import__? > I was clearly talking about files and you assumed I was talking about > namespace. That's Pythonic thinking... and I don't mean that in a good > way! Hmmm... Why not? How are you going to track down where is something, on which file? I can make sucessive imports and I can subclass things, so I might be importing a subclass of a subclass of the class that provides the method that I want to change. Having a direct correlation helps me a lot with big projects. For small ones I don't care since they are very simple and a grep usually takes me directly to where I want (just to avoid tools that map classes to files that are specific to one IDE or editor). > Because I have written a project with 50,000 lines of Python and I'm trying > to organize it in such a way that it'll scale up cleanly by another order of > magnitude. Because I've worked on projects with millions of lines of code > and I know about how such things are organized. It's funny, I'm a newbie to > Python but it seems like I'm one of the only people here thinking about it > as a large scale development language rather than a scripting language. I don't se a problem scaling my biggest project with, now, 65K lines of code. What are the problems you're seeing for yours? In fact, the Python part of this code is the easiest to deal with. And there's ctypes involved here, which messes things up a bit since I need to keep C + Python in sync. And if I once imagined I'd write that many LOC and would reach the millions of LOC of *Python* code then it would certainly make me feel comfortable knowing that this approach *do* scale. At least to me and to the ones that work with me and use the system... Implementing new features is fast and extremely modular. There are modules specific to one client, modules specific to another, modules shared between all clients, etc. It isn't a monolithic take all or nothing. And even like that it works. There are customizations on some features that only exists at one client's branch, there are customizations that might be selected "on the fly" by choosing something on a preferences screen, etc. It is a "normal" (but rather complex) application on any aspect that we see around. And it scales. I don't fear changing code. I don't fear adding new features. It "simply works". -- Jorge Godoy From tjreedy at udel.edu Sun Mar 4 22:46:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Mar 2007 22:46:24 -0500 Subject: list-like behaviour of etree.Element References: <5f56302b0703041248k1d2b3d85g1cf9954eed475c22@mail.gmail.com> Message-ID: "Daniel Nogradi" wrote in message news:5f56302b0703041248k1d2b3d85g1cf9954eed475c22 at mail.gmail.com... | The etree.Element (or ElementTree.Element) supports a number of | list-like methods: append, insert, remove. Any special reason why it | doesn't support pop and extend (and maybe count)? I think you should turn the question around: why should such be added? I imagine that the author wrote the methods he and his users thought necessary. Anything more has various costs. tjr From enleverlesX.XmcX at XmclaveauX.com Wed Mar 14 05:14:51 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 14 Mar 2007 10:14:51 +0100 Subject: Mocking OpenOffice in python? References: <1173861553.036985.74670@p15g2000hsd.googlegroups.com> Message-ID: <45f7be02$0$27406$ba4acef3@news.orange.fr> Hi! Under windows, I drive OOo, from Python, via COM/OLE-automation. It's run OK, but some bugs, in the OOo-COM-Python, had stop my devloppements... However, this way is usable (only on Win, ok?) @-salutations -- Michel Claveau From jura.grozni at gmail.com Fri Mar 9 10:27:15 2007 From: jura.grozni at gmail.com (azrael) Date: 9 Mar 2007 07:27:15 -0800 Subject: opinion needed Message-ID: <1173454035.316124.307620@h3g2000cwc.googlegroups.com> id like to hear your opinion about something. I just started using Prolog yesterday and i have my doubts about it, but it seems to me something like object oriented. so i wanted to ask you how usefull prolog is. Sure this is no prolog newsgroup so my question is: because it seems object oriented, how important is it by understanding python and improving my python skills. because i just started it, i may bee totaly wrong or i missunderstood. thnx From gagsl-py2 at yahoo.com.ar Thu Mar 15 01:38:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Mar 2007 05:38:04 +0000 (UTC) Subject: Circular Class Logic References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> <1173921593.166607.240390@e65g2000hsc.googlegroups.com> Message-ID: gmail.com> writes: > That's not exactly what I'm doing, but your comment still might help. > I actually want to include an instance of a subclass in it's > superclass like this: Move the initialization to another function. > > ===== foo.py ===== > # import Baz Remove the line above > > class Foo: > # baz = Baz.Baz() Remove the line above > > def __init__(self): > pass > ===== and add this below: def initFoo(): import baz Foo.baz = baz.Baz() initFoo() No changes in bar.py, baz.py Instead of initFoo, you could use a custom metaclass. Or a class decorator (if and when they become available...) The code above is an effective way of doing what you want. But I'd think about the actual need of doing such things - are you sure it's a good design? -- Gabriel Genellina From liam_herron at hotmail.com Wed Mar 21 15:15:04 2007 From: liam_herron at hotmail.com (liam_herron) Date: 21 Mar 2007 12:15:04 -0700 Subject: Python COM Outlook Question Message-ID: <1174504504.910510.219050@b75g2000hsg.googlegroups.com> Say I want to open a shared email inbox (named "DailyGoodEmails") that is different from my default Outlook inbox, how do I specify this? Currently, I would do: s = Dispatch("Outlook.Application") space = s.GetNameSpace("MAPI") inbox = space.GetDefaultFolder(6) myFolder = inbox.Folders[9] #open the folder i want I have no idea where the "6" comes from but I want to be able to specify "DailyGoodEmails" somewhere and be able to iterate over the emails. From anton.vredegoor at gmail.com Tue Mar 13 09:59:23 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 13 Mar 2007 14:59:23 +0100 Subject: number generator In-Reply-To: References: Message-ID: Dick Moores wrote: > If the added constraint is instead that the probability of generating > a given list of length N be the same as that of generating any other > list of length N, then I believe my function does the job. Of course, > [1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran > this test for M == 8 and N == 4: Yes, I believe your function is OK. But the 'fencepost' method posted earlier in this thread also does this and it's faster AND it's only two line of code ... > A = [] > B = [] > for x in range(100000): > lst = sumRndInt(8,4) > if lst not in A: > A.append(lst) > B.append(1) > else: > i = A.index(lst) > B[i] += 1 > > A.sort() Doesn't sorting break the correspondence between A and B? Also, a more pythonic way to count would be to convert the lst into a tuple and then do something with a dictionary. Dictionaries have faster lookup. For example: T = tuple(lst) D[T] = D.get(T,0) + 1 in the loop in order to count the occurrences. I'm totally fascinated with this stuff myself so it's a bit hard to guess whether someone still is interested, but anyway, here are some further explorations involving partitions. The code prints the number of distinct permutations for each partition. from operator import mul def part(m,n,r): L = [0]*n while m: x = pn(m-1,n-1) if r < x: L[n-1] += 1 m -= 1 n -= 1 else: for i in range(n): L[i] += 1 r -= x m -= n return L def memoize(fn): cache = {} def proxy(*args): try: return cache[args] except KeyError: return cache.setdefault(args, fn(*args)) return proxy @memoize def pn(m,n): if m Dear, I have wrote a script and want to group some functions of the script in a separate modulo so that I can import the module in other scripts and use the same functions there.. The problem is that the common functions need access to some global variables defined in the script. Python uses different namespaces for different modules so I can't access the variables of the script in the module. What is the best solution to solve this problem? Thanks in advance, Bart From nogradi at gmail.com Mon Mar 5 04:35:52 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 5 Mar 2007 10:35:52 +0100 Subject: list-like behaviour of etree.Element In-Reply-To: References: <1173080656.077853.249520@8g2000cwh.googlegroups.com> Message-ID: <5f56302b0703050135x5ae6ec9pbd21ef4abe533bf8@mail.gmail.com> > >> The etree.Element (or ElementTree.Element) supports a number of > >> list-like methods: append, insert, remove. Any special reason why it > >> doesn't support pop and extend (and maybe count)? > > > > Those methods would not be hard to add. Perhaps, submit a feature > > request to Fredrik Lundh on SourceForge and see what he thinks there > > is merit in more closely emulating the list API. Of the methods you > > listed, the case is probably strongest for extend(). > > extend() will be in the next release: > > http://effbot.org/zone/elementtree-changes-13.htm > > (lxml.etree already has it, btw). > > not sure I see the point of pop() and count(). a successful feature request > would need to include some really compelling use cases. Great! I also first thought of extend because that would be really useful, pop and count just came to mind because they exist for lists. But if extend will be added that'll already make life easier, pop/count is probably not that much needed. From andmarti at gmail.com Mon Mar 19 01:37:32 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Mon, 19 Mar 2007 02:37:32 -0300 Subject: struct.pack returns nothing In-Reply-To: <1174281765.884607.113420@p15g2000hsd.googlegroups.com> References: <1174281765.884607.113420@p15g2000hsd.googlegroups.com> Message-ID: <20070319053732.GA8746@lacordilleraandina.com.ar> On Sun, Mar 18, 2007 at 10:22:45PM -0700, AWasilenko at gmail.com wrote: > On Mar 19, 1:12 am, andma... at gmail.com wrote: > > If I build a strict with: > > > > import struct > > print struck.pack ('i', 1) > > > > it returns a '\n'. > > What's wrong with it??? > > :( > > > > -- > > Andr?s M. > > --------------------------------------------- > > Looks like you spelled struct wrong in the code :) You're right. I meant struct there too. heh. -- Andr?s M. --------------------------------------------- From duncan.booth at invalid.invalid Thu Mar 15 11:56:46 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Mar 2007 15:56:46 GMT Subject: dict.items() vs dict.iteritems and similar questions References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <1173955724.284863.97340@y80g2000hsf.googlegroups.com> <1hv0bc4.4o7cz81m7dokrN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote: >> Of course this is a little like the Heisenberg uncertainty principle if >> the iterator has no __len__ attribute - once you know how long it is you >> no longer have access to the elements. Or did I miss something? > > Right. However, "return sum(1 for _ in iterator)" may be a handier way > to express the same desctructive semantics as the last 4 lines here. I think I'd prefer the barbaric: return len(list(iterator)) since at least it is guaranteed to terminate. From paul at boddie.org.uk Fri Mar 2 07:03:03 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Mar 2007 04:03:03 -0800 Subject: Writing an interpreter for language similar to python!! In-Reply-To: <1172684281.057538.224370@h3g2000cwc.googlegroups.com> References: <1172684281.057538.224370@h3g2000cwc.googlegroups.com> Message-ID: <1172836982.941683.259780@z35g2000cwz.googlegroups.com> On 28 Feb, 18:38, "luvsat" wrote: > > I am new to python and working on a project that involves designing a > new language. The grammar of the language is very much inspired from > python as in is supports nearly all the statements and expressions > that are supported by python. Since my project is in initial stage, so > I think it would be appropriate if I clarify the following questions: Sounds interesting! > 1. Would it make sense if I parse the whole program from scratch and > then construct the valid python strings back so that they can be > executed using ''exec'' and ''eval'' commands? I wouldn't bother parsing the program from scratch - there's a module called "compiler" in the standard library which will give you an abstract syntax tree for virtually all of the syntax supported by the version of Python you're using. Despite complaints about the API, it's quite easy to work with and will save you from dealing with the tedious details of actually parsing the source code. If you want to produce the source code from the AST, some people have written visitor classes which will probably do what you want. Paul From paul at boddie.org.uk Sun Mar 25 18:20:01 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Mar 2007 15:20:01 -0700 Subject: problem at installing phyton on windows In-Reply-To: <1174857800.421722.218190@e65g2000hsc.googlegroups.com> References: <1174846017.637862.284100@l77g2000hsb.googlegroups.com> <1174846576.353998.161110@e65g2000hsc.googlegroups.com> <1174848014.932107.206320@e65g2000hsc.googlegroups.com> <1174857800.421722.218190@e65g2000hsc.googlegroups.com> Message-ID: <1174861201.580038.306360@n76g2000hsh.googlegroups.com> gslm wrote: > Please, can you read again? > Yes, I understand that in phyton interpreter, i can't call phyton > command.Thanks... > > But how can i run '.py' files from this command line?I wanted to use > the phyton command for this. Once you are in the Python interpreter you can run Python files, but the best way to run files is one of the following: * From the command prompt (DOS prompt); type something like this: python file.py * In the file manager (Windows Explorer, not Internet Explorer), open/ run file.py. If you *really* want to run files in the interpreter, you can do something like this: execfile("file.py") > When i click a py extended file, for example calendar.py in lib > directory, file opens, then suddenly close,except graphical ones.Why? > How can i see the results? For things that don't open windows you really need to run them from the command prompt. > And where can i learn which library must i import for whic class? Look at the library reference: each of the listed libraries are named, and for the calendar module you'd put this in your program (or type it at the Python prompt): import calendar Note that in Python programs or at the Python prompt you do not refer to it as calendar.py or C:\Python24\Lib\calendar.py (or wherever it lives): Python knows where to look and knows to add the .py on the end of the file. Note also that this doesn't run the calendar module, so it isn't quite the same as running the calendar.py file as described above. > Sorry, i ask much:(But after learning these starting knowledeges, i > read tutorials, manuals etc. > But now i haven't found my answers yet. I hope this helps a little. Paul From steve at holdenweb.com Sun Mar 25 18:48:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 25 Mar 2007 18:48:19 -0400 Subject: call to function by text variable In-Reply-To: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> References: <1174862186.134912.117270@p15g2000hsd.googlegroups.com> Message-ID: <4606FC33.7050906@holdenweb.com> ianar? wrote: > yeah the subject doesn't really make sense does it? > > anyway want I want to do is this: > if n == 1: > > self.operations.insert(pos, operations.Replace.Panel(self, main)) > > elif n == 2: > > self.operations.insert(pos, operations.ChangeCase.Panel(self, > main)) > > elif n == 3: > > self.operations.insert(pos, operations.Move.Panel(self, main)) > > As you can see all the different functions have the same variables, so > it would be easier if I could just make a list and use that. > > like this: > > > list = ["Replace", "ChangeCase", "Move"] > textVariable = list[n] > self.operations.insert(pos, operations.[textVariable].Panel(self, > main)) > > Is something sort of like that possible? > Indeed. You don't need to use textual names (though for that you can investigate "getattr()) - the following, naturally, is untested: ops = [operations.Replace, operations.ChangeCase, operations.Move ] self.operations.insert(pos, ops[n-1].Panel(self, main) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From deets at nospam.web.de Sat Mar 3 05:26:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 03 Mar 2007 11:26:08 +0100 Subject: Sort with extra variables In-Reply-To: References: <54rchkF21jehuU1@mid.uni-berlin.de> <1172877633.676612.141450@31g2000cwt.googlegroups.com> <1172881667.825628.93490@t69g2000cwt.googlegroups.com> Message-ID: <54t0qsF22bn49U1@mid.uni-berlin.de> > Well, you'd have to define the function inside the sortMoves function, as > it is where the variables exists. > > def sortMoves(board, table, ply, moves): > def sortKey(move): > return getMoveValue(board, table, ply, move) > moves.sort(key=sortKey, reverse=True) return moves > > Wouldn't that make it create the callable at each call? Yes, it does. But it's only created _once_ per sortMoves-call, and afterwards doesn't affect performance. And no, it's not slower than you lambda version - they _should_ be equally fast, if not it's neglible. And also doesn't affect sorting-performance. Diez From bgporter at acm.org Tue Mar 13 11:05:07 2007 From: bgporter at acm.org (Brett g Porter) Date: Tue, 13 Mar 2007 11:05:07 -0400 Subject: Eureka moments in Python In-Reply-To: References: Message-ID: <45F6BDA3.7080208@acm.org> Steven D'Aprano wrote: > I'd be interested in hearing people's stories of Eureka moments in Python, > moments where you suddenly realise that some task which seemed like it > would be hard work was easy with Python. Mine was definitely when I was first working with the xmlrpc module, and I was puzzled to no end how it was that I was able to make a call to a method of an object when that method didn't exist. All the talk about Python being a dynamic language had bounced off of me until that moment, when I walked through the __getattr__ method in the debugger and was enlightened. Not surprisingly, that was also the moment when C++ started feeling like a straightjacket to me... From jmazzonelli at gmail.com Fri Mar 16 10:56:56 2007 From: jmazzonelli at gmail.com (Jorge Mazzonelli) Date: Fri, 16 Mar 2007 11:56:56 -0300 Subject: Python COM called from VB/Delphi In-Reply-To: References: <3KidnaXVSJHiDWXYnZ2dnUVZ_vGinZ2d@comcast.com> Message-ID: <138a70320703160756l76c53a19yae4fe04858354bd0@mail.gmail.com> Larry, It's been a while since I coded something in VB or Delphi because I'm mostly turn on Python ;) so please excuse me any mistakes I can make 8I don't have neither VB or Delphi installed on this computer) For Delphi to use an OLE/COM Object it requires a TypeLibrary that explains how to access to this COM Object. For this you can use Project-->Import TypeLibrary. This will create automatically a .pas file with all the declaratons needed so you can use the object from Delphi. The Object exposed from python is from the point of view of Delphi simply a COM object. So if you need help on implementing a COM client in Delphi I suggest you to turn to the Delphi-related groups or do some google search about it. I found myself a simple tip about optional parameters and how they are handle in Delphi, here: http://blogs.teamb.com/CraigStuntz/archive/2005/07/01/UsingCOMOptionalParamsFromDelphi.aspx On the VB side, you can see on the link below how to create a callback in VB (it requires calling to the Windows API) http://www.thevbzone.com/secrets.htm#AddressOf But if I understand you well, you need to make the client aware that something has change (the progress of download for example or the end of the downloading) I think that the simplest way may be to raise events from you python code. This way the events are treat naturally in VB. For an example on how to raise events from you python code, you can look at the sample demo in win32com/demos/connect.py (implements client and server) or in win32com/server/connect.py (for server implementation. The demo server inherits from this one) Last, Mark Hammond respond while ago about COM Server & Events: http://mail.python.org/pipermail/python-win32/2004-September/002386.html, I don't know if there are changes... Regards, Jorge On 3/15/07, Gabriel Genellina wrote: > > En Wed, 14 Mar 2007 21:17:12 -0300, Larry Bates > escribi?: > > > I have a rather large Python class that I've converted to > > a COM object. I can dispatch (using either Python or VB) > > and call the methods perfectly. Now a new client wants > > to call it from Delphi. Can anyone out there give me > > any pointers on how that would be done. Are there any > > "gotchas" about the way arguments or return values > > would need to be different for Delphi. I have NO Delphi > > experience so I'm completely lost. > > The same as he would do for any other COM object. There are tools in > Delphi for building automatically the needed Delphi declarations > (interfases, classes, methods, constants... similar to what makepy does > for Python). > All OLE types work fine. (Variants are a bit hard to process, yes, but it > can be done) > > > Secondly, I need a callback function in VB (progress > > meter) that I can pass to Python COM object to show > > Sorry, I try to stay away of VB as far as possible :) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Fri Mar 16 14:26:06 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 16 Mar 2007 13:26:06 -0500 Subject: distributing python software in jar like fashion In-Reply-To: References: Message-ID: John Nagle wrote: > Were Python "eggs" a flop, or what? No. > We need to have one packager that everyone agrees on. > Otherwise, installs become a mess, and then you have to have > installers that handle multiple packagers. Eggs and Squisher are complementary tools. Squisher is good for distributing an application with all of its dependencies in a single file; it is not a packager or installer for libraries. Eggs are good for distributing libraries and plugins and their dependencies. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From lojicdotcomNOSPAM at gmail.com Wed Mar 7 18:30:53 2007 From: lojicdotcomNOSPAM at gmail.com (Brian Adkins) Date: Wed, 07 Mar 2007 18:30:53 -0500 Subject: merits of Lisp vs Python In-Reply-To: References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> Message-ID: John Nagle wrote: > Neither Lisp nor Python is an "industrial strength language". > The infrastructure is too weak. Hosting providers and distro > makers aren't concerned over whether Python works. They > care if C, C++, Java, PHP, and Perl work, but not Python or LISP. > Ask them. > > John Nagle In your excitement to post a sweeping and inaccurate generalization (you missed diss'ing Ruby), I think you may have missed the point of my post. I surely wasn't trying to restart a dead thread, I just thought it was funny that there was a similarity to a line from Princess Bride in the thread (see relevant part below that you cut out). If you want to restart a debate, please go back and reply to some serious post in the thread - don't hijack mine for your own evil purposes and cut out the good parts - did you even see the movie? George Sakkis wrote: > You keep using that phrase. I don't think it means what you think it > means. [Vizzini has just cut the rope The Dread Pirate Roberts is climbing up] Vizzini: HE DIDN'T FALL? INCONCEIVABLE. Inigo Montoya: You keep using that word. I do not think it means what you think it means. From nagle at animats.com Sun Mar 4 01:50:06 2007 From: nagle at animats.com (John Nagle) Date: Sun, 04 Mar 2007 06:50:06 GMT Subject: Questions about app design - OOP with python classes In-Reply-To: References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <54q5lnF22aafrU1@mid.uni-berlin.de> Message-ID: Steven D'Aprano wrote: > On Fri, 02 Mar 2007 09:30:20 +0100, Diez B. Roggisch wrote: > > >>>A type system doesn't help. So what if they're both floats? The test >>>is still bogus, your code will still wait too long to engage the >>>retro-rockets, and the billion dollar space craft will still be travelling >>>at hundreds of miles an hour when it reaches the surface of Mars. >> >>A type system _could_ help. > > > It's easy to wave your hands and say that Microsoft could have done > something different, but they had to work with what they had, not some > hypothetical alternative language with a hypothetical type system that > didn't exist then (if it even exists now). The Pascal/Ada/Modula family of languages all had type systems with restrictions on conversion. Unlike C, types in Pascal are not simply abbreviations of the type; they're unique types. This turns out to be too restrictive, but it's certainly been tried. There are C++ class libraries that understand units. And the conversion factors can be dealt with at compile time, so the overhead goes away. John Nagle From bbxx789_05ss at yahoo.com Mon Mar 26 12:15:04 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 Mar 2007 09:15:04 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> <1174803233.118069.234290@l75g2000hse.googlegroups.com> <1174813227.275145.211000@o5g2000hsb.googlegroups.com> <1174854156.298431.68150@n59g2000hsh.googlegroups.com> Message-ID: <1174925704.394888.18170@d57g2000hsg.googlegroups.com> On Mar 25, 3:09 pm, Steven Bethard wrote: > Here's another way of looking at it:: > > >>> class Test(object): > ... pass > ... > >>> def greet(): > ... print 'Hello' > ... >>> Test.greet = greet >>> Test.greet > Interesting. After playing around with that example a bit and finally thinking I understood bound v. unbound, I found what appears to be an anomaly: ------------ class Test(object): pass def greet(x): print "hello" Test.func = greet print Test.func t = Test() print t.func def sayBye(x): print "bye" t.bye = sayBye print t.bye ------------output: > Why doesn't t.bye cause a method object to be created? > ... under the covers, classes are actually using > doing something like this:: > > >>> Test.__dict__['greet'].__get__(None, Test) > > >>> Test.greet == Test.__dict__['greet'].__get__(None, Test) > True > ...via __getattribute_, right? > ... if you want to get a method from a function, you can always do that > manually yourself:: > > >>> greet.__get__(None, Test) > Manually creating a method object. Nice. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 16 09:37:51 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 16 Mar 2007 14:37:51 +0100 Subject: CSV module and "fileobj" In-Reply-To: <1174042670.829441.286490@n59g2000hsh.googlegroups.com> References: <1174042670.829441.286490@n59g2000hsh.googlegroups.com> Message-ID: <45fa9d7e$0$29896$426a34cc@news.free.fr> Jon Clements a ?crit : > Hi Group, > > If I have a CSV reader that's passed to a function, is it possible for > that function to retrieve a reference to the "fileobj" like object > that was passed to the reader's __init__? For instance, if it's using > an actual file object, then depending on the current row, I'd like to > open the file object again, seek to the current position, then create > a csv.reader on that, exhaust it until a certain point, then return. > ie, leaving the passed iterator intact and ready to carry on as > normal. > > (And yes, I know passing in the source object is probably easier -- > assume a constraint that I can't...) > As Skip pointed out, this won't work that way. There might be a possible workaround using itertools.tee and eventually StringIO. My 2 cents From dbhbarton at googlemail.com Fri Mar 9 05:31:14 2007 From: dbhbarton at googlemail.com (dbhbarton at googlemail.com) Date: 9 Mar 2007 02:31:14 -0800 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> Message-ID: <1173436274.346506.200920@q40g2000cwq.googlegroups.com> Thanks for the thoughts. > This could be implemented without new syntax: just make your editor > recognize some special comments, and apply the highlighting to the > following block. By example, > > # XXX Remove this when FuruFaifa is fixed to always provide > # XXX the names in the same order > names.sort() > names.reverse() Yes I recognise that we can use existing comments for this purpose, and if I was suitably gifted I guess I could try to make the IDE recognise these 'special comments', and maybe even work out what block they're meant to apply to. Of course I'll still argue that the WIP character would be a more elegant, speedy and versatile alternative. > You accidentally type a ! somewhere, and your module stops working - not > so good :( and worse, hard to find. By my reckoning it would be very very easy to find. Even if the IDE wasn't greying out everything after it. And how often do you accidentally mistype a ! at the beginning of a line? > I sometimes use '''this string marks''' to ignore whole blocks of code. It > works fine unless the block already contains the same kind of > triple-quoted string... Indeed. Moreover those quotes have to be in pairs, so it's not exactly a quick and dandy way of doing what I'd like. > The main problem with new syntax is breaking compatibility with older > versions... Agreed. But both characters are currently disallowed in the positions concerned, and in the proposal they're optional extras. This can't stop old scripts from working, it can only stop new scripts from working on old installations- just like any new feature. >, and I doubt it's worth the pain just for highlighting or playing > interactively Ah well there's the issue! >, so you don't have a great chance of them being > implemented... Obviously I like the idea, but I never hold out much hope that people will agree with me! From asandstrom at accesswave.ca Sat Mar 31 01:20:48 2007 From: asandstrom at accesswave.ca (Arved Sandstrom) Date: Sat, 31 Mar 2007 05:20:48 GMT Subject: What are OOP's Jargons and Complexities References: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> <460cc83a.2652073@news.readfreenews.net> Message-ID: "Timofei Shatrov" wrote in message news:460cc83a.2652073 at news.readfreenews.net... > On Fri, 30 Mar 2007 06:48:05 GMT, "Mike Schilling" > > tried to confuse everyone with this message: > >>Xah Lee wrote: >> >>> So, a simple code like this in normal languages: > >>> becomes in Java: >> >>Only when written by someone almost entirely ignorant of Java. >> > > Which is the state most people want to be in... Which based on what I've seen, is the state that most Java programmers are in. They'd have no idea why Mike said what he did. AHS From george.sakkis at gmail.com Sun Mar 18 22:01:27 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Mar 2007 19:01:27 -0700 Subject: list comprehension help In-Reply-To: References: Message-ID: <1174269687.497013.249480@o5g2000hsb.googlegroups.com> On Mar 18, 12:11 pm, "rkmr... at gmail.com" wrote: > Hi > I need to process a really huge text file (4GB) and this is what i > need to do. It takes for ever to complete this. I read some where that > "list comprehension" can fast up things. Can you point out how to do > it in this case? > thanks a lot! > > f = open('file.txt','r') > for line in f: > db[line.split(' ')[0]] = line.split(' ')[-1] > db.sync() You got several good suggestions; one that has not been mentioned but makes a big (or even the biggest) difference for large/huge file is the buffering parameter of open(). Set it to the largest value you can afford to keep the I/O as low as possible. I'm processing 15-25 GB files (you see "huge" is really relative ;-)) on 2-4GB RAM boxes and setting a big buffer (1GB or more) reduces the wall time by 30 to 50% compared to the default value. BerkeleyDB should have a buffering option too, make sure you use it and don't synchronize on every line. Best, George From steve at REMOVE.THIS.cybersource.com.au Tue Mar 20 00:23:32 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 20 Mar 2007 15:23:32 +1100 Subject: Documentation for "str()" could use some adjustment - Unicode issue References: Message-ID: On Mon, 19 Mar 2007 17:01:23 +0000, John Nagle wrote: >> Hi John, I'm not at all an expert around here but my understanding of >> the workflow is that bug reports should be submitted to the tracker at >> sourceforge. There is no guarantee that they will be noticed there but >> the chances there are much higher than for a message on the mailing >> list. I just mention this because I've seen your mysqld, urllib and >> other potentially important bug reports here with no action taken but >> maybe submitting them to sourceforge would attract some developers. > > More people read the mailing list than the bug reports, and > Google indexes it, so it puts the problem on record. "More people" is irrelevant. What matters is "the right people". I believe Google also indexes bug reports. It depends whether the site allows Google's spiders or not. > If this problem > were reported as a bug, there'd be denial that it was a problem, on > the grounds that it will be fixed in a future version of Python. I don't think so much it's denied as that the developers have decided that fixing it isn't a valuable use of their time because there are more important (or more interesting) problems that they could be fixing instead, and it will go away on its own with Python 3. > This was addressed in PEP 349 (status "Deferred"), so it's > a known problem that's being ignored. Then stop ignoring it, and submit a fix! If you personally don't have the time or expertise to fix the problem yourself, pay somebody to do so. Who says Open Source isn't compatible with capitalism? -- Steven. From tonyr1988 at gmail.com Thu Mar 15 13:24:02 2007 From: tonyr1988 at gmail.com (tonyr1988) Date: 15 Mar 2007 10:24:02 -0700 Subject: Pickle Problem In-Reply-To: References: <1173971633.305988.207530@d57g2000hsg.googlegroups.com> Message-ID: <1173979442.025584.282090@e65g2000hsc.googlegroups.com> On Mar 15, 10:38 am, Gary Herron wrote: > tonyr1988 wrote: > > I'm a complete python n00b writing my first program (or attempting to, > > anyway). I'm trying to make the transition from Java, so if you could > > help me, it would be greatly appreciated. Here's the code I'm stuck on > > (It's very basic): > > > class DemoClass: > > def __init__(self): > > self.title = ["Hello", "Goodbye"] > > > def WriteToFile(self, path = "test.txt"): > > fw = file(path, "w") > > pickle.dump(self.title, fw) > > fw.close() > > > if __name__=='__main__': > > x = DemoClass > > x.WriteToFile > > > It doesn't do any file I/O at all (that I see). I hope my syntax is > > alright. If I just call WriteToFile, shouldn't it perform with the > > default path? It gives me no errors and pretends to execute just fine. > > Several people have pointed out the problem, but when you get that > fixed, I see another bit of trouble. The pickle format is a binary > format (be default), but you don't open the file in binary mode. On > Unix the distinction is (wisely) irrelevant, but on Windows you should > open the file with a mode of "wb" not just "w". Thanks guys for all the help. Sure enough, it was the parenthesis. Most of my problems seem to be from under-simplifying (using semicolons, brackets, etc) or, rarely, over-simplifying (forgetting parenthesis). The biggest thing that was messing me up was the mandatory "self" input. For some reason I was thinking that, if I had parenthesis, I would have to define it. Fixing that works perfectly. Also, about the binary format for opening files. The program that I'm working on now is completely Linux-based - it's impossible for it to work on any other OS. Should I still open with "wb" or not? Either way, thanks for that tip! One more (completely irrelevant) question. I don't quite understand the double-underscore functions / methods / etc, such as __name__, __main__, __init__. Is there a reason for the double-underscore? Does it make anything special? Again, thanks for the help...I'm probably going to ask a lot more of it before too long. :) From slawomir.nowaczyk.847 at student.lu.se Fri Mar 16 05:40:36 2007 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 16 Mar 2007 10:40:36 +0100 Subject: execfile locks file forever if there are any syntax errors - is it python bug? In-Reply-To: <17911.61901.32043.373777@montanaro.dyndns.org> References: <20070314130014.A4F9.SLAWOMIR.NOWACZYK.847@student.lu.se> <17911.61901.32043.373777@montanaro.dyndns.org> Message-ID: <20070316103316.A518.SLAWOMIR.NOWACZYK.847@student.lu.se> On Wed, 14 Mar 2007 07:59:57 -0500 skip at pobox.com wrote: #> #> Slawomir> When I execfile a file which contains a syntax error, the file #> Slawomir> becomes locked and stays this way all the way until I exit the #> Slawomir> interpreter (I am unable to delete it, for example). I have #> Slawomir> tried but failed to find any way to unlock the file... Is this #> Slawomir> a bug in Python? #> #> Kinda seems like it might be. Please file a bug report on SourceForge. I did, and it is a bug, but it seems to be already fixed in SVN. https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1681020&group_id=5470 -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Does a clean house indicate that there is a broken computer in it? From bearophileHUGS at lycos.com Fri Mar 9 16:59:16 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 9 Mar 2007 13:59:16 -0800 Subject: bisect on a list of lists In-Reply-To: <1173471342.957772@iceman.esoterica.pt> References: <1173471342.957772@iceman.esoterica.pt> Message-ID: <1173477556.637586.320300@p10g2000cwp.googlegroups.com> Paulo da Silva: > What is the best way to have something like the bisect_left > method on a list of lists being the comparision based on an > specified arbitrary i_th element of each list element? You may use this recipe of mine that I've just put there for you, but it's not fully tested yet (if you spot problems I'm willing to fix them): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502295 Or you can create a little class, that wraps your list with just a __cmp__ method that works on the n-th element of the list. Then you can use heapq on many instances of that class created with a list comphrension. Probably there are other solutions too. Bye, bearophile From nieuws.pv at xs4all.nl Wed Mar 21 19:21:23 2007 From: nieuws.pv at xs4all.nl (Patrick Vrijlandt) Date: Thu, 22 Mar 2007 00:21:23 +0100 Subject: Python COM Outlook Question In-Reply-To: <1174504504.910510.219050@b75g2000hsg.googlegroups.com> Message-ID: <200703212321.l2LNLBgK021123@smtp-vbr13.xs4all.nl> Hi, It seems that space.Folders["DailyGoodEmails"] might be a valid expression; otherwise you might have experiment with space.GetSharedDefaultFolder() HTH, Patrick -----Oorspronkelijk bericht----- On Mar 21, 2:15 pm, "liam_herron" wrote: > Say I want to open a shared email inbox (named "DailyGoodEmails") that > is different from my default Outlook inbox, how do I specify this? > > Currently, I would do: > > s = Dispatch("Outlook.Application") > space = s.GetNameSpace("MAPI") > inbox = space.GetDefaultFolder(6) > myFolder = inbox.Folders[9] #open the folder i want > > I have no idea where the "6" comes from but I want to be able to > specify "DailyGoodEmails" somewhere and be able to iterate over the > emails. I don't know how to do this, but I found you a couple websites that should point you in the right direction: http://www.boddie.org.uk/python/COM.html http://webservices.xml.com/pub/a/ws/2003/05/13/email.html Hope that helps. Mike -- http://mail.python.org/mailman/listinfo/python-list From jmcmonagle at velseis.com.au Thu Mar 8 19:29:49 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 09 Mar 2007 10:29:49 +1000 Subject: {Possible_Spam} tkinter text editor In-Reply-To: References: Message-ID: <45F0AA7D.9080806@velseis.com.au> Gigs_ wrote: > I'm writing text editor. > > How to enable/disable (cut, copy etc.) when text is selected/not selected Bind the Button1-ButtonRelease event to a function which checks the length of the SEL tag of the text widget. If it is zero length, disable the appropriate menu entries, if it is non-zero, enable the appropriate menu entries. Simple example: from Tkinter import * root = Tk() textWidget = Text(root) textWidget.pack() def onButton1Release(event): if len(textWidget.tag_ranges(SEL)) == 0: print 'No text selected. Disable appropriate menu entries' else: print 'Some text selected. Enable appropriate menu entries' textWidget.bind('', onButton1Release) root.mainloop() From kyosohma at gmail.com Tue Mar 20 11:33:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Mar 2007 08:33:54 -0700 Subject: difference between urllib2.urlopen and firefox view 'page source'? In-Reply-To: References: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> Message-ID: <1174404834.789749.89760@p15g2000hsd.googlegroups.com> On Mar 20, 1:56 am, Tina I wrote: > cjl wrote: > > Hi. > > > I am trying to screen scrape some stock data from yahoo, so I am > > trying to use urllib2 to retrieve the html and beautiful soup for the > > parsing. > > > Maybe (most likely) I am doing something wrong, but when I use > > urllib2.urlopen to fetch a page, and when I view 'page source' of the > > exact same URL in firefox, I am seeing slight differences in the raw > > html. > > > Do I need to set a browser agent so yahoo thinks urllib2 is firefox? > > Is yahoo detecting that urllib2 doesn't process javascript, and > > passing different data? > > > -cjl > > Unless the data you you need depends on the site detecting a specific > browser you will probably receive a 'cleaner' code that's more easily > parsed if you don't set a user agent. Usually the browser optimization > they do is just eye candy, bells and whistles anyway in order to give > you a more 'pleasing experience'. I doubt that your program will care > about that ;) > > Tina You can do this fairly easily. I found a similar program in the book Core Python Programming. It actually sticks the stocks into an Excel spreadsheet. The code is below. You can easily modify it to send the output elsewhere. # Core Python Chp 23, pg 994 # estock.pyw from Tkinter import Tk from time import sleep, ctime from tkMessageBox import showwarning from urllib import urlopen import win32com.client as win32 warn = lambda app: showwarning(app, 'Exit?') RANGE = range(3, 8) TICKS = ('AMZN', 'AMD', 'EBAY', 'GOOG', 'MSFT', 'YHOO') COLS = ('TICKER', 'PRICE', 'CHG', '%AGE') URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2' def excel(): app = 'Excel' xl = win32.gencache.EnsureDispatch('%s.Application' % app) ss = xl.Workbooks.Add() sh = ss.ActiveSheet xl.Visible = True sleep(1) sh.Cells(1, 1).Value = 'Python-to-%s Stock Quote Demo' % app sleep(1) sh.Cells(3, 1).Value = 'Prices quoted as of: %s' % ctime() sleep(1) for i in range(4): sh.Cells(5, i+1).Value = COLS[i] sleep(1) sh.Range(sh.Cells(5, 1), sh.Cells(5, 4)).Font.Bold = True sleep(1) row = 6 u = urlopen(URL % ','.join(TICKS)) for data in u: tick, price, chg, per = data.split(',') sh.Cells(row, 1).Value = eval(tick) sh.Cells(row, 2).Value = ('%.2f' % round(float(price), 2)) sh.Cells(row, 3).Value = chg sh.Cells(row, 4).Value = eval(per.rstrip()) row += 1 sleep(1) u.close() warn(app) ss.Close(False) xl.Application.Quit() if __name__ == '__main__': Tk().withdraw() excel() # Have fun - Mike From felipe.lessa at gmail.com Sat Mar 24 17:07:57 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 24 Mar 2007 18:07:57 -0300 Subject: Python object overhead? In-Reply-To: <56ja46F28lpp9U1@mid.individual.net> References: <56ja46F28lpp9U1@mid.individual.net> Message-ID: On 3/23/07, Bjoern Schliessmann wrote: > (Note that almost everything in Python is an object!) Could you tell me what in Python isn't an object? Are you counting old-style classes and instances as "not object"s? -- Felipe. From lbates at websafe.com Fri Mar 9 12:52:50 2007 From: lbates at websafe.com (Larry Bates) Date: Fri, 09 Mar 2007 11:52:50 -0600 Subject: Creat a DLL File from python code, and use that DLL file in other Platform (Labview, Java .NET etc) In-Reply-To: <1173441503.965228.95590@j27g2000cwj.googlegroups.com> References: <1173441503.965228.95590@j27g2000cwj.googlegroups.com> Message-ID: macedo.silva at gmail.com wrote: > Hi, > > I would like to request your attention for this very specific issue: > > I have several classes in Python, and now I want simply re-use it, in > other language. > > > The closest to solution I think I came was with this site: > http://www.py2exe.org/index.cgi/Py2exeAndCtypesComExeServer?highlight=%28%28Py2exeAndCtypesComDllServer%29%29 > but I not able to solve questions related with TLB files and > __init__.py files. > > So, could anyone give a tip about HOW TO CREAT a dll file from Python? > > thank in advance > > AMMS > Do you absolutely need .DLL? You can make a class into a COM object that nearly every language on the planet can dispatch with ease. Here is some info: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Calling an existing .DLL? Use ctypes module. -Larry From deets at nospam.web.de Tue Mar 27 11:16:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Mar 2007 17:16:53 +0200 Subject: Please help!! SAXParseException: not well-formed (invalid token) References: <1175007585.758109.127490@r56g2000hsd.googlegroups.com> Message-ID: <56sqr5F29auttU1@mid.uni-berlin.de> jvictor118 at yahoo.fr wrote: > I've been using the xml.sax.handler module to do event-driven parsing > of XML files in this python application I'm working on. However, I > keep having really pesky invalid token exceptions. Initially, I was > only getting them on control characters, and a little "sed -e 's/ > [^[:print:]]/ /g' $1;" took care of that just fine. But recently, I've > been getting these invalid token excpetions with n-tildes (like the n > in Espa?a), smart/fancy/curly quotes and other seemingly harmless > characters. Specifying encoding="utf-8" in the xml header hasn't > helped matters. > > Any ideas? As a last resort, I'd be willing to scrub invalid > characters.... it just seems strange that curly quotes and n-tildes > wouldn't be valid XML! Is that really the case? It's not the case, unless you have a wrong encoding. Then the whole XML-Document isn't a XML-document at all. Just putting an encoding header that doesn't match the actually used encoding won't fix that. Read up on what encodings are, and ensure your XML-generation respects that. Then reading these files will cause no problems. Diez From arnodel at googlemail.com Mon Mar 5 14:14:56 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 5 Mar 2007 11:14:56 -0800 Subject: New to Python In-Reply-To: <1173119634.739433.240520@s48g2000cws.googlegroups.com> References: <1173119634.739433.240520@s48g2000cws.googlegroups.com> Message-ID: <1173122096.762869.16920@64g2000cwx.googlegroups.com> On Mar 5, 6:33 pm, "dnwu... at gmail.com" wrote: > I am trying to get a program to add up input from the user to get to > the number 100 using a loop. However, I am having some issues. Here > is what I have so far. I know I am just trying to hard, but I am > stuck. Thank you for any help. > > print "We need to count to 100" > > high_number = 100 > total = 0 > > number = input("Enter your first number ") > sum = number + total > while sum < high_number: > print "Not there yet..." > number = input("Enter another number ") > > print "We are there!!!" There is no need for 'sum' and 'total'. Here's a working version of your program. Look at the differences with your attempt. ---------- print "We need to count to 100" high_number = 100 total = input("Enter your first number ") # first total is the fist number while total < high_number: print "Not there yet..." number = input("Enter another number ") total = total + number # Add the new number to the total print "We are there!!!" ---------- Good luck ! As others have pointed out, 'input' is a function to be careful with. You could use answer=raw_input(...) and then convert the result to an int by using number=int(answer). -- Arnaud From steve at REMOVE.THIS.cybersource.com.au Sun Mar 25 04:57:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 25 Mar 2007 18:57:43 +1000 Subject: List comprehension returning subclassed list type? References: <1174804990.037158.22790@l77g2000hsb.googlegroups.com> Message-ID: On Sat, 24 Mar 2007 23:43:10 -0700, bullockbefriending bard wrote: > z_list = [Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y] > > Of course this just gives me a plain list and no access to the > methodsof z_list. List comprehensions give you a list. If you want to convert that list into the type of z_list, you need to do it yourself. Since ZList sub-classes from list, probably the easiest way is just: z_list = ZList([some list comprehension here]) > I could, of course go and write a static method in > ZList which takes a plain list of Z objects and returns a ZList. Yes, that would be one such way. Another way is: z_list.extend([some list comprehension here]) If you are using a recent enough version of Python, you probably don't even need the list comprehension. Just use a generator expression: z_list.extend(Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y) That's especially useful if the list of objects is huge, because it avoids creating the list twice: once in the list comp, and once as z_list. -- Steven. From maxerickson at gmail.com Sat Mar 10 19:44:52 2007 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 11 Mar 2007 00:44:52 +0000 (UTC) Subject: PIL: reading bytes from Image References: <1173568560.648691.61760@64g2000cwx.googlegroups.com> Message-ID: "cyberco" wrote: > I'm using web.py to send an image to the client. This works > (shortened): > > print open(path, "rb").read() > > but this doesn't: > > img = Image.open(path) > img.thumbnail((10,10)) > print img.getdata() > > or > > print img.load() > > > How do I get the bytes of the Image object? 'getdata()' seemed the > way, but unfortunately... > getdata() returns the data in a PIL format. Saving the image, in a format your client understands, to a file like object like StringIO.StringIO is an easy path to take. Sparklines shows this in action: http://bitworking.org/projects/sparklines/ max From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Mar 2 10:01:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Mar 2007 16:01:52 +0100 Subject: class declaration shortcut References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <54mh20F21ho3eU1@mid.individual.net> <45e61068$0$30655$426a34cc@news.free.fr> <54msaoF21c6h3U3@mid.individual.net> <1172741018.978417.233160@v33g2000cwv.googlegroups.com> <54nlkgF21ft8aU3@mid.individual.net> Message-ID: <54qsj0F21kdccU1@mid.individual.net> Steven D'Aprano wrote: > Overkill? Storage of a single attribute holding a (usually short) > string is overkill? No, but storing the first name a class is bound to in it is a bit of, IMHO. > When you do that, you wouldn't expect the __name__ of > some.module.function to change to f, and it doesn't. But what is it for then? =) Showing the first name the class was bound to? Regards, Bj?rn -- BOFH excuse #217: The MGs ran out of gas. From nobody at invalid.com Tue Mar 27 15:00:22 2007 From: nobody at invalid.com (Erik Johnson) Date: Tue, 27 Mar 2007 13:00:22 -0600 Subject: Numeric Soup References: <46094afe$1@nntp.zianet.com> Message-ID: <460969b6$1@nntp.zianet.com> "Robert Kern" wrote in message news:mailman.5676.1175016264.32031.python-list at python.org... > http://www.scipy.org/History_of_SciPy > > numpy is the current array package and supercedes Numeric and numarray. scipy > provides a bunch of computational routines (linear algebra, optimization, > statistics, signal processing, etc.) built on top of numpy. Thank you. From bearophileHUGS at lycos.com Wed Mar 7 17:57:54 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Mar 2007 14:57:54 -0800 Subject: Best place for a function? In-Reply-To: <558soiF23polgU1@mid.uni-berlin.de> References: <558soiF23polgU1@mid.uni-berlin.de> Message-ID: <1173308274.223424.14950@h3g2000cwc.googlegroups.com> Diez B. Roggisch: > If it really has no other use as in this class, put it as an > instancemethod in there. Alternatively, you _could_ nest it like this: Using an instancemethod may be the most formally correct solution for that problem, but often nested function are the simpler solution. A downside of nested functions is that you can't give them a doctest (in a simple way). Bye, bearophile From B.Ogryczak at gmail.com Mon Mar 26 09:40:55 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 26 Mar 2007 06:40:55 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174916455.390214.139120@n76g2000hsh.googlegroups.com> On Mar 26, 3:20 pm, "Noma... at gmail.com" wrote: > OK... > I've been told that Both Fortran and Python are easy to read, and are > quite useful in creating scientific apps for the number crunching, but > then Python is a tad slower than Fortran because of its a high level > language nature, so what are the advantages of using Python for > creating number crunching apps over Fortran?? Portability, scalability & RAD. From jg307 at cam.ac.uk Fri Mar 2 19:27:25 2007 From: jg307 at cam.ac.uk (James Graham) Date: Sat, 03 Mar 2007 00:27:25 +0000 Subject: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles.. In-Reply-To: <1172878378.291106.321050@h3g2000cwc.googlegroups.com> References: <1172878378.291106.321050@h3g2000cwc.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > I'm trying to extract some data from an XHTML Transitional web page. > > What is best way to do this? May I suggest html5lib [1]? It's based on the parsing section of the WHATWG "HTML5" spec [2] which is in turn based on the behavior of major web browsers so it should parse more or less* any invalid markup you throw at it. Despite the name "html5lib" it works with any (X)HTML document. By default, you have the option of producing a minidom tree, an ElementTree, or a "simpletree" - a lightweight DOM-like html5lib-specific tree. If you are happy to pull from SVN I recommend that version; it has a few bug fixes over the 0.2 release as well as improved features including better error reporting and detection of encoding from elements (the next release is imminent). [1] http://code.google.com/p/html5lib/ [2] http://whatwg.org/specs/web-apps/current-work/#parsing * There might be a problem if e.g. the document uses a character encoding that python does not support, otherwise it should parse anything. From web at pobox.com Mon Mar 12 14:09:42 2007 From: web at pobox.com (Dr. Who) Date: 12 Mar 2007 11:09:42 -0700 Subject: File locking Message-ID: <1173722982.696539.24360@64g2000cwx.googlegroups.com> I'm always disappointed when I find something that Python doesn't handle in a platform independent way. It seems to me that file locking is in that boat. 1. I don't see a way to atomically open a file for writing if and only if it doesn't exist without resorting to os.open and specialized platform O_XXX flags. 2. I don't see a way to atomically open a file for writing and obtain a lock on the file. 3. I don't see a platform independent way to obtain a lock on a file. You have to do something goofy like if sys.platform == win32: import msvcrt else: import fcntl and then similar things to call the correct functions with the correct flags. Please let me know if I'm missing something since they seem like normal file operations that I would hope Python would abstract away. If not, are there any PEPs concerning this for Python3K? Thanks, Jeff From kyosohma at gmail.com Tue Mar 27 13:25:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Mar 2007 10:25:09 -0700 Subject: Auto execute python in USB flash disk In-Reply-To: <1175014574.359563.26630@o5g2000hsb.googlegroups.com> References: <1175014574.359563.26630@o5g2000hsb.googlegroups.com> Message-ID: <1175016309.707429.298790@r56g2000hsd.googlegroups.com> On Mar 27, 11:56 am, "Brian Erhard" wrote: > I am still fairly new to python and wanted to attempt a home made > password protection program. There are files that I carry on a USB > flash drive that I would like to password protect. Essentially, I > would like to password protect an entire directory of files. Is there > a way to auto execute a python script after a user double clicks to > open a folder on the USB drive? How can you capture that double click > event on a specific folder? > > Thanks. I've never done this before, but it sounds cool. You would need to create some kind of python file object to do this properly. So instead of actually clicking a folder, you would click a pickled file or something. I found some cool info about encrypting files here: http://www.methods.co.nz/python/ There's also a python cryptography kit: http://www.amk.ca/python/writing/pycrypt/ Finally, I found a fellow python programmer that wrote his own: http://mail.python.org/pipermail/python-list/2006-April/378510.html There's also PortablePython... Enjoy! Mike From http Mon Mar 19 22:52:51 2007 From: http (Paul Rubin) Date: 19 Mar 2007 18:52:51 -0800 Subject: an enumerate question References: <1174354730.832021.263940@p15g2000hsd.googlegroups.com> <7xr6rkr8gw.fsf@ruckus.brouhaha.com> <1174356075.710324.321150@b75g2000hsg.googlegroups.com> Message-ID: <7x1wjkoccc.fsf@ruckus.brouhaha.com> eight02645999 at yahoo.com writes: > for n,l in enumerate(open("file")): > print n,l # this prints current line > print next line in this current iteration of the loop. > hope you can understand now. I see. It just seemed a little weird. If the file contains first line second line third line You want the output: 1 first line second line 2 second line third line 3 third line Is that right? Anyway all the ways I can think of to do it are at least somewhat messy. Skip suggested one. It's easier if you're sure the file is small enough to fit all its lines completely into memory. From kyosohma at gmail.com Tue Mar 20 12:25:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Mar 2007 09:25:19 -0700 Subject: making objects with individual attributes! In-Reply-To: <1174406902.445936.261450@y66g2000hsf.googlegroups.com> References: <1174406902.445936.261450@y66g2000hsf.googlegroups.com> Message-ID: <1174407919.263659.294430@e1g2000hsg.googlegroups.com> On Mar 20, 11:08 am, "Alejandro" wrote: > I have created a class: > > class document: > > titre = '' > haveWords = set() > > def __init__(self, string): > > self.titre = string > > ######### > > doc1 = document('doc1') > doc2 = document('doc2') > > doc1.haveWords.add(1) > doc2.haveWords.add(2) > > print doc1.haveWords > > # i get set([1, 2]) > > doc1 and doc are sharing attribute haveWords! > Why ??? there's a way to assign every objetc "document" a different > "set" You're just slightly off. The code needs to be more like this: class document: def __init__(self, string): self.titre = string self.haveWords = set() ################## I think what you did was create some kind of global variable that was then accessible through the namespace. But I really don't know for sure. This code seems to work now, though. Mike From bbxx789_05ss at yahoo.com Fri Mar 30 14:48:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 30 Mar 2007 11:48:46 -0700 Subject: manually implementing staticmethod()? In-Reply-To: <1hvqagu.mn0e7yxfqvmrN%aleax@mac.com> References: <1175115664.288706.183390@p77g2000hsh.googlegroups.com> <1hvqagu.mn0e7yxfqvmrN%aleax@mac.com> Message-ID: <1175280526.733006.153540@e65g2000hsc.googlegroups.com> Hi, Thanks for the responses. On Mar 28, 4:01 pm, "Michael Spencer" wrote: > "7stud" wrote in message > > news:1175115664.288706.183390 at p77g2000hsh.googlegroups.com...> Hi, > > > Can someone show me how to manually implement staticmethod()? Here is > > my latest attempt: > > ---------------- > > Raymond Hettinger can: > > http://users.rcn.com/python/download/Descriptor.htm#static-methods-an... I was using that article to help me. My problem was I was trying to implement smeth() as a function rather than a class. I hacked around some more, and I came up with the following before peeking at this thread for the answer: class smeth(object): def __init__(self, func): self.func = func def __getattribute__(self, name): print "smeth -- getattribute" return super(smeth, self).__getattribute__(name) def __get__(self, inst, cls=None): print "smeth get" return self.func class Test(object): def __getattribute__(self, name): print "Test - gettattribute" return super(Test, self).__getattribute__(name) def f(): print "executing f()" return 10 f = smeth(f) print Test.f #displays function obj not unbound method obj! Test.f() However, my code does not seem to obey this description in the How-To Guide to Descriptors: --------- Alternatively, it is more common for a descriptor to be invoked automatically upon attribute access. For example, obj.d looks up d in the dictionary of obj. If d defines the method __get__, then d.__get__(obj) is invoked according to the precedence rules listed below.***The details of invocation depend on whether obj is an object or a class***. ... For objects, the machinery is in object.__getattribute__ which transforms b.x into type(b).__dict__['x'].__get__(b, type(b)). ... For classes, the machinery is in type.__getattribute__ which transforms B.x into B.__dict__['x'].__get__(None, B). --------- When I examine the output from my code, Test.f does not call Test.__getattribute__(), instead it calls smeth.__get__() directly. Yet that last sentence from the How-To Guide to Descriptors seems to say that Test.__getattribute__() should be called first. I'm using python 2.3.5. On Mar 29, 9:34 am, a... at mac.com (Alex Martelli) wrote: > Simplest way: > > class smethod(object): > def __init__(self, f): self.f=f > def __call__(self, *a, **k): return self.f(*a, **k) > > Alex Interesting. That looks like a functor to me. Thanks. I notice that __get__() overrides __call__(). From paul at boddie.org.uk Fri Mar 2 18:50:59 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Mar 2007 15:50:59 -0800 Subject: How *extract* data from XHTML Transitional web pages? got xml.dom.minidom troubles.. In-Reply-To: <1172878378.291106.321050@h3g2000cwc.googlegroups.com> References: <1172878378.291106.321050@h3g2000cwc.googlegroups.com> Message-ID: <1172879459.318432.218250@z35g2000cwz.googlegroups.com> seberino at spawar.navy.mil wrote: > I'm trying to extract some data from an XHTML Transitional web page. > > What is best way to do this? An XML parser should be sufficient. However... > xml.dom.minidom.parseString("text of web page") gives errors about it > not being well formed XML. > > Do I just need to add something like or what? If the page isn't well-formed then it isn't proper XHTML since the XHTML specification [1] says... 4.1. Documents must be well-formed Yes, it's a heading, albeit in an "informative" section describing how XHTML differs from HTML 4. See "3.2. User Agent Conformance" for a "normative" mention of well-formedness. You could try libxml2dom (or other libxml2-based solutions) for some fairly effective HTML parsing: libxml2dom.parseString("text of document here", html=1) See http://www.python.org/pypi/libxml2dom for more details. Paul [1] http://www.w3.org/TR/xhtml1/ From gagsl-py2 at yahoo.com.ar Mon Mar 5 21:41:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Mar 2007 23:41:16 -0300 Subject: classes and functions References: <1172952273.482935.129850@8g2000cwh.googlegroups.com> Message-ID: En Sat, 03 Mar 2007 17:04:33 -0300, Arnaud Delobelle escribi?: > On Mar 2, 11:01 pm, Nicholas Parsons > wrote: >> That is the beauty of using Python. You have a choice of using >> classes and traditional OOP techniques or sticking to top level >> functions. For short, small scripts it would probably be overkill to >> use classes. Yet the programmer still has classes in his tool chest >> if he/she is writing code that is going to be reused in larger >> projects. > > Exactly the same thing can be said about Lisp, C++, Perl, PHP, and no > doubt many other languages that I don't know ;) > (Well I guess C++ programs are not called 'scripts') A notable exception being Java, even a "Hello world!" program must use a class. And Eiffel, too. -- Gabriel Genellina From bendorge at gmail.com Sat Mar 17 03:09:25 2007 From: bendorge at gmail.com (bendorge at gmail.com) Date: 17 Mar 2007 00:09:25 -0700 Subject: Generating HTML containing XML in an INPUT tag Message-ID: <1174115365.139421.272970@l75g2000hse.googlegroups.com> Hi there, Using Python, I'm auto-generating an HTML file that contains: , where XXX is XML data (encoded somehow). Articles regarding unicode are making my head spin! Is there a way to encode XML file contents to a hexadecimal string that could be decoded on a PHP server? I have an XML file that is generated based on user entries (GUI from PythonCard). After the XML file is created, I want the user to see an HTML preview, and then click an Upload button on the page. Hidden in the page is the tag I showed above. I decided not to generate because from a usability standpoint, I want the user to create this file and upload it to my PHP server in as few steps as possible. Also, I tried setting the value to the XML file path...my browser security settings don't like it and I'm sure other browsers won't like it either. Any ideas? From hg at nospam.org Fri Mar 30 06:15:04 2007 From: hg at nospam.org (hg) Date: Fri, 30 Mar 2007 12:15:04 +0200 Subject: Islam, the Religion of Ease References: <1175178981.676137.156340@n59g2000hsh.googlegroups.com> <1175270653.284511.3820@l77g2000hsb.googlegroups.com> <2ubPh.257454$BK1.244465@newsfe13.lga> Message-ID: Just came to me ... if wars were always fought with fish as weapons, they'd be much less hunger in the world ... lol ... (as a non-anglo-saxon, I thought for many years that lol meant "Lord, Oh Lord !) hg (Holly Grail) From skip at pobox.com Mon Mar 26 14:04:20 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 26 Mar 2007 13:04:20 -0500 Subject: how to abort on syntax errors In-Reply-To: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> References: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <17928.2852.617743.752260@montanaro.dyndns.org> Josh> I have a lot of except Exception, e statements in my code, which Josh> poses some problems. One of the biggest is whenever I refactor Josh> even the triviallest thing in my code. Josh> I would like python to abort, almost as if it were a compile-time Josh> error, whenever it cannot find a function, or if I introduced a Josh> syntax error. But, instead, it merrily proceeds on its way. Josh> Is there some idiom that you use in situations like these? In general, I think you should be more specific in the exceptions you catch. For example, if you want to look up a key in a dictionary and most of the time it's there, but every now and again you need to add it, I'd use something like this: try: val = somedict[key] except KeyError: # need to initialize slot somedict[key] = INITIAL_VALUE That is, be as precise as you can in the exceptions you catch. Also, try to keep the body of the try block as small as you can. Skip From sgeiger at ncee.net Tue Mar 20 10:57:36 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 20 Mar 2007 09:57:36 -0500 Subject: Pycron for windows - please help In-Reply-To: References: <1174330804.722975.84900@n59g2000hsh.googlegroups.com> Message-ID: <45FFF660.7050900@ncee.net> Here's something else you should consider: Look at the source code of pycron. I just downloaded it. Much to my surprise, this is implemented in about 115 lines of code. In particular, look at the run() function. You should try adding a try-except block around the system call to get a hint as to where the problem lies: try: os.system('start ' + command) except: print "Unexpected error to catch:", sys.exc_info()[0] I've been trying to use it myself (on a Mac) since I saw you mention it on the mailing list. I'm also having problems using pycron. Email me directly if you figure out the problem. I'll do the same for you. Gabriel Genellina wrote: > En Mon, 19 Mar 2007 16:00:04 -0300, Al escribi?: > > >> I looked in the pycron.log file, and I noticed that for the entires of >> my new job, I see "rc=4" and the end of each line. All other jobs have >> "rc=0" at the end of the line. I assume then, that rc=4 is a reference >> to an error code of some kind, but there is no information on this in >> the readme.txt, at the pycron website, or here in groups. >> >> Does anyone know how to troubleshhot this? Thanks in advance. >> > > Contacting the author? > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From turd.flop.down.mleg at gmail.com Thu Mar 15 03:10:00 2007 From: turd.flop.down.mleg at gmail.com (Turd Flop Down M'leg) Date: 15 Mar 2007 00:10:00 -0700 Subject: Python eggs and openSuse 10.2 errors Message-ID: <1173942600.262524.196550@n59g2000hsh.googlegroups.com> Heyas So I got all hooked on python eggs at pycon, but then I got all hooked on openSuse 10.2 (with the xgl cube and the beryl fanciness, and some other misc debris). Unfortunately, it doesnt appear that openSuse 10.2, which is using python 2.5, wants to play nicely with python eggs. When I try to run `sudo python ez_setup.py`, I simply get an error: Downloading http://cheeseshop.python.org/packages/2.5/s/setuptools/setuptools-0.6c5-py2.5.egg error: invalid Python installation: unable to open /usr/lib/ python2.5/config/Makefile (No such file or directory) The /usr/lib/python2.5/config directory didnt exist, so I tried creating it but with no change in results. Thanks, Tfdml From rahul986 at gmail.com Tue Mar 27 09:19:41 2007 From: rahul986 at gmail.com (Legend) Date: 27 Mar 2007 06:19:41 -0700 Subject: Python Error :( Message-ID: <1175001581.323552.37250@n59g2000hsh.googlegroups.com> I wasn't able to run a Python script. But then later I was able to run it through the Shell. I was experimenting with cron jobs and set up the python execution in as a cron. The first time it ran, It was fine but then after that, it started giving me some errors. Now when I try to run the script directly, I get the following error: Traceback (most recent call last): File "", line 1, in ? File "userbot.py", line 637, in ? con = connect() File "userbot.py", line 607, in connect con.requestRoster() File "user.py", line 531, in requestRoster self.SendAndWaitForResponse(rost_iq) File "user.py", line 326, in SendAndWaitForResponse return self.waitForResponse(ID) File "user.py", line 300, in waitForResponse self.process(1) File "xmlstream.py", line 459, in process if not len(self.read()): # length of 0 means disconnect File "xmlstream.py", line 398, in read data_in=data_in+self._sslObj.read(BLOCK_SIZE).decode('utf-8') socket.sslerror: (6, 'TLS/SSL connection has been closed') Any help please? From http Thu Mar 8 19:19:27 2007 From: http (Paul Rubin) Date: 08 Mar 2007 16:19:27 -0800 Subject: catching exceptions from an except: block References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173345456.968709.128870@j27g2000cwj.googlegroups.com> Message-ID: <7xbqj3i7zk.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I thought "raise" on its own was supposed to re-raise the previous > exception, but I've just tried it in the interactive interpreter and it > doesn't work for me. It means you can catch an exception, do stuff with it, and then pass it upward to earlier callers: def foo(n): try: bar(n) except (ValueError, TypeError): print "invalid n:", n raise # re-signal the same error to foo's caler From nagle at animats.com Mon Mar 19 17:34:39 2007 From: nagle at animats.com (John Nagle) Date: Mon, 19 Mar 2007 21:34:39 GMT Subject: Anything available that can read Microsoft .MDB files from Python? In-Reply-To: <1174334517.125928.274140@l75g2000hse.googlegroups.com> References: <56863eF27p5bmU1@mid.uni-berlin.de> <1174334517.125928.274140@l75g2000hse.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Mar 19, 2:45 pm, John Nagle wrote: > >>Diez B. Roggisch wrote: >> >>>John Nagle schrieb: >> >>>> I'm looking for something that can read .MDB files, the format ... > I've read .MDB files using ODBC. I don't know how big your files are, > but I had a file with almost 3000 rows and I was able to fetch it in > 1-2 seconds. If you want to give it whirl, you just need to create an > ODBC connection .... But that was on Windows, right? ODBC is just a connection mechanism. You have to have a database of the right type to which you can connect. On Windows, there's Jet, the engine behind Microsoft Access, but what do you connect to on Linux? John Nagle From kyosohma at gmail.com Fri Mar 16 14:48:27 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Mar 2007 11:48:27 -0700 Subject: TypeError: 'module' object is not callable In-Reply-To: <1174066969.563803.216040@p15g2000hsd.googlegroups.com> References: <1174066969.563803.216040@p15g2000hsd.googlegroups.com> Message-ID: <1174070907.553345.59340@n76g2000hsh.googlegroups.com> On Mar 16, 12:42 pm, randomt... at gmail.com wrote: > Hello everyone! > i have the following test code: > class temp: > def __init__(self): > self.hello = "hello world!" > def printworld(self): > print(self.hello) > t = temp() > > and i tried to call profile('t.printworld()') > > but i received the following error: > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'module' object is not callable > > I'm not sure what is wrong exactly, if anyone can point me to the > right direction, it would be much appreciated! If you're using the profile module, you need to do something like profile.run('t.printworld()') Good luck, Mike From grante at visi.com Mon Mar 12 23:33:03 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 13 Mar 2007 03:33:03 -0000 Subject: Python in a desktop environment References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> <1173595945.530722.273030@30g2000cwc.googlegroups.com> <1173605193.585675.217210@30g2000cwc.googlegroups.com> <12vas8rhv0ji28d@corp.supernews.com> <45f573c4$0$27462$426a34cc@news.free.fr> <55lbl1F25geaaU1@mid.uni-berlin.de> <45f58642$0$1408$426a74cc@news.free.fr> <1173747820.728559.102360@q40g2000cwq.googlegroups.com> Message-ID: <12vc6rfq995undb@corp.supernews.com> On 2007-03-13, David Cramer wrote: > Everyone seems to have misunderstood what I want. One might suspect that your request was unclear. ;) > I'm a Python developer, I don't give a rats ass about what > people say about C#, Python, or c++, they all have their uses. > My main reasoning for considering C++ as the backend is some > things (reading memory for example) are much easier to do in > C++ than in Python, and we already have a lot written in C++. Reading memory is actually pretty trivial in Python. > The argument about robustness, has nothing to do with how > nicely formatted the language is, or how great the tracebacks > are, it's strictly about how high the memory cost is and how > much CPU it's going to take. No, that's not at all what "robust" means (at least not to anybody I know). Robust means that the program is always well-behaved. It doesn't crash. It doesn't leak memory. It isn't full of security holes. It's got nothing to do with resource usage. > Python is well known for being high on memory and C++ being > compiled can be a lot faster for things. True, but that's nothing to due with robustness. A fast, small program that crashes, leaks memory, and gives incorrect results is not robust. A large slow program that doesn't crash regardless of input and produces correct results is robust. > Anyways, thanks for everyones feedback, we will most likely go > with a combination of Python and C++. I think you're nuts to decide that you need C++ before you've tested a Python implementation, but it's your nickle. :) -- Grant Edwards grante Yow! Make me look like at LINDA RONSTADT again!! visi.com From anil.jupiter9 at gmail.com Sat Mar 10 10:40:23 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 10 Mar 2007 07:40:23 -0800 Subject: Database module & multithreading In-Reply-To: References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> Message-ID: <1173541223.545628.29650@64g2000cwx.googlegroups.com> On Mar 10, 8:16 pm, Michael Bentley wrote: > > Thanx for this pointer buddy! I have done my homework. Some Database > > modules are not actively maintained some modules does not work with > > Python 2.5. At this moment I am using Sqlite3 which is pretty fast but > > it dosent allow me to use multi threading so which database module is > > better in terms of multithreading > > Actually, I think sqlite3 just requires that each thread have its own > connection and cursor. Exception in thread Thread-2: Traceback (most recent call last): File "D:\Python25\lib\threading.py", line 460, in __bootstrap self.run() File "url_part1.py", line 161, in run dbacc(self.o, self.dbase).dataenter() File "url_part1.py", line 64, in dataenter self.c.execute('insert into '+self.odbase+' values (?,?,?,?,?,?,?,?,?,?,?,?, ?)',self.odata) InterfaceError: Error binding parameter 3 - probably unsupported type. this is the error I am getting................ From ceball at gmail.com Tue Mar 27 04:54:40 2007 From: ceball at gmail.com (Chris) Date: 27 Mar 2007 01:54:40 -0700 Subject: Tkinter Toplevel geometry In-Reply-To: References: <1174803181.656189.303200@l77g2000hsb.googlegroups.com> <0dtNh.9164$JZ3.2879@newssvr13.news.prodigy.net> <1174824649.683426.78990@d57g2000hsg.googlegroups.com> Message-ID: <1174985680.393901.170910@p77g2000hsh.googlegroups.com> > A TRULY good way to show your thanks for help like this > is to write up what you learned at theTkinterWiki . Note: > A. You have to log in to edit pages > on this particular Wiki. If you > decide to join us, then, you'll > first need to create an account. I'll do that, yes. I guess I should create a 'Toplevel' page and put the information on there? Unless someone can suggest something better. I also wonder if I should have posted this question to the tkinter- discuss mailing list (see http://tkinter.unpythonic.net/wiki/TkinterDiscuss) instead of to comp.lang.python. However, I wasn't aware of that list before, and it's not linked to from the python.org 'community' page (as far as I can see - and in fact, the python.org pages imply that tkinter questions should be asked on comp.lang.python). I'm new to tkinter, so it wasn't immediately clear where to get help. From ad_scriven at postmaster.co.uk Thu Mar 8 09:17:24 2007 From: ad_scriven at postmaster.co.uk (Antony Scriven) Date: 8 Mar 2007 06:17:24 -0800 Subject: VIM: Python type indented-block command equivalent to % for C? In-Reply-To: <1173330126.098105.275160@n33g2000cwc.googlegroups.com> References: <1173330126.098105.275160@n33g2000cwc.googlegroups.com> Message-ID: <1173363444.322590.105280@v33g2000cwv.googlegroups.com> [F-ups set to comp.editors] Paddy3118 wrote: > Not python: > but python type > indented text > > Notice the blank line above. > It could have several > spaces or tabs, and still > be a part of the block > beginning 'Not python:': > The block ends at the > first non-blank line > with less indent. > > Assuming that only space characters are allowed > for indenting, is their a way to yank a Python > block like y% works for C , or a way to move to > the end of a block defined by indentation? I expect there are scripts for Python. Try googling and www.vim.org. Anyway I'm not sure that I understand your description 100%, but try something like this. :ono = /\n.*\%<=indent('.')c\S\\|\%$/+0 Now try d= y= etc. Also note that I've made it work linewise. And take look at :help /\%v if you want it to work with tabs. --Antony From mattias at comtech-data.se Wed Mar 7 04:47:30 2007 From: mattias at comtech-data.se (Mattias Nilsson) Date: Wed, 07 Mar 2007 10:47:30 +0100 Subject: How to check whether file is open or not In-Reply-To: <1173245313.037991.89380@s48g2000cws.googlegroups.com> References: <1173245313.037991.89380@s48g2000cws.googlegroups.com> Message-ID: Ros wrote: > There are 10 files in the folder. I wish to process all the files one > by one. But if the files are open or some processing is going on them > then I do not want to disturb that process. In that case I would > ignore processing that particular file and move to next file. > > How can I check whether the file is open or not? > From what I know: You can't, in a platform independent way. You'd still be in trouble even if python would let you write something like: if file_is_open(filename): process_file(filename) There's nothing that says no one will open the file after the file_is_open call but before the process_file call. Also, the file might be opened during the processing. If the files to be processed only are written and then closed without being reopened or modified, then your situation is a bit simpler. If you can get the process that creates the files to cooperate, a common way to solve this problem is to have a temporary suffix on files while they are being created. Once the file is complete, the temporary suffix is removed and that signals to other processes that this file is ready for processing. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Mar 31 07:38:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 31 Mar 2007 13:38:19 +0200 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed References: Message-ID: <576vhbF2ca1guU1@mid.individual.net> Mark Dufour wrote: > Shed Skin allows for translation of pure (unmodified), implicitly > statically typed Python programs into optimized C++, and hence, ^^^^^ > highly optimized machine language. ^^^^^^^^^^^^^^^^ Wow, I bet all C++ compiler manufacturers would want you to work for them. Regards, Bj?rn -- BOFH excuse #23: improperly oriented keyboard From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 15 08:58:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 15 Mar 2007 13:58:35 +0100 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <1173955724.284863.97340@y80g2000hsf.googlegroups.com> Message-ID: <45f942d7$0$3217$426a74cc@news.free.fr> Steve Holden a ?crit : > bearophileHUGS at lycos.com wrote: >> Laurent Pointal: >>> you may prefer range/items when processing of the result >>> value explicitly need a list (ex. calculate its length) >> >> Creating a very long list just to know the len of an iterator is >> barbaric, so sometimes I use this: >> >> def leniter(iterator): >> if hasattr(iterator, "__len__"): >> return len(iterator) >> nelements = 0 >> for _ in iterator: >> nelements += 1 >> return nelements >> > Of course this is a little like the Heisenberg uncertainty principle if > the iterator has no __len__ attribute - once you know how long it is you > no longer have access to the elements. Or did I miss something? yes, that's one of the side effects. Another interesting case: import itertools it = itertools.cycle(range(10)) print "it has %d elements" % leniter(it) From bignose+hates-spam at benfinney.id.au Mon Mar 5 09:13:12 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 06 Mar 2007 01:13:12 +1100 Subject: implementing SFTP using Python References: <586552.89486.qm@web38809.mail.mud.yahoo.com> Message-ID: <87649f22yv.fsf@benfinney.id.au> kadarla kiran kumar writes: Please don't top-post; instead, place your reply directly beneath the quoted text you're responding to, and remove any quoted lines that aren't relevant to your response. > Now Iam trying to run the demo scripts available with paramiko package. You've gone further than me, then. Hopefully you can find help from someone more experienced with that package; perhaps it has its own support mailing list, or a developer contact email address. -- \ "He who laughs last, thinks slowest." -- Anonymous | `\ | _o__) | Ben Finney From sjmachin at lexicon.net Sat Mar 24 17:48:16 2007 From: sjmachin at lexicon.net (John Machin) Date: 24 Mar 2007 14:48:16 -0700 Subject: Join strings - very simple Q. In-Reply-To: <1174746810.280731@jubilee.claranet.pt> References: <1174675011.244339@jubilee.claranet.pt> <1174680929.492601.140270@o5g2000hsb.googlegroups.com> <1174746810.280731@jubilee.claranet.pt> Message-ID: <1174772896.902905.25640@p15g2000hsd.googlegroups.com> On Mar 25, 12:32 am, Paulo da Silva wrote: > John Machin escreveu: > .. > > > > > 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. > > | >>> help("".join) > > Help on built-in function 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. > > > | >>> > > > OK, I'll bite: This was "new" in late 2000 when Python 2.0 was > > released. Where have you been in the last ~6.5 years? > > In a response to one of my posts I was told 'string' is > obsolet. 'string' was enough for me, but if it is obsolet > then there should be a *new* way, isn't it? The *new* > way I was told to use is "str methods". > I tried that *new* way to do *old* 'string' job. So much was obvious from your post. > Voila > the reason of my so pertinent question. What was not obvious was (1) if you have been using Python for a while, how you managed to be unaware of str methods (2) if you are a newbie, how you managed to find out about the string module but not find out about str methods [e.g. it's easy to miss the one line in the "official" Python tutorial that refers to them] (3) why you were not using obvious(?) methods to find out for yourself -- much faster than posing a question on the newsgroup, and you don't have to face the possibility of an impertinent response :-) > I am deeply sorry to have disturbed you in your python's heaven. I wasn't disturbed at all (you would have to try much harder), only mildly curious. > > Next time I'll read all books available, all texts including > the python formal description before > posting, A rather strange way of finding an answer to a simple question. A focussed search (or an index!) is more appropriate. Why would you expect the python formal description to have details on the syntax of individual class methods? Do you always do a serial scan of all tables for any database query? In addition to approaches I mentioned earlier, you could try: (1) going to the docs page on the Python website (http:// www.python.org/doc/), click on the "Search" link about one-third down the page, and search for "join". You would get 6 results, one of which is "join() (string method)" (2) If you are using Windows, use the index tab in the Python-supplied docs gadget: type in "join" and get the same 6 results. I believe this facility is available (through a 3rd party) on Linux. [Having the docs on your PC or USB storage device is very useful if you are working in an environment where access to the Internet is restricted]. (3) Use Google groups, go to comp.lang.python, type "join string" into the search box, and click on "Search this group". First result is the current thread; most (or maybe all) of the next six or so will give you the syntax your were looking for. (4) Using Google or any other reasonable web searcher, search for the 3 words: Python join string. Any one of the first few hits gives the answer you were seeking. HTH, John From skip at pobox.com Sun Mar 4 13:11:27 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Mar 2007 12:11:27 -0600 Subject: Where I could find older python releases ? In-Reply-To: <2f3066870703040152n327140f3p9d0a132a807ebe80@mail.gmail.com> References: <2f3066870703040152n327140f3p9d0a132a807ebe80@mail.gmail.com> Message-ID: <17899.3023.770908.994486@montanaro.dyndns.org> Martins> I have been searching the internet for python version 0.9.0 Martins> sources which had been posted to alt.sources list, but without Martins> any luck. Maybe someone has it available somewhere ? If you *really* want Python 0.9.0 and not PyPy 0.9.0, I think you're going to have to deduce and check out the appropriate revision from the Subversion repository. Looking at the Misc/HISTORY file it appears that 0.9.0 was released in February 1991. Looking at the Subversion log I don't see any specific comment pertaining to a release, but I see a lot of checkins on 1991-02-19, the last being r2314. The next checkin after that is on 1991-03-06. Since 0.9.1 was also released in February 1991, r2314 will probably get you that version, or something very near to it. Skip From skip at pobox.com Thu Mar 22 09:40:35 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 22 Mar 2007 08:40:35 -0500 Subject: [JOB] Sr. Python Developer, Northern VA In-Reply-To: References: Message-ID: <17922.34643.455144.575280@montanaro.dyndns.org> >>>>> "Anton" == Anton Vredegoor writes: Anton> Steve Holden wrote: >> Feel better now? Anton> Yes! But *now* I'm afraid it will have negative consequences for Anton> my future employability. However if it will lead to adjusting the Anton> kind of submissions at http://www.python.org/community/jobs/ it Anton> was probably worth it. I think the steady increase in the number of active listings over the past couple years bodes well for the job prospects of Python programmers as a whole. There are currently 99 job postings on the job board dating back to mid-December. A year ago there were about 60, a year before that, about 40. A number of those companies seem to be fairly enlightened about the use of open source software (search for "open"). You can't expect the world to completely change overnight. Most companies probably still funnel external job postings through their HR departments. As a result, a certain amount of boilerplate text and corporate puffery is bound to turn up in many postings. Be thankful they at least found the job board or comp.lang.python and aren't just trying to recruit through traditional channels. You'd probably never see job postings for the Space Telescope Science Institute or The World Wide Workshop for Children's Media Technology and Learning if they only appeared in the Washington Post or New York Times. Skip From andi.clemens at gmx.net Thu Mar 1 07:14:23 2007 From: andi.clemens at gmx.net (andi.clemens at gmx.net) Date: 1 Mar 2007 04:14:23 -0800 Subject: How to update DNS record In-Reply-To: <54nkvtF21ft8aU1@mid.individual.net> References: <54nkvtF21ft8aU1@mid.individual.net> Message-ID: <1172751262.972242.215990@p10g2000cwp.googlegroups.com> On Mar 1, 10:33 am, Bjoern Schliessmann wrote: > Read RFC 2136 (Dynamic updates in the DNS) and see if your server > can be configured to do this. If not, you'll have to change the > zone files manually and reload the DNS config. It worked before with a perl script, but now I'm using django for all our web services so I want to implement this update function in Python as well. I don't know how to do this in Python, right now I'm trying it with twisted, but I don't what to do exactly. It would be nice if somebody has an example for doing this. Andi From steve at holdenweb.com Thu Mar 22 04:48:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 04:48:27 -0400 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: References: <7WjMh.318$YL5.80@newssvr29.news.prodigy.net> <1hvcadb.134pbvp1y39wi3N%aleax@mac.com> Message-ID: Mark T wrote: > "Alex Martelli" wrote in message > news:1hvcadb.134pbvp1y39wi3N%aleax at mac.com... >> John Nagle wrote: >> >>> Marcin Ciura wrote: >>> >>>> Neither would I. I must have expressed myself not clearly enough. >>>> Currently >>>> x = y = z >>>> is roughly equivalent to >>>> x = z >>>> y = z >>>> I propose to change it to >>>> y = z >>>> x = z >>> Actually, it is equivalent to >>> >>> y = z >>> x = y >> Not really: >> >>>>> class chatty(object): >> ... def __init__(self): self.__dict__['__hide'] = {} >> ... def __setattr__(self, name, value): >> ... print 'sa', name, value >> ... self.__dict__['__hide'][name] = value >> ... def __getattr__(self, name): >> ... print 'ga', name >> ... return self.__dict__['__hide'].get(name) >> ... >>>>> c = chatty() >>>>> x = c.zop = 23 >> sa zop 23 >> As you can see, there is no read-access to c.zop, which plays the role >> of y there. >> >> >> Alex > > This is interesting: > >>>> class Test(object): > ... def __getattribute__(self,n): > ... print 'reading',n > ... return object.__getattribute__(self,n) > ... def __setattr__(self,n,v): > ... print 'writing',n,v > ... return object.__setattr__(self,n,v) > ... >>>> x=Test() >>>> x.a=1; x.b=2; x.c=3 > writing a 1 > writing b 2 > writing c 3 >>>> x.a=x.b=x.c > reading c > writing a 3 > writing b 3 > > I wouldn't have expected "a" to be assigned first in a right-to-left parsing > order. The result is the same in any case. > It would be nice if your confusion could have been avoided by reading the reference manual, but unfortunately the current syntax definition doesn't seem to even acknowledge the possibility of multiple assignments such as the one under discussion! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From jjl at pobox.com Thu Mar 15 16:10:43 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 15 Mar 2007 20:10:43 GMT Subject: merits of Lisp vs Python References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> <1173581125.663707.5810@s48g2000cws.googlegroups.com> <87odmvinhf.fsf@pobox.com> <871wjrs4vo.fsf@pobox.com> <87ps7bz527.fsf@gmail.com> Message-ID: <87y7lymfna.fsf@pobox.com> Jorge Godoy writes: > jjl at pobox.com (John J. Lee) writes: > > > John Nagle writes: > > > >> John J. Lee wrote: > >> > "Graham Dumpleton" writes: > >> > > >> >>On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: > >> > >> > Is it possible to ask mod_python to start separate processes to serve > >> > requests, rather than "separate" interpreters? We couldn't see a way. > >> > >> That's what CGI does. > > > > I meant long running processes, as I hoped was obvious from context... > > Maybe FastCGI should help, then. It can run "forever" after a request has > finished so it is suitable for long running processes. Yes, we've used FastCGI too. My question was specifically about mod_python. John From hg at nospam.org Wed Mar 14 08:08:00 2007 From: hg at nospam.org (hg) Date: Wed, 14 Mar 2007 13:08:00 +0100 Subject: logging and wx.Timer References: <1173890343.427588.285370@l77g2000hsb.googlegroups.com> Message-ID: Jordan wrote: > On Mar 14, 1:52 am, hg wrote: >> Hi, >> >> I read that logging was thread safe ... but can I use it under a GUI >> timer ? >> >> Thanks, >> >> hg > > That was barely enough information to be worthy of a reply. Need more > than that. What do you mean under a gui timer? What gui? What type of > usage? More info = more (and better) help. Cheers. > > JT Twas in the title: wx.timer REgards, hg From gagsl-py2 at yahoo.com.ar Thu Mar 15 19:31:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 Mar 2007 20:31:53 -0300 Subject: problem with str() References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> <1173990743.998399.82020@b75g2000hsg.googlegroups.com> Message-ID: En Thu, 15 Mar 2007 17:32:24 -0300, escribi?: > methodList = [str for str in names if callable(getattr(obj, str))] > > instead, do something like this: > > methodList = [i for i in names if callable(getattr(obj, i))] The fact that a list comprehension "leaks" its variables into the containing scope is a bit weird. A generator expression doesn't: py> str py> w = (str for str in range(10)) py> w py> str py> w.next() 0 py> str -- Gabriel Genellina From aahz at pythoncraft.com Tue Mar 20 09:12:23 2007 From: aahz at pythoncraft.com (Aahz) Date: 20 Mar 2007 06:12:23 -0700 Subject: When is List Comprehension inappropriate? References: <1174315319.860848.289890@p15g2000hsd.googlegroups.com> <1hv8wz8.19mj0kb1k9m2m8N%aleax@mac.com> Message-ID: In article <1hv8wz8.19mj0kb1k9m2m8N%aleax at mac.com>, Alex Martelli wrote: > >list(iterimage(etc etc)) > >is surely a better way to express identical semantics. More generally, >[x for x in whatever] (whether x is a single name or gets peculiarly >unpacked and repacked like here) is a good example of inappropriate LC, >to get back to the question in the subject: list(whatever) is the "one >obvious way" to perform the same task. Except of course, when it's [x for x in whatever if x] I'm exceedingly fond of replacing filter() with listcomps. They're so much more readable and often faster. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From nick at craig-wood.com Mon Mar 26 06:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 26 Mar 2007 05:30:04 -0500 Subject: with timeout(...): Message-ID: Did anyone write a contextmanager implementing a timeout for python2.5? I'd love to be able to write something like with timeout(5.0) as exceeded: some_long_running_stuff() if exceeded: print "Oops - took too long!" And have it work reliably and in a cross platform way! >From my experiments with timeouts I suspect it won't be possible to implement it perfectly in python 2.5 - maybe we could add some extra core infrastructure to Python 3k to make it possible? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From davecook at nowhere.net Thu Mar 29 23:04:17 2007 From: davecook at nowhere.net (Dave Cook) Date: Fri, 30 Mar 2007 03:04:17 GMT Subject: pygtk: how to make a screenlocking window? References: Message-ID: On 2007-03-28, Andr? Wyrwa wrote: > can anyone please point me to the relevant pygtk window properties i > need to set to make a window > - fullscreen > - stay in front > - grab all input focus > so that i can use it as a screen lock the likes that gksu or > gnome-power-manager do? See the reference page for gtk.Window: http://pygtk.org/docs/pygtk/class-gtkwindow.html Methods of interest are fullscreen(), set_modal(), set_type_hint(), set_keep_above(). Dave Cook From steve at REMOVE.THIS.cybersource.com.au Sat Mar 17 02:01:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Mar 2007 17:01:13 +1100 Subject: Finding the insertion point in a list References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> <7xird0bom3.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 16 Mar 2007 18:17:08 -0800, Paul Rubin wrote: > tkpmep at hotmail.com writes: >> Or with a generator comprehension >> n = sum ( y>x[i] for i in range(len(x)) ) - 1 >> >> But there has to be a cleaner way, as the first approach is unwieldy >> and does not adapt to changing list lengths, and the second is not >> obvious to a casual reader of the code. > > How about: > > n = len([y > t for t in x]) (1) It's wrong. That always returns the length of the list. Perhaps you meant something like this? len(["anything will do" for t in x if y > t]) or even len(filter(lambda t, y=y: y>t, x)) (2) It's barely more comprehensible than the alternative that the Original Poster rejected for being insufficiently clear. Since (almost) everyone insists on ignoring the bisect module and re-inventing the wheel, here's my wheel: def find(alist, n): """Return the position where n should be inserted in a sorted list.""" if alist != sorted(alist): raise ValueError('list must be sorted') where = None for i in range(len(alist)): if where is not None: break alist.insert(i, n) if alist == sorted(alist): where = i del alist[i] if where is None: where = len(alist) return where Here's another dodgy implementation: def find(alist, n): return sorted(alist + [n]).index(n) It's especially good for large lists. Not! -- Steven. From bbxx789_05ss at yahoo.com Sun Mar 25 02:13:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 24 Mar 2007 23:13:53 -0700 Subject: functions, classes, bound, unbound? In-Reply-To: References: <1174793076.053192.16780@o5g2000hsb.googlegroups.com> Message-ID: <1174803233.118069.234290@l75g2000hse.googlegroups.com> > ...classes don't invoke the function directly, they convert it to > an 'unbound method' object:: > > >>> class Test(object): > ... def greet(): > ... print 'Hello' > ... > >>> Test.greet > > >>> Test.greet() > Traceback (most recent call last): > File "", line 1, in > TypeError: unbound method greet() must be called with Test instance > as first argument (got nothing instead) > I think I found the rule in the GvF tutorial, which is essentially what the error message says: ------- When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof. -------- So, if you call a function using the syntax TheClass.theMethod(), then you are required to use an instance object as an argument. In section 3.2 The Standard Class Hierarchy, it also says this: ------- When a user-defined method object is created by retrieving a user- defined function object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its im_self attribute is the instance, and the method object is said to be bound. -------- In that first sentence, is he talking about retrieving the user- defined function object from the class using the class name, e.g: MyClass.someFunc Is there some other way to retrieve a user-defined function object from a class other than using the class name or an instance? > If you really want to get to the original function, there are a couple > of options. No. Just trying to figure out how some things work. From texiereric at yahoo.com Thu Mar 15 01:27:46 2007 From: texiereric at yahoo.com (Eric Texier) Date: Thu, 15 Mar 2007 05:27:46 GMT Subject: performance question Message-ID: I need speed here. What will be the fastest method or does it matter? (for the example 'a' is only 3 values for the clarity of the example) a = [1,3,4.] ## method1: f.write("vec %f %f %f \n" % (a[0],a[1],a[2])) method2: f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n") also it there a relevant speed difference between making few small write instead of 1 bigger one. Thanks for any feed back, Eric From duncan.booth at invalid.invalid Mon Mar 5 10:23:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Mar 2007 15:23:08 GMT Subject: ANN: pyftpdlib 0.1 released References: <1173102514.190879.7600@p10g2000cwp.googlegroups.com> <1173104494.751597.98150@p10g2000cwp.googlegroups.com> Message-ID: "billiejoex" wrote: > I removed them by using google groups interface but maybe > with no success. You were probably successful in removing them from Google groups, but that is just one amongst many usenet servers. In general you cannot expect to delete messages from other servers. The best thing is to always make a point of reading a post carefully before hitting the send button, live with any minor typos, and post a correction as a followup if you need to correct any major mistakes. From ptmcg at austin.rr.com Fri Mar 16 04:02:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Mar 2007 01:02:32 -0700 Subject: To count number of quadruplets with sum = 0 In-Reply-To: <1174024143.049965.25710@l77g2000hsb.googlegroups.com> References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> Message-ID: <1174032152.756826.150950@o5g2000hsb.googlegroups.com> On Mar 16, 12:49 am, "n00m" wrote: > for o in range(int(f.readline())): > row = map(int, f.readline().split()) > q.append(row[0]) > w.append(row[1]) > e.append(row[2]) > r.append(row[3]) Does this help at all in reading in your data? numlines = f.readline() rows = [ map(int,f.readline().split()) for _ in range(numlines) ] q,w,e,r = zip(rows) -- Paul From vorner at ucw.cz Mon Mar 12 06:55:58 2007 From: vorner at ucw.cz (Michal 'vorner' Vaner) Date: Mon, 12 Mar 2007 11:55:58 +0100 Subject: programmatically manipulation environment variables of the calling shell In-Reply-To: <55kp0cF25ntciU1@mid.uni-berlin.de> References: <55kp0cF25ntciU1@mid.uni-berlin.de> Message-ID: <20070312105558.GC10058@tarantula.kolej.mff.cuni.cz> Hello, On Mon, Mar 12, 2007 at 11:40:11AM +0100, Diez B. Roggisch wrote: > Maxim Veksler wrote: > > I'm trying to write a python script that would allow me to manipulate > > shell variables of the calling shell. I'm trying to write some logic > > that would know to add LD_LIBRARY_PATH to the users environment. > > It's not possible, OS restrictions - you are not allowed to alter the > environment of a parent process. Actually, you are able to modify only your own environment (and call a new process with any possible environment). And the restrictions seem to me rather technical - the process would have to change its behaviour each time it changes. With regards -- grep me no patterns and I'll tell you no lines. Michal 'vorner' Vaner -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From deets at nospam.web.de Wed Mar 7 17:30:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Mar 2007 23:30:10 +0100 Subject: Best place for a function? In-Reply-To: References: Message-ID: <558soiF23polgU1@mid.uni-berlin.de> Sergio Correia schrieb: > I'm writing a class, where one of the methods is kinda complex. The > method uses a function which I know for certain will not be used > anywhere else. This function does not require anything from self, only > the args passed by the method. > > Where should I put the function? > > a) Inside the module but outside the class (to avoid cluttering it; > besides the function does not require to access any property or method > of the class). > > # mymodule.py > > def _myfunction(): > ... > > class myclass(object): > def mymethod(self): > ... > spam = _myfunction() > ... > > > b) Inside the class but outside the method > > # mymodule.py > > class myclass(object): > def _myfunction(self): > ... > > def mymethod(self): > ... > spam = self._myfunction() > ... > > c) Inside the method: > > # mymodule.py > > class myclass(object): > ... > def mymethod(self): > def _myfunction(self): > ... > ... > spam = self._myfunction() > ... > > > I'm new to python (and couldn't find anything about this in PEP 8). > What would you suggest me? If it really has no other use as in this class, put it as an instancemethod in there. Alternatively, you _could_ nest it like this: class Foo(object): def bar(self): def my_long_important_method(argument): pass pass Diez From dadapapa at googlemail.com Thu Mar 15 03:11:56 2007 From: dadapapa at googlemail.com (Harold Fellermann) Date: 15 Mar 2007 00:11:56 -0700 Subject: design question: no new attributes In-Reply-To: <61IFh.7997$KE2.5053@trnddc06> References: <8BIEh.1349$QI4.489@trnddc01> <45e60fdc$0$30655$426a34cc@news.free.fr> <45e7438f$0$29410$426a74cc@news.free.fr> <61IFh.7997$KE2.5053@trnddc06> Message-ID: <1173942716.446942.213160@b75g2000hsg.googlegroups.com> Hi Alan, > One last point. While I remain interested in examples of how > "late" addition ofattributesto class instances is useful, > I must note that everyone who responded agreed that it > has been a source of bugs. This seems to argue against a > general ban on "locking" objects in some way, in some > circumstances. If you want to restrict "late" addition of attributes, no-one will prevent you to do so. Arnaud has already given you an example implementation. Here is mine: >>> class Foo(object) : ... ... _locked = False ... ... def __setattr__(self,attr,var) : ... if self._locked and not attr in dir(self): ... raise RuntimeError ... else : ... object.__setattr__(self,attr,var) ... ... def lock(self) : ... self._locked = True ... >>> foo = Foo() >>> foo.bar = 'allowed' >>> foo.lock() >>> foo.spam = 'fails' Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __setattr__ NotImplementedError >>> >>> foo.bar = 'still works' See how it works? The lock method *dynamically* adds the attribute foo._locked *after* initialization to the instance. Before the call of foo.lock() foo._locked is a class attribute. Now you might argue that one should better set foo._locked = False in the __init__ method rather than as a class attribute. Something like: class Foo(object) : def __init__(self) : self._locked = False But no! The initialization would trigger Foo.__setattr__(foo,'_locked',False) which naturally runs into an attribute error since __setattr__ looks up this attribute. So this very same implementation is one of the pro examples you asked for :-) cheers, - harold - From mgi820 at motorola.com Thu Mar 15 13:20:25 2007 From: mgi820 at motorola.com (Gary Duzan) Date: Thu, 15 Mar 2007 17:20:25 +0000 (UTC) Subject: distributing python software in jar like fashion References: Message-ID: In article , alf wrote: >Hi, > >I have a small app which consist of a few .py files. Is there any way to >distribute it in jar like fashion as a single file I can just run python >on. I obviously look for platform independent solution. > >Thx in advance, A. There is a new package that has been discussed here recently called Squisher that should do what you want by packing things into a single pyc file. There are still some minor issues that need to be ironed out with running the pyc directly, but it should do exactly what you want Real Soon Now. http://groups.google.com/groups/search?q=group%3Acomp.lang.python+squisher&qt_s=Search Gary Duzan Motorola CHS From scott.daniels at acm.org Fri Mar 9 01:07:15 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 08 Mar 2007 22:07:15 -0800 Subject: Dyanmic import of a class In-Reply-To: <1173391303.350661.120820@v33g2000cwv.googlegroups.com> References: <1173388141.820852.98880@j27g2000cwj.googlegroups.com> <1173391303.350661.120820@v33g2000cwv.googlegroups.com> Message-ID: <12v1uastjikkbd@corp.supernews.com> Arnaud Delobelle wrote: > On Mar 8, 9:09 pm, "rh0dium" wrote: > [snip] >> for mod in listdir(): >> __import__(mod) >> a=mod() >> a.dosomething() # This is a function which each class shares. >> >> Can anyone help? > > You are not using __import__ correctly. Perhaps reading the doc would > be a good start: > http://docs.python.org/lib/built-in-funcs.html > > For example to import the module defined in 'foo.py' you would do > foo = __import__('foo') > Then your class foo would be accessible as foo.foo To get even more explicit: import glob, os.path for filename in glob.glob('*.py*'): modname, ext = os.path.splitext(filename) try: class_ = getattr(__import__(modname), modname) except (ImportError, AttributeError, SyntaxError), err: print filename, modname, err else: class_().dosomething() -- --Scott David Daniels scott.daniels at acm.org From DierkErdmann at mail.com Fri Mar 2 08:59:35 2007 From: DierkErdmann at mail.com (DierkErdmann at mail.com) Date: 2 Mar 2007 05:59:35 -0800 Subject: Sorting strings containing special characters (german 'Umlaute') Message-ID: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> Hi ! I know that this topic has been discussed in the past, but I could not find a working solution for my problem: sorting (lists of) strings containing special characters like "?", "?",... (german umlaute). Consider the following list: l = ["Aber", "Beere", "?rger"] For sorting the letter "?" is supposed to be treated like "Ae", therefore sorting this list should yield l = ["Aber, "?rger", "Beere"] I know about the module locale and its method strcoll(string1, string2), but currently this does not work correctly for me. Consider >>> locale.strcoll("?rger", "Beere") 1 Therefore "?rger" ist sorted after "Beere", which is not correct IMO. Can someone help? Btw: I'm using WinXP (german) and >>> locale.getdefaultlocale() prints ('de_DE', 'cp1252') TIA. Dierk From deets at nospam.web.de Thu Mar 8 04:39:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Mar 2007 10:39:29 +0100 Subject: Jython Data Extraction problem References: <6gMHh.10662$Ih.388@trnddc02> Message-ID: <55a3uhF23vc6oU1@mid.uni-berlin.de> Steve Williams wrote: > The data is an 8-byte 2s complement binary integer stored in a MSSQL > 2005 CHAR column. (COBOL did that, not me). I'm using zxJDBC to read > the data and Jython to process. > I could extract the integer if it wasn't returned in the resultset as > unicode. Things like ord(char) and struct.unpack('>B',char) to get at > the bits don't seem to work. struct.unpack('>g',string) is not available. > I've tried fooling with charset in the url and the connect statement and > tried encode, but I have no experience here. > Is there anyway to get Jython/zxJDBC to stop converting the string to > unicode? > Any advice is welcome. It's a JDBC-thing in the end, see if you find a solution there. Apart from that, I don't see the problem really - why can't you just create a byte-string by using the .encode-method? Sure, you need to know which encoding was actually used when reading the bytes from the DB. But you should be able to figure that out, there aren't too much candidates - basically the usual suspects of cp1250, latin1 and the like. Diez From gagsl-py2 at yahoo.com.ar Fri Mar 9 05:13:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 07:13:09 -0300 Subject: 2 new comment-like characters in Python to aid development? References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> Message-ID: En Fri, 09 Mar 2007 06:14:46 -0300, escribi?: > A '?' placed in the preceding whitespace of a line as a means of > quickly highlighting a line or block of code for special attention. > The interpreter simply ignores these characters, and executes the code > as if each WIP character wasn't there. The value-added comes from how > IDEs can exploit this to color the line or code block (in a > customisable fashion as with other context-dependent IDE formatting). This could be implemented without new syntax: just make your editor recognize some special comments, and apply the highlighting to the following block. By example, # XXX Remove this when FuruFaifa is fixed to always provide # XXX the names in the same order names.sort() names.reverse() if names==oldnames: ... would highlight the first 4 lines (let's say, up to the next blank line or dedent). > 2. The HALT comment: > > A '!' at the start of a line, indicating the end of the script proper. > The interpreter would register this one, and ignore everything after > it, a bit like a sys.exit() call but also stopping it from picking > syntax errors after the HALT. IDEs could then 'grey out' (or 'yellow > out' or whatever) all following characters, including later HALT > comments. You accidentally type a ! somewhere, and your module stops working - not so good :( and worse, hard to find. I sometimes use '''this string marks''' to ignore whole blocks of code. It works fine unless the block already contains the same kind of triple-quoted string... > As far as I can see, neither of these would break backwards > compatibility and, like the @ decorator, if you don't like it, you > wouldn't have to use it. I don't know enough about the guts of Python > to say much about ease of implementation, but it doesn't seem like it > would be too hard. The main problem with new syntax is breaking compatibility with older versions, and I doubt it's worth the pain just for highlighting or playing interactively, so you don't have a great chance of them being implemented... -- Gabriel Genellina From supervau at gmail.com Tue Mar 27 17:09:54 2007 From: supervau at gmail.com (Frank) Date: 27 Mar 2007 14:09:54 -0700 Subject: plotting R graphics with rpy: figure crashes Message-ID: <1175029794.861002.121210@l77g2000hsb.googlegroups.com> Hi, I use rpy to plot functions and have the following problem. When I execute the following code line by line (start python and then execute line by line) the resulting figure looks as it should. However, when I put these lines in a script and execute the script the figure appears for half a second but then crashes. Using pylab.show() at the end of the script prevents the crash but now the window is no longer refreshed (e.g., changing the size of the window makes the contents disappear). import pylab import rpy x = range(0, 10) y = [ 2*i for i in x ] rpy.r.plot(x,y) I compared already with sys.version if the python version is the same in both cases (it is). Hence, the problem might be caused by rpy. Has anyone an idea how to figure that out? Thanks! Frank From bthom at cs.hmc.edu Thu Mar 22 22:01:27 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Thu, 22 Mar 2007 19:01:27 -0700 Subject: class / instance question Message-ID: <96B6F7A8-E09A-433B-ACC8-EF90A66DBEC8@cs.hmc.edu> Hello, I'm hoping the Python community knows whether or not the following is possible, and if it is possible, how I would go about writing code to do this. I've written two game classes---Nim and TicTacToe---where each derives from a Game class that I've created (it is essentially an abstract base class, where I've used an "abstract()" hack to somewhat enforce this). I now want to be able to pass either of these classes into a game- playing engine, for instance a function playGame(classOfGameToBePlayed) : # inside of which I create a new game using that class's constructor Is this possible, and if so, how to approach it? Thanks a lot, --b From gagsl-py2 at yahoo.com.ar Mon Mar 26 14:07:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 Mar 2007 15:07:42 -0300 Subject: how to abort on syntax errors References: <46080186$0$14151$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: En Mon, 26 Mar 2007 14:21:22 -0300, Josh escribi?: > I have a lot of except Exception, e statements in my code, which poses > some > problems. *many* problems, I'd say. Don't do that :) > One of the biggest is whenever I refactor even the triviallest > thing in my code. > > I would like python to abort, almost as if it were a compile-time error, > whenever it cannot find a function, or if I introduced a syntax error. > But, > instead, it merrily proceeds on its way. Because you have told Python to do so, using a catch-all except clause. Try to be as specific as possible. Syntax errors, indentation errors and such can be caught just by compiling the module, even before you try to test it. > Is there some idiom that you use in situations like these? Avoid bare except clauses as much as you can. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Fri Mar 9 21:58:59 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Mar 2007 13:58:59 +1100 Subject: Unexpected behavior of list of list References: <1173490209.398081.200420@h3g2000cwc.googlegroups.com> Message-ID: On Fri, 09 Mar 2007 17:30:09 -0800, kghose wrote: > Hi, > > The following code > > listoflists = [[]]*2 > listoflists[0].append(1) > > appends(1) to both listoflists[0] and listoflists[1] (which I did not > expect) I think you will find the same question raised barely a few hours ago. Hint: >>> list_of_lists = [[]]*2 >>> id(list_of_lists[0]) -1211466452 >>> id(list_of_lists[1]) -1211466452 Notice that both inner lists have the same ID? That tells you that they are the same list. Like about what [obj]*2 does. Does it create multiple copies of obj? No it does not. Python never makes copies of objects unless you explicitly tell it to. [] on it's own creates a new empty list, so [[], []] creates a list with two DIFFERENT empty lists in it. [[]] creates a list with one empty list in it; *2 makes a second reference (not a copy!) of that empty list. > while > > listoflists = [[]]*2 > listoflists[0] = [1] > listoflists[0].append(2) > > works as expected.i.e. only listoflists[0] gets 2 appended to it and > any further operations work as expected. >>> list_of_lists[0] = [] # creates a new empty list >>> id(list_of_lists[0]) -1211466228 >>> id(list_of_lists[1]) # same ID as before -1211466452 You know, now that Python has a warnings module, it would be really good if list-of-lists*int raised a warning. Does anyone know if that's feasible or possible? It needn't catch every imaginable Gotcha, just the common case. I'm thinking something like this: # pseudo-code class list: def __mul__(self, count): for item in self: if isinstance(item, list): warn("this duplicates references, not copies") break ...do the rest -- Steven. From george.sakkis at gmail.com Wed Mar 7 14:15:34 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 7 Mar 2007 11:15:34 -0800 Subject: Debugging segmentation faults Message-ID: <1173294934.182507.116790@h3g2000cwc.googlegroups.com> I have a pure python program (no C extensions) that occasionally core dumps in a non-reproducible way. The program is started by a (non- python) cgi script when a form is submitted. It involves running a bunch of other programs through subprocess in multiple threads and writing its output in several files. So the only suspicious parts I can think of is subprocess and/or multithreading. For the multithreading part I'm using a modified version of threadpool.py (http://www.chrisarndt.de/en/software/python/threadpool/), which is built on top of the threading and Queue stdlib modules. Whatever bugs may linger there, I'd hope that they would show up as normal Python exceptions instead of segfaults. All I have now is a few not particularly insightful core files (actual path names and args changed for privacy): /home/gsakkis/foo>gdb --core core.20140 GNU gdb Red Hat Linux (5.2-2) Copyright 2002 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux". Core was generated by `python2.5 /home/gsakkis/foo/foo.py --XXX -- max=30 --bar=/tmp/83840` Program terminated with signal 11, Segmentation fault. #0 0x080b222d in ?? () (gdb) backtrace #0 0x080b222d in ?? () #1 0x080b28d1 in ?? () #2 0x080fa8ab in ?? () #3 0x0805c918 in ?? () (...) #28 0x080b310f in ?? () #29 0x080dbfdd in ?? () #30 0x40021fef in ?? () Any hints ? From bdesth.quelquechose at free.quelquepart.fr Sun Mar 11 13:48:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 11 Mar 2007 18:48:49 +0100 Subject: Python in a desktop environment In-Reply-To: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> Message-ID: <45f438da$0$2327$426a34cc@news.free.fr> David Cramer a ?crit : > If you had an application that you were about to begin development on > which you wanted to be cross platform (at least Mac and Windows), > would you suggest using c++ and Python? > > I'm asking because we were originally thinking about doing c# but > after attending PyCon this year I'm reconsidering. We are already > using Python for the website and I figure a c++ backend w/ a Python > GUI may work really well, and would be pretty easy to port. > > Any opinions? > Yes : forget about the c++ backend. From deets at nospam.web.de Wed Mar 28 05:51:18 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 Mar 2007 11:51:18 +0200 Subject: XML Parsing References: <1175067518.919256.243090@n59g2000hsh.googlegroups.com> Message-ID: <56us4mF2a9rq7U1@mid.uni-berlin.de> pyapplico at gmail.com wrote: > I want to parse this XML file: > > > > > > > filename > > Hello > > > > > filename2 > > Hello2 > > > > > > This XML will be in a file called filecreate.xml > > As you might have guessed, I want to create files from this XML file > contents, so how can I do this? > What modules should I use? What options do I have? Where can I find > tutorials? Will I be able to put > this on the internet (on a googlepages server)? > > Thanks in advance to everyone who helps me. > And yes I have used Google but I am unsure what to use. The above file is not valid XML. It misses a xmlns:text namespace declaration. So you won't be able to parse it regardless of what parser you use. Diez From arnodel at googlemail.com Tue Mar 13 18:12:12 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 13 Mar 2007 15:12:12 -0700 Subject: Iterating across a filtered list In-Reply-To: References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <1173813714.767225.164790@q40g2000cwq.googlegroups.com> <7xird5ndey.fsf@ruckus.brouhaha.com> <1173817193.179354.235790@p15g2000hsd.googlegroups.com> Message-ID: <1173823932.685855.241940@n76g2000hsh.googlegroups.com> On Mar 13, 9:31 pm, "Gabriel Genellina" wrote: > En Tue, 13 Mar 2007 17:19:53 -0300, Arnaud Delobelle > escribi?: > > > On Mar 13, 7:36 pm, Paul Rubin wrote: > > >> The re library caches the compiled regexp, I think. > > > That would surprise me. > > How can re.search know that string.lower(search) is the same each > > time? Or else there is something that I misunderstand. > > It does. > > py> import re > py> x = re.compile("ijk") > py> y = re.compile("ijk") > py> x is y > True > > Both, separate calls, returned identical results. You can show the cache: OK I didn't realise this. But even so each time there is the cost of looking up the regexp string in the cache dictionary. -- Arnaud From jonathan.wright at gmail.com Tue Mar 27 17:38:50 2007 From: jonathan.wright at gmail.com (Jon) Date: 27 Mar 2007 14:38:50 -0700 Subject: plot dendrogram with python In-Reply-To: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> References: <1174987611.314883.150410@y80g2000hsf.googlegroups.com> Message-ID: <1175031530.221840.199850@l77g2000hsb.googlegroups.com> > does anyone know if there is a way to plot a dendrogram with python. > Pylab or matplotlib do not provide such a function. This makes a datafile for gnuplot using output from pycluster. I'd be interested to see something like this added to pylab/matplotlib, although I don't have time myself. Not very elegant, but someone can probably transform it to the three line recursion which escapes me. Best, Jon import Numeric from Pycluster import treecluster dist = Numeric.zeros((10,10),Numeric.Float) for i in range(dist.shape[0]): dist[i:,i:]=i tree , dist = treecluster(distancematrix=dist,method='a') tree=tree.tolist() base = [] line = [] names = range(dist.shape[0]+1) def f(i,tree,names,spos): height=dist[spos] if i>=0: try: base.append(names[i]) except: print i x=len(base) line.append((x,0)) line.append((x,height)) line.append(("#","#")) else: cluster = tree[-i-1] h1,x1=f(cluster[0],tree,names,-i-1) h2,x2=f(cluster[1],tree,names,-i-1) x=(x1+x2)/2.0 if h1==h2: # tie line.append((x1,h1)) line.append((x2,h2)) line.append(("#","#")) line.append((x,height)) line.append((x,h1)) line.append(("#","#")) else: raise Exception("Whoops") tree[-i-1].append((x,h1)) return height,x h1,x1 = f(tree[-1][0],tree,names,len(tree)-1) h2,x2 = f(tree[-1][1],tree,names,len(tree)-1) x=(x1+x2)/2.0 height = dist[-1] tree[-1].append((x,h1)) if h1==h2: # tie line.append((x1,h1)) line.append((x2,h2)) line.append(("#","#")) line.append((x,height)) line.append((x,h1)) line.append(("#","#")) else: raise Exception("Whoops") # print base d=open("dend.dat","w") # make a tree diagram for point in line: if point[0]!="#": print >> d, point[0],point[1] else: print >> d print >> d d.close() # # os.system("gnuplot") # """plot "dend.dat" u 1:2 w l""" From bill.tydeman at gmail.com Sat Mar 3 08:08:00 2007 From: bill.tydeman at gmail.com (Bill Tydeman) Date: Sat, 3 Mar 2007 08:08:00 -0500 Subject: Python 2.5, problems reading large ( > 4Gbyes) files on win2k In-Reply-To: <1172858955.189032.73800@t69g2000cwt.googlegroups.com> References: <1172858955.189032.73800@t69g2000cwt.googlegroups.com> Message-ID: <501e09e0703030508i6d92e313sa412d352c998564b@mail.gmail.com> Just curious, but since the file size limitation on NTFS is 4 GB, have you confirmed that it isn't some other part of the interaction that is causing the problem? What FS is hosting the files? On 2 Mar 2007 10:09:15 -0800, paduffy at cisco.com wrote: > > Folks, > > I've a Python 2.5 app running on 32 bit Win 2k SP4 (NTFS volume). > Reading a file of 13 GBytes, one line at a time. It appears that, > once the read line passes the 4 GByte boundary, I am getting > occasional random line concatenations. Input file is confirmed good > via UltraEdit. Groovy version of the same app runs fine. > > Any ideas? > > Cheers > > -- > http://mail.python.org/mailman/listinfo/python-list > -- There is no reason for any individual to have a computer in his home. Ken Olsen, President, Digital Equipment, 1977 US computer engineer & industrialist (1926 - ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Fri Mar 23 09:02:02 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 23 Mar 2007 08:02:02 -0500 Subject: Cleanly exiting multi thread application on SIGINT In-Reply-To: <1174653622.239148.185270@y80g2000hsf.googlegroups.com> References: <1174653622.239148.185270@y80g2000hsf.googlegroups.com> Message-ID: <17923.53194.182200.856085@montanaro.dyndns.org> Jon> Is the following the most elegant way to exit a multi-threaded Jon> application on a Ctrl-C? I am a complete beginner and would have Jon> thought there was some way of doing it without having to use while Jon> 1: pass, but have yet to find a way. I thought there was some sort of wait() method in the threading module, but I was mistaken. Maybe: while threading.activeCount(): time.sleep(0.01) ? Skip From dbhbarton at googlemail.com Fri Mar 9 08:48:35 2007 From: dbhbarton at googlemail.com (dbhbarton at googlemail.com) Date: 9 Mar 2007 05:48:35 -0800 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: <55d34sF24ijrdU1@mid.individual.net> References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <1173436274.346506.200920@q40g2000cwq.googlegroups.com> <55cs24F23meg4U1@mid.individual.net> <1173438105.600342.243200@n33g2000cwc.googlegroups.com> <55d34sF24ijrdU1@mid.individual.net> Message-ID: <1173448114.905480.47200@h3g2000cwc.googlegroups.com> > Yes, it has. It says "disregard the following characters until EOL". > If you remove it, the following code will be interpreted as ... > code (and not be disregarded). and ! would say "disregard the following characters until End Of Program". Is it really so different? > > Well I'm not a big fan of decorators so I know how you must feel. > > Mh, not sure -- why do you have decorators in mind? I don't dislike > them. Just because I remember reading similar aesthetic arguments against the @ syntax- that it looked alien, messy, unpythonic and obfuscating. I certainly agree with the latter point even if I find the former ones a little hand-wavey for my tastes. > I think it's much cleaner to have language and "fixme" levels > separate. "fixme" features can then depend fully on the editor/IDE > and don't have to be part of the source code (though they may). That's certainly a solid ideological argument against the "WIP character". Maybe I should just change my editor! It sounds like other Python users *do* like to do the kind of things I suggested, but seasoned users would rather rely on macros and features of specific editors. Unfortunately, to a newbie like myself, these seem like obscure 'tricks' to be mastered rather than simple built-in conveniences that any newbie can profit from. I suppose my ideology is that Python's greatest strength is (and focus should be) its visual simplicity and ease of learning, making programming more accessible to the masses. But hey I'm just a fresh- faced conscript. I guess I've got to leave the battle planning to the five-star generals on the hill! Thanks for all the comments and the spirit of tolerance. dave From duncan.booth at invalid.invalid Thu Mar 8 03:35:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Mar 2007 08:35:31 GMT Subject: Is numeric keys of Python's dictionary automatically sorted? References: Message-ID: Carsten Haese wrote: > Here is a simple counterexample that breaks the ordering, at least for > the version I'm running: > >>>> d = {} >>>> for i in range(0,6): d[10**i] = [] > ... >>>> d > {100000: [], 1: [], 100: [], 1000: [], 10: [], 10000: []} Here's another counterexample which shows that even dictionaries with the same consecutively numbered small integer keys can vary the order in which the keys are returned: >>> d1 = dict.fromkeys([1,2]) >>> d2 = dict.fromkeys([9,1,2]) >>> del d2[9] >>> d1 {1: None, 2: None} >>> d2 {2: None, 1: None} In current C-Python implementations, the hash code for an integer is simply the integer itself. That means there is a strong tendency for consecutive integers to be stored in consecutive slots in the dictionary. However as soon as you get gaps, or add the keys out of order, there is a opportunity for higher valued keys to displace lower valued keys into a different slot. If you want the keys sorted then sort them. From socialanxiety at gmail.com Sat Mar 3 18:53:45 2007 From: socialanxiety at gmail.com (socialanxiety at gmail.com) Date: 3 Mar 2007 15:53:45 -0800 Subject: logging into forms on an ssl server using python Message-ID: <1172966025.124339.163860@p10g2000cwp.googlegroups.com> Hi, I need some help, I'm trying to create a script that will fill in the forms on an ssl website, and submit them. Could anyone help me out, examples would be nice. Thanks in advance From steve at REMOVE.THIS.cybersource.com.au Wed Mar 21 18:28:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 09:28:45 +1100 Subject: Python 3000 idea: reversing the order of chained assignments References: Message-ID: On Wed, 21 Mar 2007 22:53:55 +0100, Marcin Ciura wrote: > Given > class Node(object): > pass > > node = Node() > nextnode = Node() > > I tried to refactor the following piece of code > node.next = nextnode > node = nextnode > > as > node = node.next = nextnode > > only to discover that Python performs chained assignments > backwards compared to other languages, i.e. left-to-right > instead of right-to-left. From the user's perspective, > I can't think of any reasonable argument for keeping it > this way in Python 3000. What is your opinion? Well, this user's perspective is that if I read from left to right, which I do, then I expect most operations to also go from left to right, and not from right to left. Assignment is one exception to that. If I say "x = y = z" then I expect that afterwards x and y and z should all have the same value. >>> x, y, z = 1, 2, 3 >>> x, y, z (1, 2, 3) >>> x = y = z >>> x, y, z (3, 3, 3) I certainly wouldn't expect to get (2, 3, 3). -- Steven. From markg85 at gmail.com Tue Mar 13 11:04:05 2007 From: markg85 at gmail.com (Mark) Date: Tue, 13 Mar 2007 16:04:05 +0100 Subject: i can`t get python working on the command line (linux) Message-ID: <6e24a8e80703130804y7a88f1b0wf7ed30e98d6a35f7@mail.gmail.com> Hey, first of all: sorry for the 100% n00b question i`m brand new to python and i seem to start off with the biggest problem of all.. not even getting python to work. i`m running Fedora core 7 test 2 and all the python based applications are working fine (like pirut, pipet, and some other yum related tools) but when i try to run this script: #!/usr/bin/python # # python script tel.py # gevonden door Jan Mooij 24 september 2000 # from sys import * from string import * # Create an empty dictionary. count = {} for line in open(argv[1], 'r').readlines(): for word in split(line): if count.has_key(word): count[word] = count[word] + 1 else: count[word] = 1 words = count.keys() words.sort() for word in words: print "%15s\t%10d" % (word, count[word]) and i`ve put it in tel.py (just the same as in the sample) than chmod it to 777 (just to make sure it isn`t a permission issue) and than i run it with: ./tel.py now this is the error that i get: Traceback (most recent call last): File "./tel.py", line 12, in for line in open(argv[1], 'r').readlines(): IndexError: list index out of range also i`m not even getting the most simple sample code to work.. "Hello World". everything works fine when i first enter the python console by typing python. than i have the >>> things than print "Hello World" gives me the expected result but that`s not what i want.. i want to do it from a file.. the solution is probable extremely simple but i have no idea as a complete n00b in python. i do have alot php experience. hope someone could help me out with this. o and any function that i use in python gives me "command not found: print/whatever function i use" (probable just a simple yum install command that i need to do to get this working.. just try to figure that out with no python knowledge) Thanx alot in favor. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thinker at branda.to Wed Mar 21 16:31:26 2007 From: thinker at branda.to (Thinker) Date: Thu, 22 Mar 2007 04:31:26 +0800 Subject: Make variable global In-Reply-To: <1174506941.618827.48450@l75g2000hse.googlegroups.com> References: <1174506941.618827.48450@l75g2000hse.googlegroups.com> Message-ID: <4601961E.2070303@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 abcd wrote: > I have a file, "a.py" > > blah = None def go(): global blah blah = 5 > >> From the python interpreter I try.... > >>>> from a import * blah go() blah >>>> > > ...i was hoping to see "5" get printed out the second time I > displayed blah, but it doesn't. Now, if I type this same code > directly into the python interpreter it works as i was hoping. > what i am missing? > > thanks > "import" imports bindings between symbols and objects into the module from another one. When you call a function in another module, it changes global space of module where it is defined. The global space of the module, where caller is in, is kept from touched except accessing through module names. - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGAZYd1LDUVnWfY8gRAsdNAJ9niVqdGz1aG0NUzN+Ggmk+vnqZSgCfQB9s SBuV/fWo8lqAytQP/QXQPXE= =1BiL -----END PGP SIGNATURE----- From Ingo.Wolf at gmx.de Wed Mar 7 05:05:16 2007 From: Ingo.Wolf at gmx.de (iwl) Date: 7 Mar 2007 02:05:16 -0800 Subject: askstring Window to the top under Windows In-Reply-To: References: <1173186819.622405.121170@30g2000cwc.googlegroups.com> Message-ID: <1173261916.618914.69130@8g2000cwh.googlegroups.com> On 7 Mrz., 02:49, jim-on-linux wrote: > On Tuesday 06 March 2007 08:13, iwl wrote: > > > Hi, > > > I tryed askstring to input some text in my > > script, but some ugly empty Window appears with > > the Input-Window behind and all together behind > > my Console showing my script. So all have to > > brought to the top first by the user - very > > unconfortable > > By default > tk will open a root window. Is this default changeable befor askstring? From pecora at anvil.nrl.navy.mil Fri Mar 9 11:18:47 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Fri, 09 Mar 2007 11:18:47 -0500 Subject: Is this right? Multiple imports of same module. References: Message-ID: In article , Marc 'BlackJack' Rintsch wrote: > In , Lou Pecora wrote: > > > *In mod1.py > > > > import mymodule > > > > *In mod2.py > > > > import mymodule > > > > *In mod3.py > > > > import mymodule as MM > > > > Then mymodule is imported only once, but each module has access to it > > through the module name (mod1 and mod2) and the alias MM (mod3). Is > > that right? > > Yes, that's correct. > > Ciao, > Marc 'BlackJack' Rintsch Thank you. A further confusion (if I may): I have noticed that using from xxx import * can lead to problems when trying to access variables in the xxx module. E.g. -- File f2.py imvar=1 def prn(): print imvar -- File junk.py from f2 import * prn() imvar=2 prn() -- Running junk.py gives the output: 1 1 Not what I would expect which is, 1 2 Namespaces get confusing. I have begun to switch to using 'import f2 as' which gives the 2nd expected result. Safer, but still a bit puzzling. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From MonkeeSage at gmail.com Mon Mar 12 08:40:44 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 12 Mar 2007 05:40:44 -0700 Subject: Single string print statements on multiple lines. In-Reply-To: <55kv29F24oq26U1@mid.uni-berlin.de> References: <1173702080.939606.169630@j27g2000cwj.googlegroups.com> <55kv29F24oq26U1@mid.uni-berlin.de> Message-ID: <1173703244.814332.63850@64g2000cwx.googlegroups.com> HeEm wrote: > In my 100 level CS course, I was asked to create multiple lines of > output within a single string. Of course I know how to: If this is for a CS course, you shouldn't really be cheating and asking for an answer here, should you? I mean, the whole point of taking (and paying for!) a CS course is to learn CS, right? But like Diez said, the standard C escapes work in python: \t = TAB, \r = CARRIAGERETURN, \n = NEWLINE/LINEFEED, &c. Regards, Jordan From deets at nospam.web.de Tue Mar 20 03:58:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Mar 2007 08:58:25 +0100 Subject: Anything available that can read Microsoft .MDB files from Python? In-Reply-To: References: <56863eF27p5bmU1@mid.uni-berlin.de> Message-ID: <569ih4F27o9bdU1@mid.uni-berlin.de> > > What MDBtools did you install? The RPM, a checkout from CVS, > or the downloadable distribution? They're all different. The one that comes with ubuntu edgy. Just apt-get install mdbtools or something, that's it. I don't want to start a distro war here - but I always found the RPM-based distros lacking, to say the least. Diez From sgeiger at ncee.net Sat Mar 24 09:02:23 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Sat, 24 Mar 2007 08:02:23 -0500 Subject: Join strings - very simple Q. In-Reply-To: <1174739951.358958.245240@o5g2000hsb.googlegroups.com> References: <1174675011.244339@jubilee.claranet.pt> <1174676818.207543.246080@l75g2000hse.googlegroups.com> <1174678166.970277@jubilee.claranet.pt> <1174737587.638835.137070@y80g2000hsf.googlegroups.com> <1174739951.358958.245240@o5g2000hsb.googlegroups.com> Message-ID: <4605215F.8090108@ncee.net> import string def test_join(l): print "Joining with commas: ", string.join(l,',') print "Joining with empty string: ", string.join(l,'') print "Joining same way, using another syntax: ", ''.join(l) print "Joining with the letter X: ", 'X'.join(l) print "Joining with <-> ", '<->'.join(l) l = ['a','b','c'] test_join(l) """ Example output: Joining with commas: a,b,c Joining with empty string: abc Joining same way, using another syntax: abc Joining with the letter X: aXbXc Joining with <-> a<->b<->c """ Dustan wrote: > On Mar 24, 5:59 am, "Dustan" wrote: > >> On Mar 23, 1:30 pm, Paulo da Silva wrote: >> >> >>> Mike Kent escreveu: >>> ... >>> >>>> New way: >>>> l=['a','b','c'] >>>> jl=','.join(l) >>>> >>> I thank you all. >>> >>> Almost there ... >>> I tried "".join(l,',') but no success ... :-( >>> >>> Paulo >>> >> Perhaps you're doing it wrong, despite having an example right in >> front of you? >> >> Side by side comparison: >> jl=string.join(l,',') >> jl=','.join(l) >> >> The sequence is passed as an argument to the join method, and the >> delimiter is the string whose method is being called. >> > > To further demonstrate (because I got a weird email that seemed to > think that my code didn't work): > > >>>> import string >>>> l = ['a','b','c'] >>>> string.join(l,',') >>>> > 'a,b,c' > >>>> ','.join(l) >>>> > 'a,b,c' > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From deets at nospam.web.de Tue Mar 27 17:49:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Mar 2007 23:49:11 +0200 Subject: Please help!! SAXParseException: not well-formed (invalid token) In-Reply-To: <1175015481.265701.206970@d57g2000hsg.googlegroups.com> References: <1175007585.758109.127490@r56g2000hsd.googlegroups.com> <56sqr5F29auttU1@mid.uni-berlin.de> <1175015481.265701.206970@d57g2000hsg.googlegroups.com> Message-ID: <56thr2F28t97kU2@mid.uni-berlin.de> jvictor118 at yahoo.fr schrieb: > I checked the file format (of the file containing the n-tilde - ?) and > it is indeed UTF-8! I'm baffled! Any ideas? Without you showing us your actual code and data - no. Because it works for me and a lot of other people. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 13 04:38:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 13 Mar 2007 09:38:20 +0100 Subject: Starting Python... some questions In-Reply-To: <1173760751.798442.300550@s48g2000cws.googlegroups.com> References: <1173760751.798442.300550@s48g2000cws.googlegroups.com> Message-ID: <45f662f3$0$15552$426a74cc@news.free.fr> jezonthenet at yahoo.com a ?crit : > I started using Python a couple of days ago - here are a few > questions: > > * Doesn't the __main__() method automatically execute when I run my > python program? Which "__main__" method ??? Anyway, the answer is no. Every code at the top-level (which includes import, class and def statements...) is executed when the module is first loaded - whether as a proper module (ie: imported from somewhere else) or as a main program (ie-> python mymodule.py). In the first case, the special variable __name__ is set to the module's name, in the second to '__main__'. So you can rely on this to have code executed when the module is used as a program. The usual idiom is # mymodule.py (imports here) (classes and defs here) def main(argv): (code of main function here) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv)) > * Only when I do an import of my test.py file within python and then > run test.__main__() BTW, you should *not* use names with 2 leadings and 2 trailing underscores. These names are reserved for Python implementation stuff. > I can see where my bugs are. Is this correct? Nope. You can also spot bugs by reading the code or running it thru the debugger !-) More seriously : using the above idiom (or any variant of - the important part being the conditional on __name__ == '__main__'), you can just $ python mymodule.py to run your program. > (right now this is my only way of running my python program and see > where I have problems) > * Once I've done an import and then I wish to make a change to the > file I've imported I have to quit Python, restart and import that > module again in order for the module to be refreshed. Is there no "re- > import" ? reload(module_object) But it's of very limited use. The best thing to do is usually to have a simple test file that setup the desired state (imports etc) that you execute after each change, passing the -i option to the python interpreter (this will leave the interpreter in interactive mode after execution of the test file, so you can inspect your objects, test things etc). > * Finally, could someone tell me why I'm having problems with the > small module below? > - Python pretends I provide chassis_id() with three parameters, even > though I clearly only provide it with two - why? Without even reading the code, I can tell you it's an instance or classmethod with either a wrong declaration or wrongly called. > > #!/usr/bin/python > import scapy > import struct > > class lldp_class: Do yourself a favor: use new-style classes. Also, it would be better to stick to usual naming conventions (Python relies heavily on conventions): http://www.python.org/dev/peps/pep-0008/ class Lldp(object): > def __init__(self): > self.chassis_id_tlv = None > > def chassis_id(subtype, chassis_info): Bingo. You need to have self as the first argument. The instance is passed as the first argument of a method. def chassis_id(self, subtype, chassis_info): > if subtype == 4: > chassis_data = struct.pack("!B",chassis_info) > subtype_data = struct.pack("!B",subtype) > self.chassis_id_tlv = subtype_data + chassis_data > > def __main__(): def main(): > p = lldp_class() > p.chassis_id(4, "01:80:C2:00:00:0E") For the record: this is interpreted as: lldp_class.chassis_id(p, 4, "01:80:C2:00:00:0E") > payload = p.chassis_id_tlv > ether = scapy.Ether(dst="01:02:03:04:05:06") > fullpayload = ether + payload > sendp(fullpayload) > if __name__ == '__main__': main() As a side note, it looks like there are a couple point where your design may be improved. Like passing subtype and chassis_info to the __init__ of your class. HTH From steve at holdenweb.com Thu Mar 15 23:13:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Mar 2007 23:13:01 -0400 Subject: problem with str() In-Reply-To: <1hv191c.1bj9j73fp25ldN%aleax@mac.com> References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> <1173992205.985657.167970@y66g2000hsf.googlegroups.com> <1hv191c.1bj9j73fp25ldN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steve Holden wrote: > >> 7stud wrote: >>> Sheesh! You would think that after looking at every inch of the code >>> for way too many hours, at some point that would have poked me in the >>> eye. >>> >>> Thanks all. >>> >> Get yourself a stuffed bear, and next time you have this kind of problem >> spend a few minutes explaining to the bear exactly how your program >> can't possibly be wrong. Works like a charm. > > A rubber ducky works much better for that, btw -- more easily washable > than a stuffed bear, for example. > But stuffed bears are so much more knowledgeable about the minutiae of software design. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From kibleur.christophe at gmail.com Fri Mar 2 20:11:00 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 2 Mar 2007 17:11:00 -0800 Subject: cyclic iterators ? Message-ID: <1172884260.852007.122260@64g2000cwx.googlegroups.com> Hi, Let say I've got a simple list like my_list = [ 'a', ',b', 'c' ]. We can have an iterator from it by k = iter( my_list), then we can access each of her (his ?) element by k.next(), etc. Now, I just wanted k to have the following cyclic behaviour (without rising the ) : >> k.next() 'a' >> k.next() 'b' >> k.next() 'c' >> k.next() -> not raising StopIteration error 'a' >> k.next() 'b' etc. I've tried something like this to have a cyclic iterator without sucess: def iterate_mylist(my_list): k = len((my_list) i=0 while i <= k : yield my_list[i] i += 1 i = 0 yield my_list[0] I missed something, but I don't know what exactly. Thanks. From gigs at hi.t-com.hr Sun Mar 18 11:49:28 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Sun, 18 Mar 2007 16:49:28 +0100 Subject: tkinter grid vs pack Message-ID: For what is grid better than pack, and otherwise? thanks in advance From steve at REMOVEME.cybersource.com.au Thu Mar 22 03:22:07 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Mar 2007 18:22:07 +1100 Subject: Technical Answer - Protecting code in python References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> <1tkMh.115$mG4.94@newsfe12.lga> <1174543186.407031.165640@l77g2000hsb.googlegroups.com> Message-ID: On Wed, 21 Mar 2007 22:59:46 -0700, flit wrote: > Going back in the beginning I said : > > "So PLEASE, don't try to convince me about the social / economical / > open source / give to all / be open / all people are honest until > prove contrary / dance with the rabbits... " I have done NONE of that. I've just pointed out, time and time again, that you haven't asked a meaningful question. Even after all these posts, still won't tell us what you are trying to protect against. People copying your program? Competitors infringing your patents? Your "corrupt and "bad" government (your words) infringing your moral rights as an author? Your customer editing your program and breaking it? Who knows? I don't. I wonder whether even you do. You keep asking for a technical solution, even if a technical solution is not appropriate, but you won't tell us what the problem is. Tell us the threat you want to protect against, and we'll suggest meaningful solutions. -- Steven D'Aprano From deets at nospam.web.de Tue Mar 27 10:49:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Mar 2007 16:49:24 +0200 Subject: Help in Placing Object in Memory References: <1175006005.782360.233620@b75g2000hsg.googlegroups.com> Message-ID: <56sp7kF2b0fj6U1@mid.uni-berlin.de> Clement wrote: > I am newbie to Python...... i want to know something.......... > > can i place an object in disk instead of placing in Main Memory...? > If possible, can you please explain with some scripts...? See the module pickle and it's examples. > can two python script share a common object....? What do you mean by that? They can both load a pickled object, yes. But they can't share it as a at-runtime object, where changes in one script are immediately are known to the other. To do such a thing, look at pyro. Diez From gagsl-py2 at yahoo.com.ar Sun Mar 18 20:54:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 Mar 2007 21:54:08 -0300 Subject: Private data References: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> <1174220701.206419.77780@e65g2000hsc.googlegroups.com> <1174224087.024303.102130@n59g2000hsh.googlegroups.com> Message-ID: En Sun, 18 Mar 2007 10:21:27 -0300, Dustan escribi?: >>>> dis.dis(testPrivateStaticFunctionVariables) > 21 0 LOAD_DEREF 0 (func) > 3 LOAD_DEREF 1 (internalData) > 6 LOAD_FAST 0 (args) > 9 CALL_FUNCTION_VAR 1 > 12 RETURN_VALUE > > What's the difference between 'LOAD_DEREF', 'LOAD_FAST', and > 'LOAD_CONST', and, as seen at http://docs.python.org/lib/module-dis.html, > 'LOAD_GLOBAL'? I can imagine that 'LOAD_GLOBAL' loads a global, but > seeing as python is such a dynamic language, how exactly is it > supposed to distinguish between them? The Python interpreter executes a stack-based machine. Look at Python/compile.c for the code generation and Python/ceval.c for the code execution. LOAD_CONST pushes a constant onto the stack (all constants are previously built and stored as attribute co_consts of the code object). LOAD_FAST and LOAD_GLOBAL pushes a local or global variable reference. (The compiler knows whether a name is local or not, just by lexical analysis). LOAD_DEREF appears to be used for accessing variables inside closures, I'm not sure. > I don't understand the following at all: 'DUP_TOP', 'ROT_TWO'. Any > pointers? They manipulate the stack. DUP_TOP duplicates the top entry; ROT_TWO swaps the two top entries. > What does 'INPLACE_ADD' mean, if not in place addition, and if it is > in place addition, why does it need to 'STORE_ATTR' afterward? That corresponds to A += B. The compiler can't know if A has or not an __iadd__ method; even if A implements __iadd__, that method could return a different object, not always A (it *may* try to do the operation inplace, but that might not always be possible). When the inplace method is not implemented, __add__ is used (so effectively A += B is computed as A = A+B) -- Gabriel Genellina From sjmachin at lexicon.net Fri Mar 23 22:29:52 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Mar 2007 19:29:52 -0700 Subject: except clause appears to be being skipped? In-Reply-To: <1174701061.474974.97710@y80g2000hsf.googlegroups.com> References: <1174701061.474974.97710@y80g2000hsf.googlegroups.com> Message-ID: <1174703392.857810.62030@n59g2000hsh.googlegroups.com> On Mar 24, 12:51 pm, AWasile... at gmail.com wrote: [snip] > def pager(self,dex): > #Input page filename, Output pagetitle and the HTML output > #Find out if the file requested actually exists > try: > j = dex + ".html" > textfile = open("pages/" + j, "r") > #If not 404' it > except: > self.err404(dex) > > #The first line in the .html files is the title, this reads that one > line > pagetitle = textfile.readline() > [snip] > File "/home2/awasilenko/webapps/cp/html.py", line 25, in pager > pagetitle = textfile.readline() > UnboundLocalError: local variable 'textfile' referenced before > assignment > > I know the except is being executed because I put a break in there for > testing purposes and it did break, but as for why its not pulling up > the 404 function and returning the error page, I have no idea. It *is* "pulling up the 404 function", which *is* returning your error page. However all your except clause does is "self.err404(dex)" -- you ignore the return value, and fall out of the except clause with textfile undefined, with the expected consequences. I'm not at all familiar with cherrypy, but you probably need to do either: errpage = self.err404(dex) dosomethingwith(errpage, dex) return or simply: return "404 page title", self.err404(dex) [Actually it would be better style if the err404 method returned a tuple of (pagetitle, pagebody), then your except clause contains only: return self.err404(dex) The main point being to return instead of falling through the bottom of the except clause. BTW, you should not use a bare except. Be a little more specific, like except IOError: Looking at the cherrypy docs would seem indicated. AFAIK there was a v1 and a v2 with different naming conventions and there's now a v3 -- do ensure that you mention which version you are using if you need to come back with more questions. HTH, John From codecraig at gmail.com Thu Mar 15 10:49:28 2007 From: codecraig at gmail.com (abcd) Date: 15 Mar 2007 07:49:28 -0700 Subject: wxTextCtrl - copy and paste 65, 000 characters of text into it only seems to hold 30, 003 Message-ID: <1173970168.287858.277380@l77g2000hsb.googlegroups.com> I have a wxTextCtrl: wx.TextCtrl(self.myPanel, -1, "", style=wx.TE_MULTILINE) I take a set of text (65,000 characters), and paste it into the text control. all looks well. Then when I click a button I print out the entered text and the length of that text. Here is what I am seeing... 1. Paste in text (65,000 characters) 2. Click button 3. Output on screen shows that the message length (i.e. len(msg)) is 30003 (strange since it should be 65000) 4. Select all text in the text control and hit delete. The text control should now be empty. 5. Paste in text (65,000 characters) 6. Click Button 7. Output on screen shows that the message length (i.e. len(msg)) is 65000 (as expected). Any idea why the first time it gives me 30003, but on subsequent attempts I get 65000? Thanks From S.Mientki-nospam at mailbox.kun.nl Sun Mar 11 09:21:24 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 11 Mar 2007 14:21:24 +0100 Subject: Parsing Indented Text (like parsing Python) In-Reply-To: References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com><1173595945.530722.273030@30g2000cwc.googlegroups.com><000a01c763c0$6863a560$2102fea9@Guides.local> Message-ID: <265da$45f40233$d443bb3a$4271@news.speedlinq.nl> > > The problem is, how do I figure out how many spaces represent a tab? In one > case, someone could have their editor configured to allow tabs to use 3 > spaces and the user could intermingle tabs and spaces. In other cases, a > user might have their editor configured to have a tab equal 8 spaces yet > also intermingle tabs and spaces. When a human looks at the document it is > obvious the setting but how can I make it obvious to my program? then statistics can do it too. -- cheers, Stef Mientki http://pic.flappie.nl From pavlovevidence at gmail.com Mon Mar 26 11:45:46 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 26 Mar 2007 08:45:46 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174923946.011579.262980@p15g2000hsd.googlegroups.com> On Mar 26, 9:42 am, Jean-Paul Calderone wrote: > On 26 Mar 2007 06:20:32 -0700, "Noma... at gmail.com" wrote: > > >OK... > >I've been told that Both Fortran and Python are easy to read, and are > > Python is hugely easier to read. > > >quite useful in creating scientific apps for the number crunching, but > >then Python is a tad slower than Fortran because of its a high level > > Fortran is massively faster than Python. > > >language nature, so what are the advantages of using Python for > >creating number crunching apps over Fortran?? > > You can get the speed of fortran in Python by using libraries like > Numeric without losing the readability of Python. This is true only for problems that can take advantage of scalability, which is a large and important subset of all numerical problems, but is still only a subset. Some problems (e.g., simulation) require repeated sequential evaluation of formulas. For other problems (e.g., collision detection) the operands change rapidly. The scalability of numpy doesn't help so much here. (Anecdote: I once did a collision detection using Numeric. It would take slices out of the data set as it narrowed down the possible collisions. It actually worked pretty well. But the slicing was crazy and hard to follow. I rewrote it in C and it was both faster and more readable.) Carl Banks From gigs at hi.t-com.hr Tue Mar 27 07:29:25 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 27 Mar 2007 13:29:25 +0200 Subject: tkinter MVC Message-ID: Can someone give me example how to write text editor in tkintter with model-view-controler? What goes to controler and what goes to model? thanks in advance From jstroud at mbi.ucla.edu Thu Mar 29 19:41:21 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 29 Mar 2007 16:41:21 -0700 Subject: What are OOP's Jargons and Complexities In-Reply-To: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> References: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> Message-ID: This idiot is a troll. This idiot is a troll. ThThis idiot is a troll. This idiot is a troll. is idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. This idiot is a troll. From superprad at gmail.com Wed Mar 21 14:42:29 2007 From: superprad at gmail.com (PKKR) Date: 21 Mar 2007 11:42:29 -0700 Subject: parsing combination strings Message-ID: <1174502549.103908.129150@b75g2000hsg.googlegroups.com> I need a fast and efficient way to parse a combination string(digits + chars) ex: s = "12ABA" or "1ACD" or "123CSD" etc I want to parse the the above string such that i can grab only the first digits and ignore the rest of the chacters, so if i have s = "12ABA" , parser(s) should give me "12" or "1" or "123". I can think of a quick dirty way by checking each element in the string and do a 'str.isdigit()' and stop once its not a digit, but appreciate any eligent way. From mail at timgolden.me.uk Tue Mar 27 13:42:36 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 27 Mar 2007 18:42:36 +0100 Subject: Auto execute python in USB flash disk In-Reply-To: <1175014574.359563.26630@o5g2000hsb.googlegroups.com> References: <1175014574.359563.26630@o5g2000hsb.googlegroups.com> Message-ID: <4609578C.5040601@timgolden.me.uk> Brian Erhard wrote: > Is there > a way to auto execute a python script after a user double clicks to > open a folder on the USB drive? How can you capture that double click > event on a specific folder? That would depend on what desktop / Operating System you're using. If it's Windows, you need a shell extension (which is non-trivial to understand and write). If it's one of the Linux desktops, someone else had better chip in! TJG From radek.svarz at gmail.com Mon Mar 26 13:29:58 2007 From: radek.svarz at gmail.com (Radek) Date: 26 Mar 2007 10:29:58 -0700 Subject: fetch html page via isa proxy Message-ID: <1174930197.366764.102320@y66g2000hsf.googlegroups.com> Hi, I have been trying several days to get the html page of www.python.org when behind the corporate MS isa proxy. I have tried setting http_proxy environment, played with proxy openers, use ntlm proxy server all without success. I can get the page using Firefox and IE with proxy settings. As the last resort I started to play with pywin32 win32inet, but even the test_win32inet.py does not get there. Any advice? Or better working example? Thanks a lot, Radek From aspineux at gmail.com Thu Mar 29 10:34:47 2007 From: aspineux at gmail.com (aspineux) Date: 29 Mar 2007 07:34:47 -0700 Subject: A nice way to use regex for complicate parsing Message-ID: <1175178887.494344.313070@d57g2000hsg.googlegroups.com> My goal is to write a parser for these imaginary string from the SMTP protocol, regarding RFC 821 and 1869. I'm a little flexible with the BNF from these RFC :-) Any comment ? tests=[ 'MAIL FROM:', 'MAIL FROM:john.smith at address.com', 'MAIL FROM: SIZE=1234 OTHER=foo at bar.com', 'MAIL FROM:john.smith at address.com SIZE=1234 OTHER=foo at bar.com', 'MAIL FROM:<"this at is.a> legal=email"@address.com>', 'MAIL FROM:"this at is.a> legal=email"@address.com', 'MAIL FROM:<"this at is.a> legal=email"@address.com> SIZE=1234 OTHER=foo at bar.com', 'MAIL FROM:"this at is.a> legal=email"@address.com SIZE=1234 OTHER=foo at bar.com', ] def RN(name, regex): """protect using () and give an optional name to a regex""" if name: return r'(?P<%s>%s)' % (name, regex) else: return r'(?:%s)' % regex regex={} # ::= "." "." "." regex['dotnum']=RN(None, r'[012]?\d?\d\.[012]?\d?\d\.[012]?\d?\d\. [012]?\d?\d' % regex) # ::= | "." regex['dot_string']=RN(None, r'[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*' % regex) # ::= | "." regex['domain']=RN('domain', r'%(dotnum)s|%(dot_string)s' % regex) # ::= any one of the 128 ASCII characters except , , quote ("), or backslash (\) regex['q']=RN(None, r'[^\n\r"\\]' % regex) # ::= any one of the 128 ASCII characters (no exceptions) regex['x']=RN(None, r'.' % regex) # ::= "\" | "\" | | regex['qtext']=RN(None, r'(?:\\%(x)s|%(q)s)+' % regex) # ::= """ """ regex['quoted_string']=RN('quoted_string', r'"%(qtext)s"' % regex) # ::= | regex['local_part']=RN('local_part', r'%(quoted_string)s|% (dot_string)s' % regex) # ::= "@" regex['mailbox']=RN('mailbox', r'%(local_part)s@%(domain)s' % regex) # ::= "<" [ ":" ] ">" # also accept address without <> regex['path']=RN('path', r'(?P<)?%(mailbox)s(?(path_lt)>)' % regex) # esmtp-keyword ::= (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") regex['esmtp_keyword']=RN(None, r'[a-zA-Z0-9][-a-zA-Z0-9]*' % regex) # esmtp-value ::= 1* <55h495F250nqbU1@mid.individual.net> <7xhcsssgsm.fsf@ruckus.brouhaha.com> <55ib3rF24d6qgU4@mid.individual.net> Message-ID: <7xbqixd6vo.fsf@ruckus.brouhaha.com> Bjoern Schliessmann writes: > Twisted _is_ asynchronous networking. It also has database classes: > http://twistedmatrix.com/documents/current/api/twisted.enterprise.html I see it uses threads: http://twistedmatrix.com/trac/browser/trunk/twisted/enterprise/adbapi.py#L326 From Leo.Kislov at gmail.com Fri Mar 16 02:31:39 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 15 Mar 2007 23:31:39 -0700 Subject: lock problem In-Reply-To: References: Message-ID: <1174026699.143415.69940@n59g2000hsh.googlegroups.com> On Mar 15, 2:31 pm, Ritesh Raj Sarraf wrote: [snip] > os.environ['__kabc_ldap'] = temp_file_name [snip] > Now as per the above code, "aa" is the first string which will be executed in > Thread-1. In my query to the ldap server, I am getting a record which matches > the "aa" string. I've verified it by putting a breakpoint and checking the > value. > > The problem is that when I run the program manually, I don't get the data from > the first thread i.e. of the string "aa". > > I'm not sure if there's something wrong in the code mentioned above or is it > really a lock problem. > > Can somebody please help about where I'm doing any mistake ? You're changing environmental variable __kabc_ldap that is shared between your threads. Environment is not designed for that kind of usage, it was designed for settings. Either use an option to set output file or just redirect stdout. If the interface of ldapsearch is so lame that it requires environmental variable use env to set the variable: "env __kabc_ldap=/tmp/wrjhdsf ldapsearch ..." -- Leo From gagsl-py2 at yahoo.com.ar Mon Mar 12 23:46:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Mar 2007 00:46:31 -0300 Subject: httplib/socket problems reading 404 Not Found response References: <1173755273.697153.97270@64g2000cwx.googlegroups.com> Message-ID: En Tue, 13 Mar 2007 00:07:55 -0300, Patrick Altman escribi?: > I am attempting to use a HEAD request against Amazon S3 to check > whether a file exists or not and if it does parse the md5 hash from > the ETag in the response to verify the contents of the file so as to > save on bandwidth of uploading files when it is not necessary. > The problem lies when I attempt to send a HEAD request when no file > exists. As expected, a 404 Not Found response is sent back from > Amazon however, my test scripts seem to hang. I run python with > trace.py and it hangs here: Yes, it's a known problem. See this message with a self-response: http://mail.python.org/pipermail/python-list/2006-March/375087.html -- Gabriel Genellina From claird at lairds.us Fri Mar 30 07:46:19 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 30 Mar 2007 11:46:19 +0000 Subject: PyPy for dummies References: <460c5515$0$90269$14726298@news.sunsite.dk> <1175234352.463435.36720@n76g2000hsh.googlegroups.com> Message-ID: In article <1175234352.463435.36720 at n76g2000hsh.googlegroups.com>, Paddy wrote: . . . >It is also European funding for an open source project with sprints. >I'm sure some eurocrat will be dissecting the project to see if it is >aa good way to fund technical projects. > >- Paddy. > PyPy-ers, what *are* the prospects in this direction? Are there write-ups planned that'll be of interest to computing people? From gigs at hi.t-com.hr Tue Mar 20 12:45:31 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 20 Mar 2007 17:45:31 +0100 Subject: P: maticna graficka monitor Message-ID: prodajem: maticnu sapphire am2rd580adv, pola god stara, pod garancijom -> 700kn graficku sapphire x1650 pro 256 mb pola god start pod garancijom -> 600kn monitor philips 190p6es brilliance (kostao 4.100), star 1.5 godinu garancija vrijedi jos 1.5 godinu -> 2000kn From bignose+hates-spam at benfinney.id.au Wed Mar 21 04:02:59 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 21 Mar 2007 19:02:59 +1100 Subject: How to tell easy_install that a package is already installed References: <4600dd4d$0$98624$c30e37c6@lon-reader.news.telstra.net> Message-ID: <87slbz3txo.fsf@benfinney.id.au> Charles Sanders writes: > I am not sure if this is the right forum to ask this. If it is not, > could someone pleas point me to a more appropriate newsgroup. You want the distutils SIG mailing list for Python. Setuptools is an extension of Python's standard distutils. Be sure to read the information links on that page before posting. -- \ "If you get invited to your first orgy, don't just show up | `\ nude. That's a common mistake. You have to let nudity | _o__) 'happen.'" -- Jack Handey | Ben Finney From __peter__ at web.de Thu Mar 1 05:12:24 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Mar 2007 11:12:24 +0100 Subject: splitting perl-style find/replace regexp using python References: <1172741100.414936.269460@q2g2000cwa.googlegroups.com> Message-ID: John Pye wrote: > I have a file with a bunch of perl regular expressions like so: > > /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ # > bold > /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/ > b>''$3/ # italic bold > /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ # > italic > > These are all find/replace expressions delimited as '/search/replace/ > # comment' where 'search' is the regular expression we're searching > for and 'replace' is the replacement expression. > > Is there an easy and general way that I can split these perl-style > find-and-replace expressions into something I can use with Python, eg > re.sub('search','replace',str) ? > > I though generally it would be good enough to split on '/' but as you > see the <\/b> messes that up. I really don't want to learn perl > here :-) How about matching all escaped chars and '/', and then throwing away the former: def split(s): breaks = re.compile(r"(\\.)|(/)").finditer(s) left, mid, right = [b.start() for b in breaks if b.group(2)] return s[left+1:mid], s[mid+1:right] Peter From __peter__ at web.de Fri Mar 2 09:25:49 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Mar 2007 15:25:49 +0100 Subject: Sorting strings containing special characters (german 'Umlaute') References: <1172843975.333807.312130@t69g2000cwt.googlegroups.com> Message-ID: DierkErdmann at mail.com wrote: > I know that this topic has been discussed in the past, but I could not > find a working solution for my problem: sorting (lists of) strings > containing special characters like "?", "?",... (german umlaute). > Consider the following list: > l = ["Aber", "Beere", "?rger"] > > For sorting the letter "?" is supposed to be treated like "Ae", I don't think so: >>> sorted(["Ast", "?rger", "Ara"], locale.strcoll) ['Ara', '\xc3\x84rger', 'Ast'] >>> sorted(["Ast", "Aerger", "Ara"]) ['Aerger', 'Ara', 'Ast'] > therefore sorting this list should yield > l = ["Aber, "?rger", "Beere"] > > I know about the module locale and its method strcoll(string1, > string2), but currently this does not work correctly for me. Consider > >>> locale.strcoll("?rger", "Beere") > 1 > > Therefore "?rger" ist sorted after "Beere", which is not correct IMO. > Can someone help? > > Btw: I'm using WinXP (german) and >>>> locale.getdefaultlocale() > prints > ('de_DE', 'cp1252') The default locale is not used by default; you have to set it explicitly >>> import locale >>> locale.strcoll("?rger", "Beere") 1 >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> locale.strcoll("?rger", "Beere") -1 By the way, you will avoid a lot of "?rger"* if you use unicode right from the start. Finally, for efficient sorting, a key function is preferable over a cmp function: >>> sorted(["Ast", "?rger", "Ara"], key=locale.strxfrm) ['Ara', '\xc3\x84rger', 'Ast'] Peter (*) German for "trouble" From aleax at mac.com Thu Mar 29 03:49:14 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 29 Mar 2007 00:49:14 -0700 Subject: Modal value of an array References: <1175139622.547938.73080@o5g2000hsb.googlegroups.com> <877it0u2h4.fsf@benfinney.id.au> Message-ID: <1hvpovd.1anin2by4gjl1N%aleax@mac.com> Ben Finney wrote: ... > That's not the only case though. What do you expect to be returned for > an input of ["eggs", "beans", "beans", "eggs", "spam"] ? > > Assuming you want *a* mode value, and any one will do (e.g. any of > "spam", "eggs" or "beans" is okay), I'd write it this way as a first > guess: > > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >>> counts = [(foo.count(val), val) for val in set(foo)] > >>> counts > [(2, 'eggs'), (1, 'beans'), (4, 'spam')] > >>> sorted(counts)[-1] > (4, 'spam') > >>> sorted(counts)[-1][1] > 'spam' A bit more directly: >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] >>> max(foo, key=foo.count) 'spam' Alex From bj_666 at gmx.net Thu Mar 29 13:57:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 29 Mar 2007 19:57:13 +0200 Subject: Best way to wait for string input References: <1175189403.036584.239880@o5g2000hsb.googlegroups.com> Message-ID: In <1175189403.036584.239880 at o5g2000hsb.googlegroups.com>, kevinliu23 wrote: > Python newbie here for some expert help. So basically I want to design > a menu system that waits for a string input. I'm not sure what the > best way of going about this is. The current system waits for a single > character input using msvcrt.kbhit( ) and msvcrt.getch( ). Is there > something equivalent to wait for string inputs? The builtin `raw_input()`? Ciao, Marc 'BlackJack' Rintsch From Allerdyce.John at gmail.com Tue Mar 20 00:48:36 2007 From: Allerdyce.John at gmail.com (John) Date: 19 Mar 2007 21:48:36 -0700 Subject: How to calculate a file of equations in python Message-ID: <1174366116.474507.298010@b75g2000hsg.googlegroups.com> Hi, I have a text file which contains math expression, like this 134 +234 +234 (i.e. an operation (e.g. '+) and then a number and then a new line). Can you please tell me what is the easiest way to calculate that file? for example the above example should be = 134 + 234 + 234 = 602. Thank you. From jimburton1 at gmail.com Thu Mar 22 10:58:04 2007 From: jimburton1 at gmail.com (jim burton) Date: 22 Mar 2007 07:58:04 -0700 Subject: On Java's Interface (the meaning of interface in computer programing) In-Reply-To: <57idnf5DTKfj55_bnZ2dnUVZ_uzinZ2d@comcast.com> References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> <1174557840.338374.25990@d57g2000hsg.googlegroups.com> <57idnf5DTKfj55_bnZ2dnUVZ_uzinZ2d@comcast.com> Message-ID: <1174575484.699736.260130@n59g2000hsh.googlegroups.com> On 22 Mar, 12:45, Lew wrote: > Jim Burton wrote: > > Or you could stop feeding the trolls. > > People need to stop saying that. The original post was a detailed if incorrect > exposition of Java information. How in the world do you rate that trollish? > > I have absolutely no reason to rate the OP as a troll or their post as trollish. > > -- Lew Oh, in that case welcome to usenet. Take a while to settle in. There's this guy here called Xah and he is a troll. From steve at holdenweb.com Sun Mar 25 17:14:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 25 Mar 2007 17:14:43 -0400 Subject: Multi-line strings with formatting In-Reply-To: References: <1174668885.347602.117970@n59g2000hsh.googlegroups.com> <1174669850.3450.40.camel@dot.uniqsys.com> <1174703993.715410.173780@e65g2000hsc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 23 Mar 2007 19:39:53 -0700, Paul McGuire wrote: > >> (and I'm glad I'm not the only one who uses 'l' for a scratch list >> variable...) > > Yes, and come the revolution, every last one of you will be down the salt > mines. > Better that than up against the wall, I suppose. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From gagsl-py2 at yahoo.com.ar Wed Mar 21 00:15:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 21 Mar 2007 01:15:37 -0300 Subject: How to receive a FILE* from Python under MinGW? References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> Message-ID: En Wed, 21 Mar 2007 00:46:03 -0300, John Pye escribi?: > This is not an option for me, as I want to pass the > FILE* from Python and all the way into into a existing shared-library > code. I can't change the latter; it must work ok with standard fprintf > (etc) functions. You can get the file descriptor from the Python file object using its fileno() method. The file descriptor lives at the OS level, so it's safe to pass around. You can regenerate a new FILE struct (using the other runtime library) with fdopen. -- Gabriel Genellina From Afro.Systems at gmail.com Sat Mar 3 04:22:08 2007 From: Afro.Systems at gmail.com (Tzury) Date: 3 Mar 2007 01:22:08 -0800 Subject: How to query a unicode data from sqlite database Message-ID: <1172913727.974743.208450@p10g2000cwp.googlegroups.com> Can anyone tell the technique of composing a WHERE clause that refer to a unicode data. e.g. "WHERE FirstName = ABCD" where ABCD is the unicoded first name in the form that sqlite will match with its records. From http Wed Mar 21 21:13:11 2007 From: http (Paul Rubin) Date: 21 Mar 2007 17:13:11 -0800 Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <871wjiuz5q.fsf@pobox.com> <1174508599.250404.176510@y66g2000hsf.googlegroups.com> <87slbyt908.fsf@pobox.com> Message-ID: <7xfy7y5bdk.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > You've explained that *linking* to a non-permanent URL would break the > rules. You haven't explained why *pasting in* the text of the post > would break the rules (I don't say it wouldn't break them, I'm just > curious). I've looked into this situation and I advise just not worrying about it for now. The link is likely to be restored pretty soon if it hasn't been already. If not, wait a day or two and then put it back. It was removed along with a zillion other Usenet links because someone got overzealous about spam reversion and turned an automatic script loose that removed all such links indiscriminately, including a lot that there wasn't anything wrong with. There was a discussion on the wiki about it, the person stopped the script, and is now (slowly) undoing the script's removals. From michele.simionato at gmail.com Fri Mar 9 11:55:26 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Mar 2007 08:55:26 -0800 Subject: Is this right? Multiple imports of same module. In-Reply-To: References: Message-ID: <1173459326.494262.19940@64g2000cwx.googlegroups.com> On Mar 9, 5:18 pm, Lou Pecora wrote: > I have noticed that using from xxx import * can lead to problems when > trying to access variables in the xxx module. ``from xxx import *`` is intended to be used in the interactive interpreter only. Michele Simionato From adam at atlas.st Mon Mar 5 16:42:30 2007 From: adam at atlas.st (Adam Atlas) Date: 5 Mar 2007 13:42:30 -0800 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <45ec89a4$0$2349$426a74cc@news.free.fr> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> <45ec89a4$0$2349$426a74cc@news.free.fr> Message-ID: <1173130950.396201.181900@8g2000cwh.googlegroups.com> This could be easily made into a distutils extension (which was my intention all along, though that's not implemented yet). That's not the point. This is not intended as a "way to package source code". It's analogous to bdist, not sdist. The convenience gain is for the users, not (primarily) the developers, of the package. To use an Egg, you have to either put it in your sys.path manually or install setuptools and use it to install the Egg in some global scope. The advantage of Squisher is that you can take a whole package, squish it into one .pyc file, and distribute that. Then, anyone who downloads it can get a simple module file that can be used anywhere a usual .py file can, without editing sys.path or installing it somewhere. (Actually, this could be combined with eggs, since they're just ZIP files. You could use the same file as an egg or as a squished module simply by changing its extension.) ...Or am I missing something obvious about setuptools that already does this and making a fool of myself? :) From jjl at pobox.com Sat Mar 10 19:22:34 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 11 Mar 2007 00:22:34 GMT Subject: Python 2.5 incompatible with Fedora Core 6 - packaging problems again References: Message-ID: <87hcsszl0w.fsf@pobox.com> John Nagle writes: [...] > This kind of nonsense is why hosting companies don't want to support Python. There seems a more obvious reason... > Perl and PHP may be dumb, but they just work. Java has a company behind it. > Python just isn't ready. Which is embarassing, ten years on. [...] I recall similar pain with Perl. The one Perl list I still frequent has regular postings about these kinds of problems (which are rarely answered -- perhaps the maintainers have moved on). My occasional Java experiences have been *far*, *far* worse in this respect that what I've seen with either Perl or Python. Does that tell you much? Not really, and neither do your experiences. John From kevinliu23 at gmail.com Fri Mar 30 11:38:27 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 30 Mar 2007 08:38:27 -0700 Subject: Inserting '-' character in front of all numbers in a string Message-ID: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> Hey guys, I want to be able to insert a '-' character in front of all numeric values in a string. I want to insert the '-' character to use in conjunction with the getopt.getopt() function. Rigt now, I'm implementing a menu system where users will be able to select a set of options like "2a 3ab" which corresponds to menu choices. However, with getopt.getopt(), it'll only return what I want if I input -2a -3ab as my string. I don't want the user have to insert a '-' character in front of all their choices, so I was thinking of accepting the string input first, then adding in the '-' character myself. So my qusetion is, how do I change: "2a 3ab" into "-2a -3ab". Regular expressions? :/ From kibleur.christophe at gmail.com Fri Mar 2 20:12:02 2007 From: kibleur.christophe at gmail.com (Tool69) Date: 2 Mar 2007 17:12:02 -0800 Subject: Newbie Test In-Reply-To: References: Message-ID: <1172884322.248679.278100@n33g2000cwc.googlegroups.com> On 3 mar, 01:44, Nicholas Parsons wrote: > Greetings, > > This is just a test to see if I can post to this mailing list. Can > someone from the list please respond to this email so I know it worked? > > Thanks in advance! > --Nick Hi Nicholas, Does it work for you ? From pabloreda at gmail.com Sat Mar 31 15:18:02 2007 From: pabloreda at gmail.com (pabloreda) Date: 31 Mar 2007 12:18:02 -0700 Subject: Game programming for kids: looking for open source 2D game development kit In-Reply-To: <87slbmq6pe.fsf@rudin.co.uk> References: <460d4f36$0$10784$c3e8da3@news.astraweb.com> <87slbmq6pe.fsf@rudin.co.uk> Message-ID: <1175368682.323305.70490@p15g2000hsd.googlegroups.com> I 'm doing the same in forth... www.reda4.org From nobody at invalid.com Tue Mar 13 12:55:54 2007 From: nobody at invalid.com (Erik Johnson) Date: Tue, 13 Mar 2007 10:55:54 -0600 Subject: struct.pack oddity References: <45f6bd4a$0$6972$afc38c87@> Message-ID: <45f6d7a9$1@nntp.zianet.com> "Dave Opstad" wrote in message news:45f6bd4a$0$6972$afc38c87 at ... > Is the lack of a struct.error when the byte-order mark is at the start > of the format intentional? This seems like a bug to me, but maybe > there's a subtlety here I'm not seeing. I am by no means any sort of expert on this module, but for what it's worth, the behaviour is basically the same for my Python 2.4.3 under Cygwin (except that there is no deprecation warning) and I agree with you: this seems like a bug to me. Or maybe not technically a bug, but the behaviour could be improved. I would expect to get the same struct.error in all three cases: $ python Python 2.4.3 (#1, May 18 2006, 07:40:45) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from struct import * >>> pack('H', 100000) Traceback (most recent call last): File "", line 1, in ? struct.error: short format requires 0<=number<=USHRT_MAX >>> pack('>H', 100000) '\x86\xa0' >>> pack('>> There used to be a form at the bottom left of the main site: www.python.org for reporting bugs, but that now seems to be used only for reporting stuff about the web site itself. The struct module comes from struct.dll, so I can't see any comments about who wrote or maintains that module. Barring anyone else disagreeing with classifying it as a bug, I would suggest reporting it. Proper procedure for reporting a bug appears to be covered in section B of the Python Library Reference: http://docs.python.org/lib/reporting-bugs.html Hope that helps, -ej From martinunsal at gmail.com Mon Mar 5 11:32:34 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 5 Mar 2007 08:32:34 -0800 Subject: Project organization and import In-Reply-To: <87mz2s32rb.fsf@gmail.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> Message-ID: <1173112353.210937.214020@v33g2000cwv.googlegroups.com> Jorge, thanks for your response. I replied earlier but I think my response got lost. I'm trying again. On Mar 4, 5:20 pm, Jorge Godoy wrote: > Why? RCS systems can merge changes. A RCS system is not a substitute for > design or programmers communication. Text merges are an error-prone process. They can't be eliminated but they are best avoided when possible. When refactoring, it's much better to move small files around than to move chunks of code between large files. In the former case your SCM system can track integration history, which is a big win. > Unit tests help being sure that one change doesn't break the project as a > whole and for a big project you're surely going to have a lot of those tests. But unit tests are never an excuse for error prone workflow. "Oh, don't worry, we'll catch that with unit tests" is never something you want to say or hear. > I don't reload... When my investigative tests gets bigger I write a script > and run it with the interpreter. It is easy since my text editor can call > Python on a buffer (I use Emacs). That's interesting, is this workflow pretty universal in the Python world? I guess that seems unfortunate to me, one of the big wins for interpreted languages is to make the development cycle as short and interactive as possible. As I see it, the Python way should be to reload a file and reinvoke the class directly, not to restart the interpreter, load an entire package and then run a test script to set up your test conditions again. Martin From aleax at mac.com Tue Mar 6 01:06:44 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 5 Mar 2007 22:06:44 -0800 Subject: Project organization and import References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <45ec933a$0$15549$426a34cc@news.free.fr> Message-ID: <1huivd7.7l18eh1paqp0aN%aleax@mac.com> Bruno Desthuilliers wrote: > >>I don't reload... When my investigative tests gets bigger I write a script > >>and run it with the interpreter. It is easy since my text editor can call > >>Python on a buffer (I use Emacs). > > > > That's interesting, is this workflow pretty universal in the Python > > world? > > I don't know, but that's also mostly how I do work. My favorite way of working: add a test (or a limited set of tests) for the new or changed feature, run it, check that it fails, change the code, rerun the test, check that the test now runs, rerun all tests to see that nothing broke, add and run more tests to make sure the new code is excellently covered, rinse, repeat. Occasionally, to ensure the code stays clean, stop to refactor, rerunning tests as I go. I'm also keen on bigger tests (integration tests, as well as system tests for regressions, acceptance, etc), but of course I don't run those anywhere as frequently (they're not part of my daily workflow, iterated multiple times per day -- more like a "nightly run" kind of thing, or for special occasions such as just before committing into HEAD... I'm somewhat of a stickler about HEAD *always* passing *all* tests...). Not exactly TDD, please note -- I tend to start the cycle with a few tests (not strictly just one), implement some large chunk of the new/changed stuff, and add "coverage" and "boundary cases" tests towards the end of the cycle (more often than not I don't need further changes to satisfy the coverage and boundary-case tests, because of the "large chunk" thing). So, a TDD purist would blast me for heresy. Nevertheless, having tried everything from pure TDD to papertrail-heavy waterfall (including the "toss the bits over the wall to QA", shudder!) to typical Chaos Driven Development, in over a quarter century of experience, this almost-TDD is what works best for me -- in Python, C, and C++, at least (it's been a long time, if ever, since I did enough production Java, Haskell, Ruby, SML, assembly, Perl, bash, Fortran, Cobol, Objective C, Tcl, awk, Scheme, PL/I, Rexx, Forth, Pascal, Modula-2, or Basic, to be sure that the same approach would work well in each of these cases, though I have no reason to think otherwise). Alex From godzillaismad at gmail.com Fri Mar 23 20:44:15 2007 From: godzillaismad at gmail.com (Godzilla) Date: 23 Mar 2007 17:44:15 -0700 Subject: Create new processes over telnet in XP In-Reply-To: <1174658259.620897.171480@o5g2000hsb.googlegroups.com> References: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> <1174658259.620897.171480@o5g2000hsb.googlegroups.com> Message-ID: <1174697054.986447.310890@l75g2000hse.googlegroups.com> On Mar 24, 12:57 am, "Rob Wolfe" wrote: > Godzilla wrote: > > Hello, > > > How do you create/spawn new processes in XP over telnet using python? > > I.e. I would like to create a new process and have it running in the > > background... when I terminate the telnet connection, I would what the > > spawned processes to keep running until I shut it off... > > > I got the os.popen method to spawn a new process running in the > > backgroun, but not over telnet... tried os.popen[2, 3, 4] and also > > subprocesses.popen without any luck... > > I don't know what kind of OS there is on that remote host you telnet > to. > The idea boils down to appropriate using of methods > `read_until` and `write` from class `telnetlib.Telnet`. > > For more complicated stuff you can consider using pyexpect. > > Here is a small example of connecting to HP-UX. > You can adjust that to your needs. > > > import telnetlib, time > > def login(tn, login, passwd, prompt): > tn.read_until("login: ") > tn.write(login + "\n") > if passwd: > tn.read_until("Password: ") > tn.write(passwd + "\n") > tn.read_until(prompt) > time.sleep(2) > print "logged in" > > def run_proc(tn, progname): > tn.write("nohup %s &\n" % progname) > tn.write("exit\n") > print "program <%s> running" % progname > > def kill_proc(tn, login, prompt, progname): > tn.write("ps -u %s\n" % login) > buf = tn.read_until(prompt) > pid = get_pid(buf, progname) > if not pid: > print "program <%s> not killed" % progname > tn.write("exit\n") > return > tn.write("kill -TERM %s\n" % pid) > tn.write("exit\n") > print "program <%s> killed" % progname > > def get_pid(buf, progname): > pid, comm = None, None > for line in buf.split("\n"): > try: > pid, _, _, comm = line.split() > except ValueError: > continue > if comm == progname: > return pid > > tn = telnetlib.Telnet(HOST, PORT) > #tn.set_debuglevel(1) > login(tn, "login", "passwd", "/home/user") > run_proc(tn, "python ~/test.py") > #kill_proc(tn, "login", "/home/user", "python") > > > -- > HTH, > Rob Thanks guys for your input... Rob, I will give your example a go soon and tell you how i go... Have a nice day... From nick at craig-wood.com Sat Mar 31 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 31 Mar 2007 04:30:04 -0500 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: Hendrik van Rooyen wrote: > "Nick Craig-Wood" wrote: > > > I'd like there to be something which works well enough for day to day > > use. Ie doesn't ever wreck the internals of python. It could have > > some caveats like "may not timeout during C functions which haven't > > released the GIL" and that would still make it very useable. > > I second this (or third or whatever if my post is slow). > It is tremendously useful to start something and to be told it has timed > out by a call, rather than to have to unblock the i/o yourself and > to "busy-loop" to see if its successful. Yes, exactly! > And from what I can see the select functionality is not much > different from busy looping... Conceptually it is no different. In practice your process goes to sleep until the OS wakes it up again with more data so it is much more CPU efficient (and possibly lower latency) than busy waiting. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jrpfinch at gmail.com Fri Mar 23 08:40:22 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 23 Mar 2007 05:40:22 -0700 Subject: Cleanly exiting multi thread application on SIGINT Message-ID: <1174653622.239148.185270@y80g2000hsf.googlegroups.com> Is the following the most elegant way to exit a multi-threaded application on a Ctrl-C? I am a complete beginner and would have thought there was some way of doing it without having to use while 1: pass, but have yet to find a way. N.B. exit() is a method for cleanly exiting the thread using a queue. Many thanks Jon def main: wt = workerThread() wt.setDaemon(True) wt.start() ct = counterThread() ct.setDaemon(True) ct.start() try: while 1: pass except KeyboardInterrupt: wt.exit() ct.exit() From kadarlakiran at yahoo.com Fri Mar 2 23:42:55 2007 From: kadarlakiran at yahoo.com (kadarla kiran kumar) Date: Fri, 2 Mar 2007 20:42:55 -0800 (PST) Subject: implementing SFTP using Python Message-ID: <683868.19200.qm@web38806.mail.mud.yahoo.com> Hi Everybody, I have to implement SFTP conection from client to the server using Python script. Iam very new new to python , and i dont't have much time to complete this. So I need some pointers from you. If anybody has already done this kind of stuff, please let me know. Please don't think Iam over ambitious, but i need some kind of Pseudo code ,if possible source code. Thanks in Advance, K.Kiran Kumar --------------------------------- Never Miss an Email Stay connected with Yahoo! Mail on your mobile. Get started! -------------- next part -------------- An HTML attachment was scrubbed... URL: From s99999999s2003 at yahoo.com Tue Mar 20 02:08:29 2007 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 19 Mar 2007 23:08:29 -0700 Subject: using regexp In-Reply-To: References: <1174368793.835787.57710@e1g2000hsg.googlegroups.com> <45FF7646.5030801@ncee.net> Message-ID: <1174370909.824252.98750@p15g2000hsd.googlegroups.com> On Mar 20, 1:57 pm, Shane Geiger wrote: > import re > line = '123456789123456789' > print re.findall('([0-9]{3})', line) > > > > Shane Geiger wrote: > > You don't even need regex. > > > def > > split_seq(seq,size): > > > # this is sort of the inverse of > > flatten > > > # Source: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 > > > return [seq[i:i+size] for i in range(0, len(seq), > > size)] > > > line = > > '123456789123456789' > > > print > > split_seq(line,3) > > > Will that work for you? > > > s99999999s2... at yahoo.com wrote: > >> hi > >> how can i use regexp to group these digits into groups of 3? > > >> eg > >> line 123456789123456789 > > >> i have : > > >> pat = re.compile("line\s+(\d{3})" , re.M|re.DOTALL) > > >> but this only gives the first 3. I also tried > > >> "line\s+(\d{3})+" > >> but also not working. > >> I need output to be ['123' ,'456','789', '123','456','789', .....] > >> thanks. > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgei... at ncee.net | 402-438-8958 | http://www.ncee.net > > Leading the Campaign for Economic and Financial Literacy > > sgeiger.vcf > 1KDownload hi thanks. I know it can be done without regexp, but its just for learning purpose, i want to use regexp eg someword 123456789123456789 #this is a line of a file. 'someword' is a word before the digits I need to get the digits into groups of 3 based on whether i found 'someword'. so i use this pattern : "someword\s+(\d{3})" but this will on give me the first 3. I need to group them all. hope i explain it clearly. From steven.bethard at gmail.com Thu Mar 1 15:11:50 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Mar 2007 13:11:50 -0700 Subject: class declaration shortcut In-Reply-To: <1172779488.418564.90880@j27g2000cwj.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172748388.475530.57570@k78g2000cwa.googlegroups.com> <1172772214.569734.95990@n33g2000cwc.googlegroups.com> <1172779488.418564.90880@j27g2000cwj.googlegroups.com> Message-ID: Arnaud Delobelle wrote: >>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 [snip] > Although I don't see the necessity of a metaclass: you could have > > class Record(object): > def __init__(self, *vals): > for slot, val in zip(self.__slots__, vals): > setattr(self, slot, val) > # And the other methods > > if you want positional slots initialisation. I chose keyword > arguments in mine You could certainly do it that way, but note that the one with the metaclass not only allows *either* positional or keyword arguments, but also displays better help messages -- using the *vals or **vals code, help() will tell you something like: __init__(self, **vals) while using the metaclass-generated __init__, help() will tell you the more informative: __init__(self, name) (Or whatever signature is appropriate given the __slots__.) So no, it's not necessary, but it does have a few advantages. STeVe From tismer at stackless.com Wed Mar 28 18:47:53 2007 From: tismer at stackless.com (Christian Tismer) Date: Thu, 29 Mar 2007 00:47:53 +0200 Subject: how can I clear a dictionary in python In-Reply-To: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> Message-ID: On 29.03.2007, at 00:38, Marko.Cain.23 at gmail.com wrote: > Hi, > > I create a dictionary like this > myDict = {} > > and I add entry like this: > myDict['a'] = 1 > but how can I empty the whole dictionary? Reading the Python docs might help. But before, I would try a dir(myDict). Maybe you will find an easter-egg which has exactly the name you are looking for? cheers - chris From george.sakkis at gmail.com Wed Mar 7 23:06:44 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 7 Mar 2007 20:06:44 -0800 Subject: Bug in python!? persistent value of an optional parameter in function! In-Reply-To: <7xy7m8beo9.fsf@ruckus.brouhaha.com> References: <1173321560.973941.158250@h3g2000cwc.googlegroups.com> <7xfy8gqwof.fsf@ruckus.brouhaha.com> <7xy7m8beo9.fsf@ruckus.brouhaha.com> Message-ID: <1173326803.964461.187980@8g2000cwh.googlegroups.com> On Mar 7, 10:24 pm, Paul Rubin wrote: > John Nagle writes: > > True. It would make sense to disallow mutable values as > > initial values for optional arguments. The present behavior is silly. > > That would be the worst of both worlds. The main alternative to the > present behavior is re-computing the default value every time the > function is entered. One can do this is today's Python if he's so inclined, albeit with a more verbose syntax: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502206 George From aleax at mac.com Thu Mar 1 10:55:12 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Mar 2007 07:55:12 -0800 Subject: How to Read Bytes from a file References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1hu9p0u.1rc19sp19r95zhN%aleax@mac.com> <45e6bc1b$0$6835$4d3efbfe@news.sover.net> Message-ID: <1huadvz.gpi9w517yqah5N%aleax@mac.com> Leif K-Brooks wrote: > Alex Martelli wrote: > > You should probaby prepare before the loop a mapping from char to number > > of 1 bits in that char: > > > > m = {} > > for c in range(256): > > m[c] = countones(c) > > Wouldn't a list be more efficient? > > m = [countones(c) for c in xrange(256)] Yes, or an array.array -- actually I meant to use m[chr(c)] above (so you could use the character you're reading directly to index m, rather than calling ord(byte) a bazillion times for each byte you're reading), but if you're using the numbers (as I did before) a list or array is better. Alex From dbhbarton at googlemail.com Fri Mar 9 06:01:45 2007 From: dbhbarton at googlemail.com (dbhbarton at googlemail.com) Date: 9 Mar 2007 03:01:45 -0800 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: <55cs24F23meg4U1@mid.individual.net> References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <1173436274.346506.200920@q40g2000cwq.googlegroups.com> <55cs24F23meg4U1@mid.individual.net> Message-ID: <1173438105.600342.243200@n33g2000cwc.googlegroups.com> >Those characters have no syntactical meaning... ? Neither does # until you give it syntactical meaning. I must be missing what you mean. > would, IMHO, make the language "dirty". Well I'm not a big fan of decorators so I know how you must feel. But # FIXME + a hack doesn't seem clean to me. And commenting off the bottom half of a long script with triple quotes is ugly and a pain and you can't indicate multiple alternate halt points as in the 'tutorial script' example I gave. From MonkeeSage at gmail.com Mon Mar 5 20:06:00 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 17:06:00 -0800 Subject: Interface Implementation in Python In-Reply-To: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> References: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> Message-ID: <1173143160.035896.231320@64g2000cwx.googlegroups.com> On Mar 5, 6:25 pm, p_sha... at yahoo.com wrote: > Hi, > > I would like to know the interface concept in Python.How the > Interface is defined and implemented in Python?. > > How to access the interface fromn Client? > > Thanks > PSB Not sure exactly what you mean, but in python (like most dynamic languages) an "interface" is simply a behavioral type system. Any object can implement an interface, based on its signature. For example; let's say you have a file object which implements read() and write(). Any other object with a sufficiently similar signature (e.g., StringIO), can be said to implement the same interface. An interface in python is simply a specified behavior, and any object which implements that behavior can be said to have the same "interface". HTH, Jordan From sergio.correia at gmail.com Wed Mar 7 20:06:59 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 7 Mar 2007 20:06:59 -0500 Subject: Flatten a two-level list --> one liner? In-Reply-To: References: Message-ID: O_o List comprehensions never cease to amaze me. Thanks, On 3/7/07, Gabriel Genellina wrote: > En Wed, 07 Mar 2007 21:41:16 -0300, Sergio Correia > escribi?: > > > I forgot to say: I've already checked the discussions about > > recursive/iterative/etc flatten() functions that can sweep through a > > list of arbitrary length, but that's really overkill for what I want. > > > > However, "sum(eggs, [])" or itertools seem to do it w/out the need for > > a new function. > > > > Thanks a lot! > > Just for being (a little!) constructive, given your preconditions on the > list, you can use: > eggs = [item for sublist in spam for item in sublist] > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjdevnull at yahoo.com Thu Mar 29 15:16:20 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Mar 2007 12:16:20 -0700 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: References: Message-ID: <1175195780.328033.307730@l77g2000hsb.googlegroups.com> On Mar 28, 5:36 pm, Jarek Zgoda wrote: > Carl Friedrich Bolz napisa?(a): > > > Welcome to the PyPy 1.0 release - a milestone integrating the results > > of four years of research, engineering, management and sprinting > > efforts, concluding the 28 months phase of EU co-funding! > > So it took 4 yars of work and over 2 yaers of consumption of EU funds, > yeah, great. > > Could anybody explain, what this gives to Python and its users? Would > we, eventually, get GIL-free VM, that is capable to consume all > available power of multicore processors? That is the eventual hope, along with a faster Python interpreter (with a true functional JIT), and stackless features, and more easily developed syntax, and retargetable front- and back- ends (allowing, e.g. easier development of Python on the .NET CLI, JVM, etc, or other languages like Javascript, Lisp, or whatever on the PyPy VM), and fast extensions written in RPython instead of C, and many other features. From psdasilvaX at esotericaX.ptX Fri Mar 9 23:23:11 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Sat, 10 Mar 2007 04:23:11 +0000 Subject: bisect on a list of lists In-Reply-To: References: <1173471342.957772@iceman.esoterica.pt> <1173486322.393479@iceman.esoterica.pt> Message-ID: <1173500591.747311@iceman.esoterica.pt> Gabriel Genellina escreveu: ... > Just omit the __init__ method, if you don't have anything additional to > do. The inherited method will be used instead, as always: Then, if I have something additional, I can do def __init__(self,l=None): if l!=None: list.__init__(self,l) ... Good! This is great! Thanks. From rkmr.em at gmail.com Sun Mar 18 23:40:58 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 18 Mar 2007 20:40:58 -0700 Subject: list comprehension help In-Reply-To: <1174269687.497013.249480@o5g2000hsb.googlegroups.com> References: <1174269687.497013.249480@o5g2000hsb.googlegroups.com> Message-ID: On 18 Mar 2007 19:01:27 -0700, George Sakkis wrote: > On Mar 18, 12:11 pm, "rkmr... at gmail.com" wrote: > > I need to process a really huge text file (4GB) and this is what i > > need to do. It takes for ever to complete this. I read some where that > > "list comprehension" can fast up things. Can you point out how to do > > it in this case? > > thanks a lot! > > > > f = open('file.txt','r') > > for line in f: > > db[line.split(' ')[0]] = line.split(' ')[-1] > > db.sync() > You got several good suggestions; one that has not been mentioned but > makes a big (or even the biggest) difference for large/huge file is > the buffering parameter of open(). Set it to the largest value you can > afford to keep the I/O as low as possible. I'm processing 15-25 GB Can you give example of how you process the 15-25GB files with the buffering parameter? It will be educational to everyone I think. > files (you see "huge" is really relative ;-)) on 2-4GB RAM boxes and > setting a big buffer (1GB or more) reduces the wall time by 30 to 50% > compared to the default value. BerkeleyDB should have a buffering > option too, make sure you use it and don't synchronize on every line. I changed the sync to once in every 100,000 lines. thanks a lot everyone! From giles_brown at hotmail.com Thu Mar 8 04:55:55 2007 From: giles_brown at hotmail.com (Giles Brown) Date: 8 Mar 2007 01:55:55 -0800 Subject: How to build a Windows service using win32? In-Reply-To: References: Message-ID: <1173347755.339145.194810@64g2000cwx.googlegroups.com> On 7 Mar, 16:45, "Gregor Mosheh" wrote: > Giles Brown wrote: > > Yeah. You've cleverly decided to simplify the "smallest > > possible python service" by removing the > > if __name__ == '__main__': > > Ha ha. :) > Seriously, though, I removed that long after it was failing to work, and > have since replaced it and it didn't affect a thing. Thats "didn't affect a thing" in the sense of "it was still broken but so it didn't *affect a thing* when something else about it was broken"? Yeah? For the record I'm pretty confident that the "if __name__ == '__main__':" is necessary to stop the module attempting to handle the command line with the pythonservice.exe looks to import the service class when you start the service via the SCM. Anyway you've got it working now so thats the main thing. Giles From hardcoded.software at gmail.com Wed Mar 21 21:56:02 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 21 Mar 2007 18:56:02 -0700 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: References: Message-ID: <1174528562.192439.84480@l77g2000hsb.googlegroups.com> On Mar 21, 9:24 pm, Steve Holden wrote: > Marcin Ciura wrote: > > Steven D'Aprano wrote: > >>>>> x, y, z = 1, 2, 3 > >>>>> x = y = z > >>>>> x, y, z > >> (3, 3, 3) > > >> I certainly wouldn't expect to get (2, 3, 3). > > > Neither would I. I must have expressed myself not clearly enough. > > Currently > > x = y = z > > is roughly equivalent to > > x = z > > y = z > > I propose to change it to > > y = z > > x = z > > Cheers, > > Marcin > > The difference being ... ? > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Recent Ramblings http://holdenweb.blogspot.com I think I see what Marcin means. The 'node' is changed too fast in the chain, and next is assigned to 'nextnode' instead of being assigned to node. >>> class Node: ... pass ... >>> node = Node() >>> nextnode = Node() >>> backup_node = node >>> node = node.next = nextnode >>> node.next is node True >>> hasattr(backup_node,'next') False From kyosohma at gmail.com Fri Mar 16 14:43:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Mar 2007 11:43:41 -0700 Subject: Finding the insertion point in a list In-Reply-To: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> Message-ID: <1174070621.850109.27230@l75g2000hse.googlegroups.com> On Mar 16, 12:59 pm, tkp... at hotmail.com wrote: > I have an ordered list e.g. x = [0, 100, 200, 1000], and given any > positive integer y, I want to determine its appropriate position in > the list (i.e the point at which I would have to insert it in order to > keep the list sorted. I can clearly do this with a series of if > statements: > > if y n = 0 > elif y < x[2]: > n = 1 > elif y < x[3]: > n = 2 > else: > n = 3 > > Or with a generator comprehension > n = sum ( y>x[i] for i in range(len(x)) ) - 1 > > But there has to be a cleaner way, as the first approach is unwieldy > and does not adapt to changing list lengths, and the second is not > obvious to a casual reader of the code. > > My list will typically have 2 to 5 items, so speed is not a huge > issue. I'd appreciate your guidance. > > Sincerely > > Thomas Philips One way to do this would be to use the cmp built-in and loop over the items in the list. Maybe something like this: x = [0, 100, 200, 1000] numLst = len(x) count = 0 for i in range(numLst): resultOfCmp = cmp(newNum, x[count]) if resultOfCmp == -1: print i x.insert(count, newNum) break count += 1 # Where newNum is the one to be inserted. It's a hack, but it might get the ol' creative juices flowing. Mike From claird at lairds.us Tue Mar 27 07:32:24 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 27 Mar 2007 11:32:24 +0000 Subject: Fortran vs Python - Newbie Question References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <1174918424.125068.176920@y80g2000hsf.googlegroups.com> <7o4ld4-qrv.ln1@lairds.us> <1174958090.292094.168150@e65g2000hsc.googlegroups.com> Message-ID: <8vbnd4-ulb.ln1@lairds.us> In article <1174958090.292094.168150 at e65g2000hsc.googlegroups.com>, Beliavsky wrote: . . . >Your experience with Fortran is dated -- see below. > >> >> I'll be more clear: Fortran itself is a distinguished >> language with many meritorious implementations. It can be >> costly, though, finding the implementation you want/need >> for any specific environment. > >Gfortran, which supports Fortran 95 and a little of Fortran 2003, is >part of GCC and is thus widely available. Binaries for g95, also based >on GCC, are available for more than a dozen platforms, including >Windows, Mac OS X, and Linux. I use both and consider only g95 mature, >but gfortran does produce faster programs. Intel's Fortran compilers >cost about $500 on Windows and Mac OS and $700 on Linux. It's not >free, but I would not call it costly for professional developers. > >Speaking of money, gfortran and g95 have free manuals, the latter >available in six languages >http://ftp.g95.org/ . Final drafts of Fortran standards, identical to >the official ISO standards, are freely available. The manual for Numpy >costs $40 per copy. > My experience with Fortran is indeed dated. However, I still work with university groups that balk at $500 for valuable software--sometimes because of admini- strative conflicts with licensing (example: the group needs an educational license that fits its team perfectly, but educational license have to be approved by a campus-wide office that involves the group in expenses uncovered by its grants, and ... complications ensue). Intel's compiler, for example, is a great deal, and recognized as a trivial expense sometimes--but judged utterly impossible by a research group down a different corridor. My summary: practical success depends on specific details, and specific details in the Fortran and Python worlds differ. Also, Beliavsky, thanks for your report on the pertinent Fortran compilers. There *are* other proprietary Fortan compilers extant; do you expect them to fade away, leaving only g* and Intel, or are you simply remarking on those two as the (intellectual) market leaders? From ptmcg at austin.rr.com Sat Mar 17 18:26:59 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 17 Mar 2007 15:26:59 -0700 Subject: Still the __new__ hell ... In-Reply-To: <1174167360.522350@jubilee.claranet.pt> References: <1174167360.522350@jubilee.claranet.pt> Message-ID: <1174170419.213275.213890@e1g2000hsg.googlegroups.com> On Mar 17, 4:31 pm, Paulo da Silva wrote: > Sorry to put here too many questions about __init__ __new__ > stuff but I always found a new problem when using them. > I have searched for simple __new__ docs on how to do the > basic things but find none. > > After trying the solutions people gently posted here > (thanks) I run into new trouble when I go with further > development. > > Here is the new situation. > > As suggested in a previous post, I used __new__ to > subclass date class but now cPickle/pickle loads > does not work. > > from datetime import date > import cPickle,string > > class MyDate(date): > def __new__(cls,year,month=None,day=None): > if type(year) is str: > year,month,day=map(int,string.split(year,'-')) > if year<100: > year+=2000 > return date.__new__(cls,year,month,day) > > class C1(object): > def __init__(self): > self.x=MyDate("2007-3-15") > > def f(self): > print self.x > > c1=C1() > > d=cPickle.dumps(c1) > c2=cPickle.loads(d) > c2.f() > > 1. year is passed to __new__ as a string but with invalid > contents! > > 2. If I had a __new__ in class C1, cPickle.loads invokes it > with only one parameter. This forces to allow __new__ accept > only 1 parameter (cls) which I don't want for the normal > situation. > > Thanks for your patience. > Paulo Any special reason you have to use __new__ for this factory method? This version works, without the problems with __new__: def getDate(*args): if isinstance(args[0],basestring): year,month,day = map(int,string.split(args[0],'-')) else: year,month,day = args if year < 100: year += 2000 return date(year,month,day) class C1(object): def __init__(self): #self.x=MyDate("2007-3-15") self.x = getDate("2007-3-15") def f(self): print self.x -- Paul From mailmaverick666 at gmail.com Tue Mar 13 05:57:33 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Tue, 13 Mar 2007 15:27:33 +0530 Subject: Starting an external, independent process from a script In-Reply-To: <1173741230.908314.23080@c51g2000cwc.googlegroups.com> References: <1173741230.908314.23080@c51g2000cwc.googlegroups.com> Message-ID: <180b672e0703130257w281a182kc722ad2b705c68f2@mail.gmail.com> You can do something like this: pid = os.fork() if pid != 0: os.execl("mencoder variables here and its arguments") else: continue exec will replace the current child process with the given command and as we are doing fork the command will get executed in a child process.You can also use os.system there On 12 Mar 2007 16:13:51 -0700, Henrik Lied wrote: > > Hi there! > > I'm trying to create a video uploading service (just to learn). The > system is mostly based on Django, but the question I'm looking an > answer for is more related to Python. > > So, the user gets to upload a video file. This can either be a mpg, > avi or mp4-file. When the file is saved to its location, I want to > convert it to FLA (Flash Video). I'm currently using Mplayers > Mencoder, and this works great. The Mencoder is retrieved through > running os.system("mencoder variables here") > > The problem with this is that the user has to wait until the movie is > done encoding until he can go around with his business. I don't look > upon this as ideal. > > So - I want to spawn a new system process. I need some good pointers > on how to do this right. > > Any input? :-) > > Thanks a lot in advance! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Mar 9 07:53:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 09:53:46 -0300 Subject: catching exceptions from an except: block References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173345456.968709.128870@j27g2000cwj.googlegroups.com> <1173426599.403173.49240@v33g2000cwv.googlegroups.com> <1173436219.937145.12550@64g2000cwx.googlegroups.com> <1173438858.819893.268240@n33g2000cwc.googlegroups.com> Message-ID: En Fri, 09 Mar 2007 08:14:18 -0300, Gerard Flanagan escribi?: > Mea culpa. Ego te absolvo in nomine Patris Guidii et Filii Python et Spiritus Sancti Computatorium. -- Gabriel Genellina From phil at riverbankcomputing.co.uk Sun Mar 18 18:07:41 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 18 Mar 2007 22:07:41 +0000 Subject: python QT or python-GTK In-Reply-To: <45fdb561$0$17201$4c368faf@roadrunner.com> References: <45fdb561$0$17201$4c368faf@roadrunner.com> Message-ID: <200703182207.41196.phil@riverbankcomputing.co.uk> On Sunday 18 March 2007 9:55 pm, Jon Van DeVries wrote: > ** All the posts found in google are old. I'm assuming new improvements > have been made to both IDEs. ** > > Please correct me if I'm wrong, I'm a newbie. > > 1. Which one of them requires fewer lines to accomplish the same thing? > from what I understand QT it's just like Borland J-Builder. Meaning, you > want a button, you draw it, then you double-click on it, a window opens up > and you type events and behavior. And with GTK, you just type everything. > > 2. Which one is cross platform? (Linux, MacOS, Windows,etc). > > 3. Which one has more widgets? > > 4. Which one is the easiest to pick up? I tried perl-QT and oh boy that > mother is cryptic. > > 5. Which one has a bigger support community? > > 6. or if you think both pythonQT and PythonGTK are junk please suggest the > one you like/use? I work on a Linux platform with Python 2.4. A good start would be to appreciate that both PyQt and PyGTK are GUI toolkits. Neither are IDEs. Phil From nagle at animats.com Thu Mar 8 00:24:17 2007 From: nagle at animats.com (John Nagle) Date: Thu, 08 Mar 2007 05:24:17 GMT Subject: merits of Lisp vs Python In-Reply-To: References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> Message-ID: <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> Brian Adkins wrote: > alex23 wrote: > >> John Nagle wrote: >> >>> Hosting providers and distro >>> makers aren't concerned over whether Python works. They >>> care if C, C++, Java, PHP, and Perl work, but not Python or LISP. >>> Ask them. >> >> >> Do you have any real experience with recent linux distros? Or with any >> _real_ hosting providers? Do you? You're writing from a gmail account, not your own site. I have four hosting accounts with EZpublishing and a dedicated server at Aplus.net. I spent weeks trying to find a hosting provider that would provide a Python environment that "just works", like everyone does for Perl. What you typically get is a basic Python 2.4, and a refusal to install more packages, because it's so time-consuming. Or a quote of $50 to $150 per hour to install Python packages. There are a very few hosting providers that actually want to provide Python hosting, such as Hard Hat Hosting. But most don't. >> >> Because what you've said is clearly not true. Just because the >> situation isn't as easy _for you_ as you would like, doesn't mean that >> Python is being ignored to the extent you're trying to claim. I don't see any evidence to back up this unsubstantiated claim. John Nagle From jgodoy at gmail.com Sun Mar 4 12:53:58 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 04 Mar 2007 14:53:58 -0300 Subject: How use XML parsing tools on this one specific URL? References: <1173030156.276363.174250@i80g2000cwc.googlegroups.com> Message-ID: <87zm6s3nex.fsf@gmail.com> "seberino at spawar.navy.mil" writes: > I understand that the web is full of ill-formed XHTML web pages but > this is Microsoft: Yes... And Microsoft is responsible for a lot of the ill-formed pages on the web be it on their website or made by their applications. > > http://moneycentral.msn.com/companyreport?Symbol=BBBY > > I can't validate it and xml.minidom.dom.parseString won't work on it. > > If this was just some teenager's web site I'd move on. Is there any > hope avoiding regular expression hacks to extract the data from this > page? It all depends on what data you want. Probably a non-validating parser would be able to extract some things. Another option is pass the page through some validator that can fix the page, like tidy... -- Jorge Godoy From slm_guzel at hotmail.com Sun Mar 25 14:09:54 2007 From: slm_guzel at hotmail.com (gslm) Date: 25 Mar 2007 11:09:54 -0700 Subject: a calendar example Message-ID: <1174846194.616548.210390@p15g2000hsd.googlegroups.com> Hi! I want to do a calendar where pictures on.Can you have any free example like this which can help me ? Regards... From arkanes at gmail.com Tue Mar 6 12:19:52 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Mar 2007 11:19:52 -0600 Subject: Project organization and import In-Reply-To: <1173200953.714165.157200@h3g2000cwc.googlegroups.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <1173119492.198000.252500@v33g2000cwv.googlegroups.com> <1173166500.640781.252520@t69g2000cwt.googlegroups.com> <1173200953.714165.157200@h3g2000cwc.googlegroups.com> Message-ID: <4866bea60703060919u26e8c29clff32dcbbd8521abf@mail.gmail.com> On 6 Mar 2007 09:09:13 -0800, Martin Unsal wrote: > On Mar 6, 6:07 am, "Chris Mellon" wrote: > > Because you're advocating single class per file. > > What I actually said was "Smallest practical functional block." I > never said one class per file, in fact I generally have more than one > class per file. Nonetheless I frequently have a class which has the > same name as the file it's contained in, which is where I start having > trouble. You do? Or do you only have trouble because you don't like using "from foo import Foo" because you need to do more work to reload such an import? > > > What you said was A scan through the > > standard library may be instructive, where there are some modules that > > expose a single class (StringIO, pprint) and others that expose many, > > and some that expose none at all. > > AHA! Here we see the insidious Python package system at work! ;) > > I said "file" and you assume that I am talking about the exposed > namespace. Files should not have to be isomorphic with namespace! A > package that exposes many classes may still use one class per file if > it wants to. > What makes you think that the exposed namespace has to be isomorphic with the filesystem? Further, why do you think doing so is bad? People do it because it's convenient and simple, not because its necessary. Why don't you like filesystems? > > In any > > case, as I hinted at, I prefer an organic, developer driven approach > > to deciding these things, not handed down from above style guidelines. > > PRECISELY. And in the case of Python, package stucture is dictated, > not by a style guideline, but by the design flaws of Python's package > system. > What design flaws are those? Is it because you're trying to have packages as part of your project without installing them on your PYTHONPATH somewhere? If you want to break a module internally into multiple files, then make it a package. To an importer, they're almost indistinguishable. If you want to break a module into multiple packages and then stick the files that make up the package in bizarre spots all over the filesystem, can you give a reason why? From mail at timgolden.me.uk Mon Mar 5 04:44:31 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 05 Mar 2007 09:44:31 +0000 Subject: MS SQL Database connection In-Reply-To: <1173047639.166841.301030@h3g2000cwc.googlegroups.com> References: <1173047639.166841.301030@h3g2000cwc.googlegroups.com> Message-ID: <45EBE67F.5010803@timgolden.me.uk> Hitesh wrote: > Hi currently I am using DNS and ODBC to connect to MS SQL database. > Is there any other non-dns way to connect? If I want to run my script > from different server I first have to create the DNS in win2k3. Here are several ways to connect to an MSSQL database w/o having to create "DNS" or anything else in win2k3 ;) There are other ways (the slightly stale MSSQL module from Object Craft, for example, which still works fine for Python <= 2.3). TJG def adodbapi_connection (server, database, username, password): # # http://adodbapi.sf.net # import adodbapi connectors = ["Provider=SQLOLEDB"] connectors.append ("Data Source=%s" % server) connectors.append ("Initial Catalog=%s" % database) if username: connectors.append ("User Id=%s" % username) connectors.append ("Password=%s" % password) else: connectors.append("Integrated Security=SSPI") return adodbapi.connect (";".join (connectors)) def pymssql_connection (server, database, username, password): # # http://pymssql.sf.net # import pymssql if not username: raise RuntimeError, "Unable to use NT authentication for pymssql" return pymssql.connect (user=username, password=password, host=server, database=database) def pyodbc_connection (server, database, username, password): # # http://pyodbc.sf.net # import pyodbc connectors = ["Driver={SQL Server}"] connectors.append ("Server=%s" % server) connectors.append ("Database=%s" % database) if username: connectors.append ("UID=%s" % username) connectors.append ("PWD=%s" % password) else: connectors.append ("TrustedConnection=Yes") return pyodbc.connect (";".join (connectors)) From nagle at animats.com Sun Mar 25 20:27:45 2007 From: nagle at animats.com (John Nagle) Date: Sun, 25 Mar 2007 17:27:45 -0700 Subject: How to find to HTML strings and 'save' them? In-Reply-To: <1174862657.151504.136350@b75g2000hsg.googlegroups.com> References: <1174842241.781281.72500@p77g2000hsh.googlegroups.com> <874po95hz5.fsf@gmail.com> <1174862657.151504.136350@b75g2000hsg.googlegroups.com> Message-ID: mark at agtechnical.co.uk wrote: > Great, thanks so much for posting that. It's worked a treat and I'm > getting HTML files with the list of h2 tags I was looking for. Here's > the code just to share, what a relief :) : > ............................... > from BeautifulSoup import BeautifulSoup > import re > > page = open("soup_test/tomatoandcream.html", 'r') > soup = BeautifulSoup(page) > > myTagSearch = str(soup.findAll('h2')) > > myFile = open('Soup_Results.html', 'w') > myFile.write(myTagSearch) > myFile.close() > > del myTagSearch > ............................... > > I do have two other small queries that I wonder if anyone can help > with. > > Firstly, I'm getting the following character: "[" at the start, "]" at > the end of the code. Along with "," in between each tag line listing. > This seems like normal behaviour but I can't find the way to strip > them out. Ah. What you want is more like this: page = open("soup_test/tomatoandcream.html", 'r') soup = BeautifulSoup(page) htags = soup.findAll({'h2':True, 'H2' : True}) # get all H2 tags, both cases myFile = open('Soup_Results.html', 'w') for htag in htags : # for each H2 tag texts = htag.findAll(text=True) # find all text items within this h2 s = ' '.join(texts).strip() + '\n' # combine text items into clean string myFile.write(s) # write each text from an H2 element on a line. myFile.close() John Nagle From michael at jedimindworks.com Thu Mar 29 08:22:50 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 29 Mar 2007 07:22:50 -0500 Subject: Weird behavior in search in a list In-Reply-To: <1175169060.414834.235040@d57g2000hsg.googlegroups.com> References: <1175169060.414834.235040@d57g2000hsg.googlegroups.com> Message-ID: <6E125C32-13B7-4267-8CA3-6D2BF21D4F81@jedimindworks.com> On Mar 29, 2007, at 6:51 AM, Su Y wrote: > > I want find the first number in extend[] which is larger than num, so > I wrote: > def find(num): > count=0 > for elem in extend: > if elem count+=1 > return count > > I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5, > 5.6], > it works fine: find(4) returns 3, extend[3] is 4.5. > But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6, > 4.6, 3.4, 2.1, 0.3], > find(4) returns 6, extend[6] is 3.4! > > what's going on here? I really can't understand.... find() loops through the list, and every time it finds a value less than num it increments count. So in your second example the values 1.1, 2.3, 3.2, 3.4, 2.1, and 0.3 are all less than 4, which means count will be 6. As you learned, a sorted list behaves as you expect. So one approach is to sort your list first. But another perhaps better approach is to do something like: def find(num): # check to make sure there *is* a value greater than num if max(extend) > num: # then return the smallest value that is greater than num return min([x for x in extend if x > num]) else: return None Hope this helps, Michael From rodin.alexander at gmail.com Thu Mar 15 04:35:56 2007 From: rodin.alexander at gmail.com (inline) Date: 15 Mar 2007 01:35:56 -0700 Subject: Constructor of object In-Reply-To: References: <1173894809.887357.165290@p15g2000hsd.googlegroups.com> <1173897975.419864.306930@b75g2000hsg.googlegroups.com> Message-ID: <1173947756.118692.37710@b75g2000hsg.googlegroups.com> Thanks. But can I change returned by xml.get_widget() object type from gtk.Window to HelloWindow? From tjreedy at udel.edu Sat Mar 17 14:46:37 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Mar 2007 14:46:37 -0400 Subject: Odd error References: <1174109684.594766.320600@l77g2000hsb.googlegroups.com><1174123848.763283.54840@e65g2000hsc.googlegroups.com> <1174156377.840487.302740@l75g2000hse.googlegroups.com> Message-ID: wrote in message news:1174156377.840487.302740 at l75g2000hse.googlegroups.com... |I installed it using the regular download form python.org. I went | back and did a lot of testing with the file, commenting out most of | it, seeing what would actually run, and it seems I had a normal | semantic error: | | self.data(one).append(item) | | and data is in fact a dictionary, not a callable object. What gets me | is the massive red herring this error is. I wasn't doing anything | with ntpath in the script. The script selectively extracts | information from an XML file, that's all. When you run a script from IDLE, it saves it to disk, and in the process of saving, IDLE looks at the path. I don't think your script ever ran. At least that is what I gathered from the traceback. I agree with JM: the traceback and error message do not match, so this is indeed an 'odd' error. Terry Jan Reedy From inq1ltd at verizon.net Fri Mar 16 18:15:38 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 16 Mar 2007 18:15:38 -0400 Subject: SQLite3, data not found In-Reply-To: <200703161755.58549.inq1ltd@verizon.net> References: <200703161755.58549.inq1ltd@verizon.net> Message-ID: <200703161815.38314.inq1ltd@verizon.net> from John Clark use con.commit() Thanks John, this works jim-on-linux On Friday 16 March 2007 17:55, jim-on-linux wrote: > Python help, > > I just started working with SQLite3 and ran > into this problem. > > Below, the first select produces results but, > after closing then re-opening the database the > select produces an empty list. Anyone know the > reason ?? > > The table seems to be empty. > > > > import sqlite3 > con = sqlite3.connect('myData') > cursor = con.cursor() > > cursor.execute ("""create table data > (recordNo varchar, > caseNo varchar)"""); > > record = ['A', 'B'] > > cursor.execute("insert into data values (?,?)", > record ) ; > > cursor.execute("select * from data "); > print cursor.fetchall(); > con.close() > > con = sqlite3.connect('myData') > cursor = con.cursor() > cursor.execute("select * from data"); > print cursor.fetchall(); > > > jim-on-linux From gherron at islandtraining.com Thu Mar 15 11:38:34 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 15 Mar 2007 08:38:34 -0700 Subject: Pickle Problem In-Reply-To: <1173971633.305988.207530@d57g2000hsg.googlegroups.com> References: <1173971633.305988.207530@d57g2000hsg.googlegroups.com> Message-ID: <45F9687A.1000601@islandtraining.com> tonyr1988 wrote: > I'm a complete python n00b writing my first program (or attempting to, > anyway). I'm trying to make the transition from Java, so if you could > help me, it would be greatly appreciated. Here's the code I'm stuck on > (It's very basic): > > class DemoClass: > def __init__(self): > self.title = ["Hello", "Goodbye"] > > def WriteToFile(self, path = "test.txt"): > fw = file(path, "w") > pickle.dump(self.title, fw) > fw.close() > > if __name__=='__main__': > x = DemoClass > x.WriteToFile > > It doesn't do any file I/O at all (that I see). I hope my syntax is > alright. If I just call WriteToFile, shouldn't it perform with the > default path? It gives me no errors and pretends to execute just fine. > Several people have pointed out the problem, but when you get that fixed, I see another bit of trouble. The pickle format is a binary format (be default), but you don't open the file in binary mode. On Unix the distinction is (wisely) irrelevant, but on Windows you should open the file with a mode of "wb" not just "w". From arnodel at googlemail.com Tue Mar 13 15:21:54 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 13 Mar 2007 12:21:54 -0700 Subject: Iterating across a filtered list In-Reply-To: <1173809090.092546.255710@64g2000cwx.googlegroups.com> References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> Message-ID: <1173813714.767225.164790@q40g2000cwq.googlegroups.com> On Mar 13, 6:04 pm, "Drew" wrote: > All - Hi! [snip] > http://pastie.caboo.se/46647 There is no need for such a convoluted list comprehension as you iterate over it immediately! It is clearer to put the filtering logic in the for loop. Moreover you recalculate the regexp for each element of the list. Instead I would do something like this: def find(search_str, flags=re.IGNORECASE): print "Contact(s) found:" search = re.compile(search_str, flags).search for name, contact in self.contacts.items(): if search(name): print contact print Although I would rather have one function that returns the list of all found contacts: def find(search_str, flags=re.IGNORECASE): search = re.compile(search_str, flags).search for name, contact in self.contacts.items(): if search(name): yield contact And then another one that prints it. > Side note: I'm learning python after ruby experience. In ruby I would > do something like: > > contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact| > puts contact} And that's why you're right to learn Python ;) HTH -- Arnaud From sjmachin at lexicon.net Wed Mar 14 17:34:36 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 Mar 2007 14:34:36 -0700 Subject: most complete xml package for Python? In-Reply-To: References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> <45F811A3.1050208@web.de> <1173887937.251026.175260@y66g2000hsf.googlegroups.com> Message-ID: <1173908076.351577.75000@n59g2000hsh.googlegroups.com> On Mar 15, 3:45 am, Steve Holden wrote: > Paul Boddie wrote: > > On 14 Mar, 16:15, Stefan Behnel wrote: > >> metaperl wrote: > >>> Without even checking them all out, I'm thinking the Amara XML Toolkit > >>> must be the most feature-packed. > >> Please check out lxml before you post FUD like this. > > >>http://codespeak.net/lxml/ > > > Calm down, Stefan! The inquirer must have got the impression of > > Amara's superiority from somewhere; all you need to do is to discover > > which resource gave that impression and balance the situation out. In > > any case, it's an opinion: there's no fear involved, and the only > > uncertainty and doubt are in the inquirer's mind, which I suppose is > > why they posted the inquiry. > > Although the phrase "without even checking them all out" hardly lends > credence to the OP's assertion of Amara's superiority, and does tend to > support a hypothesis involving some ulterior motive (or would if less > ingenuously done). > Given keywords like "Amara" and "Elementtree" and past history, it looked to me like a troll of one kind trying to incite a troll of another kind to pop out from under the bridge and chew on his ankle :-) From paul at boddie.org.uk Thu Mar 1 05:46:37 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Mar 2007 02:46:37 -0800 Subject: installing "pysqlite" In-Reply-To: <1172741654.589821.255220@v33g2000cwv.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> <1172663495.011225.76410@v33g2000cwv.googlegroups.com> <1172741654.589821.255220@v33g2000cwv.googlegroups.com> Message-ID: <1172745997.863121.96940@8g2000cwh.googlegroups.com> On 1 Mar, 10:34, "Nader" wrote: > > I have expanded the LD_LIBRARY_PATH to my home lib (export > LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/people/emami/lib). > I have built and installed the 'pysqlite-2.3.3' with the next > 'setup.cfg' : > > [build_ext] > define= > include_dirs=/usr/people/emami/include > library_dirs=/usr/people/emami/lib > #libraries=/usr/people/emami/lib/libsqlite3.so (this line as a > comment) This looks alright. Be sure to verify that libsqlite3.so is in /usr/ people/emami/lib, although I suppose you've done this, looking at your comment. > The resutl of this process was: > > running install_lib > copying build/lib.linux-i686-2.4/pysqlite2/_sqlite.so -> /usr/people/ > emami/lib/python2.4/site-packages/pysqlite2 > running install_data > > This message had given after installing. I have controll the '/usr/ > people/emami/lib/python2.4/site-packages/pysqlite2' whether the > '_sqlite.so' has copied there. Yes it has. Okay! So pysqlite2 has installed properly at least. > I go to python and I give the next command: > > >>> from pysqlite import test > > and Unfortunately I get the next error message: [...] > ImportError: /usr/people/emami/lib/python2.4/site-packages/pysqlite2/ > _sqlite.so: undefined symbol: sqlite3_set_authorizer I'm running out of ideas here, but you could try doing this: ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so This should show a list of references to libraries, but if one of them is missing in some way then it means that it isn't found by the linker and it's not on the LD_LIBRARY_PATH. Another thought is that sqlite3_set_authorizer isn't found in the SQLite library - you can test this by doing the following: nm /usr/people/emami/lib/libsqlite3.so I get something like this in response: 00000000000110b0 T sqlite3_set_authorizer If you don't get anything in response or if you see "U" instead of "T", then this might indicate an problem with the way SQLite has been configured. > Do you know what option I have to give to if I want to use the > 'easy_install" tool? > %easy_install pysqlite (with some optione with which it cab find the > installed 'libsqlite.so') I'm no easy_install expert, I'm afraid. You might want to talk to the pysqlite people directly if what I've suggested doesn't help you further: http://www.initd.org/tracker/pysqlite/wiki/pysqlite Paul From hardcoded.software at gmail.com Wed Mar 21 22:13:42 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 21 Mar 2007 19:13:42 -0700 Subject: Python 3000 idea: reversing the order of chained assignments In-Reply-To: References: <1174528562.192439.84480@l77g2000hsb.googlegroups.com> Message-ID: <1174529622.860892.133800@d57g2000hsg.googlegroups.com> On Mar 21, 10:05 pm, Steve Holden wrote: > Virgil Dupras wrote: > > On Mar 21, 9:24 pm, Steve Holden wrote: > >> Marcin Ciura wrote: > >>> Steven D'Aprano wrote: > >>>>>>> x, y, z = 1, 2, 3 > >>>>>>> x = y = z > >>>>>>> x, y, z > >>>> (3, 3, 3) > >>>> I certainly wouldn't expect to get (2, 3, 3). > >>> Neither would I. I must have expressed myself not clearly enough. > >>> Currently > >>> x = y = z > >>> is roughly equivalent to > >>> x = z > >>> y = z > >>> I propose to change it to > >>> y = z > >>> x = z > >>> Cheers, > >>> Marcin > >> The difference being ... ? > >> -- > >> Steve Holden +44 150 684 7255 +1 800 494 3119 > >> Holden Web LLC/Ltd http://www.holdenweb.com > >> Skype: holdenweb http://del.icio.us/steve.holden > >> Recent Ramblings http://holdenweb.blogspot.com > > > I think I see what Marcin means. The 'node' is changed too fast in the > > chain, and next is assigned to 'nextnode' instead of being assigned to > > node. > > >>>> class Node: > > ... pass > > ... > >>>> node = Node() > >>>> nextnode = Node() > >>>> backup_node = node > >>>> node = node.next = nextnode > >>>> node.next is node > > True > >>>> hasattr(backup_node,'next') > > False > > So we should take the already well-defined semantics of assignment and > change them because it seems more obvious to J. Random User? I think I > might be a little concerned about potential code breakage there. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Recent Ramblings http://holdenweb.blogspot.com I totally agree. This assignment is way too ambiguous anyway. Readability first. I just wanted to enlighten the readers on what the problem actually was since it wasn't obvious in the original post. From tew24 at spam.ac.uk Wed Mar 21 09:13:29 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Wed, 21 Mar 2007 13:13:29 +0000 Subject: Garbage collection Message-ID: Hi all I suspect I may be missing something vital here, but Python's garbage collection doesn't seem to work as I expect it to. Here's a small test program which shows the problem on python 2.4 and 2.5: $ python2.5 Python 2.5 (release25-maint, Dec 9 2006, 15:33:01) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> (at this point, Python is using 15MB) >>> a = range(int(1e7)) >>> (at this point, Python is using 327MB) >>> a = None >>> (at this point, Python is using 251MB) >>> import gc >>> gc.collect() 0 >>> (at this point, Python is using 252MB) Is there something I've forgotten to do? Why is Python still using such a lot of memory? Thanks! -- I'm at CAMbridge, not SPAMbridge From carsten at uniqsys.com Fri Mar 23 13:10:50 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 23 Mar 2007 13:10:50 -0400 Subject: Multi-line strings with formatting In-Reply-To: <1174668885.347602.117970@n59g2000hsh.googlegroups.com> References: <1174668885.347602.117970@n59g2000hsh.googlegroups.com> Message-ID: <1174669850.3450.40.camel@dot.uniqsys.com> On Fri, 2007-03-23 at 09:54 -0700, gburdell1 at gmail.com wrote: > When constructing a particularly long and complicated command to be > sent to the shell, I usually do something like this, to make the > command as easy as possible to follow: > > commands.getoutput( > 'mycommand -S %d -T %d ' % (s_switch, t_switch) + > '-f1 %s -f2 %s ' % (filename1, filename2) + > '> %s' % (log_filename) > ) > > Can anyone suggest a better way to construct the command, especially > without the "+" sign at the end of each line (except the last) ? If I > take out the "+", then I need to move all the variables to the end, as > so: > > commands.getoutput( > 'mycommand -S %d -T %d ' > '-f1 %s -f2 %s ' > '> %s' > % (s_switch, t_switch, filename1, filename2, log_filename) > ) > > or: > > commands.getoutput( > '''mycommand -S %d -T %d \ > -f1 %s -f2 %s \ > > %s''' > % (s_switch, t_switch, filename1, filename2, log_filename) > ) You get the best of both worlds, i.e. one big multiline string with in-line parameters, by using a mapping: commands.getoutput( '''mycommand -S %(s_switch)d -T %(t_switch)d \ -f1 %(filename1)s -f2 %(filename2)s \ > %(log_filename)s''' % locals() ) Of course I'm assuming that s_switch etc. are local variables. If they're not, well, they ought to be. -Carsten From exarkun at divmod.com Mon Mar 19 11:59:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 19 Mar 2007 10:59:39 -0500 Subject: Still the __new__ hell ... In-Reply-To: <45fea0b3$0$15544$426a74cc@news.free.fr> Message-ID: <20070319155939.18920.1857970362.divmod.quotient.3961@ohm> On Mon, 19 Mar 2007 15:39:49 +0100, Bruno Desthuilliers wrote: >Jean-Paul Calderone a ?crit : >> On Mon, 19 Mar 2007 13:17:11 +0100, Bruno Desthuilliers >>> >>> [snip] >>> >>> And what if it's a unicode string ? >>> The correct idiom here is: >>> if isinstance(year, basestring): >>> >>>> year,month,day=map(int,string.split(year,'-')) >>> year, month, day = map(int, year.split('-')) >> >> And what if it's another kind of string? > >One that doesn't inherit from basestring ? > >> The correct idiom is: >> >> try: >> parts = year.split('-') >> except AttributeError: >> # Handle int case >> else: >> year, month, day = map(int, parts) >> >>> >>>> if year < 100: >>>> year += 2000 >>>> return date.__new__(cls,year,month,day) >>>> > >And what if it's an object that has nothing to do with a string but >happens to have a split() method ?-) > >>> (snip) > >Jean-Paul, you're of course right from a theoretical POV. Practically >speaking, chances that such a method will ever be fed with a string-like >object not deriving from basestring are IMVHO *very* low. While I >usually raise a big warning flag when I spot a test against >isinstance(), I'd say this is an example of the few cases where it's ok. > YMMV of course... http://mail.python.org/pipermail/python-dev/2005-February/051717.html Jean-Paul From samuel.kortas at gmail.com Wed Mar 21 20:11:32 2007 From: samuel.kortas at gmail.com (Samkos) Date: 21 Mar 2007 17:11:32 -0700 Subject: the second of nested buttons using textvariable remains void! Message-ID: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> Hi there, I am fighting with a problem I intended to believe trivial that I could not solve yet! I am trying to have a button with a variable text, that pops up another button with a variable text when pressed. I did that with the following program in Python, but the second button remains always void!!! is it related to the textvariable parameters? If any of you had a clue, please don't hesitate! in advance, many thanks Samuel #----------------------- program 2 buttons.py -------------------------- from Tkinter import * def go(event): root = Tk() s1=StringVar() s1.set("s1") label1 = Label(root, textvariable=s1) label1.pack(side=LEFT) root.mainloop() root = Tk() s0=StringVar() s0.set("s0") label0 = Label(root, textvariable=s0) label0.pack(side=LEFT) root.bind("",go) root.mainloop() From http Sat Mar 31 01:09:30 2007 From: http (Paul Rubin) Date: 30 Mar 2007 22:09:30 -0700 Subject: Hpw make lists that are easy to sort. References: <7xbqidgqy0.fsf@ruckus.brouhaha.com> Message-ID: <7xtzw2xalx.fsf@ruckus.brouhaha.com> Anton Vredegoor writes: > I want the product, but sorted in less time. If Fourier transforms can > help, I want them :-) Oh, I see what you mean. I don't see an obvious faster way to do it and I don't have the feeling that one necessarily exists. As someone mentioned, you could do an n-way merge, which at least avoids using quadratic memory. Here's a version using Frederik Lundh's trick of representing a lazy list as its head plus the generator for the tail: from heapq import heapify, heappop, heappush import random def sortedsums(L,R): # yield elements of [(i+j) for i in L for j in R] in sorted order # assumes L and R are themselves sorted def lundh(x): g = ((a+x) for a in L) return (g.next(), g) heap = [lundh(x) for x in R] heapify (heap) # not sure this is needed while heap: z,zn = heappop(heap) try: heappush(heap, (zn.next(), zn)) except StopIteration: pass yield z def test(): L = sorted(random.sample(xrange(2000),150)) R = sorted(random.sample(xrange(2000),150)) t = sortedsums(L,R) t2 = sorted([(i+j) for i in L for j in R]) assert list(t) == t2 test() From B.Ogryczak at gmail.com Thu Mar 1 12:46:01 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 1 Mar 2007 09:46:01 -0800 Subject: How to Read Bytes from a file In-Reply-To: <1172764725.827624.298180@j27g2000cwj.googlegroups.com> References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com> <1172757183.819978.219440@v33g2000cwv.googlegroups.com> <1172764725.827624.298180@j27g2000cwj.googlegroups.com> Message-ID: <1172771161.015437.50000@n33g2000cwc.googlegroups.com> On Mar 1, 4:58 pm, "gregpin... at gmail.com" wrote: > On Mar 1, 8:53 am, "Bart Ogryczak" wrote: > > > > > On Mar 1, 7:52 am, "gregpin... at gmail.com" > > wrote: > > > > It seems like this would be easy but I'm drawing a blank. > > > > What I want to do is be able to open any file in binary mode, and read > > > in one byte (8 bits) at a time and then count the number of 1 bits in > > > that byte. > > > > I got as far as this but it is giving me strings and I'm not sure how > > > to accurately get to the byte/bit level. > > > > f1=file('somefile','rb') > > > while 1: > > > abyte=f1.read(1) > > > import struct > > buf = open('somefile','rb').read() > > count1 = lambda x: (x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+ > > (x&64>0)+(x&128>0) > > byteOnes = map(count1,struct.unpack('B'*len(buf),buf)) > > > byteOnes[n] is number is number of ones in byte n. > > This solution looks nice, but how does it work? I'm guessing > struct.unpack will provide me with 8 bit bytes unpack with 'B' format gives you int value equivalent to unsigned char (1 byte). > (will this work on any system?) Any system with 8-bit bytes, which would mean any system made after 1965. I'm not aware of any Python implementation for UNIVAC, so I wouldn't worry ;-) > How does count1 work exactly? 1,2,4,8,16,32,64,128 in binary are 1,10,100,1000,10000,100000,1000000,10000000 x&1 == 1 if x has first bit set to 1 x&2 == 2, so (x&2>0) == True if x has second bit set to 1 ... and so on. In the context of int, True is interpreted as 1, False as 0. From bignose+hates-spam at benfinney.id.au Wed Mar 14 23:05:29 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 Mar 2007 14:05:29 +1100 Subject: distributing python software in jar like fashion References: Message-ID: <87odmv9pfq.fsf@benfinney.id.au> alf writes: > I have a small app which consist of a few .py files. Is there any > way to distribute it in jar like fashion as a single file I can just > run python on. I obviously look for platform independent solution. Python eggs are the platform-independent distributable single-file archive. Given the way Python works, you can't simply execute them as-is; you can, however, easily install them. -- \ "I think it would be a good idea." -- Mahatma Gandhi (when | `\ asked what he thought of Western civilization) | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Wed Mar 7 17:33:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 07 Mar 2007 23:33:00 +0100 Subject: catching exceptions from an except: block In-Reply-To: <1173292373.770519.158490@8g2000cwh.googlegroups.com> References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> Message-ID: <45ef3593$0$7504$426a74cc@news.free.fr> Arnaud Delobelle a ?crit : > Hi all, > > Imagine I have three functions a(x), b(x), c(x) that each return > something or raise an exception. Imagine I want to define a function > that returns a(x) if possible, otherwise b(x), otherwise c(x), > otherwise raise CantDoIt. > > Here are three ways I can think of doing it: > > ---------- > # This one looks ugly Yes. > def nested_first(x): > try: > return a(x) > except: Try avoiding bare except clauses. It's usually way better to specify the type(s) of exception you're expecting to catch, and let other propagate. > try: > return b(x) > except: > try: > return c(x) > except: > raise CantDoIt > > # This one looks long-winded Yes. And not's very generic. > def flat_first(x): > try: > return a(x) > except: > pass > try: > return b(x) > except: > pass > try: > return c(x) > except: > raise CantDoIt > > # This one only works because a,b,c are functions It works with any callable. Anyway, what else would you use here ??? > # Moreover it seems like an abuse of a loop construct to me Why so ? loops are made for looping, adn functions are objects like any other. > def rolled_first(x): > for f in a, b, c: > try: > return f(x) > except: > continue > raise CantDoIt Here's an attempt at making it a bit more generic (it still lacks a way to specify which kind of exceptions should be silently swallowed. def trythese(*functions): def try_(*args, **kw): for func in functions: try: return func(*args, **kw) except: # FIX ME : bare except clause pass else: # really can't do it, sorry raise CantDoIt return try_ result = trythese(a, b, c)(x) > ---------- > # This one isn't correct but looks the clearest to me > def wished_first(x): > try: > return a(x) > except: > return b(x) > except: > return c(x) > except: > raise CantDoIt Having multiple except clauses is correct - but it has another semantic. > Note: I've chosen functions a, b, c, but really I'm looking for a way > that is suitable for any chunk of code. A function is an object wrapping a chunk of code... I personnaly find the loop-based approach quite clean and pythonic. From steven.bethard at gmail.com Thu Mar 1 15:58:01 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Mar 2007 13:58:01 -0700 Subject: class declaration shortcut In-Reply-To: <1172780513.838701.136340@j27g2000cwj.googlegroups.com> References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172748388.475530.57570@k78g2000cwa.googlegroups.com> <1172772214.569734.95990@n33g2000cwc.googlegroups.com> <1172780513.838701.136340@j27g2000cwj.googlegroups.com> Message-ID: <2cOdnUbR46bKo3rYnZ2dneKdnZydnZ2d@comcast.com> Luis M. Gonz?lez wrote: > This is the closest we got so far to the intended result. > If there was a way to enter attributes without quotes, it would be > almost identical. Ok, below is the Python code so that the following works:: class Person(Struct): "name birthday children" Note that * The "Person" name is not repeated * The attribute names are not individually quoted * It's two characters shorter than the Ruby code:: Person = Struct.new(:name, :birthday, :children) Is that good enough? ;-) STeVe class InitFromSlots(type): def __new__(meta, name, bases, bodydict): slots = bodydict.get('__doc__', '').split() bodydict.setdefault('__slots__', slots) if slots and '__init__' not in bodydict: parts = ['def __init__(self, %s):' % ', '.join(slots)] for slot in slots: parts.append(' self.%s = %s' % (slot, slot)) exec '\n'.join(parts) in bodydict super_new = super(InitFromSlots, meta).__new__ return super_new(meta, name, bases, bodydict) class Struct(object): __metaclass__ = InitFromSlots __slots__ = () def _items(self): for name in self.__slots__: yield name, getattr(self, name) def __repr__(self): args = ', '.join('%s=%r' % tup for tup in self._items()) return '%s(%s)' % (type(self).__name__, args) def __iter__(self): for name in self.__slots__: yield getattr(self, name) def __getstate__(self): return dict(self._items()) def __setstate__(self, statedict): self.__init__(**statedict) From paul at subsignal.org Sat Mar 10 06:10:39 2007 From: paul at subsignal.org (paul) Date: Sat, 10 Mar 2007 12:10:39 +0100 Subject: SQLite3 trapping OperationalError In-Reply-To: <200703091314.49199.inq1ltd@verizon.net> References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <200703091314.49199.inq1ltd@verizon.net> Message-ID: jim-on-linux schrieb: > pyhelp, > > I set up a table in SQLite3. > > While running other modules I want to know if a > table exists. > > SQL has a command "List Tables" but I don't think > SQLlite3 has this command. I think "list tables" is a mysqlism > > I've tried > cursor.execute("select * from debtor where key > is not null ") FROM sqlite_master SELECT name WHERE type='table'; cheers Paul From newsgroups at nospam.nowire.org Thu Mar 29 10:07:34 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-15?Q?Thomas_Kr=FCger?=) Date: Thu, 29 Mar 2007 16:07:34 +0200 Subject: Problem with class variables In-Reply-To: References: Message-ID: Dag schrieb: > I have a problem which is probaly very simple to solve, but I can't > find a nice solution. > I have the following code > > class Test: > def __init__(self): > self.a=[1,2,3,4] > self.b=self.a > def swap(self): > self.a[0],self.a[3]=self.a[3],self.a[0] > def prnt(self): > print self.a > print self.b > c=Test() > c.swap() > c.prnt() > > which returns > [4,2,3,1] > [4,2,3,1] > > Now I understand why it is doing this, but it's not what I want. How to > I get it to return > [4,2,3,1] > [1,2,3,4] > > Dag Use a copy of self.a: self.b = self.a[:] Thomas From http Fri Mar 9 09:51:22 2007 From: http (Paul Rubin) Date: 09 Mar 2007 06:51:22 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> Message-ID: <7x7itqqxlh.fsf@ruckus.brouhaha.com> "cesco" writes: > I have to generate a list of N random numbers (integer) whose sum is > equal to M. If, for example, I have to generate 5 random numbers whose > sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a > simple pattern or function in Python to accomplish that? Erm, yes, lots of ways, there are probably further constraints on the problem, such as the size of the integers, how the lists are supposed to be distributed, etc. Can you be more specific? Is this for an application? If it's a homework problem, that's fine, but it's better in that case for respondents to suggest hints rather than full solutions. From steve at holdenweb.com Wed Mar 14 14:18:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 14 Mar 2007 14:18:23 -0400 Subject: Grep Equivalent for Python In-Reply-To: <1173894933.677887.176140@b75g2000hsg.googlegroups.com> References: <1173875870.566931.152380@d57g2000hsg.googlegroups.com> <1173890256.024442.138840@e1g2000hsg.googlegroups.com> <1173894933.677887.176140@b75g2000hsg.googlegroups.com> Message-ID: tereglow wrote: > Okay, > > It is now working as follows: > > memFile = open('/proc/meminfo') > for line in memFile.readlines(): > if line.startswith("MemTotal"): > memStr = line.split() > memTotal = memStr[1] > memFile.close() > print "Memory: " + memTotal + "kB" > > I'm learning the whole try, finally exception stuff so will add that > in as well. Now, I'm trying to figure out the CPU speed. In shell, > I'd do: > > grep "^cpu MHz" /proc/cpuinfo | awk '{print $4}' | head -1 > > The "head -1" is added because if the server has 2 or more processors, > 2 or more lines will result, and I only need data from the first > line. So, now I'm looking for the equivalent to "head (or tail" in > Python. Is this a case where I'll need to break down and use the re > module? No need to give me the answer, a hint in the right direction > would be great though. > > Thanks again, > Tom > If you are interested in a number of fields I'd create a dict or set containing the keys you are interested in. For each line, if the text indicates you are interested in the value then extract the value and store it in a dict against the text as a key. Something like (untested): kwdlist = "cpu MHz|MemTotal" d = dict((x, None) for x in kwdlist.split("|")) memFile = open('/proc/meminfo') for line in memFile.readlines(): keyword = line.split(":")[0] if keyword in d and d[keyword] is None: d[keyword] = line.split()[1] memFile.close() This should give you a dict with non-None values against the keywords you have found. Because of the "and d[keyword] is None" test you won;t overwrite an existing value, meaning you only see the first value for any given keyword. Again, bear in mind this code is untested. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From newsgroups at nospam.nowire.org Fri Mar 30 05:20:38 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Fri, 30 Mar 2007 11:20:38 +0200 Subject: Indentation for code readability In-Reply-To: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> Message-ID: DE schrieb: > Hello, > > Here is what I do in C++ and can not right now in python : > > pushMatrix() > { > drawStuff(); > > pushMatrix(); > { > drawSomeOtherStuff() > } > popMatrix(); > } > popMatrix(); > > The curly brackets have no functional meaning but increase the > readability significantly. I want to be able to do the same thing in > python. Since curly brackets are not available and indenting without > an if or while conditional doesn't work, I have started to question if > this is possible in python at all. > > Any ideas ? I've been thinking about that for some minutes now and I have doubts that it will increase the readability. Maybe for you as you invented that style but not for others. There are a few standards for formatting C code and even this few have cause many discussions between developers. Python has one convention (defined in PEP 8) and the deeper you dive into the language the more you will like it. BTW: having one way to do it is one of the main ideas of Python's philosophy. Thomas From deets at nospam.web.de Fri Mar 30 08:08:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 Mar 2007 14:08:10 +0200 Subject: with timeout(...): In-Reply-To: References: <56prsrF2am4a1U1@mid.uni-berlin.de> <571hbfF2a7ngiU1@mid.uni-berlin.de> Message-ID: <574ctnF2b0iseU1@mid.uni-berlin.de> Nick Craig-Wood schrieb: > Diez B. Roggisch wrote: >>> I beleive the convention is when calling an OS function which might >>> block the global interpreter lock is dropped, thus allowing other >>> python bytecode to run. >> >> So what? That doesn't help you, as you are single-threaded here. The >> released lock won't prevent the called C-code from taking as long as it >> wants. |And there is nothing you can do about that. > > I'm assuming that the timeout function is running in a thread... I wouldn't assume that - it could be a python on a platform without threads. I really don't think that your idea is worth the effort. If there is something that can be safely interrupted at any given point in time - which is the exception, not the rule - then one can "code around" that missing feature, by spawning a subprocess python, using pyro to communicate, and terminate it. I've done so before. Some people here said "we're adults, we make sure our code will be safely interruptable". But first of all, even adults make errors, and even more important: most of the time such a feature is wanted, it's about limiting some scripts that come from an untrusted source - like user-written plugins. Such a feature would encourage people to use it in such cases, but not stand up for the nastiness it may provoke. Diez From martinunsal at gmail.com Tue Mar 6 02:57:18 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 5 Mar 2007 23:57:18 -0800 Subject: Project organization and import In-Reply-To: <1huivd7.7l18eh1paqp0aN%aleax@mac.com> References: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> <87mz2s32rb.fsf@gmail.com> <1173112353.210937.214020@v33g2000cwv.googlegroups.com> <45ec933a$0$15549$426a34cc@news.free.fr> <1huivd7.7l18eh1paqp0aN%aleax@mac.com> Message-ID: <1173167838.173634.62810@c51g2000cwc.googlegroups.com> On Mar 5, 10:06 pm, a... at mac.com (Alex Martelli) wrote: > My favorite way of working: add a test (or a limited set of tests) for > the new or changed feature, run it, check that it fails, change the > code, rerun the test, check that the test now runs, rerun all tests to > see that nothing broke, add and run more tests to make sure the new code > is excellently covered, rinse, repeat. Occasionally, to ensure the code > stays clean, stop to refactor, rerunning tests as I go. >From the way you describe your workflow, it sounds like you spend very little time working interactively in the interpreter. Is that the case or have I misunderstood? Martin From steve at holdenweb.com Thu Mar 22 18:49:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 18:49:31 -0400 Subject: Upgrading python question In-Reply-To: <3AD132C2-B09B-4FF9-AA86-928DE171B634@mac.com> References: <3AD132C2-B09B-4FF9-AA86-928DE171B634@mac.com> Message-ID: Tommy Grav wrote: > I am currently using Activepython 2.4.4, but would like to upgrade to > 2.5. Am I right in thinking that if I do that I need to reinstall all > the > packages and modules (like numpy, scipy, pyfits, and so on)? Or is > there a way to avoid that? > > Cheers > Tommy There's a decent chance that "pure Python" modules can be copied across to the new installation. Extension modules, however, with compiled C or C++ components, will need to be rebuilt or reinstalled. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From nogradi at gmail.com Sun Mar 18 12:24:15 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 18 Mar 2007 17:24:15 +0100 Subject: list comprehension help In-Reply-To: References: Message-ID: <5f56302b0703180924o3ebf61e2nb2d50280456f8448@mail.gmail.com> > I need to process a really huge text file (4GB) and this is what i > need to do. It takes for ever to complete this. I read some where that > "list comprehension" can fast up things. Can you point out how to do > it in this case? > thanks a lot! > > > f = open('file.txt','r') > for line in f: > db[line.split(' ')[0]] = line.split(' ')[-1] > db.sync() What is db here? Looks like a dictionary but that doesn't have a sync method. If the file is 4GB are you sure you want to store the whole thing into memory? In case yes and you want to store it in a list then you can use list comprehension like this: db = [ line.split(' ')[-1] for line in open('file.txt','r') ] or db = [ ( line.split(' ')[0], line.split(' ')[-1] ) for line in open('file.txt','r') ] depending on what exactly you want to store. But reading 4GB into memory will be slow in any case. You can use the timeit module to find out which method is fastest. HTH, Daniel From taurelin at gmail.com Fri Mar 9 11:55:16 2007 From: taurelin at gmail.com (Arne Jamtgaard) Date: 9 Mar 2007 08:55:16 -0800 Subject: Problem with new Vista and os.system Message-ID: <1173459316.361843.41010@c51g2000cwc.googlegroups.com> I'm getting myself set up on a new Vista box at work, and one of my old scripts has stopped working. Specifically, all calls to os.system return a -1. Whatever action I was asking os.system to run does not take place. Is this a Vista thing, or perhaps just a wonky setting in my environment? I've installed the latest python (2.5) within the past two weeks... I've double-checked other functions for os.* and they seem to work from the python command line - it's just os.system. Arne From http Wed Mar 7 00:39:46 2007 From: http (Paul Rubin) Date: 06 Mar 2007 21:39:46 -0800 Subject: This web site creates a *popup window* => how fetch contents in a script? References: <1173161903.046347.192300@j27g2000cwj.googlegroups.com> <1173211320.042518.121890@8g2000cwh.googlegroups.com> Message-ID: <7x1wk14nod.fsf@ruckus.brouhaha.com> "Gabriel Genellina" writes: > - same as above, but using a protocol sniffer to record the HTTP > requests/responses. This may be needed if HTTP POST is used instead. Usually studying the originating page is enough, or at worst use a client side proxy to log the http session. A protocol sniffer sounds like too much trouble and I've never needed to resort to one for something like this. From gtcopeland at gmail.com Thu Mar 8 16:55:17 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 8 Mar 2007 13:55:17 -0800 Subject: SQLAlchemy and Oracle Functions? In-Reply-To: <1173389744.483855.230520@q40g2000cwq.googlegroups.com> References: <1173388785.133560.146300@p10g2000cwp.googlegroups.com> <1173389744.483855.230520@q40g2000cwq.googlegroups.com> Message-ID: <1173390917.481411.89510@c51g2000cwc.googlegroups.com> On Mar 8, 3:35 pm, "Giles Brown" wrote: http://www.sqlalchemy.org/docs/sqlconstruction.myt#sql_whereclause_fu... > SQLAlchemy has its own google group > > http://groups.google.co.uk/group/sqlalchemy > > You could try asking there too. > > Giles Very nice. That exactly answered by question. It works! Also, I didn't know about the sqlalchemy group so I appreciate the heads up. Thanks, Greg From carsten at uniqsys.com Tue Mar 20 21:17:40 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 20 Mar 2007 21:17:40 -0400 Subject: mysterious unicode In-Reply-To: <200703202026.34160.inq1ltd@verizon.net> References: <1174430100.666040.43970@l77g2000hsb.googlegroups.com> <200703202026.34160.inq1ltd@verizon.net> Message-ID: <1174439860.3251.30.camel@localhost.localdomain> On Tue, 2007-03-20 at 20:26 -0400, jim-on-linux wrote: > I have been getting the same thing using SQLite3 > when extracting data fron an SQLite3 database. Many APIs that exchange data choose to exchange text in Unicode because that eliminates encoding uncertainty. Whether an API uses Unicode would probably be noted somewhere in its documentation. > I take the database info which is in a list and do > > name = str.record[0] You probably mean str(record[0]) . > rather than > name = record[0] > > So far, I havn't had any problems. > For some reason the unicode u is removed. > I havn't wanted to spend the time to figure out > why. As a software engineer, I'd get worried if I didn't know why the code I wrote works. Maybe that's just me. Unicode is not rocket science. I suggest you read http://www.amk.ca/python/howto/unicode to demystify what Unicode objects are and do. With str(), you're asking the Unicode object for its byte string interpretation, which causes the Unicode object to give you its encoding in the system default encoding. The default encoding is normally ascii. That can be tweaked for your particular Python installation, but if you need an encoding other than ascii it's recommended that you explicitly encode and decode from and to Unicode, lest you risk writing non-portable code. Using str() coercion of Unicode objects will work well enough until you run into a string that contains characters that can't be represented in the default encoding. Once that happens, you're better off explicitly encoding the Unicode object into a well-defined encoding on input, or, even better, just work with Unicode objects internally and only encode to byte strings when absolutely necessary, such as when outputting to a file or to the console. Hope this helps, Carsten. From duncan.booth at invalid.invalid Thu Mar 22 09:23:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Mar 2007 13:23:08 GMT Subject: Python 3000 idea: reversing the order of chained assignments References: Message-ID: Steve Holden wrote: >> As a matter of interest do PyLint or PyChecker check for this situation >> (chained assignment where the target of an assignment is also a >> subexpression of a later assignment)? >> > Where's the published syntax for chained assignment? http://docs.python.org/ref/assignment.html More specifically, since you seem to have missed it, it's the '+' in the line: assignment_stmt ::= (target_list "=")+ expression_list And then the clear statement "assigns the single resulting object to each of the target lists, from left to right". From deets at nospam.web.de Mon Mar 5 08:44:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Mar 2007 14:44:05 +0100 Subject: CherryPy + Database questions References: Message-ID: <552l55F22aph6U1@mid.uni-berlin.de> Brian Blais wrote: > Hello, > > I have more of a conceptual question about the way databases work, in a > web > framework, but I will be implementing things with CherryPy and SQLAlchemy. > If you make a web form that adds rows to a database, and use sqlite as > the engine, is there a danger of a race condition if several users at the > same time try to submit the > form? I want a unique row id, and make a unique identifier for the > submissions. Am I in danger of having multiple submissions given the same > identifier? > > I know that if I implemented things without a database, but used a flat > file or something like it, I would have that possibility, when two > processes try to read and update the file at the same time. > > If you want something more specific, I can throw some code together, but I > wanted to get an answer before that because it will change the way I > develop the code. Usually, that is exactly what a RDBMS gives you. See the database connector module's threadsaftey property to see what exactly you can expect. Diez From spam at chezmarshall.freeserve.co.uk Fri Mar 9 06:50:41 2007 From: spam at chezmarshall.freeserve.co.uk (Robert Marshall) Date: Fri, 09 Mar 2007 11:50:41 GMT Subject: 2 new comment-like characters in Python to aid development? References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> <45f138ee$0$23918$426a74cc@news.free.fr> Message-ID: On Fri, 09 Mar 2007, Bruno Desthuilliers wrote: > > Nick Craig-Wood a ?crit : >> dbhbarton at googlemail.com wrote: >>> What if 2 new 'special' comment-like characters were added to >>> Python?: >>> >>> >>> 1. The WIP (Work In Progress) comment: >> >> I use # FIXME for this purpose or /* FIXME */ in C etc. >> >> I have an emacs macro which shows it up in bright red / yellow text >> so it is easy to see > > > Care to share this macro ? > I have this (cond (window-system (progn (font-lock-add-keywords 'python-mode '(("\\ Hi, i have created an application in pygtk. The application creates files with its own file type and extensions and saves them. I would like to extend the application to be able to send these files over WLAN. I would use the application in my Nokia 770 Internet tablet and send the files from one tablet to the other. Does anybody know how to make python application send files over the WLAN. Best regards Admir _________________________________________________________________ Schlagerfeber p? MSN! http://festival.msn.se/ From gagsl-py2 at yahoo.com.ar Wed Mar 14 19:26:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Mar 2007 20:26:14 -0300 Subject: Attribute monitoring in a class References: <45f7d65b$0$23624$426a74cc@news.free.fr> <45F7F242.9070002@gmail.com> Message-ID: En Wed, 14 Mar 2007 10:01:54 -0300, Joel Andres Granados escribi?: > Bruno Desthuilliers wrote: >> Joel Andres Granados a ?crit : >>> I'm >>> working with code that is not of my authorship and there is a class >>> attribute that is changes by directly referencing it (object.attr = >>> value) instead of using a getter/setter (object.setAttr(Value) ) >> yes : object.__setattr__(self, name, value) > I used this ^^^^^^^^^^^^^^^ one. Thank for the help. The problem with __setattr__ is that it slows down significantly *all* attributes. Yours is the typical case when it's good to switch from using simple attributes to using properties. See -- Gabriel Genellina From AWasilenko at gmail.com Thu Mar 22 21:28:11 2007 From: AWasilenko at gmail.com (AWasilenko at gmail.com) Date: 22 Mar 2007 18:28:11 -0700 Subject: TypeError: 'int' object is not callable In-Reply-To: <1174611587.000306.210790@b75g2000hsg.googlegroups.com> References: <1174611244.465956.104060@n76g2000hsh.googlegroups.com> <1174611587.000306.210790@b75g2000hsg.googlegroups.com> Message-ID: <1174613291.027531.244670@y66g2000hsf.googlegroups.com> On Mar 22, 8:59 pm, "Dan Bishop" wrote: > On Mar 22, 6:54 pm, AWasile... at gmail.com wrote: > > > > > > > I'm trying to test a few different approaches to displaying pages via > > Cherrypy and I'm not having much luck. Here is my code so far: > > > import sys, cherrypy, html > > > class Root: > > @cherrypy.expose > > def index(self, pageid = None): > > selection = html.Page() > > return selection.input() > > > cherrypy.config.update({'server.socket_port': 2572, 'log.screen': > > False}) > > cherrypy.quickstart(Root()) > > > and here is the html.py file that I import: > > > class Page: > > def input(self,dex=None): > > if dex == None: > > return 404(dex) > > else: > > return "Something else?" > > > def err404(self,whatitis="N/A"): > > return """ > >















> > >
Sorry the page: """ + str(whatitis) + """ does not exist.
> > Page cannot be found.
> > """ > > > and here is the error I get when trying to run this: > > > 500 Internal Server Error > > The server encountered an unexpected condition which prevented it from > > fulfilling the request. > > > Traceback (most recent call last): > > File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line > > 342, in respond > > cherrypy.response.body = self.handler() > > File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line > > 15, in __call__ > > return self.callable(*self.args, **self.kwargs) > > File "/home2/awasilenko/webapps/cp/site.py", line 7, in index > > return selection.input() > > File "/home2/awasilenko/webapps/cp/html.py", line 4, in input > > return 404(dex) > > TypeError: 'int' object is not callable > > > I know this isn't a Cherrypy issue since I have made other pages work, > > I'm just making a dumb mistake somewhere. My plan is to eventually be > > able to pass dex to the input def in the page class so it can display > > the right page. Right now I am just trying to make ANY thing show up, > > what should happen is since I'm not passing anything everything should > > be None and the 404 page should pop up. I would also like to make the > > 404 page print the page that was requested, I have already coded the > > return but have not "connected" it yet, one step at a time... > > 404 is an integer literal; you can't use it as a function name.- Hide quoted text - > > - Show quoted text - I saw that 404 was turning colors in my editor when I used it, that's why I changed the def name, I just forgot to change it in the input def also. Here is the working code now: class Page: def input(self,dex=None): if dex == None: return self.err404(dex) else: return "Something else?" def err404(self,whatitis="N/A"): return """













Sorry the page: """ + str(whatitis) + """ does not exist.
Page cannot be found.
""" Now I can work on getting the other stuff working. I can't believe something that stupid was holding me up, oh well :) From aahz at pythoncraft.com Thu Mar 8 11:31:14 2007 From: aahz at pythoncraft.com (Aahz) Date: 8 Mar 2007 08:31:14 -0800 Subject: worker thread catching exceptions and putting them in queue References: <45ec4936$0$323$e4fe514c@news.xs4all.nl> Message-ID: In article <45ec4936$0$323$e4fe514c at news.xs4all.nl>, Paul Sijben wrote: > >in a worker thread setup that communicates via queues is it possible to >catch exceptions raised by the worker executed, put them in an object >and send them over the queue to another thread where the exception is >raised in that scope? > >considering that an exception is an object I feel it ought to be >possible, however I do not see how to go about it. One caution: because exceptions keep stack frames alive, you can have garbage collection problems. Make sure to del the exception when you're done with it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From n.emami at gmail.com Thu Mar 1 09:16:35 2007 From: n.emami at gmail.com (Nader) Date: 1 Mar 2007 06:16:35 -0800 Subject: installing "pysqlite" In-Reply-To: <1172756443.839448.327280@h3g2000cwc.googlegroups.com> References: <9258d$45e3fa5d$9117fe9b$16503@news2.tudelft.nl> <1172576685.560386.306740@m58g2000cwm.googlegroups.com> <639dd$45e5625a$9117fe9b$1180@news1.tudelft.nl> <1172663495.011225.76410@v33g2000cwv.googlegroups.com> <1172741654.589821.255220@v33g2000cwv.googlegroups.com> <1172745997.863121.96940@8g2000cwh.googlegroups.com> <1172749563.834987.197840@z35g2000cwz.googlegroups.com> <1172756443.839448.327280@h3g2000cwc.googlegroups.com> Message-ID: <1172758595.499977.287130@8g2000cwh.googlegroups.com> On Mar 1, 2:40 pm, "Paul Boddie" wrote: > On 1 Mar, 12:46, "Nader" wrote: > > > > > ldd returens the next result: > > ldd /usr/people/emami/lib/python2.4/site-packages/pysqlite2/_sqlite.so > > linux-gate.so.1 => (0xffffe000) > > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x40040000) > > libc.so.6 => /lib/tls/libc.so.6 (0x40050000) > > I think you pasted the nm result in here, but you seem to be missing > libsqlite3.so.0 (from what I see myself). From what I've just read > about linux-gate.so, the linker can't seem to find the SQLite > libraries. More on linux-gate.so here: > > http://www.trilithium.com/johan/2005/08/linux-gate/ > > > and the 'nm' gives this: > > > nm usr/people/emami/lib/libsqlite3.so | grep sqlite3_set_authorize > > 0000ce40 T sqlite3_set_authorizer > > That looks alright. > > > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) > > I guess this was the end of the ldd result. > > I'm out of ideas, unfortunately. I think you should experiment with > LD_LIBRARY_PATH and run ldd again to see if you can get it to show > libsqlite3.so.0. The pysqlite mailing list might be the best place to > ask for help if that doesn't work. Sorry! > > Paul Hello Paul, I have returnd to the begining and have installed everthing again. Fortunately now I have the 'pysqlite2' module, because the test.test() workd after importing of 'pysqlite2' >>> from pysqlite2 import test >>> test.test >>> test.test() ............................................................................................................................................................................. ---------------------------------------------------------------------- Ran 173 tests in 0.585s OK >>> And the result of running of 'ldd' is : emami at bcw009:~> ldd lib/python2.4/site-packages/pysqlite2/_sqlite.so linux-gate.so.1 => (0xffffe000) libsqlite3.so.0 => /usr/people/emami/lib/libsqlite3.so.0 (0x40010000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0x40096000) libc.so.6 => /lib/tls/libc.so.6 (0x400a7000) Now I can ggo on with TurboGears! I have at home a Laptop and I have installed the 'gentoo' on it, and have no problem. But I would like to experiment with TurboGears at my work and It was a problem that I had no 'root' password. However I appreciate well your help in this case. I you like Indian or oriental music I can send you some! With regards, Nader From mail at microcorp.co.za Thu Mar 29 01:22:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 29 Mar 2007 07:22:58 +0200 Subject: with timeout(...): References: <56prsrF2am4a1U1@mid.uni-berlin.de> Message-ID: <000d01c771d2$2e8e5860$03000080@hendrik> "Nick Craig-Wood" wrote: > Well, yes there are different levels of potential reliability with > different implementation strategies for each! Gadzooks! Foiled again by the horses for courses argument. ; - ) - Hendrik From paltman at gmail.com Mon Mar 12 23:07:55 2007 From: paltman at gmail.com (Patrick Altman) Date: 12 Mar 2007 20:07:55 -0700 Subject: httplib/socket problems reading 404 Not Found response Message-ID: <1173755273.697153.97270@64g2000cwx.googlegroups.com> I am attempting to use a HEAD request against Amazon S3 to check whether a file exists or not and if it does parse the md5 hash from the ETag in the response to verify the contents of the file so as to save on bandwidth of uploading files when it is not necessary. If the file exist, the HEAD works as expected and I get valid headers back that I can parse and pull the ETag out of the dictionary using getheader('ETag')[1:-1] (using the slice to trim off the double-quotes in the string. The problem lies when I attempt to send a HEAD request when no file exists. As expected, a 404 Not Found response is sent back from Amazon however, my test scripts seem to hang. I run python with trace.py and it hangs here: --- modulename: httplib, funcname: _read_chunked httplib.py(536): assert self.chunked != _UNKNOWN httplib.py(537): chunk_left = self.chunk_left httplib.py(538): value = '' httplib.py(542): while True: httplib.py(543): if chunk_left is None: httplib.py(544): line = self.fp.readline() --- modulename: socket, funcname: readline socket.py(321): data = self._rbuf socket.py(322): if size < 0: socket.py(324): if self._rbufsize <= 1: socket.py(326): assert data == "" socket.py(327): buffers = [] socket.py(328): recv = self._sock.recv socket.py(329): while data != "\n": socket.py(330): data = recv(1) It eventually completes with an exception here: File "C:\Python25\lib\httplib.py", line 509, in read return self._read_chunked(amt) File "C:\Python25\lib\httplib.py", line 548, in _read_chunked chunk_left = int(line, 16) ValueError: invalid literal for int() with base 16: '' For reference, ethereal captured the following request and response: HEAD HTTP/1.1 Host: s3.amazonaws.com Accept-Encoding: identity Date: Tue, 13 Mar 2007 02:54:12 GMT Authorization: AWS HTTP/1.1 404 Not Found x-amz-request-id: E20B4C0D0C48B2EF x-amz-id-2: Content-Type: application/xml Transfer-Encoding: chunked Date: Tue, 13 Mar 2007 02:54:16 GMT Server: AmazonS3 Am I doing something wrong? Is this a known issue? I am an experienced developer, but pretty new to Python and dynamic languages in general. Thanks, Patrick From nobody at invalid.com Mon Mar 26 11:57:20 2007 From: nobody at invalid.com (Erik Johnson) Date: Mon, 26 Mar 2007 09:57:20 -0600 Subject: calling class instances and their methods References: <1174921229.208577.8290@e65g2000hsc.googlegroups.com> Message-ID: <4607ed52$1@nntp.zianet.com> "spohle" wrote in message news:1174921229.208577.8290 at e65g2000hsc.googlegroups.com... > hi, > > i created an instance of a my own class which has methods and all. now > i get an outside function called, which is unfortunatly not aware of > the instace at all (i don't control how this outside function is > called). but i would like to get access back to my instance and it's > methods. > > is there any clean way of doing this ? > > thanks in advance Ummm... I'm not exactly sure what you mean by "an outside function", but let's refer to that function as f(). Are you saying you want to re-implement f() to use your new object but don't want to (or can't) change calls to f()? If so, then you can either use a global reference to your new object if it is the sort of thing you want to keep around between invocations of f() (i.e., create your object somewhere and then save in a scope that f() can access). Otherwise, you can simply instantiate your object inside of f() as a local variable and use it. If you mean something else, I guess you will have to clarify. From bj_666 at gmx.net Sat Mar 10 04:12:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 10 Mar 2007 10:12:06 +0100 Subject: UTF-8 output problems References: Message-ID: In , Michael B. Trausch wrote: > However, when I attempt to redirect the output to a file: > > mbt at pepper:~/tmp$ python test.py >f > Traceback (most recent call last): > File "test.py", line 6, in > print u"This is Unicode code point %d (0x%x): %s" % (x, x, > unichr(x)) > UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in > position 39: ordinal not in range(128) > > This is slightly confusing to me. The output goes all the way to the > end of the program when it is not redirected. Why is Python treating > the situation differently when the output is redirected? If you print to a terminal `sys.stdout` is connected to that terminal and there are ways to figure out that it is a terminal (`os.isatty()`) and which encoding the terminal excepts. At least in most cases. But there is no way to tell what encoding a file or pipe should have. So Python refuses to guess. If an encoding could be determined the `sys.stdout.encoding` attribute is set to the name, otherwise it's `None`. Ciao, Marc 'BlackJack' Rintsch From pete at shinners.org Thu Mar 1 12:57:46 2007 From: pete at shinners.org (shredwheat) Date: 1 Mar 2007 09:57:46 -0800 Subject: BeautifulSoup modified to use weak refs and avoid circular links. In-Reply-To: References: Message-ID: <1172771866.600972.76530@h3g2000cwc.googlegroups.com> The timeit code disables the garbage collector while running. I ran the tests on my system after adding the following lines to t1() and t2(). del base gc.collect() Original timetest.py: Using proxy 100 loops, best of 3: 4.45 msec per loop Call to dummy proxy 100 loops, best of 3: 2.24 msec per loop Without proxy call 100 loops, best of 3: 3.01 msec per loop With garbage collection: Using proxy 100 loops, best of 3: 5.17 msec per loop Call to dummy proxy 100 loops, best of 3: 4.27 msec per loop Without proxy call 100 loops, best of 3: 3.99 msec per loop The overhead of weakref still doesn't outweigh the overhead of cyclic garbage collection, but they narrow the gap. I also saw a bit of noise while running this benchmark. Different runs were giving me varying times. Large enough to see about 20% discrepencies. From lojicdotcomNOSPAM at gmail.com Thu Mar 8 00:58:39 2007 From: lojicdotcomNOSPAM at gmail.com (Brian Adkins) Date: Thu, 08 Mar 2007 00:58:39 -0500 Subject: merits of Lisp vs Python In-Reply-To: <7xhcsws35x.fsf@ruckus.brouhaha.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Brian Adkins writes: >> With prices of dedicated servers and virtual private servers so cheap, >> why would anyone get a hosting account without root access? > > Because it turns you into a sysadmin instead of letting specialists > handle all the OS stuff so you can concentrate on your application. I'm not sure what "OS stuff" you're referring to, but my interactions with my dedicated host are quite similar to when I had a shared hosting account (except I never have to contact the hosting company like I used to with a shared account - it just keeps humming along). Besides, this whole thing got started with John resurrecting the "industrial strength" argument. I hardly think a shared hosting account would be considered "industrial strength". If you're not willing to deal with a dedicated server, then I don't think you're serious about "industrial strength", right? Not to mention the fact that none of this has anything to do with the "industrial strengthness" of the language. > > Also, no VPS where you have to run your own httpd instance (and > usually your own database if you're using one) can possibly be as > cheap as a virtual host where you're sharing the same httpd with > thousands of other sites. And you *want* to share the same httpd with thousands of other sites? I can relate to what you're saying. I tried the shared hosting thing originally, but the saying, "you get what you pay for" holds some truth here. Maybe y'all should change the thread to "Why don't shared hosting companies treat Python customers better?" or something along those lines. We seem to have drifted from "Princess Bride" quotes and the merits of Lisp vs. Python ;) From paul.rudin at ntlworld.com Fri Mar 23 15:05:49 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Fri, 23 Mar 2007 19:05:49 +0000 Subject: Join strings - very simple Q. References: <1174675011.244339@jubilee.claranet.pt> Message-ID: <87ejnfzsoi.fsf@rudin.co.uk> Paulo da Silva writes: > Hi! > > I was told in this NG that string is obsolet. I should use > str methods. > > So, how do I join a list of strings delimited by a given > char, let's say ','? > > Old way: > > l=['a','b','c'] > jl=string.join(l,',') > > New way? Dunno if it's the "new way", but you can do: ''.join(l) From jgodoy at gmail.com Sun Mar 11 22:12:04 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 11 Mar 2007 23:12:04 -0300 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1173629090.993914.55570@30g2000cwc.googlegroups.com> <1173631052.614449.51370@h3g2000cwc.googlegroups.com> <7xy7m3tqq8.fsf@ruckus.brouhaha.com> <1173653364.059431.19990@v33g2000cwv.googlegroups.com> <7xps7f5ptp.fsf@ruckus.brouhaha.com> <1hutrb3.e1sbu5kvxk8nN%aleax@mac.com> Message-ID: <87odmznrbf.fsf@gmail.com> aleax at mac.com (Alex Martelli) writes: > Incidentally (and I know you know that, Paul, but others interested in > this thread might not) fast exact rational arithmetic (based on the LGPL > library named GMP) is supplied, among other functionality, by module > gmpy, currently found at http://code.google.com/p/gmpy/ (this version is > more recent than the older one at sourceforce, which for some reason > doesn't let me update things right any more). For some reason setuptools isn't finding it: jupiter:~ # easy_install gmpy Searching for gmpy Reading http://cheeseshop.python.org/pypi/gmpy/ Reading http://code.google.com/p/gmpy/ Reading http://cheeseshop.python.org/pypi/gmpy/1.02 No local packages or download links found for gmpy error: Could not find suitable distribution for Requirement.parse('gmpy') I believe that setuptools isn't ready to find packages on code.google.com yet... ;-) -- Jorge Godoy From rehceb at no.spam.plz Sat Mar 31 14:19:52 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 31 Mar 2007 13:19:52 -0500 Subject: Sorting a multidimensional array by multiple keys References: Message-ID: Thank you all for your helpful solutions! Regards, Rehceb From gherron at islandtraining.com Tue Mar 20 12:25:17 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 20 Mar 2007 09:25:17 -0700 Subject: making objects with individual attributes! In-Reply-To: <1174406902.445936.261450@y66g2000hsf.googlegroups.com> References: <1174406902.445936.261450@y66g2000hsf.googlegroups.com> Message-ID: <46000AED.1090006@islandtraining.com> Alejandro wrote: > I have created a class: > > class document: > > titre = '' > haveWords = set() > > def __init__(self, string): > > self.titre = string > > ######### > > doc1 = document('doc1') > doc2 = document('doc2') > > doc1.haveWords.add(1) > doc2.haveWords.add(2) > > > print doc1.haveWords > > # i get set([1, 2]) > > > doc1 and doc are sharing attribute haveWords! > Why ??? there's a way to assign every objetc "document" a different > "set" > Of course. Try this: class document: def __init__(self, string): self.titre = string self.haveWords = set() Each instance creation will call __init__ with the instance accessible through self, and that code will create two instance specific attributes. Don't use so called class level attributes (as in your example) unless you *want* sharing between all instances of a class. Gary Herron From sunil_25aug at yahoo.co.in Mon Mar 5 16:58:27 2007 From: sunil_25aug at yahoo.co.in (BITTU ROY) Date: Mon, 5 Mar 2007 21:58:27 +0000 (GMT) Subject: XXX Fucking Pics Message-ID: <408331.95022.qm@web7804.mail.in.yahoo.com> --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From aboudouvas at panafonet.gr Mon Mar 19 08:08:29 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Mar 2007 05:08:29 -0700 Subject: PythonCard thoughts Message-ID: <1174306109.635443.88060@y66g2000hsf.googlegroups.com> Hi to all folks here, i downloaded and "playing" with PythonCard and i just want to share my thoughts so maybe we can discuss a little about it. I was used to wxGlade before and i think PythonCard is even better. I like the separate implementation of GUI and Code that PythonCard provides, i also like the "binding system" so you can bind functions to events and have them executed at runtime. I also like that it does not force you to use sizers and all that stuff and that you can freely place your components on the form and set their exact position just with the mouse. The only "problem" i see with this design is that by that separation of Gui/Code, you loose the intellisense that (ex. PyDev) some editors/ plugins can provide because in the .py file nothing is indicating that , for example, the btnDoWork is a Button object. This force you to remember many properties and switch back and forth between your code and the wxPython help file. This is not the case for wxGlade because all boilerplate code is in the same file (for good and for bad) and PyDev (and others too) can "understand" for which kind of objects we are talking about and so can display -and thus help us- with their properties. Apart from that, everything else is great. Any opinions/suggestion on all this ? From yinglcs at gmail.com Sat Mar 17 20:28:56 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 17 Mar 2007 17:28:56 -0700 Subject: How to parse the os.system() output in python Message-ID: <1174177736.241481.115150@d57g2000hsg.googlegroups.com> Hi, I use os.system() to execute a system command in python. Can you please tell me how can I parse (in python) the output of the os.system() ? Thank you. From jstroud at mbi.ucla.edu Thu Mar 1 05:33:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 01 Mar 2007 10:33:07 GMT Subject: splitting perl-style find/replace regexp using python In-Reply-To: References: <1172741100.414936.269460@q2g2000cwa.googlegroups.com> <1LxFh.3180$BE2.57@newssvr27.news.prodigy.net> Message-ID: Peter Otten wrote: > James Stroud wrote: > >> James Stroud wrote: >>> John Pye wrote: >>>> Hi all >>>> >>>> I have a file with a bunch of perl regular expressions like so: >>>> >>>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ # >>>> bold >>>> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/ >>>> b>''$3/ # italic bold >>>> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ # >>>> italic >>>> >>>> These are all find/replace expressions delimited as '/search/replace/ >>>> # comment' where 'search' is the regular expression we're searching >>>> for and 'replace' is the replacement expression. >>>> >>>> Is there an easy and general way that I can split these perl-style >>>> find-and-replace expressions into something I can use with Python, eg >>>> re.sub('search','replace',str) ? >>>> >>>> I though generally it would be good enough to split on '/' but as you >>>> see the <\/b> messes that up. I really don't want to learn perl >>>> here :-) >>>> >>>> Cheers >>>> JP >>>> >>> This could be more general, in principal a perl regex could end with a >>> "\", e.g. "\\/", but I'm guessing that won't happen here. >>> >>> py> for p in perlish: >>> ... print p >>> ... >>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ >>> /(^|[\s\(])\_\_([^ ].*?[^ >>> ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/ /(^|[\s\(])\_([^ ].*?[^ >>> ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ py> import re >>> py> splitter = re.compile(r'[^\\]/') >>> py> for p in perlish: >>> ... print splitter.split(p) >>> ... >>> ['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >>> "$1'''$2'''$", ''] >>> ['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >>> "$1''$2<\\/b>''$", ''] >>> ['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >>> "$1''$2''$", ''] >>> >>> (I'm hoping this doesn't wrap!) >>> >>> James >> I realized that threw away the closing parentheses. This is the correct >> version: >> >> py> splitter = re.compile(r'(?> py> for p in perlish: >> ... print splitter.split(p) >> ... >> ['', '(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', >> "$1'''$2'''$3", ''] >> ['', '(^|[\\s\\(])\\_\\_([^ ].*?[^ >> ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', "$1''$2<\\/b>''$3", ''] >> ['', '(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', >> "$1''$2''$3", ''] > > There is another problem with escaped backslashes: > >>>> re.compile(r'(? ['', 'abc\\\\/def', ''] > > Peter Yes, this would be a case of the expression (left side) ending with a "\" as I mentioned above. James From thinker at branda.to Wed Mar 21 09:37:12 2007 From: thinker at branda.to (Thinker) Date: Wed, 21 Mar 2007 21:37:12 +0800 Subject: Garbage collection In-Reply-To: References: Message-ID: <46013508.4010407@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Tom Wright wrote: > Hi all > > I suspect I may be missing something vital here, but Python's garbage > collection doesn't seem to work as I expect it to. Here's a small test > program which shows the problem on python 2.4 and 2.5: ............... skip ..................... > (at this point, Python is using 252MB) > > > Is there something I've forgotten to do? Why is Python still using such a > lot of memory? > > > Thanks! > How do you know amount of memory used by Python? ps ? top or something? - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGATUI1LDUVnWfY8gRAhy9AKDTA2vZYkF7ZLl9Ufy4i+onVSmWhACfTAOv PdQn/V1ppnaKAhdrblA3y+0= =dmnr -----END PGP SIGNATURE----- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 9 05:38:22 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 09 Mar 2007 11:38:22 +0100 Subject: 2 new comment-like characters in Python to aid development? In-Reply-To: References: <1173431686.793240.11780@p10g2000cwp.googlegroups.com> Message-ID: <45f138ee$0$23918$426a74cc@news.free.fr> Nick Craig-Wood a ?crit : > dbhbarton at googlemail.com wrote: >> What if 2 new 'special' comment-like characters were added to Python?: >> >> >> 1. The WIP (Work In Progress) comment: > > I use # FIXME for this purpose or /* FIXME */ in C etc. > > I have an emacs macro which shows it up in bright red / yellow text so > it is easy to see Care to share this macro ? From steve at REMOVE.THIS.cybersource.com.au Tue Mar 20 13:25:00 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Mar 2007 04:25:00 +1100 Subject: Exceptions when closing a file Message-ID: Closing a file can (I believe) raise an exception. Is that documented anywhere? I've spent a lot of frustrating time trying to track this down, with no luck, which suggests that either my google-foo is weak or that it isn't documented. Is IOError the only exception it can raise? The only thing I have found is this: http://mail.python.org/pipermail/python-bugs-list/2004-November/026031.html Out of curiosity, is there a simple way to demonstrate close() raising an exception that doesn't involve messing about with disk quotas? -- Steven. From C.delete_this.Sanders at BoM.GOv.AU Wed Mar 21 03:22:52 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Wed, 21 Mar 2007 18:22:52 +1100 Subject: How to tell easy_install that a package is already installed Message-ID: <4600dd4d$0$98624$c30e37c6@lon-reader.news.telstra.net> I am not sure if this is the right forum to ask this. If it is not, could someone pleas point me to a more appropriate newsgroup. I am attempting to install dap.plugins.netcdf using easy_install on HP-UX 11. As a user, I do not have access to root so have followed the easy_install recommendation to set up a "virtual" python, as described at http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python and this is mostly working well. One of the dependencies, numpy is already installed, but easy_install does not detect this, and tries to install numpy, which fails with many compilation errors. (numerous pointer type mismatches, undeclared functions like rintf that do not exist on HP, ...) I could try to install numpy myself from the tar.gz file, but this seems pointless since it is already installed. Is there any way to tell easy_install that numpy is installed, while still installing any other dependencies ? Would the best option be to just use the --no-deps option and see if it works ? Charles From sgeiger at ncee.net Fri Mar 23 17:17:43 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 23 Mar 2007 16:17:43 -0500 Subject: Create new processes over telnet in XP In-Reply-To: <46043ad8$0$27402$ba4acef3@news.orange.fr> References: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> <46043ad8$0$27402$ba4acef3@news.orange.fr> Message-ID: <460443F7.9000406@ncee.net> This reminds me of something I once wanted to do: How can I install Python in a totally non-gui way on Windows (without the use of VNC)? I think I was telnetted into a computer (or something like that) and I was unable to run the usual Python installer because it uses a GUI. Laurent Pointal wrote: > Jorgen Grahn wrote: > > >> On 23 Mar 2007 03:47:14 -0700, Godzilla wrote: >> >>> Hello, >>> >>> How do you create/spawn new processes in XP over telnet using python? >>> I.e. I would like to create a new process and have it running in the >>> background... >>> >> Ssh -- or even rsh -- are better choices than telnet for these things. >> For some reason, they are not standard in Windows, though. >> >> ssh somewhere some command with arguments >> rsh somewhere some command with arguments >> >> compared to >> >> telnet somewhere >> >> and then performing expect-like things (basically simulating >> someone typing "some command with arguments" in the telnet >> session). >> > > + for an sshd running as a service under XP, look at CopSSH. > > + hope started process doesn't want a GUI... else, look at UltraVNC running > as daemon, and port redirection using ssh. > > >>> when I terminate the telnet connection, I would what the >>> spawned processes to keep running until I shut it off... >>> >> That's a function of the remote OS; what happens when its terminal >> goes away is not under the control of the client side. >> > > Maybe the process starting job can be done by a Python program running as > Windows service and waiting for requests on a port (or Pyro object or Corba > object...). > No need for telnet/ssh connection, no logout problem. > > Just care of possible security problems :-) > > > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From laurent.pointal at limsi.fr Wed Mar 14 11:44:22 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 14 Mar 2007 16:44:22 +0100 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: <1173886227.609832.170540@l75g2000hse.googlegroups.com> References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> Message-ID: Drew a ?crit : > When is it appropriate to use dict.items() vs dict.iteritems. Both > seem to work for something like: > > for key,val in mydict.items(): > print key,val > > for key,val in mydict.iteritems(): > print key,val > > Also, when is it appropriate to use range() vs xrange(). From my > understanding, xrange() essentially gives you an iterator across a > range, so it should be used when iterating. Should you only use > range() when want to physically store the range as a list? iteritems and xrange only provide values when requested. items and range build complete list when called. Both work, you may prefer xrange/iteritems for iteration on large collections, you may prefer range/items when processing of the result value explicitly need a list (ex. calculate its length) or when you are going to manipulate the original container in the loop. A+ Laurent. From nisimura at gmail.com Thu Mar 15 20:33:29 2007 From: nisimura at gmail.com (nisimura at gmail.com) Date: 15 Mar 2007 17:33:29 -0700 Subject: Python Eggs on Cygwin Message-ID: <1174005208.972118.104860@l77g2000hsb.googlegroups.com> Hi, I'm trying to use MySQL Python module on Cygwin. Since there is no binary package, I compiled MySQL C client library and Python module (http://sourceforge.net/projects/mysql-python) manually. But when I was trying to load MySQLdb module, following errors happened. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? File "build/bdist.cygwin-1.5.22-i686/egg/MySQLdb/__init__.py", line 19, in ? File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 7, in ? File "build/bdist.cygwin-1.5.22-i686/egg/_mysql.py", line 6, in __bootstrap__ ImportError: Permission denied This seems to be Eggs/Cygwin problem. Is there any solution? Regards, -- Kazu Nisimura From matthew.garman at gmail.com Fri Mar 23 17:11:35 2007 From: matthew.garman at gmail.com (Matt Garman) Date: Fri, 23 Mar 2007 15:11:35 -0600 Subject: Python object overhead? Message-ID: I'm trying to use Python to work with large pipe ('|') delimited data files. The files range in size from 25 MB to 200 MB. Since each line corresponds to a record, what I'm trying to do is create an object from each record. However, it seems that doing this causes the memory overhead to go up two or three times. See the two examples below: running each on the same input file results in 3x the memory usage for Example 2. (Memory usage is checked using top.) This happens for both Python 2.4.3 on Gentoo Linux (64bit) and Python 2.3.4 on CentOS 4.4 (64bit). Is this "just the way it is" or am I overlooking something obvious? Thanks, Matt Example 1: read lines into list: # begin readlines.py import sys, time filedata = list() file = open(sys.argv[1]) while True: line = file.readline() if len(line) == 0: break # EOF filedata.append(line) file.close() print "data read; sleeping 20 seconds..." time.sleep(20) # gives time to check top # end readlines.py Example 2: read lines into objects: # begin readobjects.py import sys, time class FileRecord: def __init__(self, line): self.line = line records = list() file = open(sys.argv[1]) while True: line = file.readline() if len(line) == 0: break # EOF rec = FileRecord(line) records.append(rec) file.close() print "data read; sleeping 20 seconds..." time.sleep(20) # gives time to check top # end readobjects.py From steve at REMOVE.THIS.cybersource.com.au Sun Mar 11 00:26:12 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Mar 2007 16:26:12 +1100 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7xr6rxkqp6.fsf@ruckus.brouhaha.com> <7xwt1or6j3.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 10 Mar 2007 16:02:56 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> > By your method, what is the probability of the first number being >> > higher than 30? What is the probability of the fifth number being >> > higher than 30? If these probabilities are unequal, can we really say >> > the sequences are random? >> >> Of course we can! "Uniform probability distribution" is a special case of >> random. Most random quantities are far from uniform. The Python random >> module includes a couple of non-uniform distributions, including >> exponential distribution (random.expovariate) and the famous bell curve >> distribution (random.normalvariate). > > Ehh. Say we call some generator repeatedly and get back the sequence > (3, 3, 3, 3, 3, ...). Would we say this is a random sequence using a > distribution that puts 100% of the probability density at 3? Or would > we just say it isn't random? Oh! You know that bit where I said that every imaginable sequence of integers was random? I take it back. Oh wait. I never said anything of the sort. Not every sequence of ints is a random sequence. Although... your question is deeper than it appears at first glance. In any truly random sequence, you should expect to find repeated values. If you wait long enough, you should get a sequence of 3,3,3... for any number of threes you like. (Or, naturally, any other integer.) If you wait long enough, you should get a billion threes. -- Steven. From j.spies at hccnet.nl Tue Mar 27 12:55:20 2007 From: j.spies at hccnet.nl (Jaap Spies) Date: Tue, 27 Mar 2007 18:55:20 +0200 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1175005457.115349.92940@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> <4607fbf4$1@nntp.zianet.com> <1175005457.115349.92940@p15g2000hsd.googlegroups.com> Message-ID: Mark Morss wrote: > > Maybe somebody reading this will be able to convince me to look again > at Numpy/Scipy, but for the time being I will continue to do my > serious numerical computation in Fortran. > What I am missing in this discussion is a link to Pyrex to speed up Python: Pyrex is almost Python with the speed of compiled C. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Pyrex is adapted in SAGE (Software for Algebra and Geometry Experimentation) as Sagex: http://modular.math.washington.edu/sage/ Jaap From albmont at centroin.com.br Mon Mar 12 07:07:31 2007 From: albmont at centroin.com.br (Alberto Monteiro) Date: Mon, 12 Mar 2007 09:07:31 -0200 Subject: New to Python In-Reply-To: <55kmslF249ihcU1@mid.uni-berlin.de> References: <55kmslF249ihcU1@mid.uni-berlin.de> Message-ID: <20070312110348.M44118@centroin.com.br> I wrote: > >> Hi, I am new to Python, how stupid can be the questions I ask? >> >> For example, how can I add (mathematically) two tuples? >> x = (1,2) >> y = (3,4) >> How can I get z = (1 + 3, 2 + 4) ? Wow, I really didn't expect that my silly little newbie question would get so many _different_ answers! What is the best way to get documentation about the functions and classes of python? I tried to google, but usually I can just find the __doc__ of the objects, without examples or anything that can help me use it. Alberto Monteiro From jon+usenet at unequivocal.co.uk Mon Mar 12 15:18:06 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 12 Mar 2007 19:18:06 GMT Subject: Watching a file another app is writing References: <1173676363.653940.133030@30g2000cwc.googlegroups.com> Message-ID: In article , John Nagle wrote: >> On Unix a quick shortcut would be to simply read the output of 'tail - >> f ' command... > > "tail -f" just checks the file size once a second. It's not doing > anything exciting. That's not actually always true these days. *BSD, at least, use 'kqueue' to avoid busy-wait on "tail -f". From ptmcg at austin.rr.com Fri Mar 16 15:32:26 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Mar 2007 12:32:26 -0700 Subject: Finding the insertion point in a list In-Reply-To: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> Message-ID: <1174073546.381358.129050@o5g2000hsb.googlegroups.com> On Mar 16, 12:59 pm, tkp... at hotmail.com wrote: > I have an ordered list e.g. x = [0, 100, 200, 1000], and given any > positive integer y, I want to determine its appropriate position in > the list (i.e the point at which I would have to insert it in order to > keep the list sorted. I can clearly do this with a series of if > statements: > > if y n = 0 > elif y < x[2]: > n = 1 > elif y < x[3]: > n = 2 > else: > n = 3 > > Or with a generator comprehension > n = sum ( y>x[i] for i in range(len(x)) ) - 1 > > But there has to be a cleaner way, as the first approach is unwieldy > and does not adapt to changing list lengths, and the second is not > obvious to a casual reader of the code. > > My list will typically have 2 to 5 items, so speed is not a huge > issue. I'd appreciate your guidance. > > Sincerely > > Thomas Philips List "will typically have 2 to 5 items"? Keep it simple! x.append(y) x.sort() -- Paul From bj_666 at gmx.net Fri Mar 30 06:35:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 30 Mar 2007 12:35:54 +0200 Subject: Game programming for kids: looking for open source 2D game development kit References: <5741ueF2bgl92U1@mid.uni-berlin.de> Message-ID: In , Max Kubierschky wrote: > What part of Squeak is targeted at 2D game development? http://www.squeak.org/Features/FunandGames/ And also take a look at http://www.squeakland.org/ (Kids play ? Etoys) which is a framework for children, that let's you paint objects and attach behaviour to them. Ciao, Marc 'BlackJack' Rintsch From mwilson at the-wire.com Thu Mar 29 00:11:06 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 29 Mar 2007 00:11:06 -0400 Subject: Fortran vs Python - Newbie Question In-Reply-To: References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com><1174916449.171929.138950@n76g2000hsh.googlegroups.com> <2e4k03l8tj9oicmn8c21vobrnvkmdstabr@4ax.com> Message-ID: Terry Reedy wrote: > "Tim Roberts" wrote in message > news:2e4k03l8tj9oicmn8c21vobrnvkmdstabr at 4ax.com... > | Once upon a time, > | Basic enthusiasts would have used the word "tokenized" to describe .pyc > files. > > Perhaps, but they would, I think, have been wrong. Tokenized Basic to the > best of my knowledge, is a reversibly compressed version of the source > file. The 'while' keyword, is there is one, is replaced by a number, but > no parsing is done. Almost reversibly. The giveaway was when you listed your BASIC program and all the keywords came out upper-case, regardless of what case you'd typed them in. Mel. From gagsl-py2 at yahoo.com.ar Sun Mar 11 07:46:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 08:46:58 -0300 Subject: threading and iterator crashing interpreter References: <1173609124.089611.242080@h3g2000cwc.googlegroups.com> Message-ID: En Sun, 11 Mar 2007 07:32:04 -0300, Janto Dreijer escribi?: > I have been having problems with the Python 2.4 and 2.5 interpreters > on both Linux and Windows crashing on me. Unfortunately it's rather > complex code and difficult to pin down the source. > > So I've been trying to reduce the code. In the process it's started to > crash in different ways. I'm not sure if any of it is related. The > following is only crashing Python 2.5 (r25:51908, Sep 19 2006, > 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 in two different(?) > ways. > > ==================== > > Using the login1() function will throw a bunch of exceptions the most > interesting of which is: > > Exception in thread Thread-34: > Traceback (most recent call last): > File "C:\Python25\lib\threading.py", line 460, in __bootstrap > self.run() > File "C:\Python25\lib\threading.py", line 440, in run > self.__target(*self.__args, **self.__kwargs) > File "Copy of scratchpad.py", line 20, in login1 > random.choice(System.sessions).session_iter.next() > RuntimeError: instance.__dict__ not accessible in restricted mode From the error message, you appear to be using some form of restricted execution - RExec or similar. I didn't try that way, but using the normal mode, I got this different exception instead (using login1): Exception in thread Thread-85: Traceback (most recent call last): File "c:\apps\python\lib\threading.py", line 460, in __bootstrap self.run() File "c:\apps\python\lib\threading.py", line 440, in run self.__target(*self.__args, **self.__kwargs) File "crash.py", line 20, in login1 random.choice(System.sessions).session_iter.next() ValueError: generator already executing It appears to indicate that you must syncronize the generators. Adding a Lock object to Session appears to work OK: class Session: def __init__(self): self.lock = Lock() self.session_iter = session_iter(self) def login1(): # first interpreter System.sessions.append(Session()) while 1: session = random.choice(System.sessions) session.lock.acquire() session.session_iter.next() session.lock.release() Your login2 version does not generate any error on my PC. -- Gabriel Genellina From jstroud at mbi.ucla.edu Sat Mar 24 20:50:46 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 25 Mar 2007 00:50:46 GMT Subject: "persistent" plot windows In-Reply-To: <1174779770.134013.256280@b75g2000hsg.googlegroups.com> References: <1174779770.134013.256280@b75g2000hsg.googlegroups.com> Message-ID: Rodrigo Lopez-Negrete wrote: > Hi all, > > I'm trying to write a python script using plotting form pylab. > Unfortunatelly I've encountered a problem. When I run the script via > 'python myscript.py' the plot windows open and close very quickly, or > when I added the show() command the shell window was locked until I > closed the figures. > > My question is: is there a way to open those windows in the background > without blocking the shell and without running it interactively?? > something like gnuplot -persist? > > Thanks all, > Rodrigo Lopez-Negrete > python whatever.py & (Don't forget the ampersand!) James From kyosohma at gmail.com Wed Mar 21 16:11:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 21 Mar 2007 13:11:48 -0700 Subject: Python COM Outlook Question In-Reply-To: <1174504504.910510.219050@b75g2000hsg.googlegroups.com> References: <1174504504.910510.219050@b75g2000hsg.googlegroups.com> Message-ID: <1174507908.631651.306870@d57g2000hsg.googlegroups.com> On Mar 21, 2:15 pm, "liam_herron" wrote: > Say I want to open a shared email inbox (named "DailyGoodEmails") that > is different from my default Outlook inbox, how do I specify this? > > Currently, I would do: > > s = Dispatch("Outlook.Application") > space = s.GetNameSpace("MAPI") > inbox = space.GetDefaultFolder(6) > myFolder = inbox.Folders[9] #open the folder i want > > I have no idea where the "6" comes from but I want to be able to > specify "DailyGoodEmails" somewhere > and be able to iterate over the emails. I don't know how to do this, but I found you a couple websites that should point you in the right direction: http://www.boddie.org.uk/python/COM.html http://webservices.xml.com/pub/a/ws/2003/05/13/email.html Hope that helps. Mike From Robert.Katic at gmail.com Sun Mar 4 08:24:25 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 4 Mar 2007 05:24:25 -0800 Subject: class attrdict In-Reply-To: <1173009806.383478.50230@i80g2000cwc.googlegroups.com> References: <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1173009806.383478.50230@i80g2000cwc.googlegroups.com> Message-ID: <1173014665.610542.285520@v33g2000cwv.googlegroups.com> On Mar 4, 1:03 pm, "goodwolf" wrote: > On Mar 3, 4:25 am, a... at mac.com (Alex Martelli) wrote: > > > > > Hallvard B Furuseth wrote: > > > > Does this class need anything more? > > > Is there any risk of a lookup loop? > > > Seems to work... > > > > class attrdict(dict): > > > """Dict where d['foo'] also can be accessed as d.foo""" > > > def __init__(self, *args, **kwargs): > > > self.__dict__ = self > > > dict.__init__(self, *args, **kwargs) > > > def __repr__(self): > > > return dict.__repr__(self).join(("attrdict(", ")")) > > > The problem is mostly that, given an instance a of attrdict, whether you > > can call (e.g.) a.update(foo) depends on whether you ever set > > a['update'], making the whole program extremely fragile -- a very high > > price to pay for some modest amount of syntax sugar. > > > Alex > > Then you will prefer something like this: > > class Namespace(object): > def __init__(self, __ns={}, **kwargs): > if kwargs: __ns.update(kwargs) > self.__dict__ = __ns oops, there is an error (empty dict is created once). Here corrected one: class Namespace(object): def __init__(self, __ns=None, **kwargs): if __ns is None: self.__dict__ = kwargs else: assert len(kwargs) == 0 self.__dict__ = __ns If you are familiar with JS then you can simulate JS Object: class JSLikeObject(object): def __init__(self, __ns={}, **kwargs): if kwargs: __ns.update(kwargs) self.__dict__ = __ns def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): setattr(self, name, value) def __delitem__(self, name): delattr(self, name) def __iter__(self): return iter(self.__dict__) def __contains__(self, name): return hasattr(self, name) but I don't sagest to use it in real life. From bdesth.quelquechose at free.quelquepart.fr Thu Mar 1 16:58:45 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Mar 2007 22:58:45 +0100 Subject: python equivalent of bash find In-Reply-To: <1172780082.961223.222500@s48g2000cws.googlegroups.com> References: <1172780082.961223.222500@s48g2000cws.googlegroups.com> Message-ID: <45e744c1$0$17997$426a74cc@news.free.fr> BartlebyScrivener a ?crit : > I recently moved from XP to Linux, but would like to use Python > whenever possible. > > line from bash script: > > find ~/Mail -xdev -type f \( -mtime 0 -or -mtime 1 \) -exec cp -aPvu > "{}" /backup-dest \; > > What modules would I use to accomplish this in Python? Or any other > Python tricks to copy or backup all files modified today? MHO is that you'd better learn linux (well... Unix) tools. Reinventing the SquareWheel(tm) is usually not a good idea. From troy.melhase at gmail.com Sat Mar 3 03:20:16 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Fri, 2 Mar 2007 23:20:16 -0900 Subject: print a ... z, A ... Z, "\n"' in Python In-Reply-To: References: Message-ID: > How do you write Perl's > > print a ... z, A ... Z, "\n"' in Python > > > In Python? you might consider this cheating, but it's packed with zen goodness: >>> import string >>> print string.letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ From http Thu Mar 15 19:34:48 2007 From: http (Paul Rubin) Date: 15 Mar 2007 15:34:48 -0800 Subject: problem with str() References: <1173988141.493995.196780@n76g2000hsh.googlegroups.com> <1173990743.998399.82020@b75g2000hsg.googlegroups.com> Message-ID: <7xd53axeqv.fsf@ruckus.brouhaha.com> kyosohma at gmail.com writes: > methodList = [str for str in names if callable(getattr(obj, str))] > > instead, do something like this: > > methodList = [i for i in names if callable(getattr(obj, i))] or: methodList = list(str for str in names if callable(getattr(obj, str))) genexps, unlike listcomps, make a new scope for their index variable. From gigs at hi.t-com.hr Fri Mar 9 14:31:17 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 09 Mar 2007 20:31:17 +0100 Subject: tkinter text editor In-Reply-To: References: Message-ID: jim-on-linux wrote: > On Friday 09 March 2007 12:04, Gigs_ wrote: >> Gigs_ wrote: >>> I'm writing text editor. >>> >>> How to enable/disable (cut, copy etc.) when >>> text is selected/not selected >> Btw it is cut copy ... in edit menu > > > state = 'diabled' ## no change allowed > ## to Text Wiget > > state = 'normal' ## default for Text Wiget > > jim-on-linux > http:\\www.inqvista.com yes man but i want to make that when there is no selected text this menu items go DISABLED and when text is selected this menu items go NORMAL From richarddotjebbatpcfltd.co.uk Fri Mar 2 15:27:48 2007 From: richarddotjebbatpcfltd.co.uk (Richard Jebb) Date: Fri, 2 Mar 2007 20:27:48 -0000 Subject: Strange method signature via COM References: <45e8087b$0$765$5a6aecb4@news.aaisp.net.uk> <45e87c5e$0$7504$426a74cc@news.free.fr> Message-ID: <45e88963$0$760$5a6aecb4@news.aaisp.net.uk> After digging around in the group archives I've figured it out. It's not been helped by my inability to identify the API's COM server/type library in the list produced by the MakePy utility, so I've largely been flying blind. Some posts on this same subject back in 1999 revealed the answer, namely that when win32com encounters a method signature like the one we had, it expects you to call it like this: obj.Value("myfield", "newvalue") If there already exists an interface to Value() with this signature, then it prepends the original method name with "Set", so that in Python you would call obj.SetValue("myfield", "newvalue") We still have some other issues with the API, but I'm hoping once the application vendor has revealed what name it will appear under in MakePy we will be able to sort those out as well. "Bruno Desthuilliers" wrote in message news:45e87c5e$0$7504$426a74cc at news.free.fr... > Richard Jebb a ?crit : > > We are trying to use the API of a Win32 app which presents the API as a COM > > interface. The sample VB code for getting and setting the values of custom > > data fields on an object shows a method named Value(): > > > > getter obj.Value("myfield") > > setter obj.Value("myfield") = newvalue > > > > Using Python 2.5 and PythonWin we can get data from data fields using the > > identical syntax > > I have no experience with Python/COM, but IIRC, in VB (at least in VB6), > the parens are also used for array subscript. > > > > >>>>print comp.Value("Phone1") > > 99080980 > > > > However the set value fails (unsurprisingly) > > > > > >>>>comp.value("Phone1") = "6876876876" > > > > SyntaxError: can't assign to function call > > > > Does anyone have any idea how to use Python to address this type of method > > signature? > > Have you tried inspecting your COM object in an interactive Python > shell, using dir(), help() and the inspect module ? > > And FWIW, disd you try the following syntaxes: > comp.value['Phone1'] = "xxx" > comp['Phone1'] = "xxx" > > My 2 cents From esj at harvee.org Sun Mar 25 12:44:54 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 25 Mar 2007 12:44:54 -0400 Subject: organizing collections of small modules Message-ID: I have a bunch of small modules that I use within my application. Most of these modules are single file modules. Currently, I have them set up as stand-alone modules but because it's a royal pain to fetch five or 10 of these modules for each application and tracking whether or not they are all up to date, I'm considering putting them all into one collection (rcsoc a.k.a. random cross-section of code[1]) so it's easier to load, install, and manage. Are there better techniques for managing collections of modules in 2.4 or later? ---eric [1] derives from the expression that hamburger is "random cross-section of cow" From rschroev_nospam_ml at fastmail.fm Sun Mar 18 19:27:44 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 18 Mar 2007 23:27:44 GMT Subject: fifo queue In-Reply-To: <1174257160.540073.113380@b75g2000hsg.googlegroups.com> References: <1174257160.540073.113380@b75g2000hsg.googlegroups.com> Message-ID: drochom schreef: > hi, > > how would u improve this code? > > class queue: > ... I think I'd use collections.deque [1] instead of using a ring buffer as you're doing (I think) and doing a lot of manual bookkeeping. [1] http://docs.python.org/lib/deque-objects.html -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gagsl-py2 at yahoo.com.ar Thu Mar 8 03:50:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 05:50:16 -0300 Subject: Problem with Packages References: <1173332271.733596.159790@p10g2000cwp.googlegroups.com> <1173342404.977567.241310@30g2000cwc.googlegroups.com> Message-ID: En Thu, 08 Mar 2007 05:26:45 -0300, Srikanth escribi?: >> It appears that you forgot the basic rule: a package is a directory with >> an __init__.py file (even if empty). > > Exactly right. I didn't know that __init__.py is a mandatory one. > Thanks for pointing out. You may want to review this section on the Python Tutorial, covering packages: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 >> You need 4 of such files here. > > Thanks again for saying 4, cause I would have definetly put only 2 > (inside dir1_1 and dir2_2) That was absolutely intentional :) so you had to figure out *where* to put the __init__.py files... >> Maybe PyDev plays some tricks with PYTHONPATH or something... >> > I got the same doubt and I checked PyDev before posting, the > PYTHONPATH is exactly the same but I didn't notice or rather > overlooked __init__.py file it created automatically when I created > packages using the dialogs. Ah, those automagical tools... > Thanks you Gabriel! I'm glad you found it helpful! -- Gabriel Genellina From nagle at animats.com Tue Mar 20 13:44:51 2007 From: nagle at animats.com (John Nagle) Date: Tue, 20 Mar 2007 17:44:51 GMT Subject: Anything available that can read Microsoft .MDB files from Python? In-Reply-To: References: <56863eF27p5bmU1@mid.uni-berlin.de> <569ih4F27o9bdU1@mid.uni-berlin.de> Message-ID: Shane Geiger wrote: > Try installing it from source. Perhaps getting a newer verion is all > you would need. If at that point you find there is a bug, report it. I did. I finally got MDBtools to build by throwing out all the "configure" stuff and the makefiles, then writing some simple makefiles of my own that just build the command line tools. The supplied build files fail if you don't have bison, flex, autoconf, etc., although the documentation claims otherwise. There are some nice little command line tools in there, fighting to get out from under all the guck. The original author intended, I think, to build this thing up into a full database module for .MDB files. But that was back around 2004 and never got done. So MDBtools doesn't have enough stuff to directly interface to MDB databases as databases, but it has too much for a file format converter. It's the extra guck that has portability problems. I posted the makefiles I used to the MDBtools forums on SourceForge. John Nagle From kyosohma at gmail.com Mon Mar 26 09:40:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 06:40:49 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174916449.171929.138950@n76g2000hsh.googlegroups.com> On Mar 26, 8:20 am, "Noma... at gmail.com" wrote: > OK... > I've been told that Both Fortran and Python are easy to read, and are > quite useful in creating scientific apps for the number crunching, but > then Python is a tad slower than Fortran because of its a high level > language nature, so what are the advantages of using Python for > creating number crunching apps over Fortran?? > Thanks > Chris While I have never personally dealt with Fortran, I looked it up here: http://en.wikipedia.org/wiki/Fortran_code_examples The code examples speak for themselves. I recommend you look those over and then look over similar simple program written in Python. Python is still easier to read. Fortran also appears to be a compiled language, whereas Python is an interpreted language. Thus, Python programs can be tested faster. Fortran programs will likely run faster though. Check out www.python.org for good examples of Python code for the beginner and the advanced programmer. Mike From gregorywieber at gmail.com Sat Mar 31 14:32:43 2007 From: gregorywieber at gmail.com (gregorywieber at gmail.com) Date: 31 Mar 2007 11:32:43 -0700 Subject: Newbie Question (real-time communication between apps: audio, 3d, PD, Blender) In-Reply-To: <460e7283$0$27377$ba4acef3@news.orange.fr> References: <1175294306.124030.272350@l77g2000hsb.googlegroups.com> <460e7283$0$27377$ba4acef3@news.orange.fr> Message-ID: <1175365963.795610.56780@d57g2000hsg.googlegroups.com> Thank you, everyone! On Mar 31, 6:43 am, Laurent Pointal wrote: > gregorywie... at gmail.com wrote: > > Hi All, > > > I'm just beginning my exploration of Python and I have a rather > > general question. If two particular programs have Python scripting > > capabilities, does that mean those two programs can communicate in > > real time through Python? > > > I'm running some audio experiments (for artistic purposes) in the > > program Pure Data (PD). I would like to use data that I extract from > > audio files to affect 3-d game simulations in Blender. I don't know > > specifically what it is I would be manipulating -- this is an artistic > > project, so intend to do a lot of experimenting to see what I come up > > with... > > > My question(s): Is this possible, reasonable, plausible? > > Plausible, with a recent PC. > > I use some Java code + a research TTS engine (C) + Python code + Pure Data + > VirChor (3D renderer+interract, C++) in a TalkingHead project at LIMSI. > All these communicate via UDP, we just tries to keep amount of transmitted > data not too huge (ie. just transmit status, positions, commands...). > For the realtime side capacity, it depend on the process you need in > Python - if Python reveal to be too slow, you may write long computing code > into a separate C module or library (may see ctypes and pyrex). > Another point, if you build Python multithreading code in same process, the > Global Lock may lead to unefficient use of your computing capacities. > > Note. You may take a look at OSC (Open Sound Control), there is a module for > PD and one for Python. > > A+ > > Laurent. From claird at lairds.us Wed Mar 21 18:31:25 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 21 Mar 2007 22:31:25 +0000 Subject: Wikipedia and a little piece of Python History References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <871wjiuz5q.fsf@pobox.com> <1174508599.250404.176510@y66g2000hsf.googlegroups.com> Message-ID: In article <1174508599.250404.176510 at y66g2000hsf.googlegroups.com>, Paddy wrote: >On Mar 21, 8:20 pm, j... at pobox.com (John J. Lee) wrote: >> "Paddy" writes: >> > I just had a link to Tim peters first post on doctest: >> >http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 >> > removed fromhttp://en.wikipedia.org/wiki/Doctestas it doesn't fit >> > their guidelines for external links. >> > I wonder, could maybe the official website be persuaded to host a copy >> > so that it could be linked to? >> >> > Tim, would you object? >> >> It (wikipedia) is a wiki, why not edit the page and paste it in? >> >> John > >They have rules, and periodically trawl pages and clean them. I'd like >to stay within the rules. > >- Paddy. > Phaseit would be honored to memorialize a permanent URL for that post, or even the thread from which it's taken. Is that an appropriate resolution, Paddy? From diefirma at comcast.net Tue Mar 6 17:34:53 2007 From: diefirma at comcast.net (Nile) Date: 6 Mar 2007 14:34:53 -0800 Subject: When will 2.5.1 be released? In-Reply-To: <1173208347.506758.166620@30g2000cwc.googlegroups.com> References: <1173037797.127119.248300@h3g2000cwc.googlegroups.com> <1173208347.506758.166620@30g2000cwc.googlegroups.com> Message-ID: <1173220493.492862.299210@q40g2000cwq.googlegroups.com> On Mar 6, 1:12 pm, "A. Lloyd Flanagan" wrote: > On Mar 4, 2:49 pm, "Nile" wrote: > > > This is not a big deal but I would like to use Tix with 2.5. My > > understanding is this bug will be fixed in the 2.5.1 release. Does > > And while we're waiting for 2.5.1, can somebody post a clear (as > opposed to the one that comes with Tix ;)) explanation of how to > manually install Tix into python 2.5? It should be possible... LLoyd -Not possible - this is a known bug and won't be fixed until 2.5.1 From frank-python at benkstein.net Thu Mar 22 13:11:46 2007 From: frank-python at benkstein.net (Frank Benkstein) Date: Thu, 22 Mar 2007 18:11:46 +0100 Subject: challenge ? In-Reply-To: <1174581702.968531.82550@y66g2000hsf.googlegroups.com> References: <1174581702.968531.82550@y66g2000hsf.googlegroups.com> Message-ID: <20070322181146.6ac4999d@localhost> Hi, On 22 Mar 2007 09:41:43 -0700 "alain" wrote: > I have a problem I wonder if it has been solved before. > I have a dictionnary and I want the values in the dictionnary to be > annotated with the rank that would be obtained by sorting the values > > def annotate_with_rank(my_dict): > .... > return my_annotated_dict > > In other words, any value a_value would become a 2-tuple > (a_value,rank_of_a_value) > > I seek an elegant solution. In your specification of the problem it is unclear what should be done with duplicate values. My solution assigns every value a different rank (starting from 0) such that the highest rank is len(my_dict) - 1. def annotate_with_rank(my_dict): items = my_dict.items() items.sort(key = lambda (k, v): v) return dict((k, (i, v)) for i, (k, v) in enumerate(items)) Best regards, Frank Benkstein. -- GPG (Mail): 7093 7A43 CC40 463A 5564 599B 88F6 D625 BE63 866F GPG (XMPP): 2243 DBBA F234 7C5A 6D71 3983 9F28 4D03 7110 6D51 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From torriem at chem.byu.edu Sat Mar 31 23:40:51 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 31 Mar 2007 21:40:51 -0600 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <%4FPh.17001$PL.7906@newsread4.news.pas.earthlink.net> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175387715.022063.171570@b75g2000hsg.googlegroups.com> <%4FPh.17001$PL.7906@newsread4.news.pas.earthlink.net> Message-ID: <1175398851.25928.24.camel@enterprise> On Sun, 2007-04-01 at 02:49 +0000, Dennis Lee Bieber wrote: > Take that up with ACT... GNAT 3.15p was explicitly unencumbered, but > the current version of GNAT, in the GPL (no-service contract) form has > gone the other direction, claiming that executables must be released > GPL. The no-service contract version of the GPL is not the same as the standard GPLv2. Ordinarily the GPLv2 does not apply to the output of the program unless the license specifies that it does (a modification or addendum). Thus the output of a program is not part of the GPL usually, unless specified MySQL's take on the GPLv2 without an addendum is mistaken, in my opinion. However, copyright law probably still applies to the programs output regardless of license, but in what way I don't think the courts have ever specified, given that the output depends largely on the input. GCC, Bison, and Flex, all explicitly state that the output of the program is not under any license, and is your own property. Perhaps the author of Shed Skin could make a note in the license file to clarify the state of the output of his program. There should be no problem with this Shed Skin program being under the GPL and using it with python scripts that are not under the GPL. But if you have any concern with a copyright license at all, you should consult your lawyer. Too many companies see GPL'd programs as a free ride, not willing to accept that they need a copyright license to use the code just as they would with any code from any source. It's sad to see because free software gets an unfair bad rap because of the greed of others. On the other hand, others take an overly paranoid view of the GPL and pretend it is viral and somehow magically infects your code with the GPL license, which is false--if you use GPL'd code in your non GPL'd application then you are in a copyright violation situation and your only options are to either GPL your code or remove the offending GPL'd source from your code and write your own dang code, thank you very much. From syrax6l at hotmail.com Sat Mar 17 02:54:22 2007 From: syrax6l at hotmail.com (Milton Segura) Date: Sat, 17 Mar 2007 05:54:22 -0100 Subject: No subject Message-ID: Hello, I'm trying to exclude files from a list using the following code: for item in dirs: if item.find('Software') > -1: dirs.remove(item) elif item.find('Images') > -1: dirs.remove(item) let's supose dirs = ['C:\Images', 'C:\Images\2006', 'C:\Images\2007', 'C:\Music', 'C:\Files', 'C:\Software', 'C:\Software\Python', 'C:\Software\iTunes'] For some reason.. it just won't exclude them. I'd like to know why and how to fix it. Thanks in advance. Milton _________________________________________________________________ Explore the seven wonders of the world http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Tue Mar 27 14:15:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Mar 2007 11:15:54 -0700 Subject: How can I catch all exception in python? In-Reply-To: <1175018958.602131.145190@y80g2000hsf.googlegroups.com> References: <1175018958.602131.145190@y80g2000hsf.googlegroups.com> Message-ID: <1175019354.070308.4080@l77g2000hsb.googlegroups.com> On Mar 27, 1:09 pm, "ying... at gmail.com" wrote: > I read the document here about exception handling in python: > > http://www.diveintopython.org/file_handling/index.html > > Can you please tell me how can I catch all exception in python? > like this in Java: > try { > .... > > } catch (Throwable t) { > ... > } Technically speaking, you can catch all errors as follows: try: # do something except Exception, e: print e However, this is NOT the recommended way of handling errors. Typically you catch only expected errors, such as when you open a file, you check for an IOError. By catching all errors, you will learn less and likely have hard-to-understand bugs in your program. Mike From arnodel at googlemail.com Sat Mar 17 18:08:03 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 17 Mar 2007 15:08:03 -0700 Subject: Still the __new__ hell ... In-Reply-To: <1174167360.522350@jubilee.claranet.pt> References: <1174167360.522350@jubilee.claranet.pt> Message-ID: <1174169283.313703.157020@n59g2000hsh.googlegroups.com> On Mar 17, 9:31 pm, Paulo da Silva wrote: > Sorry to put here too many questions about __init__ __new__ > stuff but I always found a new problem when using them. > I have searched for simple __new__ docs on how to do the > basic things but find none. > > After trying the solutions people gently posted here > (thanks) I run into new trouble when I go with further > development. > > Here is the new situation. > > As suggested in a previous post, I used __new__ to > subclass date class but now cPickle/pickle loads > does not work. > > from datetime import date > import cPickle,string > > class MyDate(date): > def __new__(cls,year,month=None,day=None): > if type(year) is str: > year,month,day=map(int,string.split(year,'-')) > if year<100: > year+=2000 > return date.__new__(cls,year,month,day) > > class C1(object): > def __init__(self): > self.x=MyDate("2007-3-15") > > def f(self): > print self.x > > c1=C1() > > d=cPickle.dumps(c1) > c2=cPickle.loads(d) > c2.f() I haven't tried your code but I think that you may need to define a __reduce__ method in your MyDate class in order to give a clue to the python as to how to pickle its instances. For more details see: http://docs.python.org/lib/node321.html Something like: class MyDate(date): ... def __reduce__(self): return type(self), (self.year, self.month, self.day) might solve your problem. HTH -- Arnaud From lobais at gmail.com Fri Mar 2 18:56:23 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Sat, 03 Mar 2007 00:56:23 +0100 Subject: classes and functions References: Message-ID: Den Fri, 02 Mar 2007 19:26:08 -0300 skrev Silver Rock: > Friends, > > I don?t see why using classes.. functions does everything already. I > read the Rossum tutotial and two other already. > > Maybe this is because I am only writing small scripts, or some more > serious misunderstandings of the language. > > Please give me a light. I guess you are fimiliar with the string methods. You can do stuff like "hi hi".split(" ") or " hi".strip(). This is because a string is a class. The same functionality could be done by functions: split("hi hi", " ") and strip(" hi") but it feals more inituitive to put the dot after the variable. It also makes it easier to know where to look for functions related to the object. And yes, I'm sure you will see the light, when doing larger programs :) Don't worry. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 15 04:36:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 15 Mar 2007 09:36:32 +0100 Subject: Attribute monitoring in a class In-Reply-To: References: <45f7d65b$0$23624$426a74cc@news.free.fr> <45F7F242.9070002@gmail.com> Message-ID: <45F90590.1030601@wtf.websiteburo.oops.com> Gabriel Genellina a ?crit : > En Wed, 14 Mar 2007 10:01:54 -0300, Joel Andres Granados > escribi?: > >> Bruno Desthuilliers wrote: >>> Joel Andres Granados a ?crit : > >>>> I'm >>>> working with code that is not of my authorship and there is a class >>>> attribute that is changes by directly referencing it (object.attr = >>>> value) instead of using a getter/setter (object.setAttr(Value) ) > >>> yes : object.__setattr__(self, name, value) >> I used this ^^^^^^^^^^^^^^^ one. Thank for the help. > > The problem with __setattr__ is that it slows down significantly *all* > attributes. > Yours is the typical case when it's good to switch from using simple > attributes to using properties. If this has to become a feature of the class, yes, indeed. If it's just a temporary hack for debugging, the using the __getattr__ hook is quicker and less intrusive. From __peter__ at web.de Sat Mar 31 12:39:48 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 31 Mar 2007 18:39:48 +0200 Subject: Sorting a multidimensional array by multiple keys References: <1175346825.986685.42430@b75g2000hsg.googlegroups.com> Message-ID: Duncan Booth wrote: >>>> from operator import itemgetter >>>> data.sort(key=itemgetter(0)) >>>> data.sort(key=itemgetter(1)) >>>> data.sort(key=itemgetter(4)) >>>> data.sort(key=itemgetter(3)) Or, in Python 2.5: >>> data.sort(key=itemgetter(3, 4, 1, 0)) Peter From openopt at ukr.net Wed Mar 14 13:17:05 2007 From: openopt at ukr.net (dmitrey) Date: 14 Mar 2007 10:17:05 -0700 Subject: Python equivalents to MATLAB str2func, func2str, ischar, isfunc? In-Reply-To: References: <1173891444.243400.41690@e65g2000hsc.googlegroups.com> Message-ID: <1173892625.206379.263780@d57g2000hsg.googlegroups.com> Thank you (however in MATLAB ischar is the same as isstr) but what if I don't know the name of module? I.e. I have def myfunc(param): ... #where param can be both funcName or a function, and I want to obtain both name and func, something like if isinstance(param, basestring): func, funcName = , param else: func, funcName = param, param.__name__ what should I type instead of ? D. On Mar 14, 7:06 pm, Alexander Schmolck wrote: > "dmitrey" writes: > > I can't find these via web serch > > > thank you in advance, > > Dmitrey > > str2func: getattr(some_module, 'f') > func2str: f.__name__ > ischar: isinstance(x, basestring) and len(x) == 1 > isfunc: callable(x) # is most likely to be what you want > > 'as From bbxx789_05ss at yahoo.com Sun Mar 18 21:07:49 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Mar 2007 18:07:49 -0700 Subject: * operator--as in *args? In-Reply-To: <1174254032.155494.228530@e65g2000hsc.googlegroups.com> References: <1174251225.056602.99810@n59g2000hsh.googlegroups.com> <1174254032.155494.228530@e65g2000hsc.googlegroups.com> Message-ID: <1174266469.127020.186120@l77g2000hsb.googlegroups.com> On Mar 18, 3:40 pm, "Dustan" wrote: > For example: > aFunction(*(1,2,3)) > is equivalent to: > aFunction(1,2,3) > That's the context I've seen it in, but written like this: someFunc(*args) I played around with it a little bit, and it appears the * operator unpacks a list, tuple, or dictionary so that each element of the container gets assigned to a different parameter variable. Although with a dictionary, only the keys appear to be assigned to the parameter variables, e.g.: def g(a,b,c): print a, b, c dict = {"x":10, "y":20, "z":30} g(*dict) Is that right? From p_shakil at yahoo.com Mon Mar 5 19:25:03 2007 From: p_shakil at yahoo.com (p_shakil at yahoo.com) Date: 5 Mar 2007 16:25:03 -0800 Subject: Interface Implementation in Python Message-ID: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> Hi, I would like to know the interface concept in Python.How the Interface is defined and implemented in Python?. How to access the interface fromn Client? Thanks PSB From bbxx789_05ss at yahoo.com Fri Mar 16 11:38:54 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Mar 2007 08:38:54 -0700 Subject: python noob, multiple file i/o In-Reply-To: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> References: <1174017362.351956.303080@n76g2000hsh.googlegroups.com> Message-ID: <1174059534.271524.175440@b75g2000hsg.googlegroups.com> The general idiom for altering lines in a file is to open the original file and write the alterations to a temp file. After you are done writing to the temp file, delete the original file, and change the temp file name to the original file name. If instead you were to read the whole file into a variable, and then start overwriting the original file with the altered data, if your program should happen to crash after writing one line to the file, all the data in your variable would disappear into the ether, and your file would only contain one line of data. You can imagine what that would be like if you had lots of important data in the file. Here's my attempt that incorporates a temp file: ----- import os filepath = "./change_files" li = os.listdir(filepath) for name in li: fullpath = filepath + "/" + name if os.path.isfile(fullpath): infile = open(fullpath, 'r') lastDotPos = fullpath.rfind(".") fileName = fullpath[:lastDotPos] ext = fullpath[lastDotPos:] tempName = fileName + ext + ".temp" outfile = open(tempName, "w") for line in infile: outfile.write(line + "altered\n") outfile.close() os.remove(fullpath) os.rename(tempName, tempName[:-5]) --------------- I think it also needs some kind of check to make sure you have permissions to delete the original file. From tim.one at comcast.net Sun Mar 11 17:15:59 2007 From: tim.one at comcast.net (Tim Peters) Date: Sun, 11 Mar 2007 16:15:59 -0500 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> <1173635074.726444.88760@t69g2000cwt.googlegroups.com> <1hut4yc.o9f1kta318hnN%aleax@mac.com> <1hut7xu.5zs31l1cohfybN%aleax@mac.com> Message-ID: [attribution lost] ... >>> Yup: the workaround seems to be as simple as replacing all occurrences >>> of -0.0 with -(0.0). I'm embarrassed that I didn't figure this out >>> sooner. >>> >>> >>> x, y = -(0.0), 0.0 >>> >>> x, y >>> (-0.0, 0.0) [Alex Martelli] >> Glad it works for you, but it's the kind of workaround that could >> break with any minor tweak/optimization to the compiler... >> very fragile:-(. [also Alex] > OTOH, Python 2.4 works just fine...: > > Python 2.4.3 (#1, Apr 7 2006, 10:54:33) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> 0.0,-0.0 > (0.0, -0.0) > >>> -0.0,0.0 > (-0.0, 0.0) > > so it seems to be very specifically a 2.5 problem. It's a bug that keeps resurfacing, probably because there's no portable way to test that it stays fixed :-( (it's not an accident that the OP relied on atan2 to distinguish +0.0 from -0.0! they act the same in /almost/ all contexts). Python's grammar doesn't have negative numeric literals. Instead "-" CONSTANT_LITERAL looks like unary minus applied to the non-negative CONSTANT_LITERAL. All early versions of Python worked that way too. The first time the +/- 0.0 bug occurred is when the front end was changed to act as if "-" CONSTANT_LITERAL were a literal in its own right, and then that +0.0 == -0.0 caused the first instance of either in a compilation unit to be used as the value for all instances of both throughout the compilation unit. That was fixed by refusing to apply the optimimization if the value of CONSTANT_LITERAL was a float that compared equal to 0.0. 2.5 introduced a new front end and more ambitious constant-folding, and I expect the bug showed up again due to one of those. Note: printing the value of a float 0 may not reveal its sign. IIRC, glibc's float-to-string routines do display the sign of 0, but Microsoft's do not. However, atan2() is sensitive to the sign under both glibm and Microsoft's libm equivalent. From cjlesh at gmail.com Wed Mar 21 14:10:27 2007 From: cjlesh at gmail.com (cjl) Date: 21 Mar 2007 11:10:27 -0700 Subject: parsing tables with beautiful soup? In-Reply-To: <1174499030.042369.312350@n76g2000hsh.googlegroups.com> References: <1174499030.042369.312350@n76g2000hsh.googlegroups.com> Message-ID: <1174500627.339029.65590@n76g2000hsh.googlegroups.com> This works: for row in soup.find("table",{"class": "class_name"}): for cell in row: print cell.contents[0] Is there a better way to do this? -cjl From __peter__ at web.de Tue Mar 20 17:42:51 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Mar 2007 22:42:51 +0100 Subject: How to copy a ClassObject? References: Message-ID: Stargaming wrote: > Leave out the `new` module and use `type()` (exactly the same call as to > `new.classobj`) to achieve the same effect. No. new.classobj() creates a classic class whereas type() creates a new-style class. Also, >>> class First: pass ... >>> type("Tmp", (First,), {}) Traceback (most recent call last): File "", line 1, in TypeError: a new-style class can't have only classic bases Peter From nagle at animats.com Sat Mar 10 19:20:45 2007 From: nagle at animats.com (John Nagle) Date: Sat, 10 Mar 2007 16:20:45 -0800 Subject: merits of Lisp vs Python In-Reply-To: <87zm6kzodq.fsf@pobox.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> Message-ID: John J. Lee wrote: > John Nagle writes: > [...] > >> Python, on the other hand, is uphill all the way. Constant trouble >>with version issues, especially with C components called from Python. >>MySQLdb, M2Crypto, SSL - they all have platform/version >>incompatibility problems. I just spent three days making M2Crypto >>work on a new Linux server with a different Red Hat version. >>Neither Python's packaging tools nor the platform's packaging >>tools deal adequately with these issues. > > [...] > > You haven't been using mod_python, by any chance? > > > John No, haven't started to deal with that yet. Still using CGI. Not sure whether to use mod_python or fastcgi for the small requests where the Python load time swamps the time to do one SQL select and reply. Comments? John Nagle From ziga.seilnacht at gmail.com Sun Mar 4 03:14:23 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 4 Mar 2007 00:14:23 -0800 Subject: How to set docstrings for extensions supporting PyNumberMethods? In-Reply-To: <1172948422.661418.312560@8g2000cwh.googlegroups.com> References: <1172948422.661418.312560@8g2000cwh.googlegroups.com> Message-ID: <1172996063.517322.208220@j27g2000cwj.googlegroups.com> Nick Alexander wrote: > Hello, > > I am writing a python extension (compiled C code) that defines an > extension type with PyNumberMethods. Everything works swimmingly, > except I can't deduce a clean way to set the docstring for tp_* > methods. That is, I always have > > type.__long__.__doc__ == 'x.__long__() <==> long(x)' > > which a quick glance at the Python 2.5 source shows is the default. > > I have found that I can use PyObject_GetAttr and PyWrapperDescrObject > and set the descriptor objects d_base->doc to a char pointer... but I > can't tell if this is safe. Or the right way to do it. > > If I'm on the wrong list, please let me know! > Thanks, > Nick Alexander I think that the right way is to add the methods to the tp_methods slot and use METH_COEXIST in the PyMethodDef flags field. Example: /* start of silly module */ #include "Python.h" typedef struct { PyObject_HEAD double value; } SillyNumber_Object; /* Forward declarations */ static PyTypeObject SillyNumber_Type; #define SillyNumber_Check(op) PyObject_TypeCheck(op, &SillyNumber_Type) static PyObject * new_SillyNumber(PyTypeObject *type, double value) { PyObject *self; self = type->tp_alloc(type, 0); if (self == NULL) return NULL; ((SillyNumber_Object *)self)->value = value; return self; } static PyObject * SillyNumber_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { double value = 0.0; static char *kwlist[] = {"value", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|d:SillyNumber", kwlist, &value)) return NULL; return new_SillyNumber(type, value); } static PyObject * SillyNumber_add(PyObject *left, PyObject *right) { double sum; if (!SillyNumber_Check(left) || !SillyNumber_Check(right)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } sum = (((SillyNumber_Object *)left)->value + ((SillyNumber_Object *)right)->value); return new_SillyNumber(&SillyNumber_Type, sum); } static PyObject * SillyNumber_radd(PyObject *right, PyObject *left) { return SillyNumber_add(left, right); } static PyNumberMethods SillyNumber_as_number = { SillyNumber_add, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_divide */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ 0, /* nb_nonzero */ }; static PyMethodDef SillyNumber_methods[] = { {"__add__", SillyNumber_add, METH_O | METH_COEXIST, "Add two SillyNumbers."}, {"__radd__", SillyNumber_radd, METH_O | METH_COEXIST, "Same as __add__."}, {NULL, NULL, 0, NULL} }; static PyTypeObject SillyNumber_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "silly.SillyNumber", /* tp_name */ sizeof(SillyNumber_Object), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ &SillyNumber_as_number, /* 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 | /* tp_flags */ Py_TPFLAGS_CHECKTYPES | /* PyNumberMethods do their own coercion */ Py_TPFLAGS_BASETYPE, /* SillyNumber_Type allows subclassing */ "Silly float numbers", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SillyNumber_methods, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ SillyNumber_new, /* tp_new */ 0, /* tp_free */ }; static PyMethodDef silly_methods[] = { {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initsilly(void) { PyObject *module; module = Py_InitModule3("silly", silly_methods, "silly floating number type"); if (module == NULL) return; if (PyType_Ready(&SillyNumber_Type) < 0) return; Py_INCREF(&SillyNumber_Type); PyModule_AddObject(module, "SillyNumber", (PyObject *) &SillyNumber_Type); } /* end of silly module */ Results from the interactive session: >>> import silly >>> print silly.SillyNumber.__add__.__doc__ Add two SillyNumbers. >>> print silly.SillyNumber.__radd__.__doc__ Same as __add__. >>> n1 = silly.SillyNumber(3) >>> n2 = silly.SillyNumber(3.14) >>> type(n1 + n2) is silly.SillyNumber True HTH, Ziga From laurent.pointal at wanadoo.fr Sat Mar 10 09:29:26 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 10 Mar 2007 15:29:26 +0100 Subject: Database module & multithreading References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> Message-ID: <45f2bfbd$0$5094$ba4acef3@news.orange.fr> jupiter wrote: > Hi guys!!! > > > Just one quick question... Which database module should I use when I > want to use multi threading as my application requires lots of data > from internet ???? I also want this database module to be fast, simple > n efficient, in any case multi threading capabilities are # 1 > requirement. > > > Thanx Guys > > Anil See the threadsafety flag of Python DB-API V2 compliant database modules. 0 = no thread safe 1 = threads may share module 2 = + may share connections 3 = + may share cursors A+ Laurent. From andre.ditador9999 at gmail.com Sun Mar 4 13:00:41 2007 From: andre.ditador9999 at gmail.com (andre.ditador9999 at gmail.com) Date: 4 Mar 2007 10:00:41 -0800 Subject: Randomizing in Python In-Reply-To: References: <1172940368.958826.273260@j27g2000cwj.googlegroups.com> Message-ID: <1173031241.661923.4200@p10g2000cwp.googlegroups.com> On Mar 3, 1:56 pm, Mark Nenadov wrote: > On Sat, 03 Mar 2007 08:46:09 -0800, andre.ditador9... at gmail.com wrote: > > I want to randomize a certain calculation in Python but haven't > > figured it out yet. To explain what i mean, I' m going to use an > > example: > > I want to get the numbers to do a random > > experience database for a game. What would be necessary to do so? > > Look into the random module (http://docs.python.org/lib/module-random.html) > > random.choice selects a random item out of a sequence > random.shuffle shuffles a sequence randomly > random.random gives a random floating point number > > -- > Mark Nenadov -> skype: marknenadov, web:http://www.marknenadov.com > -> "Relying on the government to protect your privacy is like asking a > peeping tom to install your window blinds." -- John Perry Barlow Thanks a lot for the help!!!! From pyapplico at gmail.com Sun Mar 25 01:39:47 2007 From: pyapplico at gmail.com (pyapplico at gmail.com) Date: 24 Mar 2007 22:39:47 -0700 Subject: Using remote source code In-Reply-To: <1hvi1i4.11qqgaq109btn3N%aleax@mac.com> References: <1174795795.112606.21720@e65g2000hsc.googlegroups.com> <1hvi1i4.11qqgaq109btn3N%aleax@mac.com> Message-ID: <1174801187.128393.238840@o5g2000hsb.googlegroups.com> On Mar 25, 3:20 pm, a... at mac.com (Alex Martelli) wrote: > wrote: > > Is there any possible way that I can place a .py file on the internet, > > and use that source code in an .py file on my computer? > > You can write an import hook in any way you like; see > . > > Here's a trivial example (bereft of much error checking, etc). I've > uploaded tohttp://www.aleax.it/foo.pya toy module w/contents: > > def foo(): return 'foo' > > Here's a tiny program to import said module from my site: > > import urllib2, sys, new > > theurl = 'http://www.aleax.it/' > > class Examp(object): > names = set([ 'foo', ]) > def find_module(self, fullname, path=None): > if fullname not in self.names: return None > self.foo = urllib2.urlopen(theurl+fullname+'.py') > return self > def load_module(self, fullname): > module = sys.modules.setdefault(fullname, > new.module(fullname)) > module.__file__ = fullname > module.__loader__ = self > exec self.foo.read() in module.__dict__ > return module > > def hooker(pathitem): > print 'hooker %r' % pathitem > if pathitem.startswith(theurl): return Examp() > raise ImportError > > sys.path_hooks.append(hooker) > sys.path.append(theurl) > > import foo > print foo.foo() > > Alex Thanks for your help, now I can continue building my source code generator. :) From aleax at mac.com Thu Mar 15 01:56:46 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Mar 2007 22:56:46 -0700 Subject: performance question References: Message-ID: <1huzm0z.10016t21kr0wo0N%aleax@mac.com> Eric Texier wrote: > I need speed here. What will be the fastest method or does it matter? > > (for the example 'a' is only 3 values for the clarity of the example) > a = [1,3,4.] ## > > > method1: > > f.write("vec %f %f %f \n" % (a[0],a[1],a[2])) > > method2: > > f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n") > > also it there a relevant speed difference between making few small write > instead of 1 bigger one. Learn to use the timeit module from the standard library, particularly via the handy -mtimeit commandline switch, and you can measure performance issues for yourself. E.g., on my laptop: brain:~ alex$ python -mtimeit -s"a=[1,3,4];f=open('/dev/null','w')" 'f.write("vec %f %f %f \n" % (a[0],a[1],a[2]))' 100000 loops, best of 3: 5.64 usec per loop brain:~ alex$ python -mtimeit -s"a=[1,3,4];f=open('/dev/null','w')" 'f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n")' 100000 loops, best of 3: 3.36 usec per loop So, the ugly "method 2" is about 2.3 microseconds faster than the nicer "method 1" -- when the items of a are ints which method 1 widens to floats while method 2 doesn't (the results are different between the methods). When they're floats to start with...: brain:~ alex$ python -mtimeit -s"a=[1.,3.,4.];f=open('/dev/null','w')" 'f.write("vec %f %f %f \n" % (a[0],a[1],a[2]))' 100000 loops, best of 3: 5.45 usec per loop brain:~ alex$ python -mtimeit -s"a=[1.,3.,4.];f=open('/dev/null','w')" 'f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n")' 100000 loops, best of 3: 6.26 usec per loop then method 1 accelerates a little bit and method 2 slows down a lot, so method 1 is actually about 0.8 microseconds faster. Make sure you do your measurements with data that well represents your actual application needs, and -mtimeit will serve you well (if you don't care about that microsecond or two either way, which is often the case, then choose the nicer metod 1, of course:-). Alex From jimburton1 at gmail.com Thu Mar 22 06:04:00 2007 From: jimburton1 at gmail.com (Jim Burton) Date: 22 Mar 2007 03:04:00 -0700 Subject: On Java's Interface (the meaning of interface in computer programing) In-Reply-To: <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> References: <1174454636.100363.196640@l77g2000hsb.googlegroups.com> <1174484076.994815.89820@y66g2000hsf.googlegroups.com> <4fWdnTVj-Y3-HpzbnZ2dnUVZ_v-tnZ2d@comcast.com> Message-ID: <1174557840.338374.25990@d57g2000hsg.googlegroups.com> On 21 Mar, 19:11, Lew wrote: > Dr. Who wrote: > > Don't Feed The Trolls :-) > > But, but - you fed me!? > [blah] > > We could put up a contest - whoever finds and corrects the most errors in the > post wins. Ties broken by the quality of the correct explanations. Incorrect > explanations count against the entry. > > -- Lew Or you could stop feeding the trolls. From arnodel at googlemail.com Thu Mar 1 13:03:34 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 1 Mar 2007 10:03:34 -0800 Subject: class declaration shortcut In-Reply-To: References: <1172690801.455359.79410@q2g2000cwa.googlegroups.com> <1172748388.475530.57570@k78g2000cwa.googlegroups.com> Message-ID: <1172772214.569734.95990@n33g2000cwc.googlegroups.com> On Mar 1, 4:01 pm, Steven Bethard wrote: > Arnaud Delobelle wrote: [...] > This does pretty much the same thing as the recipe I posted: Not at all. My new_struct create returns a new class which is similar to a C struct (notice the __slots__). The recipe you refer to is nothing more a class which can be initialised with some attributes. It does not address the OP's question at all. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237 > > Note that your approach requires repetition of the 'Person' and quotes > around each attribute name, which the OP complained about. The recipe at > least gets rid of the repetition of 'Person'. The 'name' argument is not necessary. It is just here to give a user- friendly name to the newly created class. One could just as well write the new_struct function so that >>> Person = new_struct('name', 'tel', ...) Of course it would be impossible for the function written as above to name the class in a user-meaningful way. The recipe you refer to does not face this problem because it is not a method to quickly create a new class, it is merely a class whose __init__ method allows you to initialise some attribute at instance-creation time. As for the quotes around the attribute names, well... Let's say that if it was possible to do without, I don't think I would be using python... -- Arnaud From aleax at mac.com Thu Mar 15 01:21:13 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 14 Mar 2007 22:21:13 -0700 Subject: Returning other instance from __init__ References: <1173933158.948806@jubilee.claranet.pt> Message-ID: <1huzkla.i6dshw1grnysmN%aleax@mac.com> Paulo da Silva wrote: > I would like to implement something like this: > > class C1: > def __init__(self,xxx): > if ... : > self.foo = foo > self.bar = bar > else: > self=C1.load(xxx) > > def load(xxx): > ... > return instance_of_C1 > load=staticmethod(load) > > This does not seem correct. How can I do it? Use __new__ for such purposes, not __init__. (You need to make C1 newstyle, e.g. inherit from object, to make special method __new__ work). >From __new__ you can return whatever you wish. However, if you return an instance of C1, it _will_ be passed to __init__; so, just make sure __init__ doesn't redo the initialization if passed an already-initialized self. E.g.: class C1(object): def __new__(cls, xxx): if xxx: return type.__new__(cls, xxx) else: return C1.load(xxx) @staticmethod def load(xxx): return ...whatever... def __init__(self, xxx): if hasattr(self, 'foo'): return self.foo = 'foo' self.bar = 'bar' Alex From robert.kern at gmail.com Sat Mar 10 18:07:12 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 10 Mar 2007 17:07:12 -0600 Subject: distributed queue? In-Reply-To: <7xwt1olnlx.fsf_-_@ruckus.brouhaha.com> References: <7xwt1olnlx.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Does anyone have an implementation of a distributed queue? I.e. I > have a long running computation f(x) and I'd like to be able to > evaluate it (for different values of x) on a bunch of different > computers simultaneously, the usual "worker thread" pattern except > distributed across a network. I guess this is pretty easy to write > with a centralized socket listener that dispatches requests through a > Queue to multiple threads on the same machine, each talking > synchronously to a server socket. I wonder if something like it > already exists. I see a little bit of discussion in the newsgroup > archive but no obvious pointers to code. Take a look at the work being done on IPython: http://ipython.scipy.org/moin/Parallel_Computing -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From http Fri Mar 16 01:59:52 2007 From: http (Paul Rubin) Date: 15 Mar 2007 21:59:52 -0800 Subject: To count number of quadruplets with sum = 0 References: <1173998523.811044.299120@n76g2000hsh.googlegroups.com> <7xtzwldh28.fsf@ruckus.brouhaha.com> <7xtzwlkhq9.fsf@ruckus.brouhaha.com> <1174024143.049965.25710@l77g2000hsb.googlegroups.com> Message-ID: <7x6491k9t3.fsf@ruckus.brouhaha.com> "n00m" writes: > h = collections.defaultdict(itertools.repeat(0).next) Something wrong with h = collections.defaultdict(int) ????? > for x in e: > for y in r: > sch += h[-(x + y)] That scares me a little: I think it makes a new entry in h, for the cases where -(x+y) is not already in h. You want: for x in e: for y in r: sch += h.get(-(x+y), 0) From jstroud at mbi.ucla.edu Sun Mar 25 08:06:36 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 25 Mar 2007 12:06:36 GMT Subject: Tkinter Toplevel geometry In-Reply-To: References: <1174803181.656189.303200@l77g2000hsb.googlegroups.com> <0dtNh.9164$JZ3.2879@newssvr13.news.prodigy.net> Message-ID: James Stroud wrote: > James Stroud wrote: >> Chris wrote: >>> Hi, >>> >>> If a user resizes a Toplevel window, or I set a Toplevel's geometry >>> using the geometry() method*, is there any way to have the geometry >>> reset to that required for all the widgets? >>> >>> I think I found what I'm looking for in tk itself: >>> """ >>> 13.3. How can I clear the geometry settings for a toplevel? >>> If you want to have Tk resize your toplevel to what the toplevel >>> requires (ie: the user might have resized it, or a widget was >>> removed), use [wm geometry $toplevel]. >>> """ >>> [from http://tcl.sourceforge.net/faqs/tk/] >>> >>> >>> >>> * for instance, if I want to turn of Tkinter's automatic adjustment of >>> the window to fit all the widgets by doing something like >>> self.geometry(self.geometry()), is there any way to undo that? >>> >>> Thanks, >>> Chris >>> >> >> Hi Chris, >> >> I think you are on to something. The equivalent of >> >> [wm geometry $toplevel] >> >> in Tkinter would be >> >> sometop.geometry() >> >> Or, equivalently, >> >> sometop.wm_geometry() >> >> Or, calling the underlying tcl/tk interpreter directly >> >> sometop.tk.call('wm', 'geometry', str(sometop)) >> >> Which is redundant, but emphasizes the point: This does not resize the >> widget as expected nor does it cause the window to resize upon adding >> new packing slaves--at least for the X11 based Tkinter for mac via the >> fink debian based package manager. >> >> Really wish things worked according to the docs a lot of the time or >> that they weren't so poorly written. Perhaps they are implying that >> you must pass parameters, however they do not explain how one might >> generate said parameters to get the required size to which they >> allude. Terribly disappointing. >> >> James > > After playing with this an inordinate amount of time, I found that one > does need to supply parameters, namely the null parameter of an empty > string. Try: > > sometop.geometry('') > > This repacks according to the widgets. Not quite clear from the > miserable docs, is it? > > James Now for the advanced question, how might one bind that to the resize/maximize button of the window decorations? I'm guessing with protocol, but its way past my bedtime. James From mahs at telcopartners.com Sun Mar 11 18:58:07 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 11 Mar 2007 15:58:07 -0700 Subject: Signed zeros: is this a bug? In-Reply-To: References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> <1hut07q.1fhewdebmz1c0N%aleax@mac.com> <1173635074.726444.88760@t69g2000cwt.googlegroups.com> <1hut4yc.o9f1kta318hnN%aleax@mac.com> Message-ID: Gabriel Genellina wrote: > > (I cannot find peephole.c on the source distribution for Python 2.5, but > you menctioned it on a previous message, and the comment above refers to > the peephole optimizer... where is it?) > The peephole optimizer is in compile.c - the entry point is optimize_code BTW, I have written a pure-Python compiler which aims to be functionally identical to the Python 2.5 compiler, and is in fact very similar (much closer than stdlib.compiler). It may be helpful in investigating alternative workarounds for the -0.0 issue. http://svn.brownspencer.com/pycompiler/branches/new_ast/ Michael From mcPas.De.Spam at mclaveauPas.De.Spam.com Sat Mar 10 14:27:10 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sat, 10 Mar 2007 20:27:10 +0100 Subject: minimum age to learn python (a.k.a graphical vs text languages) References: Message-ID: Hi! Personally, I was yet in the belly of my mom, whom I already thought in Python? -- @-salutations Michel Claveau From j23212 at hotmail.com Sun Mar 18 17:55:47 2007 From: j23212 at hotmail.com (Jon Van DeVries) Date: Sun, 18 Mar 2007 11:55:47 -1000 Subject: python QT or python-GTK Message-ID: <45fdb561$0$17201$4c368faf@roadrunner.com> ** All the posts found in google are old. I'm assuming new improvements have been made to both IDEs. ** Please correct me if I'm wrong, I'm a newbie. 1. Which one of them requires fewer lines to accomplish the same thing? from what I understand QT it's just like Borland J-Builder. Meaning, you want a button, you draw it, then you double-click on it, a window opens up and you type events and behavior. And with GTK, you just type everything. 2. Which one is cross platform? (Linux, MacOS, Windows,etc). 3. Which one has more widgets? 4. Which one is the easiest to pick up? I tried perl-QT and oh boy that mother is cryptic. 5. Which one has a bigger support community? 6. or if you think both pythonQT and PythonGTK are junk please suggest the one you like/use? I work on a Linux platform with Python 2.4. Thanks guys, I appreciate your help. --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading made easy =--------- -= Get GrabIt for free from http://www.shemes.com/ =- From http Thu Mar 8 20:53:57 2007 From: http (Paul Rubin) Date: 08 Mar 2007 17:53:57 -0800 Subject: catching exceptions from an except: block References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> <1173345456.968709.128870@j27g2000cwj.googlegroups.com> <7xbqj3i7zk.fsf@ruckus.brouhaha.com> Message-ID: <7xodn3p4ga.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Are you saying it only works as advertised within the except clause of a > try...except block? I think that's the idea. It hadn't occurred to me that it could be used any other way, but I don't have the docs in front of me right now, so maybe I missed something. From bjourne at gmail.com Tue Mar 6 10:14:28 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 6 Mar 2007 16:14:28 +0100 Subject: Interface Implementation in Python In-Reply-To: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> References: <1173140703.325379.199240@v33g2000cwv.googlegroups.com> Message-ID: <740c3aec0703060714n6720dae9v42794f54bfdbd665@mail.gmail.com> On 5 Mar 2007 16:25:03 -0800, p_shakil at yahoo.com wrote: > Hi, > > I would like to know the interface concept in Python.How the > Interface is defined and implemented in Python?. > > How to access the interface fromn Client? You have a class with methods and data. You write many unit tests for that class which defines the behaviour of your interface. Make sure your class passes all those tests. When you are done, not only does your unit tests specify an interface, you also have a concrete class that implements that interface. Now replace the original class with another class. If that class also passes all your tests, then you can conclude that it also implements the same interface. -- mvh Bj?rn From paddy3118 at googlemail.com Thu Mar 22 01:08:00 2007 From: paddy3118 at googlemail.com (Paddy) Date: 21 Mar 2007 22:08:00 -0700 Subject: Wikipedia and a little piece of Python History In-Reply-To: <7xtzwee3gw.fsf@ruckus.brouhaha.com> References: <1174504730.728688.52380@y80g2000hsf.googlegroups.com> <7xtzwee3gw.fsf@ruckus.brouhaha.com> Message-ID: <1174540080.654815.26370@n76g2000hsh.googlegroups.com> On Mar 21, 8:39 pm, Paul Rubin wrote: > "Paddy" writes: > > I just had a link to Tim peters first post on doctest: > >http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 > > removed fromhttp://en.wikipedia.org/wiki/Doctestas it doesn't fit > > their guidelines for external links. > > Just sit tight for a while. It looks like someone went a bit > overboard removing those links with a bot, and is now in the process > of putting them back. I could not wait, and have just reverted the page. Thanks guys. - Paddy. P.S. Now all I need is the time to reorganize The Duck Typing entry - The Explanation in the Talk section is better than the article itself :-) From __peter__ at web.de Tue Mar 27 03:46:50 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Mar 2007 09:46:50 +0200 Subject: PDB does not allow jumping to first statement? References: <1174946787.291632.154690@n59g2000hsh.googlegroups.com> Message-ID: Duncan Booth wrote: > "Chris Lasher" wrote: > >> I noticed that I absolutely cannot jump back to the first statement >> (line 3, "a = 1") using the jump command. I can jump to any other line >> BUT the first statement's using the "jump " command. I >> experience the same behavior with Winpdb and rpdb2. Why is this? >> > > Which version of Python, and what happens when you try it? > > It works fine for me with Python 2.5 on Windows: > > C:\Temp>\python25\python -m pdb t.py >> c:\temp\t.py(3)() > -> a = 1 > (Pdb) s >> c:\temp\t.py(4)() > -> b = 2 > (Pdb) j 3 >> c:\temp\t.py(3)() > -> a = 1 > (Pdb) It looks like you successfully jumped to the first line, but it will be skipped if you try to execute it: $ cat tmp.py print "aaa" print "bbb" print "ccc" print "ddd" $ python2.5 -m pdb tmp.py > /home/nn/tmp.py(1)() -> print "aaa" (Pdb) s aaa > /home/nn/tmp.py(2)() -> print "bbb" (Pdb) j 1 > /home/nn/tmp.py(1)() -> print "aaa" (Pdb) s bbb <-- wrong > /home/nn/tmp.py(3)() -> print "ccc" (Pdb) s ccc > /home/nn/tmp.py(4)() -> print "ddd" (Pdb) j 2 > /home/nn/tmp.py(2)() -> print "bbb" (Pdb) s bbb <-- correct > /home/nn/tmp.py(3)() -> print "ccc" Peter From samuel.kortas at gmail.com Mon Mar 26 07:40:32 2007 From: samuel.kortas at gmail.com (Samkos) Date: 26 Mar 2007 04:40:32 -0700 Subject: the second of nested buttons using textvariable remains void! In-Reply-To: References: <1174522287.135371.26220@o5g2000hsb.googlegroups.com> Message-ID: <1174909232.938710.70670@l77g2000hsb.googlegroups.com> Thanks a lot Jim and James now it works fine! Sam From roopesh.raj at gmail.com Mon Mar 5 04:23:58 2007 From: roopesh.raj at gmail.com (Roopesh) Date: 5 Mar 2007 01:23:58 -0800 Subject: Mod python - mysql lock Message-ID: <1173086638.769972.254300@t69g2000cwt.googlegroups.com> Hi, In my mod_python project I am using mysql as the database. There is table card in which unique cards are stored. When a user request comes he has to get a unique card. In this situation I want to use LOCK with which I can prevent other users accessing the table. I tried excuting "LOCK" command of mysql through python code, but it is not locking the database. Any ideas why this isn't working and how can I do the same. //python code sql = "LOCK TABLES card WRITE" cursor.execute(sql) Regards Roopesh From adaworks at sbcglobal.net Mon Mar 19 02:22:15 2007 From: adaworks at sbcglobal.net (adaworks at sbcglobal.net) Date: Mon, 19 Mar 2007 06:22:15 GMT Subject: Choosing Python References: Message-ID: "Dennis Lee Bieber" wrote in message news:q7oLh.11380$PL.6562 at newsread4.news.pas.earthlink.net... > On Mon, 19 Mar 2007 02:21:35 GMT, declaimed the > following in comp.lang.python: > >> or Ada. Java could vanish tomorrow and, with Python >> and Ruby available, no one would miss Java at all. As for > > Except for all those software firms that have based their entire > production on Java {Most of which, based on a limited example of > tools at work, tend to be klutzy, idiosyncratic, slow... and for some, > new versions are incompatible with projects created with older ones} > -- Dennis, The same can be said for those who have chosen other languages and used them in non-standard ways. COBOL comes to mind. One of the many things I like about Ada is that it is the same wherever you use it. Python seems to be that way too. Java started out that way. It was the intention for Java to be more portable than it is. I have heard that Java was released before the developers were finished designing it. That would account for some of the upheaval in the language. I do know of one set of software systems that has simply stopped working after the initial release of Java was revised. The appliation was versioned it out of compliance. The hype surrounding Java, and the overly optimistic expectations of C++ are a small sample of good intentions gone awry. The same thing could happen to Python or Ruby if those who control it are not careful. Both languages, in my view, could benefit from a model of pre-, post-, and invariant assertions, but done badly, that could do more harm than good. So let's hope that Python and Ruby evolve better than C++. For C++, every new version seems designed to compensate for something that was wrong with some earlier version. Richard From rzantow at gmail.com Sat Mar 3 14:34:36 2007 From: rzantow at gmail.com (rzed) Date: Sat, 03 Mar 2007 14:34:36 -0500 Subject: print a ... z, A ... Z, "\n"' in Python References: <1hue4db.1ifwnsjmhm2pN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote in news:1hue4db.1ifwnsjmhm2pN%aleax at mac.com: > js wrote: > >> HI guys, >> >> How do you write Perl's >> >> print a ... z, A ... Z, "\n"' in Python >> >> In Python? > > This specific one is easy, though this doesn't generalize: > > import string > print string.lowercase + string.uppercase > > For the general case, there's no way to avoid calling chr and > ord, because a string in Python doesn't have a "natural > successor". So the only issue is how you prefer to hide those > calls &c (in some class or function) and you already received > suggestions on that. > No ord or chr in sight: # Inclusive character range. def pycrange(lo,hi): import string chars = string.letters + " " rstr = '' lp = chars.find(lo) hp = chars.find(hi) if lp < hp: rstr = chars[lp:hp+1] return rstr print pycrange('c','n') Lame code, though. -- rzed From jon+usenet at unequivocal.co.uk Sun Mar 11 08:19:51 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 11 Mar 2007 12:19:51 GMT Subject: Database module & multithreading References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> <54CIh.6545$M65.2077@newssvr21.news.prodigy.net> <2uEIh.14274$bb1.6709@newssvr17.news.prodigy.net> Message-ID: In article , Gabriel Genellina wrote: >>>> I don't know, but stock Python 2.5 seems to stick mysterious '.egg' >>>> files in the site-packages directory when you install things. >>> >>> Which "stock" Python? Not the one from www.python.org... >> >> Yes, the one from www.python.org. > > Those .egg must come from other installed packages... My mistake, they are ".egg-info". And they certainly do come from stock Python 2.5 from www.python.org and not anything else. They are installed by distutils/command/install_egg_info, which is automatically called by 'python setup.py install'. From kyosohma at gmail.com Tue Mar 20 14:05:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Mar 2007 11:05:25 -0700 Subject: Exceptions when closing a file In-Reply-To: References: Message-ID: <1174413925.474168.152570@p15g2000hsd.googlegroups.com> On Mar 20, 12:25 pm, Steven D'Aprano wrote: > Closing a file can (I believe) raise an exception. Is that documented > anywhere? I've spent a lot of frustrating time trying to track this down, > with no luck, which suggests that either my google-foo is weak or that it > isn't documented. Is IOError the only exception it can raise? > > The only thing I have found is this: > > http://mail.python.org/pipermail/python-bugs-list/2004-November/02603... > > Out of curiosity, is there a simple way to demonstrate close() raising an > exception that doesn't involve messing about with disk quotas? > > -- > Steven. I've never had any problems closing a file. Maybe you need to flush it before you close it? Are you running threads that access the file in ad hoc fashion or something else out of the ordinary? Is this some sort of long running process writing a large file? Mike From supercooper at gmail.com Thu Mar 29 09:35:13 2007 From: supercooper at gmail.com (supercooper) Date: 29 Mar 2007 06:35:13 -0700 Subject: urllib timeout issues In-Reply-To: References: <1175023315.536080.276550@n76g2000hsh.googlegroups.com> <1175028104.429759.165920@n76g2000hsh.googlegroups.com> Message-ID: <1175175313.022931.304830@n59g2000hsh.googlegroups.com> On Mar 27, 4:50 pm, "Gabriel Genellina" wrote: > En Tue, 27 Mar 2007 17:41:44 -0300, supercooper > escribi?: > > > > > On Mar 27, 3:13 pm, "Gabriel Genellina" > > wrote: > >> En Tue, 27 Mar 2007 16:21:55 -0300, supercooper > >> escribi?: > > >> > I am downloading images using the script below. Sometimes it will go > >> > for 10 mins, sometimes 2 hours before timing out with the following > >> > error: > > >> > urllib.urlretrieve(fullurl, localfile) > >> > IOError: [Errno socket error] (10060, 'Operation timed out') > > >> > I have searched this forum extensively and tried to avoid timing out, > >> > but to no avail. Anyone have any ideas as to why I keep getting a > >> > timeout? I thought setting the socket timeout did it, but it didnt. > > >> You should do the opposite: timing out *early* -not waiting 2 hours- and > >> handling the error (maybe using a queue to hold pending requests) > > >> -- > >> Gabriel Genellina > > > Gabriel, thanks for the input. So are you saying there is no way to > > realistically *prevent* the timeout from occurring in the first > > Exactly. The error is out of your control: maybe the server is down, > irresponsive, overloaded, a proxy has any problems, any network problem, > etc. > > > place? And by timing out early, do you mean to set the timeout for x > > seconds and if and when the timeout occurs, handle the error and start > > the process again somehow on the pending requests? Thanks. > > Exactly! > Another option: Python is cool, but there is no need to reinvent the > wheel. Use wget instead :) > > -- > Gabriel Genellina Gabriel...thanks for the tip on wget...its awesome! I even built it on my mac. It is working like a champ for hours on end... Thanks! chad import os, shutil, string images = [['34095d2','Nashoba'], ['34096c8','Nebo'], ['36095a4','Neodesha'], ['33095h7','New Oberlin'], ['35096f3','Newby'], ['35094e5','Nicut'], ['34096g2','Non'], ['35096h6','North Village'], ['35095g3','Northeast Muskogee'], ['35095g4','Northwest Muskogee'], ['35096f2','Nuyaka'], ['34094e6','Octavia'], ['36096a5','Oilton'], ['35096d3','Okemah'], ['35096c3','Okemah SE'], ['35096e2','Okfuskee'], ['35096e1','Okmulgee Lake'], ['35095f7','Okmulgee NE'], ['35095f8','Okmulgee North'], ['35095e8','Okmulgee South'], ['35095e4','Oktaha'], ['34094b7','Old Glory Mountain'], ['36096a4','Olive'], ['34096d3','Olney'], ['36095a6','Oneta'], ['34097a2','Overbrook']] wgetDir = 'C:/Program Files/wget/o' exts = ['tif', 'tfw'] url = 'http://www.archive.org/download/' home = '//fayfiler/seecoapps/Geology/GEOREFRENCED IMAGES/TOPO/Oklahoma UTMz14meters NAD27/' for image in images: for ext in exts: fullurl = url + 'usgs_drg_ok_' + image[0][:5] + '_' + image[0] [5:] + '/o' + image[0] + '.' + ext os.system('wget %s -t 10 -a log.log' % fullurl) shutil.move(wgetDir + image[0] + '.' + ext, home + 'o' + image[0] + '_' + string.replace(image[1], ' ', '_') + '.' + ext) From jeba_ride at yahoo.com Fri Mar 16 07:41:57 2007 From: jeba_ride at yahoo.com (Clement) Date: Fri, 16 Mar 2007 04:41:57 -0700 (PDT) Subject: Sharing Objects in Python Message-ID: <701552.85861.qm@web37215.mail.mud.yahoo.com> Can a object sharable by two different python programs... If so can you please explain... because my project needs two programs to access nearly 45GB file Symentaniously... By Clement Jeba kumar, Tenkasi. --------------------------------- It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Tue Mar 27 10:48:59 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 27 Mar 2007 09:48:59 -0500 Subject: socket read timeout In-Reply-To: References: Message-ID: <17929.11995.871552.920761@montanaro.dyndns.org> >> I am looking for the most efficient / cleanest way to implement a >> socket read with timeout (Windows mainly but would be great if the >> same code worked under *nix) Jarek> Did you see http://www.timo-tasi.org/python/timeoutsocket.py ? Also socket objects have timeout attributes now. Skip From raacampbell at gmail.com Sun Mar 18 15:58:48 2007 From: raacampbell at gmail.com (raacampbell at gmail.com) Date: 18 Mar 2007 12:58:48 -0700 Subject: Stuck with pyqt: can't get/read button IDs from a qbuttongroup Message-ID: <1174247928.718201.239610@n76g2000hsh.googlegroups.com> Hi, I'm learning Python and QT and have set myself the task of writing a simple calculator applet. I'm using Qt3 and with the designer have made a button group which contains 10 buttons to allow the user to press the digits 0 to 9. The idea is that the button group is associated with a single slot. When I click a button the qbuttongroup sends a signal to a slot I've named getNumber. At the moment I just want this to read buttonGroupid of the clciked button and write this to the screen (the buttonGroupid is equal to the value the user wishes to select). So if the user clicks on, say, button "7" then this digit will be printed to the listbox. Problem is that I can't work out how to read this ID. I can't believe it's this hard--I have RTFM, some programing experience, and have searched google for 3 days. No joy. The best I've managed so far is this line from the .ui.h file void calc::getNumber(int id) { self.listBox1.insertItem(str(id)) } which translates to this in the .py: def getNumber(self,a0): self.listBox1.insertItem(str(id)) All that does is is print the text "" to my list box. What am I missing? Thanks! From swiftset at gmail.com Thu Mar 22 02:41:25 2007 From: swiftset at gmail.com (swiftset) Date: 21 Mar 2007 23:41:25 -0700 Subject: interpreting glyph outlines from ttfquery? Message-ID: <1174545685.277420.26890@e1g2000hsg.googlegroups.com> I'm try to convert a glyph into a format I can easily numerically manipulate. So far I've figured out how to use ttfquery to get a list that represents the outline of a contour in a glyph: from ttfquery import describe, glyphquery, glyph f = describe.openFont("/usr/share/fonts/truetype/freefont/ FreeSans.ttf") n = glyphquery.glyphName(f, 'D') g = glyph.Glyph(n) c = g.calculateContours(f) o = glyph.decomposeOutline(c[1]) o looks like: [array([182, 82],'s'), (354, 82), (420.22222222222229, 90.000000000000014), (474.88888888888891, 114.0), ..., array([182, 82],'s'), array([182, 82],'s')] Is this a polyline? Thanks, Alex From martinunsal at gmail.com Sun Mar 4 19:21:39 2007 From: martinunsal at gmail.com (Martin Unsal) Date: 4 Mar 2007 16:21:39 -0800 Subject: Project organization and import Message-ID: <1173054099.721593.201870@h3g2000cwc.googlegroups.com> I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the isomorphism between filesystem and namespace, doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace. Python wants my namespace heirarchy to match my filesystem heirarchy. I find that a well organized filesystem heirarchy for a nontrivial project will be totally unwieldy as a namespace. I'm either forced to use long namespace prefixes, or I'm forced to use "from foo import *" and __all__, which has its own set of problems. 1a) Module/class collision. I like to use the primary class in a file as the name of the file. However this can lead to namespace collisions between the module name and the class name. Also it means that I'm going to be stuck with the odious and wasteful syntax foo.foo everywhere, or forced to use "from foo import *". 1b) The Pythonic way seems to be to put more stuff in one file, but I believe this is categorically the wrong thing to do in large projects. The moment you have more than one developer along with a revision control system, you're going to want files to contain the smallest practical functional blocks. I feel pretty confident saying that "put more stuff in one file" is the wrong answer, even if it is the Pythonic answer. 2) Importing and reloading. I want to be able to reload changes without exiting the interpreter. This pretty much excludes "from foo import *", unless you resort to this sort of hack: http://www.python.org/search/hypermail/python-1993/0448.html Has anyone found a systematic way to solve the problem of reloading in an interactive interpreter when using "from foo import *"? I appreciate any advice I can get from the community. Martin From john.pye at gmail.com Wed Mar 14 06:57:43 2007 From: john.pye at gmail.com (John Pye) Date: 14 Mar 2007 03:57:43 -0700 Subject: Passing a FILE* from Python into a MinGW/SWIG module Message-ID: <1173869863.712750.239070@d57g2000hsg.googlegroups.com> Hi all I understand that I can't hope to pass a FILE* from the Windows version of Python into a SWIG module that I've built using MinGW gcc/g+ +, because apparently the FILE* structure are different and incompatible. Is there an official workaround for this? Presumably I need to implement a mingw-compatible version of all the 'file' class in Python, eg import mingw import myswigmodule F1 = mingw.file("newfile.txt","rw") F1.write("somestuff") F1.seek(0) F2 = mingw.tmpfile() myswigmodule.dosomething(F1,F2) F2.seek(0) print F2.read() Has anyone done this? Is there a better way that doesn't require users of my module to adapt? Do I have to use the dreaded MSVS to compile my SWIG module? Cheers JP From laurent.pointal at wanadoo.fr Sat Mar 31 10:49:39 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 31 Mar 2007 16:49:39 +0200 Subject: Remote XML Parsing References: <1175238860.680426.134400@y80g2000hsf.googlegroups.com> <1175300992.985589.172320@p77g2000hsh.googlegroups.com> Message-ID: <460e73db$0$27377$ba4acef3@news.orange.fr> pyapplico at gmail.com wrote: > On Mar 30, 5:56 pm, Laurent Pointal wrote: >> pyappl... at gmail.com a ?crit : >> >> > How can I parse a remote XML file with Python? >> > And what will I be able to do with this XML file in Python? >> >> > Sorry if this is a noob-ish question. >> >> You can process XML data with Python as long as you can get it - you >> will be able to do what you want with it. >> >> How do you access your remote file ? >> >> ...more details would be welcome... > > Well I'll be happy to access in the way your comfortable with. Net protocols -> urllib2 module Local files (or network mounted files) -> open function Remote call -> xmlrpc, omniORBpy, pyrpc... Once you get the XML data... sax/dom/elementtree & Co (see Python docs, Dive Into Python...). From efrat_regev at yahoo.com Fri Mar 23 13:10:42 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Fri, 23 Mar 2007 19:10:42 +0200 Subject: Compiler-AST-Walk-Visitor: Any Examples or Documentation? Message-ID: <4604085c@news.bezeqint.net> Hello, I'm trying to write something that will translate Python code to pseudo-code (for teaching purposes). Googling around indicated that the compiler module is pertinent, especially creating a visitor to walk the generated AST: http://docs.python.org/lib/module-compiler.html I can build the AST, but I can't figure out how to write the visitor. The package documentation didn't help me out that much, and I couldn't find any examples. In fact, google only came up with this unanswered related question: http://mail.python.org/pipermail/python-list/2006-July/392716.html Any help is appreciated. Thanks and Bye, Efrat From alfaeco at gmail.com Fri Mar 30 05:04:19 2007 From: alfaeco at gmail.com (alfaeco at gmail.com) Date: 30 Mar 2007 02:04:19 -0700 Subject: Object Oriented Database with interface for Pyhton Message-ID: <1175245459.867371.92500@n76g2000hsh.googlegroups.com> Hello all I am looking for an object oriented database with interffaces for python. Either open source or commercial. I am looking for a Database not a object persistence system. I would like to be able to execute queries outside from the aplication. If posible wih OQL ( object query language ) The only candidate I have now is Cache from Intersystem Thanks in advance From greg at cosc.canterbury.ac.nz Thu Mar 1 19:09:37 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 02 Mar 2007 13:09:37 +1300 Subject: finding out the precision of floats In-Reply-To: <1172765892.645783.125420@h3g2000cwc.googlegroups.com> References: <1172401072.607179.241290@q2g2000cwa.googlegroups.com> <1172402444.935723.192200@m58g2000cwm.googlegroups.com> <1172405198.187516.276310@h3g2000cwc.googlegroups.com> <1172410271.154309.49700@j27g2000cwj.googlegroups.com> <1172412661.998318.109180@s48g2000cws.googlegroups.com> <1172585380.631673.257410@q2g2000cwa.googlegroups.com> <1172602729.777210.23070@a75g2000cwd.googlegroups.com> <1172662682.590738.301630@k78g2000cwa.googlegroups.com> <1172674419.411077.4210@t69g2000cwt.googlegroups.com> <1172683149.885750.323640@j27g2000cwj.googlegroups.com> <1172698199.219016.57710@v33g2000cwv.googlegroups.com> <1172745203.824496.208840@h3g2000cwc.googlegroups.com> <1172765892.645783.125420@h3g2000cwc.googlegroups.com> Message-ID: <54p8e9F21oh9iU1@mid.individual.net> John Machin wrote: > Storing 1.1 and using it in calculations may save you a few > microseconds a day in your real-time apps. The main advantage would be clarity of code. > naming 1.1 as "anualRate" (sic) is utterly ludicrous. So call it annualMultiplicationFactor or something in the code. -- Greg From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 30 06:03:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 30 Mar 2007 12:03:16 +0200 Subject: Object Oriented Database with interface for Pyhton In-Reply-To: <1175247009.786698.72390@l77g2000hsb.googlegroups.com> References: <1175245459.867371.92500@n76g2000hsh.googlegroups.com> <1175247009.786698.72390@l77g2000hsb.googlegroups.com> Message-ID: <460ce036$0$1390$426a74cc@news.free.fr> csselo at gmail.com a ?crit : (top-post corrected) > > On 30 Mart, 12:04, "alfa... at gmail.com" wrote: >> Hello all >> >> I am looking for an object oriented database with interffaces for >> python. Either open source or commercial. >> >> I am looking for a Database not a object persistence system. I would >> like to be able to execute queries outside from the aplication. If >> posible wih OQL ( object query language ) > http://www.sqlalchemy.org/ > > you ll like it. While sqlalchemy is one of the best things since sliced bread, it's definitevely *not* an OODB. From gagsl-py2 at yahoo.com.ar Fri Mar 9 08:16:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Mar 2007 10:16:19 -0300 Subject: Pb with descriptor and super ... References: Message-ID: En Fri, 09 Mar 2007 08:22:46 -0300, Erwan Adam escribi?: > Thanks for your answer ... I followed the link > and tried to use the "fully functional implementation of > the super() built-in class in pure Python" given > on this page and the result is quite surprising : It appears that there is some disagreement on how the super object should behave. If you want to know what it actually *does* now (not what it *should* do) you can look at typeobject.c, but it's a bit hard to read, and I don't understand it in full... Maybe looking at the test suite is easier, in test_descr.py -- Gabriel Genellina From dingbat at codesmiths.com Mon Mar 26 10:11:26 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 26 Mar 2007 07:11:26 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174918286.213517.100190@l77g2000hsb.googlegroups.com> On 26 Mar, 14:20, "Noma... at gmail.com" wrote: > what are the advantages of using Python for > creating number crunching apps over Fortran?? If you have to ask, you've not experienced enough Fortran to know its sheer horror. You can write programs in Python that do usefully complicated things, and you can get them to work in a reasonable time. Fortran can't do this, for anything more than the trivial. "Classic" Fortran tasks of the past are now seen as trivial. OK, so they did it to a lot of data, but they really didn't do anything very complex to it. You can also write Python that other people can read and maintain. You can't do this in Fortran, without a truly insane amount of trouble. As Fortran programs have historically been authored and hacked on by successive generations of grad students, this is the most vital feature of all. Finally we're no longer so interested in "number crunching". Number crunching used to consist of simple operations over vast arrays of data, although this was data with remarkably simple structure by today's standards. These just aren't the major class of problems of interest today. There's a massive difference between old-school FEA (bashing Newton and Hooke into tinier and tinier cells) and bioinformatics or anything involving the representation of big data graphs. > Python is a tad slower than Fortran If the Fortran program turns out to have been broken all along, then who cares? From BH at bh.com Mon Mar 26 12:30:18 2007 From: BH at bh.com (BH) Date: Mon, 26 Mar 2007 18:30:18 +0200 Subject: wx.grid problem In-Reply-To: <1174925041.703904.151900@y80g2000hsf.googlegroups.com> References: <4607e4f1$0$5098$ba4acef3@news.orange.fr> <1174925041.703904.151900@y80g2000hsf.googlegroups.com> Message-ID: <4607f550$0$5092$ba4acef3@news.orange.fr> Yes, absolutely, but try to minimize it, and the scrollbars stays hidden !!! kyosohma at gmail.com a ?crit : > On Mar 26, 10:20 am, BH wrote: >> Hi ! >> >> I have a small problem with wx.Grid and scrollbars. >> Scrollbars definitively dissapears after resizing the frame. >> >> Thx for help >> >> #---------------------------------------------------------------------- >> import wx,wx.grid >> #---------------------------------------------------------------------- >> class MainWindow(wx.Frame): >> def __init__(self,parent,id,title): >> wx.Frame.__init__(self,parent,wx.ID_ANY,title) >> #-- >> self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) >> self.grid.CreateGrid(numRows=10,numCols=2) >> self.grid.Fit() >> self.Fit() >> #-- >> self.Show(1) >> #---------------------------------------------------------------------- >> app = wx.PySimpleApp() >> frame=MainWindow(None,-1,'Grid sizer') >> app.MainLoop() >> del app > > If I understand this correctly, that is normal. Your grid is only two > columns by 10 rows, so if you resize your frame so that it shows all > rows and columns, the scroll bars will disappear, much like other > apps, such as FireFox. If you enlarge the frame enough, the scrollbars > go away. > > Mike > From steve at REMOVE.THIS.cybersource.com.au Mon Mar 19 23:41:26 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 20 Mar 2007 14:41:26 +1100 Subject: any ways to judge whether an object is initilized or not in a class References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> <566vcfF27jlu4U1@mid.uni-berlin.de> <1174293300.034362.282460@l75g2000hse.googlegroups.com> Message-ID: On Mon, 19 Mar 2007 19:48:37 +1100, Ben Finney wrote: > It's also best to inherit every class from another class, leading to a > single hierarchy for all classes and types. 'object' is the one to > choose if you don't want the behaviour of any other class. What's wrong with old-style classes? On the plus side: - Why inherit from something if you don't need to? - Less typing. - Attribute-lookup is much faster, perhaps as much as twice as fast. http://www.python.org/~jeremy/weblog/030506.html - Documentation on old style classes is more extensive. - You can't use new style classes for exceptions. On the minus side: - Properties don't work as you expect them too. - Slots don't work at all. In other words, the only reason why you HAVE to use a new style class is that you need properties or __slots__. You might WANT to use a new style class to inherit from built-in types. Otherwise, the choice between old and new is not very important. -- Steven. From noway at ask.me Wed Mar 21 19:55:09 2007 From: noway at ask.me (Giovanni Bajo) Date: Thu, 22 Mar 2007 00:55:09 +0100 Subject: [Swig-user] How to receive a FILE* from Python under MinGW? In-Reply-To: References: <460078E1.7000905@student.unsw.edu.au> <6f7c837c0703202008u47d6f0bp4e8019925ca52e03@mail.gmail.com> <4600AA7B.1080605@student.unsw.edu.au> Message-ID: On 21/03/2007 6.49, Carl Douglas wrote: > Hi John, > > In my case, all I needed was a PyFile_AsFile to get the File *. > However I found that Python errors going to stdout/stderr were not > being redirected properly when my code was linking to a different > version of the CRT than the build of Python I was using. > > In the end, I came up with one of two solutions, and I really don't > like recommending either: I suggest people to try my GCC 4.1.2 binary installer for Windows which fully integrates with Python and has scripts in place to solve the MSVCR71.DLL problem. It was announced on this very list a few days ago: http://www.develer.com/oss/GccWinBinaries Feedback is welcome! -- Giovanni Bajo From mail at microcorp.co.za Tue Mar 6 00:28:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 6 Mar 2007 07:28:17 +0200 Subject: How to Read Bytes from a file References: <1172731976.798583.36220@t69g2000cwt.googlegroups.com><1172757183.819978.219440@v33g2000cwv.googlegroups.com><1172764725.827624.298180@j27g2000cwj.googlegroups.com><1172771161.015437.50000@n33g2000cwc.googlegroups.com> <1173089510.258246.37250@t69g2000cwt.googlegroups.com> Message-ID: <000301c75fbc$596aa480$03000080@hendrik> "Bart Ogryczak" wrote: > On Mar 5, 10:51 am, Piet van Oostrum wrote: > > >>>>> "Bart Ogryczak" (BO) wrote: > > >BO> Any system with 8-bit bytes, which would mean any system made after > > >BO> 1965. I'm not aware of any Python implementation for UNIVAC, so I > > >BO> wouldn't worry ;-) > > > > 1965? I worked with non-8-byte machines (CDC) until the beginning of the > > 80's. :=( In fact in that time the institution where Guido worked also had such > > a machine, but Python came later. > > Right, I should have written 'designed' not 'made'. UNIVACs also have > been produced until early 1980s. Anyway, I'd call it > paleoinformatics ;-) The correct term is: "Data Processing", or DP for short. - Hendrik From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 14 05:09:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 14 Mar 2007 10:09:20 +0100 Subject: how to detect change of list of instances In-Reply-To: <1173853239.022266.327110@d57g2000hsg.googlegroups.com> References: <1173835404.477078.306410@b75g2000hsg.googlegroups.com> <1173853239.022266.327110@d57g2000hsg.googlegroups.com> Message-ID: <45f7bbaa$0$24662$426a74cc@news.free.fr> manstey a ?crit : > Thanks. > > All I want to know is whether the newlist, as a list of instances, is > modified. I thought equality was the way to go, but is there a simpler > way? How can I monitor the state of newlist and set a flag if it is > changed in anyway? Override the mutators - or just wrap them in a decorator. But I don't know if it's "simpler". And FWIW, it won't catch modifications of contained objects - only modifications of the list itself. So you'd also need to wrap contained objects in an object that would itself detect all changes and notify the container. Err... Looks like equality is the way to go. From DustanGroups at gmail.com Sun Mar 18 17:40:32 2007 From: DustanGroups at gmail.com (Dustan) Date: 18 Mar 2007 14:40:32 -0700 Subject: * operator--as in *args? In-Reply-To: <1174251225.056602.99810@n59g2000hsh.googlegroups.com> References: <1174251225.056602.99810@n59g2000hsh.googlegroups.com> Message-ID: <1174254032.155494.228530@e65g2000hsc.googlegroups.com> On Mar 18, 3:53 pm, "7stud" wrote: > Hi, > > I can't find any documentation for the * operator when applied in > front of a name. Is it a pointer? > > What about the @ operator? > > Are there python names for these operators that would make searching > for documentation on them more fruitful? > > Thanks For the *star, see apply here: http://docs.python.org/lib/non-essential-built-in-funcs.html For example: aFunction(*(1,2,3)) is equivalent to: aFunction(1,2,3) For the @ symbol, I assume you mean function decorators: http://docs.python.org/ref/function.html For example: @someDecorator def someFunc(): pass is equivalent to: def someFunc(): pass someFunc = someDecorator(someFunc) From goodTweetieBird at hotmail.com Tue Mar 20 18:03:28 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 20 Mar 2007 15:03:28 -0700 Subject: No module named ... Message-ID: <1174428208.836953.161070@l75g2000hse.googlegroups.com> I was having trouble with the 'no module named' error message when trying to import and noticed that other successful imports were pulling from .py files that had the dot replaced with $ and .class appended to the name. Actually in one case it picked up a .pyc file then created a .class file. How do I create a .class file from my .py file so that functions can be imported. Thanx, gtb From openopt at ukr.net Wed Mar 28 15:51:59 2007 From: openopt at ukr.net (dmitrey) Date: 28 Mar 2007 12:51:59 -0700 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: References: Message-ID: <1175111519.550674.160720@n59g2000hsh.googlegroups.com> Hi! Suppose I have a py-written module. Is it possible somehow run PyPy on the whole module? I didn't find it in documentation. And if yes (or if just run in every module func) what will be after computer restart? Should I restart PyPy on the module once again? And are there any chances/intends for PyPy to be included into Python core? Thx, D. On Mar 28, 12:48 am, Carl Friedrich Bolz wrote: > ==========================================PyPy1.0: JIT compilers for free and more > ========================================== > > Welcome to thePyPy1.0 release - a milestone integrating the results > of four years of research, engineering, management and sprinting > efforts, concluding the 28 months phase of EU co-funding! > > Although still not mature enough for general use,PyPy1.0 materializes > for the first time the full extent of our original vision: > > - A flexible Python interpreter, written in "RPython": > > - Mostly unaware of threading, memory and lower-level target platform > aspects. > - Showcasing advanced interpreter features and prototypes. > - Passing core CPython regression tests, translatable to C, LLVM and > .NET. > > - An advanced framework to translate such interpreters and programs: > > - That performs whole type-inference on RPython programs. > - Can weave in threading, memory and target platform aspects. > - Has low level (C, LLVM) and high level (CLI, Java, JavaScript) > backends. > > - A **Just-In-Time Compiler generator** able to **automatically** > enhance the low level versions of our Python interpreter, leading to > run-time machine code that runs algorithmic examples at speeds typical > of JITs! > > Previous releases, particularly the 0.99.0 release from February, > already highlighted features of our Python implementation and the > abilities of our translation approach but the **new JIT generator** > clearly marks a major research result and gives weight to our vision > that one can generate efficient interpreter implementations, starting > from a description in a high level language. > > We have prepared several entry points to help you get started: > > * The main entry point for JIT documentation and status: > > http://codespeak.net/pypy/dist/pypy/doc/jit.html > > * The main documentation and getting-startedPyPyentry point: > > http://codespeak.net/pypy/dist/pypy/doc/index.html > > * Our online "play1" demos showcasing various Python interpreters, > features (and a new way to program AJAX applications): > > http://play1.codespeak.net/ > > * Our detailed and in-depth Reports about various aspects of the > project: > > http://codespeak.net/pypy/dist/pypy/doc/index-report.html > > In the next few months we are going to discuss the goals and form of > the next stage of development - now more than ever depending on your > feedback and contributions - and we hope you appreciatePyPy1.0 as an > interesting basis for greater things to come, as much as we do > ourselves! > > have fun, > > thePyPyrelease team, > Samuele Pedroni, Armin Rigo, Holger Krekel, Michael Hudson, > Carl Friedrich Bolz, Antonio Cuni, Anders Chrigstroem, Guido Wesdorp > Maciej Fijalkowski, Alexandre Fayolle > > and many others: > http://codespeak.net/pypy/dist/pypy/doc/contributor.html > > What isPyPy? > ================================ > > Technically,PyPyis both a Python interpreter implementation and an > advanced compiler, or more precisely a framework for implementing dynamic > languages and generating virtual machines for them. > > The framework allows for alternative frontends and for alternative > backends, currently C, LLVM and .NET. For our main target "C", we can > can "mix in" different garbage collectors and threading models, > including micro-threads aka "Stackless". The inherent complexity that > arises from this ambitious approach is mostly kept away from the Python > interpreter implementation, our main frontend. > > PyPyis now also a Just-In-Time compiler generator. The translation > framework contains the now-integrated JIT generation technology. This > depends only on a few hints added to the interpreter source and should > be able to cope with the changes to the interpreter and be generally > applicable to other interpreters written using the framework. > > Socially,PyPyis a collaborative effort of many individuals working > together in a distributed and sprint-driven way since 2003. PyPywould > not have gotten as far as it has without the coding, feedback and > general support from numerous people. > > Formally, many of the current developers were involved in executing an > EU contract with the goal of exploring and researching new approaches > to language and compiler development and software engineering. This > contract's duration is about to end this month (March 2007) and we are > working and preparing the according final review which is scheduled > for May 2007. > > For the future, we are in the process of setting up structures to help > maintain conceptual integrity of the project and to discuss and deal > with funding opportunities related to furtherPyPysprinting and > developments. See here for results of the discussion so far: > > http://codespeak.net/pipermail/pypy-dev/2007q1/003577.html > > 1.0.0 Feature highlights > ============================== > > Here is a summary list of key features included inPyPy1.0: > > - The Just-In-Time compiler generator, now capable of generating the > first JIT compiler versions of our Python interpreter: > > http://codespeak.net/pypy/dist/pypy/doc/jit.html > > - More Python interpreter optimizations (a CALL_METHOD bytecode, a method > cache, rope-based strings), now running benchmarks at around half of > CPython's speed (without the JIT): > > http://codespeak.net/pypy/dist/pypy/doc/interpreter-optimizations.html > > - The Python interpreter can be translated to .NET and enables > interactions with the CLR libraries: > > http://codespeak.net/pypy/dist/pypy/doc/cli-backend.html > http://codespeak.net/pypy/dist/pypy/doc/clr-module.html > > - Aspect Oriented Programming facilities (based on mutating the Abstract > Syntax Tree): > > http://codespeak.net/pypy/dist/pypy/doc/aspect_oriented_programming.html > > http://codespeak.net/pypy/extradoc/eu-report/D10.1_Aspect_Oriented_Pr... > > - The JavaScript backend has evolved to a point where it can be used to > write AJAX web applications with it. This is still an experimental > technique, though. For demo applications which also showcase various > generated Python and PROLOG interpreters, see: > > http://play1.codespeak.net/ > > - Proxying object spaces and features of our Python interpreter: > > - Tainting: a 270-line proxy object space tracking and boxing > sensitive information within an application. > > - Transparent proxies: allow the customization of both application and > builtin objects from application level code. Now featuring an > initial support module (tputil.py) for working with transparent > proxies. > > For a detailed description and discussion of high level backends and > Python interpreter features, please see our extensive "D12" report: > > http://codespeak.net/pypy/extradoc/eu-report/D12.1_H-L-Backends_and_F... > > Funding partners and organisations > ===================================================== > > PyPydevelopment and activities happen as an open source project and > with the support of a consortium partially funded by a 28 month > European Union IST research grant for the period from December 2004 to > March 2007. The full partners of that consortium are: > > Heinrich-Heine University (Germany), Open End (Sweden) > merlinux GmbH (Germany), tismerysoft GmbH (Germany) > Logilab Paris (France), DFKI GmbH (Germany) > ChangeMaker (Sweden), Impara (Germany) From stargaming at gmail.com Mon Mar 5 13:41:52 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 05 Mar 2007 19:41:52 +0100 Subject: New to Python In-Reply-To: <1173119634.739433.240520@s48g2000cws.googlegroups.com> References: <1173119634.739433.240520@s48g2000cws.googlegroups.com> Message-ID: dnwurtz at gmail.com schrieb: > I am trying to get a program to add up input from the user to get to > the number 100 using a loop. However, I am having some issues. Here > is what I have so far. I know I am just trying to hard, but I am > stuck. Thank you for any help. > > print "We need to count to 100" > > high_number = 100 > total = 0 > > number = input("Enter your first number ") > sum = number + total > while sum < high_number: > print "Not there yet..." > number = input("Enter another number ") > > print "We are there!!!" > Just reading the error messages would be a good start. You assign `sum` to `number + total` but as I see it there's no `number` so far. You have to increment some variable with the user's input. (`sum += input(..)`) Additionally, `total` and `number` seem pretty redundant. You only need two variables, one containing the targeted number, one the current progress. By the way, input() is considered pretty evil because the user can enter arbitrary expressions. It is recommended to use raw_input() (till Python 3.0), in your case e. g. int(raw_input()) wrapped in a try-except block. HTH, Stargaming From B.Ogryczak at gmail.com Mon Mar 5 09:29:23 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 5 Mar 2007 06:29:23 -0800 Subject: Dictionary of Dictionaries In-Reply-To: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> References: <1173090144.783533.163920@p10g2000cwp.googlegroups.com> Message-ID: <1173104962.782667.50760@j27g2000cwj.googlegroups.com> On Mar 5, 11:22 am, b... at yahoo.com wrote: > messagesReceived = dict.fromkeys(("one","two"), {}) This creates two references to just *one* instance of empty dictionary. I'd do it like: messagesReceived = dict([(key, {}) for key in ("one","two")]) From tavares at fe.up.pt Sat Mar 17 06:24:58 2007 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: 17 Mar 2007 03:24:58 -0700 Subject: ECCOMAS VipIMAGE 2007 - Abstracts Submission Period Extended in TWO WEEKS Message-ID: <1174127098.173714.268090@l75g2000hse.googlegroups.com> International ECCOMAS Thematic Conference VipIMAGE 2007 - I ECCOMAS THEMATIC CONFERENCE ON COMPUTATIONAL VISION AND MEDICAL IMAGE PROCESSING 17-19th October 2007, FEUP, Porto, Portugal http://www.fe.up.pt/VIPIMAGE We would appreciate if you could distribute this information by your colleagues and co-workers. Dear Colleague, The Organizing Committee of VipMAGE has decided to extend the submission period in two weeks (March 31, 2007). More details regarding VipIMAGE can be found in the conference website: http://www.fe.up.pt/VIPIMAGE We are looking forward to see you in Porto next October. Important dates Submission of extended abstracts: March 31, 2007; Authors Notification: April 15, 2007; Lectures and Final Papers: May 15, 2007; Early registration fee: May 31, 2007. Invited Lectures - Automatic Generation of Computer Models from Multi-modal Bio- medical Imaging - Chandrajit Bajaj, USA - Computational Bioimaging and Visualization - Chris Johnson, USA - From Geometrical Models to Physiological Models of the Human Body - Herv? Delingette, France - Latest advances in Cardiovascular Informatics - Ioannis A. Kakadiaris, USA - Robust Algorithms for Deformable Contours - Jorge S. Marques, Portugal - Image Sequence Evaluation - Juan J. Villanueva, Spain - Fast Surface Segmentation and remeshing by finding geodesics - Laurent Cohen, France - Processing of Simultaneous acquisition of EEG and fMRI - Mario Forjaz Secca, Portugal - Automatic Construction of Statistical Shape Models using Non-Rigid Registration - Tim Cootes, UK - Theory of Digital Manifolds and its Applications to Medical Imaging - Valentin Brimkov, USA & Reinhard Klette, NZ Kind regards, Jo?o Manuel R. S. Tavares Renato Natal Jorge (conference co-chairs) From aleax at mac.com Sat Mar 17 11:49:00 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 17 Mar 2007 08:49:00 -0700 Subject: Mastering Python References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <1hv3735.f8r5bx3czob7N%aleax@mac.com> Message-ID: <1hv42s0.svb0kn1bx26vbN%aleax@mac.com> John Nagle wrote: ... > >>Mastery and quickly are opposing terms Took me 15 years on a job > >>using FORTRAN 77 and I still wouldn't have called myself a master. (I'm ... > Python just isn't that complicated. The syntax is straightforward, Neither is/was Fortran 77, net perhaps of a few syntax quirks that were easily avoided; yet few practitioners took the trouble (for example) of learning what manners of data aliasing (e.g. between routine parameters and/or data in COMMON blocks) were legal and which were not -- such a simple rule (if you write data through an alias and read or write the same memory through a different alias, you're breaking the rules of the language and the compiler's free to make dragons fly out of your nose), yet I've lost count of the number of times I've seen it broken during my Fortran days (broken by professional programmers who used Fortran to make a living and yet didn't care enough to know better, mind you -- I'm not talking about accidental mistakes, which of course can easily happen for a rule that the compiler need not enforce, but total ignorance of this simple rule). Alex From deets at nospam.web.de Tue Mar 13 08:06:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Mar 2007 13:06:26 +0100 Subject: Request for a change in the csv module. References: <1173741982.944813@jubilee.claranet.pt> <1173744248.195944.245550@t69g2000cwt.googlegroups.com> <1173747644.616698@jubilee.claranet.pt> <55n53lF25s78sU1@mid.uni-berlin.de> <1173785251.78605@jubilee.claranet.pt> Message-ID: <55nie2F255kfqU1@mid.uni-berlin.de> Paulo da Silva wrote: > Diez B. Roggisch escreveu: >> Paulo da Silva schrieb: > ... > >>> That works but it is a pain to use. >> >> Why? I think it's straightforward. > > That is not the point. The problem is to have things generalized. > I have some general purpose tables whose fields format I don't know > in advance. > Internally the numeric values are independent of localization. > Having a table, I don't like the idea of preformating things > before sending them to the csv for exportation. A little more > of programming and there will be no need for csv at all :-) > ... This is simply _not_ true. The details of a proper CSV format are difficult to get right, which is precisely why the module is there. >> The same is essentially true for dates as well, btw. How do you want to >> deal with them? > > This is a pertinent question I didn't think of. May be csv should handle > data conversions using 'locale'. > It is already automatically converting numbers to text > anyway, but unconditionally using the '.'. > As for the dates the dialect could include a format like YYYY-MM-DD > hh:mm:ss. Dates are not always 'locale' only. In pt_PT we use > YYYY-MM-DD or YY-MM-DD and sometimes DD-MM-YYYY. > One must remember that csv is not part of the language. So, to have > some kind of universality, it must use the specs (in dialect) for > formatting and 'locale' for data conversions. I'm not too convinced. It's so darn easy to convert the values to what one really needs for the actual use-case. Even for your generic case - all you need is type-based formatting dispatch. But if you add that complexity to the writers of the csv-module, you'll end up with a nasty configuration mechanism for special casing individual columns, or otherwise the next user comes and says "well, I need to format dates differently just for this case, how to do so in the csv-module". As your own example shows. The purpose of the module is solely to assist in creating properly formatted csv content in the sense that it is readable and parsable and results in strings for column values. Not more, not less (and you seem to underestimate that task, btw.) That it does convert non-string-values to strings when writing could be seen as convenience, or actual bug as it might cause troubles as you perceived them - but the solution would clearly be to get rid of this functionality, not enhance it. Diez From __peter__ at web.de Thu Mar 1 05:25:48 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Mar 2007 11:25:48 +0100 Subject: splitting perl-style find/replace regexp using python References: <1172741100.414936.269460@q2g2000cwa.googlegroups.com> <1LxFh.3180$BE2.57@newssvr27.news.prodigy.net> Message-ID: James Stroud wrote: > James Stroud wrote: >> John Pye wrote: >>> Hi all >>> >>> I have a file with a bunch of perl regular expressions like so: >>> >>> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ # >>> bold >>> /(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/ >>> b>''$3/ # italic bold >>> /(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ # >>> italic >>> >>> These are all find/replace expressions delimited as '/search/replace/ >>> # comment' where 'search' is the regular expression we're searching >>> for and 'replace' is the replacement expression. >>> >>> Is there an easy and general way that I can split these perl-style >>> find-and-replace expressions into something I can use with Python, eg >>> re.sub('search','replace',str) ? >>> >>> I though generally it would be good enough to split on '/' but as you >>> see the <\/b> messes that up. I really don't want to learn perl >>> here :-) >>> >>> Cheers >>> JP >>> >> >> This could be more general, in principal a perl regex could end with a >> "\", e.g. "\\/", but I'm guessing that won't happen here. >> >> py> for p in perlish: >> ... print p >> ... >> /(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/$1'''$2'''$3/ >> /(^|[\s\(])\_\_([^ ].*?[^ >> ])\_\_([\s\)\.\,\:\;\!\?]|$)/$1''$2<\/b>''$3/ /(^|[\s\(])\_([^ ].*?[^ >> ])\_([\s\)\.\,\:\;\!\?]|$)/$1''$2''$3/ py> import re >> py> splitter = re.compile(r'[^\\]/') >> py> for p in perlish: >> ... print splitter.split(p) >> ... >> ['/(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >> "$1'''$2'''$", ''] >> ['/(^|[\\s\\(])\\_\\_([^ ].*?[^ ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >> "$1''$2<\\/b>''$", ''] >> ['/(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$', >> "$1''$2''$", ''] >> >> (I'm hoping this doesn't wrap!) >> >> James > > I realized that threw away the closing parentheses. This is the correct > version: > > py> splitter = re.compile(r'(? py> for p in perlish: > ... print splitter.split(p) > ... > ['', '(^|[\\s\\(])\\*([^ ].*?[^ ])\\*([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', > "$1'''$2'''$3", ''] > ['', '(^|[\\s\\(])\\_\\_([^ ].*?[^ > ])\\_\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', "$1''$2<\\/b>''$3", ''] > ['', '(^|[\\s\\(])\\_([^ ].*?[^ ])\\_([\\s\\)\\.\\,\\:\\;\\!\\?]|$)', > "$1''$2''$3", ''] There is another problem with escaped backslashes: >>> re.compile(r'(? References: Message-ID: <1173196282.319123.230430@p10g2000cwp.googlegroups.com> On 6 Mar, 16:39, "Paolo Pantaleo" wrote: > > The os.system() (but all the other funciont with similar behavior) reports > wrong exit status. I can reproduce the bug in the following way I think you should look at some previous threads related to this (obtained by searching Google Groups for "os.system exit status code"): "grabbing return codes from os.system() call" http://groups.google.com/group/comp.lang.python/browse_frm/thread/efeab8a50ff16975/ "please help me understand os.system() result" http://groups.google.com/group/comp.lang.python/browse_frm/thread/4a9ab6d5a609e9ca/ "os.system() << 8 ?" http://groups.google.com/group/comp.lang.python/browse_frm/thread/f12ccab6389f482c/ In short, the returned code is actually a combination of two values, and you need to extract the expected status code by shifting the result 8 bits to the right. It may actually be more complicated than that, but the man page for system ("man 3 system") explains this in more detail. Paul From beliavsky at aol.com Mon Mar 26 18:57:31 2007 From: beliavsky at aol.com (Beliavsky) Date: 26 Mar 2007 15:57:31 -0700 Subject: Fortran vs Python - Newbie Question In-Reply-To: References: <1174915232.414568.197250@p15g2000hsd.googlegroups.com> Message-ID: <1174949851.558066.9500@b75g2000hsg.googlegroups.com> On Mar 26, 8:42 am, Jean-Paul Calderone wrote: > You can get the speed of fortran in Python by using libraries like > Numeric without losing the readability of Python. Numeric and Numpy will faster than raw Python for array operations, but I don't think they will match well-written C or Fortran, because compilers can better optimize code in those "less dynamic" languages. Someone recently mentioned here ("Quantum term project code- for interest and for help") an example where Numeric was 180 times faster in Fortran 95 using gfortran, asking for advice on how to speed up the Python code -- see https://wiki.asu.edu/phy416/index.php/A_Simple_Bose-Einstein_Condensate_Simulation . No one replied. From greg at cosc.canterbury.ac.nz Sun Mar 4 19:39:47 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 05 Mar 2007 13:39:47 +1300 Subject: Questions about app design - OOP with python classes In-Reply-To: <7x3b4lucn1.fsf@ruckus.brouhaha.com> References: <1172755442.612209.27140@k78g2000cwa.googlegroups.com> <45e733aa$0$25247$426a74cc@news.free.fr> <7xabywnugu.fsf@ruckus.brouhaha.com> <7xtzx4i43e.fsf@ruckus.brouhaha.com> <7x3b4lucn1.fsf@ruckus.brouhaha.com> Message-ID: <5517avF227a11U1@mid.individual.net> Paul Rubin wrote: > Maybe we can concoct a cross between Python and Haskell, and call it > "Paskell" after the philosopher Blaise ;-). No, we name it after Pascall's confectionery: http://www.homesick-kiwi.com/productpage.php?id=51 Lots of syntactic sugar. :-) -- Greg From cyberco at gmail.com Sat Mar 10 18:16:00 2007 From: cyberco at gmail.com (cyberco) Date: 10 Mar 2007 15:16:00 -0800 Subject: PIL: reading bytes from Image Message-ID: <1173568560.648691.61760@64g2000cwx.googlegroups.com> I'm using web.py to send an image to the client. This works (shortened): print open(path, "rb").read() but this doesn't: img = Image.open(path) img.thumbnail((10,10)) print img.getdata() or print img.load() How do I get the bytes of the Image object? 'getdata()' seemed the way, but unfortunately... From fabiofz at gmail.com Tue Mar 6 10:40:56 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 6 Mar 2007 12:40:56 -0300 Subject: wxPython import error... In-Reply-To: <1173055327.592532.256350@p10g2000cwp.googlegroups.com> References: <1173055327.592532.256350@p10g2000cwp.googlegroups.com> Message-ID: On 4 Mar 2007 16:42:07 -0800, king kikapu wrote: > > Hi, > > i am just completed installing Python/Pydev/Eclipse/wxPython on an > Ubuntu system and all are running fine except program that contains > references to wx > > It gives me: > ImportError: /usr/lib/python2.4/site-packages/wx-2.8-gtk2-unicode/wx/ > _core_.so: undefined symbol: PyUnicodeUCS4_FromEncodedObject > > I installed the wx packages the way the wx web site says, especially > for Ubuntu. > > Can anyone help with this as i have been searching the net for this > with no luck... > Is your pythonpath configured correctly within pydev (and not just in the system?) -- see http://fabioz.com/pydev/manual_101_interpreter.html Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Mar 11 06:44:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 07:44:12 -0300 Subject: Parsing Indented Text (like parsing Python) References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com> <1173595945.530722.273030@30g2000cwc.googlegroups.com> <000a01c763c0$6863a560$2102fea9@Guides.local> Message-ID: En Sun, 11 Mar 2007 06:34:03 -0300, Mike Schinkel escribi?: > I'm trying to write an app that parses a text file containing an outline > useing essentially the same indentation rules as Python source code, i.e. > the first level has no indent, the second level has one indent, third You can get some ideas from tabnanny.py or reindent.py, but perhaps they are too specific at parsing Python code. I hope this informal description may help: Start with IC = Previous IC = 0, and a stack with a single 0 element For each line in the file: compute the indentation column IC (that is, count the number of leading whitespace characters; perhaps replacing tabs as 8 spaces) compare IC with the Previous IC: same: continue with next line IC > previous ("indent"): push IC onto indent stack IC < previous ("dedent"): discard top of stack look at the new top of stack (but dont discard it); if not the same, indentation error. Previous IC = IC Note: You can rewrite the above without using Previous IC, only the stack... left to the reader :) Note 2: At each stage, the "indentation level" is the current stack size. -- Gabriel Genellina From MonkeeSage at gmail.com Mon Mar 5 22:45:38 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 19:45:38 -0800 Subject: how can I find out the value of an environment variable? In-Reply-To: <1173147734.603718.179870@8g2000cwh.googlegroups.com> References: <1173147734.603718.179870@8g2000cwh.googlegroups.com> Message-ID: <1173152738.059111.182590@30g2000cwc.googlegroups.com> On Mar 5, 8:22 pm, "ken" wrote: > how can I find out the value of an environment variable in my pythong > script? > > Thank you. RTFM... os.getenv http://docs.python.org/lib/os-procinfo.html Regards, Jordan From paddy3118 at googlemail.com Sat Mar 3 11:02:18 2007 From: paddy3118 at googlemail.com (Paddy) Date: 3 Mar 2007 08:02:18 -0800 Subject: Perl and Python, a practical side-by-side example. In-Reply-To: References: Message-ID: <1172937737.992104.223720@8g2000cwh.googlegroups.com> On Mar 2, 10:44 pm, "Shawn Milo" wrote: > I'm new to Python and fairly experienced in Perl, although that > experience is limited to the things I use daily. > > I wrote the same script in both Perl and Python, and the output is > identical. The run speed is similar (very fast) and the line count is > similar. > > Now that they're both working, I was looking at the code and wondering > what Perl-specific and Python-specific improvements to the code would > look like, as judged by others more knowledgeable in the individual > languages. Hi Shawn, there is a web page that gives examples from Perl's Datastructures Cookbook re-implemented in Python. It might be of help for future Python projects: http://wiki.python.org/moin/PerlPhrasebook - Paddy. From mail at microcorp.co.za Tue Mar 13 02:20:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 13 Mar 2007 08:20:49 +0200 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com><55fbgjF2492skU1@mid.individual.net><1173573654.009953.266280@30g2000cwc.googlegroups.com><7xbqj01u9c.fsf@ruckus.brouhaha.com> Message-ID: <01f501c7653e$1ee8cee0$03000080@hendrik> "Nick Craig-Wood" wrote: > Paul Rubin wrote: > > The fencepost method still seems to be simplest: > > > > t = sorted(random.sample(xrange(1,50), 4)) > > print [(j-i) for i,j in zip([0]+t, t+[50])] > > Mmm, nice. > > Here is another effort which is easier to reason about the > distribution produced but not as efficient. > > def real(N, M): > while 1: > t = [ random.random() for i in range(N) ] > factor = M / sum(t) > t = [ int(round(x * factor)) for x in t] > if sum(t) == M: > break > print "again" > assert len(t) == N > assert sum(t) == M > return t > > It goes round the while loop on average 0.5 times. > > If 0 isn't required then just test for it and go around the loop again > if found. That of course skews the distribution in difficult to > calculate ways! > I have been wondering about the following as this thread unrolled: Is it possible to devise a test that can distinguish between sets of: - five random numbers that add to 50, and - four random numbers and a fudge number that add to 50? My stats are way too small and rusty to attempt to answer the question, but it seems intuitively a very difficult thing. - Hendrik From nagle at animats.com Mon Mar 19 13:01:23 2007 From: nagle at animats.com (John Nagle) Date: Mon, 19 Mar 2007 17:01:23 GMT Subject: Documentation for "str()" could use some adjustment - Unicode issue In-Reply-To: References: Message-ID: Daniel Nogradi wrote: >> The Python documentation for "str" says >> "str([object]) : >> Return a string containing a nicely printable representation of an >> object." >> >> However, there's no mention of the fact that "str" of a Unicode string >> with non-ASCII characters will raise a conversion exception. The >> documentation (and several Python books) seem to indicate that "str" will >> produce some "printable representation" for anything, not raise an >> exception. >> >> I know, it was proposed in PEP 349 to change "str" to return Unicode >> strings, and that's coming someday, along with all-Unicode Python, >> but meanwhile, the documentation should be clear about this. > > > Hi John, I'm not at all an expert around here but my understanding of > the workflow is that bug reports should be submitted to the tracker at > sourceforge. There is no guarantee that they will be noticed there but > the chances there are much higher than for a message on the mailing > list. I just mention this because I've seen your mysqld, urllib and > other potentially important bug reports here with no action taken but > maybe submitting them to sourceforge would attract some developers. More people read the mailing list than the bug reports, and Google indexes it, so it puts the problem on record. If this problem were reported as a bug, there'd be denial that it was a problem, on the grounds that it will be fixed in a future version of Python. This was addressed in PEP 349 (status "Deferred"), so it's a known problem that's being ignored. Python strings are in transition; in ASCII-only Python, "str" could never raise a conversion exception, and when we get to Unicode-only strings, "str" will never raise a conversion exception. But right now, "str" can definitely raise an exception. The real problem is the published books on Python: "Learning Python", by Lutz and Ascher: "str(string) -- returns the string representation of any object." "Python in a Nutshell", by Martelli Doesn't really address the issue, but says that "print" calls "str" for conversions. Neither of these mentions that "str" is ASCII-only. I think that you can use "unicode()" on any object on which you can use "str()", but I'm not sure that's official. Incidentally, is "repr" ASCII-only, or does it understand Unicode? And what happens if the __str__() method of an object returns Unicode? John Nagle From olsonas at gmail.com Wed Mar 14 11:49:21 2007 From: olsonas at gmail.com (Drew) Date: 14 Mar 2007 08:49:21 -0700 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> Message-ID: <1173887361.736336.215330@l75g2000hse.googlegroups.com> On Mar 14, 11:44 am, Laurent Pointal wrote: > Both work, you may prefer xrange/iteritems for iteration on large > collections, you may prefer range/items when processing of the result > value explicitly need a list (ex. calculate its length) or when you are > going to manipulate the original container in the loop. > > A+ > > Laurent. Laurent - Extremely helpful, exactly what I was looking for. Thanks, Drew From jkn_gg at nicorp.f9.co.uk Sat Mar 31 10:05:58 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 31 Mar 2007 07:05:58 -0700 Subject: Indentation for code readability In-Reply-To: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> References: <1175245483.829907.89240@r56g2000hsd.googlegroups.com> Message-ID: <1175349958.840426.50710@p15g2000hsd.googlegroups.com> If I wanted to mark out stack depth stuff like this in python, I'd do it with some form of stylised comment, like this: # LEVEL 0 pushMatrix(): # ....LEVEL 1 drawstuff() pushMatrix() # ........LEVEL 2 drawSomeOtherStuff() popMatrix() # ....LEVEL 1 popMatrix() # LEVEL 0 (there's probably a better comment form for your specific requirement). Any decent modern editor should be capable of being set up to highlight such lines in a colour/style of your choice, and you then set your eyeball filter to look for those lines when you want to be sure of where you are. jon N From kale.priya at gmail.com Fri Mar 16 00:33:15 2007 From: kale.priya at gmail.com (priya kale) Date: Fri, 16 Mar 2007 10:03:15 +0530 Subject: Need help with apack compression code Message-ID: <864f00810703152133j812649bw3d890686043ce481@mail.gmail.com> I need to code for decompressing the file which is compressed using Apack, I am supposed to code it in visual c++, Plz help me finding algorithm compatible to Widows based C or c++. Regards, Priya Kale (Pune) -------------- next part -------------- An HTML attachment was scrubbed... URL: From misterwang at gmail.com Tue Mar 6 10:08:11 2007 From: misterwang at gmail.com (Peter Wang) Date: 6 Mar 2007 07:08:11 -0800 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> Message-ID: <1173193691.204641.206600@s48g2000cws.googlegroups.com> On Mar 5, 12:31 am, "Adam Atlas" wrote: > Right now I'm just testing and polishing up the code... in the > meantime, any comments? How does this work with compiled extension modules? From lbates at websafe.com Thu Mar 1 10:24:03 2007 From: lbates at websafe.com (Larry Bates) Date: Thu, 01 Mar 2007 09:24:03 -0600 Subject: Eric on XP for Newbie In-Reply-To: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> References: <1172679222.026525.248430@a75g2000cwd.googlegroups.com> Message-ID: <45E6F013.5050901@websafe.com> jeffwatkins2000 at gmail.com wrote: > I'm starting on the path of freeing myself from proprietory software > but I need to migrate, not make one huge jump. > > I'm looking at using Python and Eric for programming > > I've got Python up and running but can someone please point me to a > simple step by step guide for installing Eric? I've downloaded the tar > files, but what do I do with them? > > Thanks > Take a look at PyScripter also. I REALLY like it a lot on Windows: http://mmm-experts.com/Products.aspx?ProductId=4 -Larry From dave.opstad at monotypeimaging.com Tue Mar 13 16:14:22 2007 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Tue, 13 Mar 2007 13:14:22 -0700 Subject: struct.pack oddity References: <45f6bd4a$0$6972$afc38c87@> <45f6d7a9$1@nntp.zianet.com> Message-ID: In article , Larry Bates wrote: > 1) You can't put 100000 into a half-word. The limit is 2**16 > or 65535. On Python 2.5 I get: Yes, I know. I used that example to illustrate the problem. If a value does not fit a format then Python should report that consistently, independent of whether a byte-order indication is explicit or implicit. Dave From aleax at mac.com Sun Mar 11 13:26:57 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 11 Mar 2007 10:26:57 -0700 Subject: Signed zeros: is this a bug? References: <1173627073.507023.36070@j27g2000cwj.googlegroups.com> Message-ID: <1hut07q.1fhewdebmz1c0N%aleax@mac.com> Mark Dickinson wrote: > I get the following behaviour on Python 2.5 (OS X 10.4.8 on PowerPC, > in case it's relevant.) > > >>> x, y = 0.0, -0.0 > >>> x, y > (0.0, 0.0) > >>> x, y = -0.0, 0.0 > >>> x, y > (-0.0, -0.0) > > I would have expected y to be -0.0 in the first case, and 0.0 in the > second. Should the above be considered a bug, or is Python not > expected to honour signs of zeros? I'm working in a situation > involving complex arithmetic where branch cuts, and hence signed > zeros, are important, and it would be handy if the above code could be > relied upon to do the right thing. Looks to me like you've found a bug with the parser/compiler: >>> c=compile('-0.0,0.0', 'eval', 'eval') >>> eval(c) (-0.0, -0.0) >>> dis.dis(c) 1 0 LOAD_CONST 1 ((-0.0, -0.0)) 3 RETURN_VALUE Similar problems appear in parsing display forms of lists and dicts and calls to functions with constant arguments (among which a constant 0.0 and a constant -0.0) -- and more generally when both constants -0.0 and 0.0 appear within the same "unit of compilation" (expression, function, ...) as for example in: >>> def f(): ... a = -0.0 ... return a, 0.0 ... >>> f() (-0.0, -0.0) >>> Why I think it has specifically to do with parsing/compiling, e.g.: >>> {23:-0.0, 45:0.0} {45: -0.0, 23: -0.0} >>> x=0.0 >>> y=-0.0 >>> {23:x, 45:y} {45: -0.0, 23: 0.0} >>> so there appears to be no problem once the 0.0 and -0.0 values come from variables or the like -- only if they're both from constants within the same "unit of compilation". Indeed, if you put the code above in a function, rather than in separate entries to the toplevel interpreter...: >>> def g(): ... x = 0.0 ... y = -0.0 ... return {23:x, 45:y} ... >>> g() {45: 0.0, 23: 0.0} >>> ...the bug surfaces again. Looks a bit like the result of a slightly errant "peephole optimizer" pass which tries to roll multiple occurrences of "the same constant" within the same codeobject into a single one, and consider two immutables a "multiple occurrence" if they're == to each other (as, indeed, 0.0 and -0.0 must be). The Python-coded compiler package does NOT give the problem: >>> compiler.compile('-0.0,0.0','zap','eval') at 0x70068, file "zap", line 1> >>> dis.dis(_) 1 0 LOAD_CONST 1 (0.0) 3 UNARY_NEGATIVE 4 LOAD_CONST 1 (0.0) 7 BUILD_TUPLE 2 10 RETURN_VALUE ...presumably because it doesn't do peephole optimization (nor any other kind of optimization). Unfortunately I've never really looked in depth into these parts of Python so I can't help much; however, if you open a bug at I think you stand a good chance of eventually seeing it fixed in 2.5.x for some x. Python/peephole.c does appear to be taking some care in constant folding: 192 case UNARY_NEGATIVE: 193 /* Preserve the sign of -0.0 */ 194 if (PyObject_IsTrue(v) == 1) 195 newconst = PyNumber_Negative(v); so I suspect the problem is elsewhere, but I can't find it yet. Alex In the meantime, I hope that some available workarounds for the bug are clear from this discussion: avoid using multiple constants in a single compilation unit where one is 0.0 and another is -0.0, or, if you really can't avoid that, perhaps use compiler.compile to explicitly build the bytecode you need. From flgoms at hotmail.com Mon Mar 12 13:01:18 2007 From: flgoms at hotmail.com (Fabio Gomes) Date: Mon, 12 Mar 2007 20:01:18 +0300 Subject: backslashes in lists Message-ID: It didn't work. I decided to submit the code in the list.It is a script running with Jython to modify some configurations in the Websphere Application Server that has a Java like command line that interprets jython or jacl. I decided to use Jython.All the properties in that server are stored in hierarchy in the form of lists into lists. An exemple of one of the properties follows:['systemProperties', [[['description', 'Arquivo de configuracao da arquitetura'], ['name', 'A_INI'], ['required', 'false'], ['value', '/xml/a_ini.xml']], [['description', 'Raiz do Ambiente'], ['name', 'A_ROOT'], ['required', 'false'], ['value', 'file://D:\\A\\D9']]]]All above in a single string.To make the things easier to me and the other people who will read that script, I decided to declare each subset of lists separatly. Something like that:list1 = ['name', 'value']list2 = ['path', 'c:\some\path']list3 = [list1, list2]But doing that, list2 will be parsed by repr() and will receive an extra '\' when inserted int list3, messing up with the path information. I need some aproach to build that string without have to write it in one long and confuse string. Maybe hash tables will be the answer. I need to read about it.The entire code follows, remembering you that AdminConfig is an object present only in the WebSphere:## Creates the JVM custom properties A_INI and A_ROOT## Custom Propertiesattr1_desc = ['description', 'Arquivo de configuracao da arquitetura']attr1_name = ['name', 'A_INI']attr1_required = ['required', 'false']attr1_value = ['value', '/xml/a_ini.xml']attr1_List = [attr1_desc, attr1_name, attr1_required, attr1_value]attr2_desc = ['description', 'Raiz do Ambiente']attr2_name = ['name', 'A_ROOT']attr2_required = ['required', 'false']# ID of all application serversallServers = AdminConfig.getid('/Server:/')import javalineSeparator = java.lang.System.getProperty('line.separator')arrayAllServers = allServers.split(lineSeparator)# processing for each serverfor serverID in arrayAllServers: # bypass if it isn't an (real) application server if AdminConfig.showAttribute(serverID, 'name') == 'dmgr': continue if AdminConfig.showAttribute(serverID, 'name') == 'nodeagent': continue if AdminConfig.showAttribute(serverID, 'name') == 'webserver': continue serverName = AdminConfig.showAttribute(serverID, 'name') print 'Atualizando o servidor', serverName, '...' jvm = AdminConfig.list('JavaVirtualMachine', serverID) path = 'file://D:\\A\\' + serverName[5:] attr2_value = ['value', path] attr2_List = [attr2_desc, attr2_name, attr2_required, attr2_value] attr_List = [attr1_List, attr2_List] property = ['systemProperties', attr_List] AdminConfig.modify(jvm, [property])print 'Salvando configuracoes...'AdminConfig.save()#EOF Date: Mon, 12 Mar 2007 13:40:58 -0300From: lucastorri at gmail.comTo: flgoms at hotmail.comSubject: Re: backslashes in listsCC: python-list at python.orgjust like the same way, but replace alist -> list:str(list).replace('\\\\','\\')as the time you call str(object) you will have an object of type string, and you can do whatever you want/could do with it... what are you trying?! isn't more interesting use a hash table?On 3/12/07, Fabio Gomes wrote: Nice, Lucas. But help me again, please. What about "echoing" the list:>>> str(alist).replace('\\\\','\\')"['a', 'b', 'c:\\some\\path']" Because in my script I'm echoing the list to mount lists into lists, like:>>> list1 = ['name', 'test']>>> list2 = ['path', 'c:\some\path'] >>> list = [list1, list2]>>> print list[['name', 'test'], ['path', 'c:\\some\\path']] That's how it is coded in my script. What do you think. Is it possible to print "list" without the doubled backslash? Thank again, Lucas. Date: Mon, 12 Mar 2007 12:15:10 -0300 From: lucastorri at gmail.comTo: flgoms at hotmail.comSubject: Re: backslashes in listsCC: python-list at python.org I don't know how ugly this look like, but { print str(alist).replace('\\\\', '\\') } works...On 3/12/07, Fabio Gomes wrote: Yes, Luca. I noticed that printing the list item will show the string as expected. But I need to print the entire list in the script I'm writing and doing that, the list will will be repr()'ed. Is there any way to print the entire list without being parsed by repr()? Date: Mon, 12 Mar 2007 12:00:19 -0300From: lucastorri at gmail.comTo: flgoms at hotmail.comSubject: Re: backslashes in listsCC: python-list at python.orgThe backslash is a key to enter especial characters, like breakline: '\n'There is two backslashes cause of this especial condition of this char, but if you try print the specific string you will see that only one backslash remain: print alist[2]On 3/12/07, Fabio Gomes wrote: Hi list, I'm trying to use a string with backslashes in a list. But Python parses strings in lists with repr().>>> alist = ['a', 'b', 'c:\some\path']>>> alist ['a', 'b', 'c:\\some\\path']>>> print alist['a', 'b', 'c:\\some\\path'] I already tried str() and raw (r) but it didn't work. All I want is to keep a single backslash in the string since it is a path information. Can anyone help me, please? Thank you.O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na Web e sua rede amigos. Confira! --http://mail.python.org/mailman/listinfo/python-list Busque em qualquer p?gina da Web com alta prote??o. Obtenha o Windows Live Toolbar GRATUITO ainda hoje! Experimente agora! --http://mail.python.org/mailman/listinfo/python-list O Windows Live Spaces est? aqui! Descubra como ? f?cil criar seu espa?o na Web e sua rede amigos. Confira! --http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Ligue para os seus amigos gr?tis. Fa?a chamadas de PC-para-PC pelo messenger-- GR?TIS http://get.live.com/messenger/overview -------------- next part -------------- An HTML attachment was scrubbed... URL: From spe.stani.be at gmail.com Tue Mar 6 11:26:09 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 6 Mar 2007 08:26:09 -0800 Subject: Graphviz Python Binding for Python 2.5 on Windows? In-Reply-To: <1173166774.038781.262760@t69g2000cwt.googlegroups.com> References: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> <1173166774.038781.262760@t69g2000cwt.googlegroups.com> Message-ID: <1173198369.791160.194030@8g2000cwh.googlegroups.com> On Mar 6, 8:39 am, "Nick Vatamaniuc" wrote: > On Mar 5, 5:16 pm, "Alex Li" wrote: > > > Hello, > > > I would like to use Python 2.5 on Windows with Graphviz to generate > > graphs. I used yapgvb but it only requires Python 2.4 (won't work > > with Python 2.5). Other packages like pydot seems to be unmaintained > > or requires custom building to be used on Windows (pygraphviz), which > > I tried to avoid. Any suggestions? > > > Thanks in advance, > > Alex > > Alex, > You can always pipe your dot file directly to the dot or neato > executables using the subprocess method then read the output. This way > you don't have to install yapgvb or other adapters and it will work > with Python 2.5. But you will need to compose your dot file as a giant > character buffer... > -Nick V. Not really a solution, but you can always install a virtual machine with Ubuntu (or other linux flavour) where pydot is available for python2.5 (sudo apt-get install python-pydot). Stani From deets at nospam.web.de Tue Mar 20 09:58:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Mar 2007 14:58:01 +0100 Subject: help - Module needs access to another module References: <1174398386.976864.109350@p15g2000hsd.googlegroups.com> Message-ID: <56a7j9F28bl1sU2@mid.uni-berlin.de> abcd wrote: > I have the following directory/file structure... > > c:\foo\utils.py > c:\foo\bar\ok.py > > In ok.py I want to do something like... > > import utils > utils.helpMeDoSomething(....) > > However, it seems that ok.py doesn't "know" about utils. Other than > manually configuring sys.path what can I do? After a bunch of questions of that kind, I suggest you take a step back, and read this: http://docs.python.org/tut/node8.html Diez From deets at nospam.web.de Sat Mar 24 14:06:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 24 Mar 2007 19:06:49 +0100 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> Message-ID: <56l7m1F29kgs9U1@mid.uni-berlin.de> Robert Hicks schrieb: > I want to upgrade to 2.5 but I don't see any unistall instructions > anywhere. Don't do it. OSX uses the shipped version for its own purposes, and you'll break things if you uninstall it. Diez From rpdooling at gmail.com Thu Mar 1 18:19:30 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Mar 2007 15:19:30 -0800 Subject: python equivalent of bash find In-Reply-To: <45e744c1$0$17997$426a74cc@news.free.fr> References: <1172780082.961223.222500@s48g2000cws.googlegroups.com> <45e744c1$0$17997$426a74cc@news.free.fr> Message-ID: <1172791170.590284.158490@31g2000cwt.googlegroups.com> On Mar 1, 3:58 pm, Bruno Desthuilliers wrote: > > MHO is that you'd better learn linux (well... Unix) tools. Reinventing > the SquareWheel(tm) is usually not a good idea. I agree. It's just a matter of experience and learning when to use Unix tools and when to use Python. The question never came up on Windows :) Thanks, rd "Artificial stupidity (AS) may be defined as the attempt by computer scientists to create computer programs capable of causing problems of a type normally associated with human thought." --Wallace Marshal From paul at eventuallyanyway.com Thu Mar 15 03:00:46 2007 From: paul at eventuallyanyway.com (Paul Hummer) Date: Thu, 15 Mar 2007 07:00:46 +0000 Subject: Python books? In-Reply-To: <1huzl72.z09y4u1xt7lpsN%aleax@mac.com> References: <1CD93DF7-4172-4FF1-B5B4-BF665762C9E7@comhem.se> <1173906223.048740.18050@b75g2000hsg.googlegroups.com> <1huzl72.z09y4u1xt7lpsN%aleax@mac.com> Message-ID: <45F8EF1E.8090403@eventuallyanyway.com> Alex Martelli wrote: > BartlebyScrivener wrote: > > >> On Mar 14, 3:50 pm, a... at pythoncraft.com (Aahz) wrote: >> >> >>> Some people prefer shorter books -- Python for Dummies (for new >>> programmers) and Python in a Nutshell (for experienced programmers) both >>> try to give a thorough survey of Python while keeping the book easy to >>> carry. >>> > > Not for me to comment about my own books, but I can second your > recommendation for your "for Dummies" for beginners. > > >> And other people like lots of examples and code organized around >> practical projects a person might like to accomplish using Python. The >> Python Cookbook 2nd edition is great for this, and Martelli et al are >> great writers, as well as great programmers. >> > > If you like _substantial_ examples, rather than the simple/short ones > typically used in manageable-sized books, Hetland's "Practical Python" > was also a great buy (I believe it's now been replaced by "Beginning > Python" by the same author, but unfortunately I haven't seen that one). > > In general I dislike books that try to teach a language (or other > technology) via "substantial examples", because the issues with the > examples may obscure those with the language or technology; e.g., > Stroustrup tries that route in "The C++ Programming Language", as Lutz > does in "Programming Python", and to my taste the results are inferior. > > However, at least in "Practical Python" (can't speak for "Beginning > Python"), Hetland managed to pull it off -- perhaps by placing the > substantial programs he develops as successive examples in a clever > sequence, so that at each step he's not dealing with many diverse new > issues but just manageably few of them. > > > Alex > I'll vouch for "Beginning Python" This was my first Python book, and it taught me everything I needed to get started. I still refer to it from time to time. After I graduated from that, I started reading "Python Network Programming," the next book in that Apress series. Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From kadeko at gmail.com Thu Mar 15 08:05:37 2007 From: kadeko at gmail.com (looping) Date: 15 Mar 2007 05:05:37 -0700 Subject: cx_Oracle and unicode data Message-ID: <1173960337.453122.168150@o5g2000hsb.googlegroups.com> Hi, I need to get data from an Oracle DB that contains unicode data (chinese text). But the chinese data that I receive is wrong (only ?). After a look at the Oracle documentation I've found an environment variable called NLS_LANG that you could set to define what charset the DB client use and it work fine. But it's not what I call a 'clean' solution and I suppose that it must exist another way to force the client DB to use UTF8, or another solution to get my data. Could someone help me ? Thanks. Example: # -*- coding: latin1 -*- import os import cx_Oracle os.environ["NLS_LANG"] = ".UTF8" con = cx_Oracle.connect("demo/demo at DEMOUTF8A") cur = con.cursor() cur.execute("select DESCRIPTION from DEC_DESCRIPTION where DEC_DESCRIPTION_ID = 1792528") val1 = cur.fetchone()[6] val2 = cur.fetchone()[6] print con.encoding, con.nencoding, con.maxBytesPerCharacter cur.close() print val1.decode(con.encoding) print val2.decode(con.encoding) del os.environ["NLS_LANG"] >>> UTF-8 UTF-8 3 ????????????? ?????????????????????????, without NLS_LANG setting I get: >>> WINDOWS-1252 WINDOWS-1252 1 ????????????? ?????????????????????????, From gagsl-py2 at yahoo.com.ar Tue Mar 13 17:48:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Mar 2007 18:48:38 -0300 Subject: Iterating across a filtered list References: <1173809090.092546.255710@64g2000cwx.googlegroups.com> <1173820592.220605.64040@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 13 Mar 2007 18:16:32 -0300, Arnaud Delobelle escribi?: > On Mar 13, 8:59 pm, "Gabriel Genellina" > wrote: > [snip] >> def find(self, search): >> search_re = re.compile(search, re.IGNORECASE) >> for result in [self.contacts[name] for name in self.contacts if >> search_re.match(name)]: >> print result > > I do not see how > > for y in [f(x) for x in L if g(x)]: > do stuff with y > > can be preferable to > > for x in L: > if g(x): > do stuff with f(x) > > What can be the benefit of creating a list by comprehension for the > sole purpose of iterating over it? No benefit... -- Gabriel Genellina From mail at timgolden.me.uk Fri Mar 2 04:34:47 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 02 Mar 2007 09:34:47 +0000 Subject: Python win32 tools In-Reply-To: <2adc542f0703011513h5fe8ad26o91b0fb6a9825eb91@mail.gmail.com> References: <2adc542f0703011513h5fe8ad26o91b0fb6a9825eb91@mail.gmail.com> Message-ID: <45E7EFB7.4080002@timgolden.me.uk> Sick Monkey wrote: > I am trying to build a python program that will reset a user's account > (password) on a windows machine. I have been working with win32 > objects and was wondering if this functionality was already built in. I'm going to assume that "win32 objects" is the stuff in the pywin32 extensions. While there isn't a "win32user.ResetPassword" function in there, you can certainly use the win32com scripting to automate ActiveDirectory and (trivially) translate this code: http://techtasks.com/code/viewbookcode/1592 And just to prove how wrong I can be :) the win32net module *does* in fact have a function named NetUserChangePassword. Doc: """ win32net.NetUserChangePassword NetUserChangePassword(server, username, oldPassword, newPassword) Changes the password for a user. Comments A server or domain can be configured to require that a user log on to change the password on a user account. If that is the case, you need administrator or account operator access to change the password for another user acount. If logging on is not required, you can change the password for any user account, so long as you know the current password. """ TJG From gagsl-py2 at yahoo.com.ar Thu Mar 1 05:23:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Mar 2007 07:23:55 -0300 Subject: Python Source Code Beautifier References: <1172621660.110666.178550@z35g2000cwz.googlegroups.com> <1t6jbjm9iv1ps$.9xz6wbyehtul.dlg@40tude.net> <1172700549.583792.41660@s48g2000cws.googlegroups.com> Message-ID: En Wed, 28 Feb 2007 19:09:09 -0300, sjdevnull at yahoo.com escribi?: > On Feb 28, 11:24 am, Alan Franzoni > wrote: >> Il 27 Feb 2007 16:14:20 -0800, sjdevn... at yahoo.com ha scritto: >> >> > Those mean different things: >> >> >>>> a=[1] >> >>>> b=a >> >>>> a += [2] >> >>>> a >> > [1, 2] >> >>>> b >> > [1, 2] >> >>>> a=[1] >> >>>> b=a >> >>>> a = a + [2] >> >>>> a >> > [1, 2] >> >>>> b >> > [1] >> >> This is a really nasty one! I just answered to Tim above here, and then >> I >> saw your example... I had never realized that kind of list behaviour. >> That's probably because i never use + and += on lists (i prefer the more >> explicit append() or extend() and i do copy list explictly when I want >> to) >> , BTW I think this behaviour is tricky! > > Seems obvious and desirable to me. Bare "=" is the way you assign a > name to an object; saying "NAME =" will rebind the name, breaking the > connection between a and b. Without it, they continue to refer to the > same object; extending the list (via += or .extend) mutates the > object, but doesn't change which objects a and b are referencing. > > It would be very counterintuitive to me if "=" didn't change the > name's binding, or if other operators did. Note that a += b first tries to use __iadd__ if it is available, if not, behaves like a = a + b. And even if __iadd__ exists, there is no restriction on it to mutate the object in place; it may return a new instance if desired. So, a += b may involve a name rebinding anyway. Try the example above using immutable objects like tuples or strings. -- Gabriel Genellina From fd.calabrese at gmail.com Sun Mar 18 14:02:29 2007 From: fd.calabrese at gmail.com (cesco) Date: 18 Mar 2007 11:02:29 -0700 Subject: Optimization problem Message-ID: <1174240949.085119.79720@p15g2000hsd.googlegroups.com> I have a set of N blocks of different lengths. The length of each block is a multiple of a basic unit. The blocks, once lined up, make a path of distance equal to R. Let's say we have 5 blocks with the following lengths: N_set_lengths = (1, 3, 2, 1, 3), then the path we cover by lining them up is equal to R = 10. Now, each of these blocks is associated with a different metric m (metric) which depends on the location/position that the block occupies within the path. So a block of length 1 will have R = 10 different m values, one for each of the 10 positions it can occupy within the path, while a block of length 3 will have R-3+1 = 8 different m values. Here is a graphical representation: -------------------------------------------------------------------------------- block 0: |m0,0|m0,1|m0,2|m0,3|m0,4|m0,5|m0,6|m0,7|m0,8|m0,9| (length 1, 10 different metrics) -------------------------------------------------------------------------------- ------------------------------------------------------------------------------- block 1: |m1,0|m1,1|m1,2|m1,3|m1,4|m1,5|m1,6|m1,7| | | (length 3, 8 different metrics, each metric ------------------------------------------------------------------------------- refers to 3 consecutive units) ------------------------------------------------------------------------------- block 2: |m2,0|m2,1|m2,2|m2,3|m2,4|m2,5|m2,6|m2,7|m2,8| | (length 2, 9 different metrics, each ------------------------------------------------------------------------------- referring to 2 consecutive units) ------------------------------------------------------------------------------- block 3: |m3,0|m3,1|m3,2|m3,3|m3,4|m3,5|m3,6|m3,7|m3,8|m3,9| (length 1, 10 different metrics) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- block 4: |m4,0|m4,1|m4,2|m4,3|m4,4|m4,5|m4,6|m4,7| | | (length 3, 8 different metrics) ------------------------------------------------------------------------------- Those blocks can be allocated in fact(N) possible different ways to cover the path (In the example considered I have 5 possible blocks to choose from to cover the first part of the path, 4 blocks to cover the second part of the path, and so on). Each of these possible combinations results in a different overall metric which we can define as the sum of the individual metrics that each block gets according to the position occupied within the path. There is at least one combination which is the optimum solution, because it maximizes the overall metric. Finding such a combination is possible but it may require a long processing time. If, for example, the number of blocks is 20 the number of possible combinations is expressed as 2.4*10^18. In the application I'm considering the time is really a constraint so I'm trying to find an algorithm which would give a near optimum solution but with a much lower complexity. Does anyone have suggestion on how should such an algorithm behave (possibly considering implementation issues)? Sorry for the lengthy description, I was just trying to be as clear as possible. Please, don't hesitate to ask questions if the problem statement is not clear. Many thanks and regards Francesco From steve at holdenweb.com Thu Mar 15 08:04:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 15 Mar 2007 08:04:18 -0400 Subject: dict.items() vs dict.iteritems and similar questions In-Reply-To: <1173955724.284863.97340@y80g2000hsf.googlegroups.com> References: <1173886227.609832.170540@l75g2000hse.googlegroups.com> <1173955724.284863.97340@y80g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Laurent Pointal: >> you may prefer range/items when processing of the result >> value explicitly need a list (ex. calculate its length) > > Creating a very long list just to know the len of an iterator is > barbaric, so sometimes I use this: > > def leniter(iterator): > if hasattr(iterator, "__len__"): > return len(iterator) > nelements = 0 > for _ in iterator: > nelements += 1 > return nelements > Of course this is a little like the Heisenberg uncertainty principle if the iterator has no __len__ attribute - once you know how long it is you no longer have access to the elements. Or did I miss something? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From bdesth.quelquechose at free.quelquepart.fr Thu Mar 15 18:38:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 15 Mar 2007 23:38:33 +0100 Subject: os.path.isfile with *.tar.gz In-Reply-To: References: <09042D621CD4AA479C678463F3A646D0E87D10@sottemail1.ent.ad.cognos.com> Message-ID: <45f9c2a4$0$15537$426a74cc@news.free.fr> > Boudreau, Emile wrote: (snip) >> I have tried variations of: os.path.isfile( os.path.join("C:\\temp\\", >> "rqp-win32-app", "*.tar.gz")) As a side note, the whole point of os.path is to help writing portable code. So passing an os.specific path componant is somewhat counter productive !-) (snip answer) From gagsl-py2 at yahoo.com.ar Sun Mar 11 13:42:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 Mar 2007 14:42:13 -0300 Subject: threading and iterator crashing interpreter References: <1173609124.089611.242080@h3g2000cwc.googlegroups.com> <1173617253.901671.136910@q40g2000cwq.googlegroups.com> <1173623758.054666.18190@s48g2000cws.googlegroups.com> Message-ID: En Sun, 11 Mar 2007 11:35:58 -0300, Janto Dreijer escribi?: >> At least, the problem of using the same generator from different threads >> still remains, if you don't use my modified code. In general, when using >> multiple threads you always need some way to syncronize access to shared >> objects. You are lucky with Sessions because append is an atomic >> operation >> on lists; for more information see >> http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-threa... > > Again you're right. But even putting a try-except:return around the > random.choice still manages to break the interpreter. I'm not looking > for any meaningful output really. I just want it not to break. A try/except won't help a concurrency problem, unfortunately. > Like I said, this is just watered down code to try and isolate the > problem. So I suggest to start with some small, *correct*, code, and then add more features until you reconstruct your big program in a safe way. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Mar 8 05:20:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 Mar 2007 07:20:36 -0300 Subject: property syntax References: <1173346452.096798.215970@t69g2000cwt.googlegroups.com> Message-ID: En Thu, 08 Mar 2007 06:34:12 -0300, escribi?: > Probably you have already discussed this topic, but maybe you can > stand touching it again briefly. > Maybe properties aren't used so often to deserve a specific syntax, > but I don't like their syntax much. Here I show some alternative > solutions that work with the current Python, followed by a syntax > idea, that may be better fit for Python 3.0 (but maybe changing its > name it can be retrofitted into Python 2.6 too). You miss this common way, that does not depend on metaclasses, nor base classes, nor custom decorators... The only drawback is the "deprecated" status of apply: class Angle(object): @apply def rad(): doc = "The angle in radians" def fget(self): return self._rad def fset(self, value): self._rad = value return property(**locals()) (Hmmm... I wonder what the 2to3 conversion tool is doing in this case?) -- Gabriel Genellina From inq1ltd at verizon.net Fri Mar 16 17:55:58 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 16 Mar 2007 17:55:58 -0400 Subject: SQLite3, data not found Message-ID: <200703161755.58549.inq1ltd@verizon.net> Python help, I just started working with SQLite3 and ran into this problem. Below, the first select produces results but, after closing then re-opening the database the select produces an empty list. Anyone know the reason ?? The table seems to be empty. import sqlite3 con = sqlite3.connect('myData') cursor = con.cursor() cursor.execute ("""create table data (recordNo varchar, caseNo varchar)"""); record = ['A', 'B'] cursor.execute("insert into data values (?,?)", record ) ; cursor.execute("select * from data "); print cursor.fetchall(); con.close() con = sqlite3.connect('myData') cursor = con.cursor() cursor.execute("select * from data"); print cursor.fetchall(); jim-on-linux From steve at REMOVEME.cybersource.com.au Wed Mar 7 22:43:47 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Mar 2007 14:43:47 +1100 Subject: catching exceptions from an except: block References: <1173292373.770519.158490@8g2000cwh.googlegroups.com> Message-ID: On Wed, 07 Mar 2007 10:32:53 -0800, Arnaud Delobelle wrote: > Hi all, > > Imagine I have three functions a(x), b(x), c(x) that each return > something or raise an exception. Imagine I want to define a function > that returns a(x) if possible, otherwise b(x), otherwise c(x), > otherwise raise CantDoIt. > > Here are three ways I can think of doing it: > > ---------- > # This one looks ugly > def nested_first(x): > try: > return a(x) > except: > try: > return b(x) > except: > try: > return c(x) > except: > raise CantDoIt Exceptions are great, but sometimes they get in the way. This is one of those times. NULL = object() # get a unique value def result_or_special(func, x): """Returns the result of func(x) or NULL.""" try: return func(x) except Exception: return NULL def failer(x): """Always fail.""" raise CantDoIt def function(x): funcs = (a, b, c, failer) for func in funcs: result = func(x) if result is not NULL: break return result Or if you prefer: def function(x): NULL = object() funcs = (a, b, c) for func in funcs: try: result = func(x) except Exception: pass else: break else: # we didn't break out of the loop raise CantDoIt # we did break out of the loop return result -- Steven D'Aprano From gagsl-py2 at yahoo.com.ar Fri Mar 23 01:13:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 02:13:36 -0300 Subject: #!/usr/bin/env python > 2.4? References: <1174407745.208492.264020@l75g2000hse.googlegroups.com> <1174415242.455972.51400@d57g2000hsg.googlegroups.com> <4Rf*J7eGr@news.chiark.greenend.org.uk> Message-ID: En Wed, 21 Mar 2007 14:42:53 -0300, Jon Ribbens escribi?: > In article <4Rf*J7eGr at news.chiark.greenend.org.uk>, Sion Arrowsmith > wrote: >> Jon Ribbens wrote: >>> if sys.hexversion < 0x020400f0: >>> ... error ... >> >> "Readability counts." >> >> if sys.version_info < (2, 4): >> ... error ... > > Maybe you should suggest a patch to the Python documentation then ;-) > > The formula I mentioned is the one suggested in the official Python > documentation ( http://docs.python.org/lib/module-sys.html#l2h-5143 ) > as being the way to check the Python version. Uh... I never thought it was an implied formula there - that F0 had to come from 1.5 = 15 = 0xF. I think it should be stated much more clearly. -- Gabriel Genellina From AWasilenko at gmail.com Thu Mar 22 23:53:15 2007 From: AWasilenko at gmail.com (AWasilenko at gmail.com) Date: 22 Mar 2007 20:53:15 -0700 Subject: Printing from a text file quirk In-Reply-To: <1174620861.374740.203670@l75g2000hse.googlegroups.com> References: <1174620861.374740.203670@l75g2000hse.googlegroups.com> Message-ID: <1174621995.759439.63770@n59g2000hsh.googlegroups.com> Humm I think I messed up the code before I pasted it, I am now able to get the left tag on the same line with this: headerp1 = "" for i in range(5): headerp1 += self.headertxt.readline() headerp2 = self.headertxt.readline(7) headerp3 = self.headertxt.readline() headerp4 = self.headertxt.read() return headerp1 + headerp2 + pagetitle + headerp3 + headerp4 output: this is a new title Now all's left is the tag to get on the same line, or a better solution, this seems like a very awkward way to do what I want. From steve at holdenweb.com Mon Mar 19 14:05:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 19 Mar 2007 14:05:13 -0400 Subject: PythonCard or Dabo? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > I'm curious to know what others think of these two frameworks for > building wxPython apps. > > PythonCard has been around longer, but its development seems to have > slowed. The last release, 0.8.2, has been out for quite awhile now. > > Dabo is newer and seems to have gathered a lot of buzz. > > Anyone try both? What's your preference and why? Is one more robust than > the other? > It's not just a matter of robustness. PythonCard is limited to GUI development, while Dabo is a fully-fledged application architecture intended to allow you to build complete suites. So not only does it have a superior GUI editor, it also has report development facilities and many other features that simply weren't envisaged for PythonCard. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From danb_83 at yahoo.com Thu Mar 15 20:52:10 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Mar 2007 17:52:10 -0700 Subject: newb: Python Floating Point In-Reply-To: <1174003795.849903.273220@l75g2000hse.googlegroups.com> References: <1174003795.849903.273220@l75g2000hse.googlegroups.com> Message-ID: <1174006330.730006.30530@n59g2000hsh.googlegroups.com> On Mar 15, 6:09 pm, "johnny" wrote: > When I do the following, rounding to 2 decimal places doesn't seem to > work. I should get 0.99 : In binary, 0.99 is the recurring fraction 0.11 11110101110000101000 11110101110000101000 11110101110000101000 .... Thus, it can't be exactly represented as a float. From siona at chiark.greenend.org.uk Fri Mar 16 13:07:30 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Mar 2007 17:07:30 +0000 (GMT) Subject: Eureka moments in Python References: <1174053730.543334.138910@n59g2000hsh.googlegroups.com> Message-ID: <+tk*0oRFr@news.chiark.greenend.org.uk> Paul McGuire wrote: >On Mar 13, 2:16 am, Steven D'Aprano >wrote: >> I'd be interested in hearing people's stories of Eureka moments in Python, >> moments where you suddenly realise that some task which seemed like it >> would be hard work was easy with Python. >The day I wrote a CORBA method intercepter in 8 lines of code [ ... ] This is more a "batteries included" eureka moment than a Python one, but writing a fetchmail substitute in 6 lines was an eye-opener. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From kyosohma at gmail.com Mon Mar 26 13:34:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Mar 2007 10:34:21 -0700 Subject: PMW widget - skip tabbing to it In-Reply-To: <1174926951.133085.294900@l75g2000hse.googlegroups.com> References: <1174924280.581238.162350@n59g2000hsh.googlegroups.com> <1174925855.552135.228190@n59g2000hsh.googlegroups.com> <1174926471.899631.228810@e65g2000hsc.googlegroups.com> <1174926951.133085.294900@l75g2000hse.googlegroups.com> Message-ID: <1174930461.108420.219960@d57g2000hsg.googlegroups.com> On Mar 26, 11:35 am, "jp" wrote: > On Mar 26, 11:27 am, kyoso... at gmail.com wrote:> On Mar 26, 11:17 am, kyoso... at gmail.com wrote: > > > > On Mar 26, 10:51 am, "jp" wrote: > > > > > I have multiple PMW widgets (EntryFields, ScrolledField etc), how can > > > > I skip over these widgets when using the tab key? > > > > > Thank you, > > > > John > > > > I would probably write some custom event handling. Something that > > > could tell it was a key-press event and not just an on-focus event. > > > Then it would be a simple, if key-press == tab, put focus on next > > #> > widget of interest. Something like that should work. > > > > > > Mike > > > I looked in my Tkinter book, and it says that if the widget has the > > "takefocus" option set to true, the widget is placed in the tab group > > and will get focus when they are tabbed to. I assume that this means > > if you set the PMW widgets' "takefocus" option to false, they will be > > skipped over since they won't be in the tab group. > > > Mike > > I've tried using the takefocus option set to 0 and 1 but either way, > the tab key still stops at my EntryField. Below is my snippet of > code. What am I doing wrong? > > entry=Pmw.EntryField(frame, > labelpos = 'w', > value = "", > label_text = > 'Name:') > entry.grid(row=1) > #entry.component('entry').takefocus = 1 > entry.component('entry').takefocus = 0 According to the Tkinter book, setting takefocus to 0 (false) should work. Are you putting th EntryField into a Grid? If so, that might be the problem. I suppose the grid may override its children's settings. I've never messed too much with skipping widgets in the tab order. You could pack the PMW widgets last so that they won't get tabbed to until the end. There's also tk_focusNext & tk_focusPrev. See the following post for more info and ideas: http://www.dbforums.com/archive/index.php/t-1377788.html Mike From bthom at cs.hmc.edu Fri Mar 23 20:04:58 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Fri, 23 Mar 2007 17:04:58 -0700 Subject: exit to interpreter? In-Reply-To: <1174679289.267429.18000@l77g2000hsb.googlegroups.com> References: <1174673079.976162.307960@n76g2000hsh.googlegroups.com> <1174679289.267429.18000@l77g2000hsb.googlegroups.com> Message-ID: Thanks to all. I had suspected this was the best way to go, but as I'm fairly new to Python, it seemed worth a check. --b On Mar 23, 2007, at 12:48 PM, kyosohma at gmail.com wrote: > On Mar 23, 1:20 pm, belinda thom wrote: >> On Mar 23, 2007, at 11:04 AM, kyoso... at gmail.com wrote: >> >> >> >>> On Mar 23, 12:52 pm, belinda thom wrote: >>>> Hi, >> >>>> I'm writing a function that polls the user for keyboard input, >>>> looping until it has determined that the user has entered a valid >>>> string of characters, in which case it returns that string so it >>>> can >>>> be processed up the call stack. My problem is this. I'd also >>>> like it >>>> to handle a special string (e.g. 'quit'), in which case control >>>> should return to the Python command line as opposed to returning >>>> the >>>> string up the call stack. >> >>>> sys.exit seemed like a good choice, but it exits the python >>>> interpreter. >> >>>> I could use an exception for this purpose, but was wondering if >>>> there's a better way? >> >>>> --b >> >>> If you're using a function, wouldn't using the keyword "return" >>> work? >> >>> Mike >> >> No, because that just returns to the caller, which is not the Python >> interpreter. > > Sorry...I didn't realize you were calling from another function or > functions. Duh. I agree with the other writer. Use a custom exception. > > -- > http://mail.python.org/mailman/listinfo/python-list From nobody at invalid.com Mon Mar 12 12:56:30 2007 From: nobody at invalid.com (Erik Johnson) Date: Mon, 12 Mar 2007 09:56:30 -0700 Subject: Newbie Question : "grep" References: <1173714587.830723.59210@8g2000cwh.googlegroups.com> Message-ID: <45f5864f$1@nntp.zianet.com> wrote in message news:1173714587.830723.59210 at 8g2000cwh.googlegroups.com... > - If I increase number of elements I am searching for, then I have > more elif...elif. Is there a cleaner solution? I'm not sure exactly what your lines look like, but this script implies that every line that matches 'i_a/i_b/ROM' is one of the known list you are looking for. Maybe that's exactly right... Below is some code that I think is an incremental improvement over writing lots of alternative if-statements. I beleive it has the same behaviour, though it is totally untested: tags = [ ['B18', (7, 6)], ['B14', (5, 4)], ['B10', (3, 2)], ['B6', (1, 0)], ] for line in lines: if "placed" in line: if "i_a/i_b/ROM/" in line: pos = (line.split()[4]).split("_")[1] found = False for (tag, (start, end)) in tags: if tag in line: found = True print " i_a/i_b/ROM/%s [%i:%i] LOC =" %\ (pos, tag, start, end) break This way, you just need to maintain your data structure (tags), instead of writing lots of repettitive code. If there is a definite pattern to the part that looks like a slice (what I am calling (start, end)), then you could programmatically generate that as well, of course. The list of things you are looking for could be in a separate file, etc. The sensible thing to do sort of depends on how big this list of stuff you are looking for is going to grow and how much you are going to use this program. Do what makes sense for you. You may want to explore the 're' module as well (regular expressions) http://docs.python.org/modindex.html , which may or may not improve performance, readability, maintainability, etc. See also section 10.10 of the Python Tutorial if you are interested in code performance issues: http://docs.python.org/tut/tut.html Hope that helps, -ej From nospam at nospam.com Thu Mar 22 00:09:52 2007 From: nospam at nospam.com (Mark T) Date: Wed, 21 Mar 2007 21:09:52 -0700 Subject: Python 3000 idea: reversing the order of chained assignments References: Message-ID: "Marcin Ciura" wrote in message news:ets9hc$74f$1 at news.onet.pl... > Given > class Node(object): > pass > > node = Node() > nextnode = Node() > > I tried to refactor the following piece of code > node.next = nextnode > node = nextnode You have an error above. The first node's "next" points to nextnode, then node is reassigned to point to nextnode, losing the original node! The refactoring below is doing the same thing. It is, however, evaluating right-to-left as you want. nextnode is place in node.next and placed in node, also losing the original value of node. -Mark T. > > as > node = node.next = nextnode > > only to discover that Python performs chained assignments > backwards compared to other languages, i.e. left-to-right > instead of right-to-left. From the user's perspective, > I can't think of any reasonable argument for keeping it > this way in Python 3000. What is your opinion? > Marcin From nagle at animats.com Sat Mar 10 12:40:17 2007 From: nagle at animats.com (John Nagle) Date: Sat, 10 Mar 2007 17:40:17 GMT Subject: Database module & multithreading In-Reply-To: References: <1173536083.417449.122600@j27g2000cwj.googlegroups.com> <45f2bfbd$0$5094$ba4acef3@news.orange.fr> <1173537553.064123.13260@t69g2000cwt.googlegroups.com> Message-ID: <54CIh.6545$M65.2077@newssvr21.news.prodigy.net> Michael Bentley wrote: >> >> Thanx for this pointer buddy! I have done my homework. Some Database >> modules are not actively maintained some modules does not work with >> Python 2.5. At this moment I am using Sqlite3 which is pretty fast but >> it dosent allow me to use multi threading so which database module is >> better in terms of multithreading > > > Actually, I think sqlite3 just requires that each thread have its own > connection and cursor. SQlite is thread-safe but not concurrent; only one thread at a time can be doing database updates to a database. The whole database is locked during each transaction that changes the database. However, multiple reads (SELECTs) can be done simultaneously. So mostly-read databases can still get some concurrency going. The question is, how many transactions per second do you need to process? This sounds like someone writing their first database program, not someone who needs thousands of transactions per second and has a farm of dedicated servers to support them. Any of the usual choices should work: SQLite, MySQL, or Postgres. As for "some modules not being maintained", it really is sad that MySQLdb is kind of behind. If you're running Windows and need MySQL, you're either stuck with Python 2.4, or have to get a 2.5 version from a World of Warcraft guild. The source version of MySQLdb, though, does build properly on Red Hat Fedora Core 6 for Python 2.5. John Nagle From http Sat Mar 10 19:02:56 2007 From: http (Paul Rubin) Date: 10 Mar 2007 16:02:56 -0800 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7xr6rxkqp6.fsf@ruckus.brouhaha.com> Message-ID: <7xwt1or6j3.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > By your method, what is the probability of the first number being > > higher than 30? What is the probability of the fifth number being > > higher than 30? If these probabilities are unequal, can we really say > > the sequences are random? > > Of course we can! "Uniform probability distribution" is a special case of > random. Most random quantities are far from uniform. The Python random > module includes a couple of non-uniform distributions, including > exponential distribution (random.expovariate) and the famous bell curve > distribution (random.normalvariate). Ehh. Say we call some generator repeatedly and get back the sequence (3, 3, 3, 3, 3, ...). Would we say this is a random sequence using a distribution that puts 100% of the probability density at 3? Or would we just say it isn't random? For something like this partition problem, describing some generator as making a random partition should contain some reasonable description of the distribution. For example, we could say the generator selects one of the P(n) possible partitions with equal probability. For another, we could say it uses the "fencepost" method and the distribution is whatever results from that. Question then is whether those two distributions are the same. From michael at jedimindworks.com Sat Mar 24 22:18:03 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 24 Mar 2007 21:18:03 -0500 Subject: Removing Python 2.4.4 on OSX In-Reply-To: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> References: <1174757428.482067.137590@n76g2000hsh.googlegroups.com> Message-ID: <60B634CE-C9C1-46DE-8CE2-263C6AD13F53@jedimindworks.com> On Mar 24, 2007, at 12:30 PM, Robert Hicks wrote: > I want to upgrade to 2.5 but I don't see any unistall instructions > anywhere. Don't uninstall it. That's why Apple put python under /Library/Frameworks/ Python.framework/Versions. So you can have multiple versions installed. Hopefully you left Apple's default install of 2.3.5 unmolested as well. My best advise is to download the binaries from python.org and install. This gives you a nice universal framework build, compete with readline support. If you do elect to build it yourself, just make sure to read the Mac specific documentation (which tells how to generate a framework build). Whichever route you take, /usr/local/bin/python and /Library/ Frameworks/Python.framework/Versions/Current/bin/python will point to pyhon2.5. Since you already have 2.4x I assume your path already contains /usr/local/bin -- otherwise, you'll probably keep picking up the default 2.3.5 in /usr/bin. It looks like Stackless has a Mac binary install as well. Does anybody here know if I can install that on top of a stock 2.5 without breaking things? regards, Michael --- Simplicity is the ultimate sophistication. -Leonardo da Vinci From paul at boddie.org.uk Wed Mar 28 09:12:35 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 28 Mar 2007 06:12:35 -0700 Subject: PyPy 1.0: JIT compilers for free and more In-Reply-To: <1175083955.167868.88610@n76g2000hsh.googlegroups.com> References: <1175083955.167868.88610@n76g2000hsh.googlegroups.com> Message-ID: <1175087555.252611.66470@p15g2000hsd.googlegroups.com> On 28 Mar, 14:12, "Kay Schluehr" wrote: > > A somewhat unrelated question. With Py3K Python gets optional type > annotations. No, I believe the consensus is that Python 3000 gets optional annotations which aren't specifically for type information... nudge nudge, wink wink! That last part is important, because that's also how many other people have interpreted this particular feature. I seem to recall that some of the PyPy people weren't interested in static analysis [1], so I'm skeptical about whether type annotations are their kind of thing, either. That said, I imagine that the handling of metadata (including type details) is an element in the way RPython works, but I also imagine that things get more complicated as such metadata diverges from plain type information and into arbitrary "observations" about other aspects of program behaviour. Still, I'd like to see the PyPy people stick their necks out and answer your questions. ;-) Paul [1] http://codespeak.net/pipermail/pypy-dev/2007q1/003607.html From hg at nospam.org Tue Mar 13 16:20:02 2007 From: hg at nospam.org (hg) Date: Tue, 13 Mar 2007 21:20:02 +0100 Subject: Problem I have with a while loop/boolean/or References: <1173825244.368771.273720@e1g2000hsg.googlegroups.com> Message-ID: hg wrote: > israphelr at googlemail.com wrote: > >> Hi all. >> >> I have a problem with some code :( >> >> ----------- >> >> hint = raw_input("\nAre you stuck? y/n: ") >> hint = hint.lower() >> >> while (hint != 'n') or (hint != 'y'): >> hint = raw_input("Please specify a valid choice: ") >> >> --------------------------------------------- >> >> so everytime I run the program, and enter my choice as y or n, I'm >> told to 'Please Specify a valid Choice Again' and can't get out of the >> loop. >> >> >> >> ----------- >> >> hint = raw_input("\nAre you stuck? y/n: ") >> hint = hint.lower() >> >> while (hint != 'n'): >> hint = raw_input("Please specify a valid choice: ") >> >> --------------------------------------------- >> >> As for here when I enter n, I can leave the while loop. >> >> Anyway I can't put my finger on this, so I'd be real grateful if >> someone could tell me what I've done wrong. Thanks. >> (I have a guy feeling it's something really silly I'm overlooking...) > > Hi, > > Whatever hint is: > (hint != 'n') or (hint != 'y') > is always going to be true > > as it cannot really be both at the same time > > use "and" instead of "or" > > hg oops, meant to answer to the main post From bytecolor at yahoo.com Mon Mar 5 01:56:13 2007 From: bytecolor at yahoo.com (bytecolor) Date: 4 Mar 2007 22:56:13 -0800 Subject: package_data question Message-ID: <1173077773.569831.249980@t69g2000cwt.googlegroups.com> I have a simple package. I'm trying to add an examples subdirectory with distutils. I'm using Python 2.4 on Linux. My file layout and setup.py can be found here: http://www.deadbeefbabe.org/paste/3870 I've tried using data_files as well, with the same result; examples/ fig2.3.apt is not added to the tarball. -- bytecolor From mccredie at gmail.com Fri Mar 16 14:20:08 2007 From: mccredie at gmail.com (Matimus) Date: 16 Mar 2007 11:20:08 -0700 Subject: Finding the insertion point in a list In-Reply-To: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> References: <1174067947.276987.232810@d57g2000hsg.googlegroups.com> Message-ID: <1174069208.088356.289020@d57g2000hsg.googlegroups.com> You might look at the bisect module (part of the standard distribution). From sgeiger at ncee.net Fri Mar 30 13:44:22 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 30 Mar 2007 12:44:22 -0500 Subject: clean up html document created by Word In-Reply-To: <1175276233.762698.105550@n59g2000hsh.googlegroups.com> References: <1175275249.200620.76590@o5g2000hsb.googlegroups.com> <1175276233.762698.105550@n59g2000hsh.googlegroups.com> Message-ID: <460D4C76.2000104@ncee.net> Tidy can now perform wonders on HTML saved from Microsoft Word 2000! Word bulks out HTML files with stuff for round-tripping presentation between HTML and Word. If you are more concerned about using HTML on the Web, check out Tidy's "Word-2000" config option! Of course Tidy does a good job on Word'97 files as well! -- source: http://www.w3.org/People/Raggett/tidy/ jkn wrote: > IIUC, the original poster is asking about 'cleaning up' in the sense > of removing the swathes of unnecessary and/or redundant 'cruft' that > Word puts in there, rather than making valid HTML out of invalid HTML. > Again, IIUC, HTMLtidy does not do this. > > If Beautiful Soup does, then I'm intererested! > > jon N > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From aahz at pythoncraft.com Wed Mar 14 16:44:33 2007 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2007 13:44:33 -0700 Subject: is it possible to give an instance a value? References: <1173221145.793008.298940@v33g2000cwv.googlegroups.com> <45edfb62$0$28523$426a74cc@news.free.fr> Message-ID: In article <45edfb62$0$28523$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: >manstey a ?crit : >> >> Is there a way to make a have the value a.val > >Forget about the value/instance distinction - it doesn't exists in Python. Actually, I think it does. For example, int('123') has the value 123. The way I would put it, any type/class that has an eval()able representation has a value. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From bdesth.quelquechose at free.quelquepart.fr Mon Mar 19 16:06:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 21:06:05 +0100 Subject: Private data In-Reply-To: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> References: <1174149061.416694.110480@p15g2000hsd.googlegroups.com> Message-ID: <45fee4c2$0$4541$426a34cc@news.free.fr> Dustan a ?crit : > http://dustangroups.googlepages.com/privateattributesinpython > May I report a small typo ? """ def interanalDataDecorator(func): """ Talking about private attributes... !-) From nanjundi at gmail.com Mon Mar 12 17:48:08 2007 From: nanjundi at gmail.com (Nanjundi) Date: 12 Mar 2007 14:48:08 -0700 Subject: New to Python In-Reply-To: <1173689360.138935.6780@j27g2000cwj.googlegroups.com> References: <1173689360.138935.6780@j27g2000cwj.googlegroups.com> Message-ID: <1173736088.103408.84180@v33g2000cwv.googlegroups.com> On Mar 12, 4:49 am, "Bert Heymans" wrote: > On Mar 12, 3:02 am, Alberto Vieira Ferreira Monteiro > > wrote: > > Hi, I am new to Python, how stupid can be the questions I ask? > > > For example, how can I add (mathematically) two tuples? > > x = (1,2) > > y = (3,4) > > How can I get z = (1 + 3, 2 + 4) ? > > > Alberto Monteiro > > Alberto - > > List comprehesion, no doubt about it:>>> z = [k+p for k,p in (x, y)] To put the correct form of the soulution here. This will give the desired output z = [k+p for k,p in zip(x, y)] Or z = [k+p for k,p in map(None, x, y)] >>> z [4, 6] -N From trentm at activestate.com Tue Mar 13 16:47:34 2007 From: trentm at activestate.com (Trent Mick) Date: Tue, 13 Mar 2007 13:47:34 -0700 Subject: ActivePython 2.5.0.0 is now available In-Reply-To: <55ofh7F25cn50U1@mid.individual.net> References: <55ofh7F25cn50U1@mid.individual.net> Message-ID: <45F70DE6.8000505@activestate.com> Bror Johansson wrote: > I did notice the download earlier today and I have installed it on five > Windows-machines (two WinXPPro and three Win2K) and have found one > consistent error. > > Whenever I try Help->Python Manuals from PythonWin I get this errormessage: > > "Internal error in help file processing :(2, > 'ShellExecute', 'Det g?r inte att hitta filen.') > > The last few words are swedish (the machine I'm using right here is arunning > a swedish WinXP) and has this meaning: "It's not possible to find the file". > > Is there a remedy for this problem? http://bugs.activestate.com/show_bug.cgi?id=68029 I don't currently have a work around for it. I should be able to fix this for the next release (but don't have a date for that yet). You could CC yourself to that bug report to get a notification for when it is fixed, if you like. Thanks, Trent -- Trent Mick trentm at activestate.com From mandus at gmail.com Fri Mar 9 09:00:26 2007 From: mandus at gmail.com (Mandus) Date: Fri, 9 Mar 2007 14:00:26 +0000 (UTC) Subject: C++ and Python References: <1173420288.646573.327340@h3g2000cwc.googlegroups.com> Message-ID: 8 Mar 2007 22:04:48 -0800 skrev bressert at gmail.com: > Hi Everyone, > > I'm considering about generating some Python Bindings for C++ > libraries. What are considered the best tools for doing something like > this? I know that there are SWIG, SIP, Boost.Python, and GCC_XML. We are doing this quite extensively at work, and have found that in the long run SWIG is the best solution. OMMV, but if you ask me, the answer is SWIG. mvh, -- Mandus - the only mandus around. From tiedon_jano at hotmail.com Tue Mar 6 08:30:20 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 06 Mar 2007 13:30:20 GMT Subject: askstring Window to the top under Windows In-Reply-To: <1173186819.622405.121170@30g2000cwc.googlegroups.com> References: <1173186819.622405.121170@30g2000cwc.googlegroups.com> Message-ID: iwl kirjoitti: > Hi, > > I tryed askstring to input some text in my script, > but some ugly empty Window appears with the > Input-Window behind and all together behind my > Console showing my script. So all have to brought > to the top first by the user - very unconfortable > Are you asking about the function AskString in the EasyDialogs module of Macintosh? If so, I can't help you. I'm just confused because the subject of your post contains the word Windows which could mean Microsoft Windows on which Python hasn't the EasyDialogs module. Cheers, Jussi From a.schmolck at gmail.com Tue Mar 6 08:52:06 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 06 Mar 2007 13:52:06 +0000 Subject: Try to get help on pymat References: Message-ID: "CHRIS CHEW" writes: > I am trying to get my pymat to work. The Python script did not interface to > matlab yet. What are the required script to get the interface to work? Please > send me email at chris9883 at msn.com You might want to have a look at . cheers, 'as From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Mar 26 18:27:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Mar 2007 00:27:26 +0200 Subject: Python object overhead? References: <56ja46F28lpp9U1@mid.individual.net> Message-ID: <56qvmeF29ud19U1@mid.individual.net> Matt Garman wrote: > In my case, I know my input data doesn't have any blank lines. 8) I work with a (not self-written) perl script that does funny things with blank lines in input files. Yeah, blank lines "aren't supposed to" be in the input data ... > However, I'm glad you (and others) clarified the issue, because I > wasn't aware of the better methods for checking for EOF. The principle was okay (to check if the string is totally empty). I always used readlines so far and didn't have the problem. > Thanks to all for your input and suggestions. I received many > more responses than I expected! You're welcome. :) Regards, Bj?rn -- BOFH excuse #374: It's the InterNIC's fault. From justin.mailinglists at gmail.com Thu Mar 29 06:24:08 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 29 Mar 2007 03:24:08 -0700 Subject: BeautifulSoup vs. Microsoft In-Reply-To: <1175163104.054405.28190@d57g2000hsg.googlegroups.com> References: <1175163104.054405.28190@d57g2000hsg.googlegroups.com> Message-ID: <1175163848.584005.88100@y66g2000hsf.googlegroups.com> On Mar 29, 6:11 pm, "Justin Ezequiel" wrote: > > FWIW, seehttp://tinyurl.com/yjtzjz > hmm. not quite right. http://tinyurl.com/ynv4ct or http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser From __peter__ at web.de Wed Mar 21 16:35:29 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Mar 2007 21:35:29 +0100 Subject: Printing __doc__ References: <1174506426.108098.243940@d57g2000hsg.googlegroups.com> Message-ID: gtb wrote: > In a function I can use the statement n = > sys._getframe().f_code.co_name to get the name of the current > function. Given that I can get the name how can I print the __doc__ > string? I cant use the following, it will tell me to bugger off as the > string has no such attribute. > > def spam(self): > n = sys._getframe().f_code.co_name > print n.__doc__ #Wrong > print __doc__ #No good either > #.... >>> import sys >>> def docstring(): ... return sys._getframe(1).f_code.co_consts[0] ... >>> def foo(): ... print "My docstring is %r" % docstring() ... >>> def bar(): ... "bar's docstring" ... print "My docstring is %r" % docstring() ... >>> foo() My docstring is None >>> bar() My docstring is "bar's docstring" No idea how brittle that might be, though. Peter From openopt at ukr.net Wed Mar 21 10:38:00 2007 From: openopt at ukr.net (dmitrey) Date: 21 Mar 2007 07:38:00 -0700 Subject: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?) Message-ID: <1174487880.610134.257840@y66g2000hsf.googlegroups.com> Hi all, I looked to the PEPs & didn't find a proposition to remove brackets & commas for to make Python func call syntax caml- or tcl- like: instead of result = myfun(param1, myfun2(param5, param8), param3) just make possible using result = myfun param1 (myfun2 param5 param8) param3 it would reduce length of code lines and make them more readable, + no needs to write annoing charecters. Maybe it will require more work than I suppose, for example handling of things like result = myfun(param1, myfun2(param5, param8), param3=15, param4=200) to result = myfun param1 (myfun2 param5 param8) param3=15 param4=200 #so it needs some more efforts to decode by compiler but anyway I think it worth. + it will not yield incompabilities with previous Python versions. WBR, D. From arnodel at googlemail.com Mon Mar 5 13:59:02 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 5 Mar 2007 10:59:02 -0800 Subject: Descriptor/Decorator challenge In-Reply-To: <1173105492.632821.326810@n33g2000cwc.googlegroups.com> References: <1173079890.154064.115300@p10g2000cwp.googlegroups.com> <1173105492.632821.326810@n33g2000cwc.googlegroups.com> Message-ID: <1173121140.087027.214600@h3g2000cwc.googlegroups.com> On 5 Mar, 14:38, "Arnaud Delobelle" wrote: > On 5 Mar, 07:31, "Raymond Hettinger" wrote: > > > I had an idea but no time to think it through. > > Perhaps the under-under name mangling trick > > can be replaced (in Py3.0) with a suitably designed decorator. > > Your challenge is to write the decorator. > > Any trick in the book (metaclasses, descriptors, etc) is fair game. > > I had some time this lunchtimes and I needed to calm my nerves so I > took up your challenge :) > Here is my poor effort. I'm sure lots of things are wrong with it but > I'm not sure I'll look at it again. Well in fact I couldn't help but try to improve it a bit. Objects now don't need a callerclass attribute, instead all necessary info is stored in a global __callerclass__. Bits that didn't work now do. So here is my final attempt, promised. The awkward bits are: * how to find out where a method is called from * how to resume method resolution once it has been established a local method has to be bypassed, as I don't know how to interfere directly with mro. Feedback of any form is welcome (though I prefer when it's polite :) -------------------- from types import MethodType, FunctionType class IdDict(object): def __init__(self): self.objects = {} def __getitem__(self, obj): return self.objects.get(id(obj), None) def __setitem__(self, obj, callerclass): self.objects[id(obj)] = callerclass def __delitem__(self, obj): del self.objects[id(obj)] # This stores the information about from what class an object is calling a method # It is decoupled from the object, better than previous version # Maybe that makes it easier to use with threads? __callerclass__ = IdDict() # The purpose of this class is to update __callerclass__ just before and after a method is called class BoundMethod(object): def __init__(self, meth, callobj, callerclass): self.values = meth, callobj, callerclass def __call__(self, *args, **kwargs): meth, callobj, callerclass = self.values if callobj is None and args: callobj = args[0] try: __callerclass__[callobj] = callerclass return meth(*args, **kwargs) finally: del __callerclass__[callobj] # A 'normal' method decorator is needed as well class method(object): def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return BoundMethod(MethodType(self.f, obj, objtype), obj, self.defclass) class LocalMethodError(AttributeError): pass # The suggested localmethod decorator class localmethod(method): def __get__(self, obj, objtype=None): callobj = obj or objtype defclass = self.defclass if __callerclass__[callobj] is defclass: return MethodType(self.f, obj, objtype) else: # The caller method is from a different class, so look for the next candidate. mro = iter((obj and type(obj) or objtype).mro()) for c in mro: # Skip all classes up to the localmethod's class if c == defclass: break name = self.name for base in mro: if name in base.__dict__: try: return base.__dict__[name].__get__(obj, objtype) except LocalMethodError: continue raise LocalMethodError, "localmethod '%s' is not accessible outside object '%s'" % (self.name, self.defclass.__name__) class Type(type): def __new__(self, name, bases, attrs): # decorate all function attributes with 'method' for attr, val in attrs.items(): if type(val) == FunctionType: attrs[attr] = method(val) return type.__new__(self, name, bases, attrs) def __init__(self, name, bases, attrs): for attr, val in attrs.iteritems(): # Inform methods of what class they are created in if isinstance(val, method): val.defclass = self # Inform localmethod of their name (in case they have to be bypassed) if isinstance(val, localmethod): val.name = attr class Object(object): __metaclass__ = Type # Here is your example code class A(Object): @localmethod def m(self): print 'A.m' def am(self): self.m() class B(A): @localmethod def m(self): print 'B.m' def bm(self): self.m() m = B() m.am() # prints 'A.m' m.bm() # prints 'B.m' # Added: B.am(m) # prints 'A.m' B.bm(m) # prints 'B.m' m.m() # LocalMethodError (which descends from AttributeError) # Untested beyond this particular example! -------------------- -- Arnaud From steve at REMOVE.THIS.cybersource.com.au Sun Mar 25 07:50:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 25 Mar 2007 21:50:36 +1000 Subject: Strange behavior when printing a returned closure function References: <1174820392.652008.123550@y80g2000hsf.googlegroups.com> Message-ID: On Sun, 25 Mar 2007 03:59:52 -0700, dartsch wrote: > I get an output like > > > > > So according to print I get the same function object returned at both > calls. Not the same function object. The first object is printed, then deleted by the garbage collector because it goes out of scope. Then the second one is created and just happens to end up in the same memory location. That's an accident of the garbage collector implementation. > That's surprising, I would expect to get two distinct function objects > because their func_closure attribute has to be different. And indeed, > if I do [snip] > > > > ie. two distinct function objects are printed. This time the first function still exists when the second is created, so the second naturally can't be in the same memory location. -- Steven. From dudaraster at gmail.com Sun Mar 4 12:02:34 2007 From: dudaraster at gmail.com (Aviroce) Date: Sun, 04 Mar 2007 17:02:34 +0000 Subject: *** CANADIAN ANTI-TERROR LAW HAS BEEN STRUCK DOWN BY ITS HONORABLE SUPREME COURT UNANIMOUSLY *** (REPOST) In-Reply-To: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> References: <1172334164.885851.200820@h3g2000cwc.googlegroups.com> Message-ID: On Feb 24, 11:22 am, stj... at rock.com wrote: > Canada anti-terror law is struck down>From the Associated Press > > February 24, 2007 > > OTTAWA - Canada's Supreme Court on Friday unanimously declared it > unconstitutional to detain foreign terrorism suspects indefinitely > while the courts review their deportation orders. > > Five Arab Muslim men have been held for years under the "security > certificate" program, which the Justice Department has said is a key > tool in the fight against global terrorism and essential to Canada's > security. > > The court found that the system violated the Charter of Rights and > Freedoms, Canada's bill of rights. However, it suspended its ruling > for a year to give Parliament time to rewrite the part of the > Immigration and Refugee Protection Act that covers the certificate > process. > > The security certificates were challenged by three men from Morocco, > Syria and Algeria - all alleged by the Canadian Security Intelligence > Service to have ties to terrorist networks. > > The men have spent years in jail while fighting deportation orders. > > They risk being labeled terrorists and sent back to their native > countries, where they say they could face torture. > > The court said the treatment of the suspects was a violation of their > rights. > > "The overarching principle of fundamental justice that applies here is > this: Before the state can detain people for significant periods of > time, it must accord them a fair judicial process," Chief Justice > Beverley McLachlin wrote in a ruling for all nine justices. > > "The secrecy required by the scheme denies the person named in a > certificate the opportunity to know the case put against him or her, > and hence to challenge the government's case," she said. > > The challenged law allows sensitive intelligence to be heard behind > closed doors by a federal judge, with only sketchy summaries given to > defense attorneys. > > The court said the men and their lawyers should have a right to > respond to the evidence used against them by intelligence agents. > > Stockwell Day, the minister of public safety, noted that because the > ruling does not take effect for a year, the certificates would remain > in place. He said the government would address the court's ruling "in > a timely and decisive fashion." > > Two of the men are out on bail and remain under house arrest. Three > others are being held in a federal facility in Ontario. <<<<<<<<<<<"The court said the treatment of the suspects was a violation of their rights. "The overarching principle of fundamental justice that applies here is this: Before the state can detain people for significant periods of time, it must accord them a fair judicial process," Chief Justice Beverley McLachlin wrote in a ruling for all nine justices. "The secrecy required by the scheme denies the person named in a certificate the opportunity to know the case put against him or her, and hence to challenge the government's case," she said. ">>>>>>>>>>>>>>>> THAT IS CALLED PROTECTING CIVIL RIGHTS. IN THE UNITED STATES OF AMERICA, WHERE CIVIL RIGHTS ARE PROTECTED BY LAW, FOREIGN SUSPECTS ARE NOT PROTECTED BY THE GENEVA CONVENTION. DR. EVIL, V.P. CHENEY, AND MINI-ME, PRESIDENT BUSH, OPTED TO MODIFY THE GENEVA CONVENTION TO DENY FOREIGN SUSPECTS DUE PROCESS DEMANDED BY THE CONVENTION. THIS MEANS ENEMIES OF THE UNITED STATES OF AMERICA WILL BE DOING JUST THAT TOO. WHAT IS GOOD FOR THE GOOSE IS GOOD FOR GANDER. From theller at ctypes.org Thu Mar 15 13:59:57 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 15 Mar 2007 18:59:57 +0100 Subject: ANN: ActivePython 2.5.0.0 is now available In-Reply-To: <45F97594.40008@activestate.com> References: <1173966133.061395.219360@n76g2000hsh.googlegroups.com> <45F97594.40008@activestate.com> Message-ID: Trent Mick schrieb: > dan.shechter at gmail.com wrote: >> >> is ctypes supported on ActivePython for Windows x64? >> > > No. > http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html > > My understanding (from http://www.python.org/sf/1545507) is that ctypes isn't > yet ported to Windows/AMD64. That may have changed though. > > Trent > I have a patch for ctypes for Windows x64. It cannot be integrated in the Python SVN repository in the Python 2.5 branch because of the feature freeze, so Python 2.6 would be the earliest. I intend to release a separate Win x64 ctypes version soon (my plan is to release this when Python 2.5.1 will be released, but this is totally arbitrary); I still have to run more tests with it. Thomas From jezonthenet at yahoo.com Tue Mar 13 00:39:11 2007 From: jezonthenet at yahoo.com (jezonthenet at yahoo.com) Date: 12 Mar 2007 21:39:11 -0700 Subject: Starting Python... some questions Message-ID: <1173760751.798442.300550@s48g2000cws.googlegroups.com> I started using Python a couple of days ago - here are a few questions: * Doesn't the __main__() method automatically execute when I run my python program? * Only when I do an import of my test.py file within python and then run test.__main__() I can see where my bugs are. Is this correct? (right now this is my only way of running my python program and see where I have problems) * Once I've done an import and then I wish to make a change to the file I've imported I have to quit Python, restart and import that module again in order for the module to be refreshed. Is there no "re- import" ? * Finally, could someone tell me why I'm having problems with the small module below? - Python pretends I provide chassis_id() with three parameters, even though I clearly only provide it with two - why? Thanks! #!/usr/bin/python import scapy import struct class lldp_class: def __init__(self): self.chassis_id_tlv = None def chassis_id(subtype, chassis_info): if subtype == 4: chassis_data = struct.pack("!B",chassis_info) subtype_data = struct.pack("!B",subtype) self.chassis_id_tlv = subtype_data + chassis_data def __main__(): p = lldp_class() p.chassis_id(4, "01:80:C2:00:00:0E") payload = p.chassis_id_tlv ether = scapy.Ether(dst="01:02:03:04:05:06") fullpayload = ether + payload sendp(fullpayload) From michele.simionato at gmail.com Mon Mar 12 12:22:31 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Mar 2007 09:22:31 -0700 Subject: nonlinear interpolation Message-ID: <1173713333.615789.287070@v33g2000cwv.googlegroups.com> I want to interpolate a data distribution with a function depending on various parameters; the function can be a Gaussian, a Breit-Wigner, a custom function. Where should I look? I am getting lost between matplotlib, numeric, numpy, scientific python, scipy, etc. etc. Any pointer would be well received :) Michele Simionato From no at spam.fr Tue Mar 27 06:14:34 2007 From: no at spam.fr (ian) Date: Tue, 27 Mar 2007 12:14:34 +0200 Subject: sys.excepthook and threads Message-ID: <4608ee59$0$17589$426a34cc@news.free.fr> Hi, sys.excepthook don't work if an exception come in a thread... It's normal or its a bug ? There are any tip ? look here : http://spyced.blogspot.com/2005_06_01_archive.html Thx From mikeschinkel at gmail.com Sun Mar 11 09:09:57 2007 From: mikeschinkel at gmail.com (Mike Schinkel) Date: Sun, 11 Mar 2007 09:09:57 -0400 Subject: Parsing Indented Text (like parsing Python) In-Reply-To: References: <1173583424.092914.148080@h3g2000cwc.googlegroups.com><1173595945.530722.273030@30g2000cwc.googlegroups.com><000a01c763c0$6863a560$2102fea9@Guides.local> Message-ID: <008f01c763de$9a1a4190$0702a8c0@Guides.local> Gabriel Genellina wrote: > Start with IC = Previous IC = 0, and a stack with a single 0 > element For each line in the file: > compute the indentation column IC (that is, count the > number of leading whitespace characters; perhaps replacing > tabs as 8 spaces) > compare IC with the Previous IC: > same: continue with next line > IC > previous ("indent"): push IC onto indent stack > IC < previous ("dedent"): > discard top of stack > look at the new top of stack (but dont discard > it); if not the same, indentation error. > Previous IC = IC I went away and reviewed this, but it appears it doesn't tackle the difficult part which was what made me ask the question in the first place. The problem is, how do I figure out how many spaces represent a tab? In one case, someone could have their editor configured to allow tabs to use 3 spaces and the user could intermingle tabs and spaces. In other cases, a user might have their editor configured to have a tab equal 8 spaces yet also intermingle tabs and spaces. When a human looks at the document it is obvious the setting but how can I make it obvious to my program? I could force the user to specify tabwidth at the top of the file, but I'd rather not. And since Python doesn't either, I know it is possible to write a parser to do this. I just don't know how. -- -Mike Schinkel http://www.mikeschinkel.com/blogs/ http://www.welldesignedurls.org http://atlanta-web.org - http://t.oolicio.us From mrmakent at cox.net Sun Mar 4 16:29:38 2007 From: mrmakent at cox.net (Mike Kent) Date: 4 Mar 2007 13:29:38 -0800 Subject: doxygen In-Reply-To: <45eb0cc2$1@griseus.its.uu.se> References: <45eb0cc2$1@griseus.its.uu.se> Message-ID: <1173043778.885450.152300@v33g2000cwv.googlegroups.com> On Mar 4, 1:15 pm, Jan Danielsson wrote: > When I run doxygen on my python files, it does document classes, but > not "standalone" functions. Look in the doxygen config file for your python project, named 'Doxyfile', for the config setting 'EXTRACT_ALL', and read the comments there. From skip at pobox.com Fri Mar 23 09:30:39 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 23 Mar 2007 08:30:39 -0500 Subject: Catching an unknown error In-Reply-To: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> References: <1174655767.755847.241670@y66g2000hsf.googlegroups.com> Message-ID: <17923.54911.261738.696420@montanaro.dyndns.org> Harlin> value = raw_input("Type a divisor: ") Harlin> try: Harlin> value = int(value) Harlin> print "42 / %d = %d" % (value, 42/value) Harlin> except ValueError: Harlin> print "I can't convert the value to an integer" Harlin> except ZeroDivisionError: Harlin> print "Your value should not be zero" Harlin> except: Harlin> print "Something unexpected happened" Harlin> In the last 'except' block, how can I print out the particular Harlin> error name even though one is not specifically named? >>> try: ... 1/0 ... except Exception, err: ... print repr(err) ... Skip From arkanes at gmail.com Mon Mar 12 11:57:16 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Mar 2007 09:57:16 -0600 Subject: a better solution for GUI in python In-Reply-To: References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> <1173613976.277044.242160@8g2000cwh.googlegroups.com> <55iaceF24d6qgU2@mid.individual.net> Message-ID: <4866bea60703120857yd437cabqb899e01bceda7554@mail.gmail.com> On 3/11/07, Jarek Zgoda wrote: > Bjoern Schliessmann napisa?(a): > > >> I'd recommend pyGTK. It's easy to use, delivers astonishing > >> results and is perfectly portable as far as I know. > > > > And how does it look on Windows? :) > > On styled Windows XP it looks like any other styled application > (counting those Qt and wx based). This is really an overstatement. While it uses the Windows theme manager to draw widgets, and will appear native in screenshots, nobody is going to mistake a Gtk app for a native Windows one in use. There are lots of behaviors and graphical differences from native applications. That said, in order to make a useful recommendation your requirements need to be better known. Browser based clients are often poor for high speed data entry, especially with highly trained data entry people. You simply don't have enough control over the browser environment, and you're limited in your ability to offload processing to the client. Ironing out browser differences is also no picnic. On the other hand you've got rapid and low cost deployment and updates. Licensing is the main reason I'd avoid pyQt, if the licensing fits your needs (or budget) then it's a perfectly reasonable solution. Gtk I consider an extremely poor contender as a cross platform toolkit. The runtime is enormous and it makes little effort to appear native on any non-GNOME platform. wxPython is also a perfectly reasonable solution, especially if you want a "native" seeming app on all platforms. If consistency of interface, rather than a native interface, is more important to you then Qt would probably be a better choice. From erokar at gmail.com Mon Mar 5 17:00:24 2007 From: erokar at gmail.com (erokar at gmail.com) Date: 5 Mar 2007 14:00:24 -0800 Subject: Make instance global -- possbile? Message-ID: <1173132019.219765.19760@h3g2000cwc.googlegroups.com> Rather new to OOP in Python... I'm writing an app where several objects need to access and change the state of ONE instance. I could of course instantiate the instance and then pass it along the objects, but that's cumbersome, especially as it would need to be "passed through" classes that don't really need it. I would be happy if I could just instantiate the object in the main module and declare it global, but classes are in different modules so I guess that won't work. Have looked a bit into singletons -- is that the way to go? From mmanns at gmx.net Wed Mar 28 23:56:28 2007 From: mmanns at gmx.net (Martin Manns) Date: Wed, 28 Mar 2007 23:56:28 -0400 Subject: gmpy floating point exception Message-ID: Hi, I am experiencing some trouble with gmpy v1.01. Multiplying an mpq with inf results in a floating point exception that exits python. Has this already been fixed in newer gmpy versions? ~ $ python Python 2.4.3 (#1, Mar 26 2007, 00:32:54) [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from gmpy import mpq as Rational >>> a=Rational(2,3) >>> b=1.0e99999 >>> b inf >>> int(b) Traceback (most recent call last): File "", line 1, in ? OverflowError: cannot convert float infinity to long >>> a+b Floating point exception ~ $ BTW. 1) What is the best way to test for inf regardless of type? 2) Is there any inf type around with a + inf == inf inf > a (as long as a != inf) etc. that works with any other type? Thanks in advance Martin From andre.dos.anjos at gmail.com Thu Mar 1 05:51:19 2007 From: andre.dos.anjos at gmail.com (andre.dos.anjos at gmail.com) Date: 1 Mar 2007 02:51:19 -0800 Subject: Importing binary modules Message-ID: <1172746279.351722.29410@p10g2000cwp.googlegroups.com> How can I, in python (linux, python version >= 2.4.2), dynamically set the path and import a binary module that depends on libraries which are not declared in LD_LIBRARY_PATH or any other automated linker path when python starts? This is a an example: Suppose I have a new python module, called MyNewModule.py. It resides in '/my/module/dir'. Internally, it loads libMyNewModule.so, which implements most of the functionality for MyNewModule, so the user can say: import sys sys.path.append('/my/module/dir') import MyNewModule And everything works fine. The problem appears when libMyNewModule.so depends on another library, say libfoo.so, which sits also in /my/module/dir. In that case, '/my/ module/dir', needs to be preset in the LD_LIBRARY_PATH *before* the python interpreter is set. In this case, the snippet of code above will not work as one would expect. It will normally give an ImportError saying it cannot find libfoo.so. That happens, apparently, because the dynamic linker cannot rescan LD_LIBRARY_PATH after the python interpreter has started. So is there any other way to circumvent this? import sys sys.path.append('/my/module/dir') #black magic to get the linker to reload the LD_LIBRARY_PATH import MyNewModule So this succeeds? From bdesth.quelquechose at free.quelquepart.fr Tue Mar 13 17:01:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 13 Mar 2007 22:01:47 +0100 Subject: Need help with a string plz! (newbie) In-Reply-To: <12vas0lj1u2ti78@corp.supernews.com> References: <1173475520.292989.239200@p10g2000cwp.googlegroups.com> <12v3ksihos7uj7a@corp.supernews.com> <1173477047.467568.298090@p10g2000cwp.googlegroups.com> <2ZqdnZCruccLRWzYnZ2dnUVZ_rqhnZ2d@comcast.com> <1173488215.913014.130190@h3g2000cwc.googlegroups.com> <12v8vk7sabb2i84@corp.supernews.com> <12vas0lj1u2ti78@corp.supernews.com> Message-ID: <45f70902$0$5892$426a34cc@news.free.fr> Grant Edwards a ?crit : (snip) > I don't know if emacs still includes Zippy quotes > (of if they've been updated), but you used to be able to do > "esc-X yow" and emacs would show you a random Zippy quote. > It's still there. From gagsl-py2 at yahoo.com.ar Fri Mar 23 01:44:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 23 Mar 2007 02:44:12 -0300 Subject: Technical Answer - Protecting code in python References: <1174484176.392674.220040@d57g2000hsg.googlegroups.com> <1tkMh.115$mG4.94@newsfe12.lga> Message-ID: En Thu, 22 Mar 2007 14:04:04 -0300, Bart Willems escribi?: >> chown scriptuser script.py # a unique user >> chmod a-rwx script.py >> chmod u+rx script.py > > If it works on the target machine - I am under the assumption that the > client is some kind of government office - more likely to run Windows > than it is to run unix/linux/etc. > > Who has a similar solution for windows? cacls /help -- Gabriel Genellina From jrpfinch at gmail.com Mon Mar 26 04:53:22 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 26 Mar 2007 01:53:22 -0700 Subject: Calling Queue experts Message-ID: <1174899202.355092.209590@l75g2000hse.googlegroups.com> I have a script which is based on the following code. Unfortunately, it only works on Python 2.3 and not 2.5 because there is no esema or fsema attribute in the 2.5 Queue. I am hunting through the Queue.py code now to try to figure out how to make it work in 2.5, but as I am a beginner, I am having difficulty and would appreciate your help. Many thanks Jon import os import Queue import threading import time import cPickle class PickleQueue(Queue.Queue): """A multi-producer, multi-consumer, persistent queue.""" def __init__(self, filename, maxsize=0): """Initialize a persistent queue with a filename and maximum size. The filename is used as a persistent data store for the queue. If maxsize <= 0, the queue size is infinite. """ self.filename = filename Queue.Queue.__init__(self, maxsize) if self.queue: self.esema.release() if self._full(): self.fsema.acquire() def _init(self, maxsize): # Implements Queue protocol _init for persistent queue. # Sets up the pickle files. self.maxsize = maxsize try: self.readfile = file(self.filename, 'r') self.queue = cPickle.load(self.readfile) self.readfile.close() except IOError, err: if err.errno == 2: # File doesn't exist, continue ... self.queue = [] else: # Some other I/O problem, reraise error raise err except EOFError: # File was null? Continue ... self.queue = [] # Rewrite file, so it's created if it doesn't exist, # and raises an exception now if we aren't allowed self.writefile = file(self.filename, 'w') cPickle.dump(self.queue, self.writefile, 1) def __sync(self): # Writes the queue to the pickle file. self.writefile.seek(0) cPickle.dump(self.queue, self.writefile, 1) self.writefile.flush() def _put(self, item): # Implements Queue protocol _put for persistent queue. self.queue.append(item) self.__sync() def _get(self): # Implements Queue protocol _get for persistent queue. item = self.queue[0] del self.queue[0] self.__sync() return item class counterThread(threading.Thread): numberQueue = PickleQueue('/export/home/jrpf/data.pkl') exitCounterQueue = Queue.Queue(1) def run(self): command = '' i = 0 while 1: self.numberQueue.put(i) if i > 10: print "i > 10 so attempting to exit" wt.exit() self.exit() print i try: command = self.exitCounterQueue.get(block=False) except Queue.Empty: pass if command == 'exit': print "Counter thread exited" break i = i + 1 time.sleep(1) def exit(self): self.exitCounterQueue.put('exit') def main(): ct = counterThread() ct.setDaemon(True) ct.start() ct.join() if __name__ == "__main__": main() From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 19 09:08:29 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 14:08:29 +0100 Subject: any ways to judge whether an object is initilized or not in a class In-Reply-To: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> References: <1174289858.932835.207500@y66g2000hsf.googlegroups.com> Message-ID: <45fe8b4c$0$16060$426a34cc@news.free.fr> momobear a ?crit : > hi, I am puzzled about how to determine whether an object is > initilized in one class, anyone could give me any instructions? > here is an example code: > > class coffee: > def boil(self): > self.temp = 80 > > a = coffer() > if a.temp > 60: > print "it's boiled" > > in C++ language we must initilized a variable first, so there is no > such problem, but in python if we don't invoke a.boil(), we will not > get self.temp to be initilized, Obviously. This is why it's good form to set all public attributes in the initializer method: class Coffee(object): def __init__(self): self.temp = 20 def boil(self): self.temp = 80 From duncan.booth at invalid.invalid Thu Mar 29 07:52:21 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Mar 2007 11:52:21 GMT Subject: BeautifulSoup vs. Microsoft References: <1175163104.054405.28190@d57g2000hsg.googlegroups.com> Message-ID: "Justin Ezequiel" wrote: > On Mar 29, 4:08 pm, Duncan Booth wrote: >> John Nagle wrote: >> > title="". Comment directive is a special comment starting with '%' character, followed by a line of python code. It is executed using 'exec' when the resource file is opened. This is useful to import plugin modules containing custom handlers which are specific to the resource file, hovewer this is of course a security hole if you use foreign XRC files. A warning is displayed if the preference option 'ask' is selected (by default). * Added support for custom controls and plugin modules. Refer to this wxPythonWiki for the details: http://wiki.wxpython.org/index.cgi/XRCed#custom * Tool panel sections can be collapsed/expanded by clicking on the label of a tool group. * Some undo/redo and other fixes. * Fixes for wxMSW (notebook highlighting, control sizes, tree Unselect). * Notebook page highlighting fix. Highlight resizes when the window is resized. ParamUnit spin button detects event handler re-entry (wxGTK probably has a bug in wxSpinButton with repeated events). * Fix for dealing with empty 'growable' property, using MiniFrame for properties panel, the panel is restored together with the main window. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From aleax at mac.com Mon Mar 19 01:22:32 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 18 Mar 2007 22:22:32 -0700 Subject: struct.pack returns nothing References: Message-ID: <1hv6zfk.kpur6sszfqo7N%aleax@mac.com> wrote: > If I build a strict with: > > import struct > print struck.pack ('i', 1) > > it returns a '\n'. > What's wrong with it??? > :( You're trying to print a binary string that's hardly printable as-is. Try printing its repr(...) and you'll see all the binary zeros and one you crave!-) Alex From kyosohma at gmail.com Fri Mar 30 11:54:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Mar 2007 08:54:45 -0700 Subject: Inserting '-' character in front of all numbers in a string In-Reply-To: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> Message-ID: <1175270085.596596.185280@o5g2000hsb.googlegroups.com> On Mar 30, 10:38 am, "kevinliu23" wrote: > Hey guys, > > I want to be able to insert a '-' character in front of all numeric > values in a string. I want to insert the '-' character to use in > conjunction with the getopt.getopt() function. > > Rigt now, I'm implementing a menu system where users will be able to > select a set of options like "2a 3ab" which corresponds to menu > choices. However, with getopt.getopt(), it'll only return what I want > if I input -2a -3ab as my string. I don't want the user have to insert > a '-' character in front of all their choices, so I was thinking of > accepting the string input first, then adding in the '-' character > myself. > > So my qusetion is, how do I change: > > "2a 3ab" into "-2a -3ab". > > Regular expressions? :/ Regular expressions would definitely work. Here's a hack though: tempInput = '2a 3ab' tempLst = tempInput.split(' ') output = '' for i in tempLst: output += ('-' + i + ' ') I'm sure there are many better and more elegant hacks than this. Mike From silverburgh.meryl at gmail.com Sat Mar 31 23:12:56 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 31 Mar 2007 20:12:56 -0700 Subject: re.findall() hangs in python Message-ID: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> Hi, I have the following regular expression. It works when 'data' contains the pattern and I see 'match2' get print out. But when 'data' does not contain pattern, it just hangs at 're.findall' pattern = re.compile("(.*) Message-ID: <20070319124137.18920.968075532.divmod.quotient.3932@ohm> On Mon, 19 Mar 2007 13:17:11 +0100, Bruno Desthuilliers > > [snip] > >And what if it's a unicode string ? >The correct idiom here is: > if isinstance(year, basestring): > >> year,month,day=map(int,string.split(year,'-')) > year, month, day = map(int, year.split('-')) And what if it's another kind of string? The correct idiom is: try: parts = year.split('-') except AttributeError: # Handle int case else: year, month, day = map(int, parts) > >> if year < 100: >> year += 2000 >> return date.__new__(cls,year,month,day) >> >(snip) >-- >http://mail.python.org/mailman/listinfo/python-list > From nogradi at gmail.com Sun Mar 18 13:12:25 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 18 Mar 2007 18:12:25 +0100 Subject: list comprehension help In-Reply-To: References: <5f56302b0703180924o3ebf61e2nb2d50280456f8448@mail.gmail.com> Message-ID: <5f56302b0703181012t6ab225a3je6375ca539451b58@mail.gmail.com> > > > I need to process a really huge text file (4GB) and this is what i > > > "list comprehension" can fast up things. Can you point out how to do > > > f = open('file.txt','r') > > > for line in f: > > > db[line.split(' ')[0]] = line.split(' ')[-1] > > > db.sync() > > > > What is db here? Looks like a dictionary but that doesn't have a sync method. > > db is a handle for Berkely db that i open with import bsddb > > import bsddb > db=bsddb.hashopen('db_filename') > > > If the file is 4GB are you sure you want to store the whole thing into > > memory? > > I dont want to load it in memory. Once I call the sync() function it > get synced to the disk, and it is not loaded completely. > > > use list comprehension like this: > > db = [ line.split(' ')[-1] for line in open('file.txt','r') ] > > or > > db = [ ( line.split(' ')[0], line.split(' ')[-1] ) for line in > > open('file.txt','r') ] > > > > depending on what exactly you want to store. > > line.split(' ')[0] is the key and line.split(' ')[-1] is the value. > THat is what I want to store. > Will the second line comprehension work in this case? No, I don't think so. I gave that example because you wanted to use list comprehension and I didn't know what db is but as the name says it is for lists. Since the bsddb handle is not a list I'm afraid you won't be able to use list comprehension. This small thing will speed up your loop but since syncing is IO bound it won't give you much (the timeit module will tell you how much you save, if at all): for line in f: sp = line.split db[sp(' ')[0]] = sp(' ')[-1] db.sync( ) HTH, Daniel From vorticitywolfe at gmail.com Sun Mar 25 16:02:02 2007 From: vorticitywolfe at gmail.com (vorticitywolfe at gmail.com) Date: 25 Mar 2007 13:02:02 -0700 Subject: Save time processing netcdf Message-ID: <1174852922.541284.23480@n59g2000hsh.googlegroups.com> Hello, I am working with a netcdf file and trying to remove a long string from it e.g. "KAST BLAH BLAH BLAH BLAH DATA BLAH DATA BLAH BLAH BLAH BLAH BLAH DATA BLAH DATA BLAH" Right now what I have works, but takes a long time to run... I think this could be cut down to a quick 2 second run, but now takes around 5 minutes primarily because of the problem described below... Why can't I use something like line 9 to get the entire string (which returns [0], not ["KAST BLAH BLAH BLAH BLAH DATA BLAH DATA BLAH BLAH BLAH BLAH BLAH DATA BLAH DATA BLAH"])? Rather I have to loop through it grabbing one character at a time which drastically increases the processing time and is very cumbersome. Any one have any ideas or suggestions? 0 #OPEN NetCDF FILE TO READ 1 allDimNames=file.dimensions.keys() 2 max_string_length=file.dimensions['maxstringLen'] 3 variableNames=file.variables.keys() 4 globalAttList=dir(file) 5 globalAttValue=getattr(file,'filePeriod') 6 7#GRABS DATA FROM STRING (2 DIMENSIONAL ARRAY) WITH THE CHARACTERS AS INDIVIDUAL 8ELEMENTS 9 #YOU CAN'T JUST SPECIFY DATA VALUES DATA[0][0:max_string_length] 10 data=file.variables['rawstring'].getValue() 11 num_stations=data.shape 12 station_id=[str(mz)] 13 14 for m in station_id: 15 station_id=m 16 prec=[] 17 temps=[] 18 19 #Cycles through all of the stations in the file (LARGE ARRAY!!) 20 for k in range(num_stations[0]): 21 #Finds a certain station 22 if data[k][6]=='K' and data[k][7]==station_id[0:1] and data[k] [8]==station_id[1:2] and 23data[k][9]==station_id[2:3] and data[k] [15]=='5' or data[k][6]=='K' and data[k][7]==station_id[0:1] and 24data[k][8]==station_id[1:2] and data[k][9]==station_id[2:3] and data[k][15]=='4': 25 26 #SEPARATES STRING CHARACTER BY CHARACTER ONLY WAY I'VE 27BEEN ABLE TO FIGURE OUT HOW TO READ ENTIRE STRING INTO A STRING 28 for j in range(max_string_length): 29 prec.append(str(data[k][j])) 30 S= ''.join(prec) 31 # # # ##THEN RIP OFF THE WHITESPACE AT THE RIGHT OF THE STRING 32 code=S.rstrip("\0") 33 Thanks for any of your help! From gdamjan at gmail.com Thu Mar 29 20:10:00 2007 From: gdamjan at gmail.com (Damjan) Date: Fri, 30 Mar 2007 02:10:00 +0200 Subject: PyPy for dummies Message-ID: <460c5515$0$90269$14726298@news.sunsite.dk> .. like me. Ok, this is what I understood why PyPy is important. Writing programing languages and implementations (compilers, interpreters, JITs, etc) is hard. Not many people can do it from scratch and create something comparable to what's available today. But we need people with new aproaches, exploring new ideas (to boldly go where no hacker has gone before). Also, evolving the current Python language and implementation is not easy either. As it becomes more complex, it's hard for newcomers to comprehend it as a whole, and as it is still harder and harder to work on details without understanding the whole. What PyPy provides is, making this easier, thus allowing for: *rapid turnaround* of language features and implementation details - this enables easier experimentation and testing of wild ideas. Most of them will fail of course, but some will succed and some will succed and suprise (NOBODY expects the Spanish Inquisition!). So that's how I see PyPy ... at the same time an interesting - let's call it - academic experiment, but also something very close to beeing usefull at the level of the current CPython. -- damjan From tuomas.vesterinen at pp.inet.fi Wed Mar 21 07:03:39 2007 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Wed, 21 Mar 2007 11:03:39 GMT Subject: Exceptions and unicode messages Message-ID: This works: >>> raise StandardError(u'Wrong type') Traceback (most recent call last): File "", line 1, in ? StandardError: Wrong type but don't in Finnish: >>> raise StandardError(u'V??r? tyyppi') Traceback (most recent call last): File "", line 1, in ? StandardError>>> >>> Any solution in Python? TV From marco at waven.com Sun Mar 4 08:48:40 2007 From: marco at waven.com (Marco) Date: Sun, 4 Mar 2007 21:48:40 +0800 Subject: Hey! A VERY c00l feature of X and mplayer(could bind to PyQt4) Message-ID: <5c62a320703040548m4e6b0e84u521336316e6b4581@mail.gmail.com> I found a Very c00l feature, that you can write your own MPlayer GUI. The core is Xembed (http://www.freedesktop.org/wiki/Standards/xembed-spec) And Of course MPlayer support it as its para: -wid I hope you like it! -- LinuX Power From paul at boddie.org.uk Wed Mar 14 11:58:57 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Mar 2007 08:58:57 -0700 Subject: most complete xml package for Python? In-Reply-To: <45F811A3.1050208@web.de> References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> <45F811A3.1050208@web.de> Message-ID: <1173887937.251026.175260@y66g2000hsf.googlegroups.com> On 14 Mar, 16:15, Stefan Behnel wrote: > metaperl wrote: > > Without even checking them all out, I'm thinking the Amara XML Toolkit > > must be the most feature-packed. > > Please check out lxml before you post FUD like this. > > http://codespeak.net/lxml/ Calm down, Stefan! The inquirer must have got the impression of Amara's superiority from somewhere; all you need to do is to discover which resource gave that impression and balance the situation out. In any case, it's an opinion: there's no fear involved, and the only uncertainty and doubt are in the inquirer's mind, which I suppose is why they posted the inquiry. Paul From steve at holdenweb.com Thu Mar 22 07:56:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 07:56:38 -0400 Subject: Python Oracle 10g odbc blob insertion problem In-Reply-To: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> References: <1174555295.324787.220700@n76g2000hsh.googlegroups.com> Message-ID: Godzilla wrote: > Dear all, > > I cannot find a solution for my problem with inserting a blob object > (>4000 in length) into an ORACLE database via ODBC. > > > I have tried the two ways of inserting the blob object (a zip file): > > > 1) > fp = open("c:/test/test.zip", "r+b") > data = fp.read() > s = odbc.odbc(cs) > qry = s.cursor() > qry.execute("Insert into tBlob (data) values ('%s')" % > data.encode('hex')) > > > return the error: Input String Too Long Limit: 4096 > > > 2) > qry.execute("Insert into tBlob (data) values (?)", > data.encode('hex')) > > > does not return error, but it does not insert the record correctly. > > > Any help will be fully appreciated... > I would certainly recommend that you think about using the cxOracle package rather than relying on odbc. Most Orcale users do, with evident satisfaction. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From cedb816 at yahoo.com Sun Mar 11 08:21:03 2007 From: cedb816 at yahoo.com (ce) Date: 11 Mar 2007 05:21:03 -0700 Subject: a better solution for GUI in python In-Reply-To: <7xmz2kq929.fsf@ruckus.brouhaha.com> References: <1173611016.810735.70700@30g2000cwc.googlegroups.com> <7xmz2kq929.fsf@ruckus.brouhaha.com> Message-ID: <1173615663.082258.302130@8g2000cwh.googlegroups.com> On Mar 11, 3:05 pm, Paul Rubin wrote: > "ce" writes: > > My company is using python currently for our website. We need to > > develop a GUI front-end for our ERP that would be portable (Windows > > and Linux). > > Some reason not to use a browser interface instead of a client gui? it is a matter of input speed only! every record posses some calculations and sometimes fresh data from the database! which i "think" would be slower in the browser than the local gui client. I know that i can implement the functionality in the browser using javascripts, however, i don't know wither it would be as effective as a local gui or not and which is more convenient. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 19 08:11:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Mar 2007 13:11:09 +0100 Subject: List to string In-Reply-To: <1174192714.014092.79380@l77g2000hsb.googlegroups.com> References: <1174192136.371754.85500@l75g2000hse.googlegroups.com> <1174192714.014092.79380@l77g2000hsb.googlegroups.com> Message-ID: <45fe7ddc$0$25292$426a34cc@news.free.fr> Hitesh a ?crit : > On Mar 18, 12:28 am, "Hitesh" wrote: >> Hi, >> >> I've a list like this.. >> str1 = ['this is a test string inside list'] >> >> I am doing it this way. >> >> for s in str1: >> temp_s = s >> print temp_s Why this useless temp_s var ? >> >> Any better suggestions? >> >> Thank you, >> hj > > I want to cast value of a list into string.. > There's no "cast" in Python. It would make no sens in a dynamically typed language, where type informations belong to the LHS of a binding, not the RHS. I guess that what you want is to build a string out of a list of strings. If so, the answer is (assuming you want a newline between each element of the list): print "\n".join(str1) From jstroud at mbi.ucla.edu Fri Mar 2 17:10:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 02 Mar 2007 14:10:20 -0800 Subject: class attrdict In-Reply-To: References: Message-ID: Hallvard B Furuseth wrote: > Does this class need anything more? > Is there any risk of a lookup loop? > Seems to work... > > class attrdict(dict): > """Dict where d['foo'] also can be accessed as d.foo""" > def __init__(self, *args, **kwargs): > self.__dict__ = self > dict.__init__(self, *args, **kwargs) > def __repr__(self): > return dict.__repr__(self).join(("attrdict(", ")")) > Strangely enough, this seems okay since an instance of a dict subclass object has an empty __dict__ attribute anyway and so you won't be unwittingly destroying some behavior. James From rdm at rcblue.com Tue Mar 27 07:28:07 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 27 Mar 2007 04:28:07 -0700 Subject: SPE question In-Reply-To: <1174991839.417993.295570@y80g2000hsf.googlegroups.com> References: <1174984775.810988.145060@p77g2000hsh.googlegroups.com> <1174991839.417993.295570@y80g2000hsf.googlegroups.com> Message-ID: <20070327112821.433CF1E4006@bag.python.org> At 03:37 AM 3/27/2007, irstas at gmail.com wrote: >On Mar 27, 11:39 am, "alain" wrote: > > Hi, > > > > Could someone tell me how to uninstall SPE under windows? > > > > Alain > >Dunno about SPE, but most Python modules I've installed can >be uninstalled from control panel/add remove programs. SPE doesn't show up on my win XP add/remove programs list. Dick Moores From ptmcg at austin.rr.com Thu Mar 15 08:48:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Mar 2007 05:48:24 -0700 Subject: Circular Class Logic In-Reply-To: <1173960067.782597.96840@e1g2000hsg.googlegroups.com> References: <1173918948.167721.46620@e1g2000hsg.googlegroups.com> <1173921593.166607.240390@e65g2000hsc.googlegroups.com> <1173960067.782597.96840@e1g2000hsg.googlegroups.com> Message-ID: <1173962904.306751.86160@n76g2000hsh.googlegroups.com> On Mar 15, 7:01 am, half.ital... at gmail.com wrote: > > Remove the line above > > and add this below: > > def initFoo(): > > import baz > > Foo.baz = baz.Baz() > > initFoo() > > I got it to work, but I had to add a check to see if the class > variable had been set.. > > def initBaz(): > import Baz > Foo.baz = Baz.Baz() > > class Foo: > baz = None > def __init__(self): > if Foo.baz == None: > Foo.baz = True > initBaz() > > What exactly is being accomplished by having the init function outside > of the class? If there is no check, wouldn't it just execute every > time an object is instantiated anyway? > > > Instead of initFoo, you could use a custom metaclass. Or a class decorator (if > > and when they become available...) > > I haven't tried either of those yet. The names scare me. :) Sounds > like this might be a good time to explore them. > > > The code above is an effective way of doing what you want. But I'd think about > > the actual need of doing such things - are you sure it's a good design? > > I thought it was a good design, but now I'm not so sure. I'm > untrained, so often I dont know the right way to do things. As I > build this into the libraries, I'll keep an eye on how the code is > developing and go from there. Thanks for the help! > > ~Sean Just initialize Folder at module level - see below. -- Paul class Folder(object): def __init__(self,path): self.path = path pass def __repr__(self): return self.__class__.__name__+"("+self.path+")" class Disk(Folder): def __init__(self,driveLetter): super(Disk,self).__init__(driveLetter+":/") # hokey function to test if a drive letter points to a drive, I'm # sure there's a better way import os,string def isDisk(d): try: os.stat(d + ":/") return True except: return False # instead of calling some initFolder() method, just include this statement # at module level in the module that declares both classes Folder.allDisks = map(Disk,[d for d in string.uppercase if isDisk(d)]) # now can reference allDisks through Folder instances f = Folder("C:/temp") print f.allDisks prints: [Disk(C:/), Disk(D:/), Disk(E:/)] From gagsl-py2 at yahoo.com.ar Sat Mar 24 18:07:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 24 Mar 2007 19:07:29 -0300 Subject: Python object overhead? References: <56ja46F28lpp9U1@mid.individual.net> Message-ID: En Sat, 24 Mar 2007 18:07:57 -0300, Felipe Almeida Lessa escribi?: > On 3/23/07, Bjoern Schliessmann > wrote: >> (Note that almost everything in Python is an object!) > > Could you tell me what in Python isn't an object? Are you counting > old-style classes and instances as "not object"s? The syntax, by example; an "if" statement is not an object. -- Gabriel Genellina From mail at timgolden.me.uk Wed Mar 28 08:57:31 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 28 Mar 2007 13:57:31 +0100 Subject: how to check whether a drive is a network drive or drive from attached hard-disk In-Reply-To: <1175086146.462161.320980@p15g2000hsd.googlegroups.com> References: <1175086146.462161.320980@p15g2000hsd.googlegroups.com> Message-ID: <460A663B.4070504@timgolden.me.uk> shailesh wrote: > Hi, > > Few very simple questions. > > Is there a way to detect whether a drive is a mapped network drive or > not in Windows? > > Also, how can I get a list of drive letters currently in use in the > system? http://tgolden.sc.sabren.com/python/wmi_cookbook.html#find-drive-types TJG From yossi.kreinin at gmail.com Sat Mar 31 10:48:13 2007 From: yossi.kreinin at gmail.com (yossi.kreinin at gmail.com) Date: 31 Mar 2007 07:48:13 -0700 Subject: saving Python process state for later debugging Message-ID: <1175352493.387046.32510@q75g2000hsh.googlegroups.com> Hi! Is there a way to save the state of a Python process for later inspection with a debugger? One way to do this is to dump core, but is the result usable for debugging with pdb (it can be debugged by gdb, which can inspect PyObjects in a CPython core, for example, but it's not much fun)? If there is no way to do this today, are there essential difficulties in implementing this on top of an OS support for "raw" core dumps? TIA, Yossi From http Tue Mar 13 21:35:51 2007 From: http (Paul Rubin) Date: 13 Mar 2007 17:35:51 -0800 Subject: number generator References: Message-ID: <7xveh4haiw.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Me too. Although Alex Martelli's algorithm: > > map([random.randrange(5) for i in xrange(45)].count, xrange(5)) > > (each value needs adjusting up by one) really boggles my brain. I'm going > to have to think about that. Heh, that is woefully inefficient, but it is cute! I must have missed Alex's post where it appeared. Basically you are taking five buckets and 45 marbles. For each marble, choose one of the buckets at random and throw the marble into the bucket you chose. When you're done, count how many marbles have ended up in each bucket. Alex's algorithm does it the hard way: for each bucket selection, write down the result in a list. Then scan through the list to count how many 0's there are, then scan again to see how many 1's there are, etc. From sjmachin at lexicon.net Thu Mar 15 05:42:46 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 Mar 2007 02:42:46 -0700 Subject: most complete xml package for Python? In-Reply-To: <1173909884.822838.264030@n76g2000hsh.googlegroups.com> References: <1173789812.657930.261350@h3g2000cwc.googlegroups.com> <45F811A3.1050208@web.de> <1173887937.251026.175260@y66g2000hsf.googlegroups.com> <1173908076.351577.75000@n59g2000hsh.googlegroups.com> <1173909884.822838.264030@n76g2000hsh.googlegroups.com> Message-ID: <1173951766.692371.206790@l75g2000hse.googlegroups.com> On Mar 15, 9:04 am, "metaperl" wrote: > On Mar 14, 5:34 pm, "John Machin" wrote: > > > Given keywords like "Amara" and "Elementtree" and past history, it > > looked to me like a troll of one kind trying to incite a troll of > > another kind to pop out from under the bridge and chew on his > > ankle :-) > > Well, I'm not a troll. And I am now even less impressed with > ElementTree. It does not preserve the document but reforms it in > certain cases. > > > > gets rewritten as > > and then it kept the XML container-style as opposed to single-tag. From goodTweetieBird at hotmail.com Tue Mar 20 17:22:33 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 20 Mar 2007 14:22:33 -0700 Subject: Imports In-Reply-To: <1174418741.771343.165360@n76g2000hsh.googlegroups.com> References: <1174415496.395993.72080@l77g2000hsb.googlegroups.com> <1174416672.629041.122320@l77g2000hsb.googlegroups.com> <1174417150.930765.141160@l77g2000hsb.googlegroups.com> <1174418741.771343.165360@n76g2000hsh.googlegroups.com> Message-ID: <1174425753.614770.61630@l75g2000hse.googlegroups.com> On Mar 20, 2:25 pm, kyoso... at gmail.com wrote: > On Mar 20, 1:59 pm, "gtb" wrote: > > > > > On Mar 20, 1:51 pm, kyoso... at gmail.com wrote: > > > > On Mar 20, 1:31 pm, "gtb" wrote: > > > > > I am working with a tool called maxQ that generates jython scripts. > > > > The tool runs in > > > > > C:\maxq\bin. > > > > > Rather than clutter up bin I want to put the scripts and other .py > > > > scripts in > > > > > c:\maxq\bin\testScripts. > > > > > When doing so the scripts need to import from > > > > > c:\maxq\jython, but can't find the modules. > > > > > I tried adding c:\maxq\jython to the environment variable pythonpath > > > > but to no avail. Perhaps I missed it in Rossum's tutorial but is there > > > > a std prgrammatic way to specify a module directory? > > > > > Could you, would you, recommend a text or another webpage for learning > > > > more (much more) about python? > > > > > Thanx, > > > > > gtb > > > > I typically just import sys and then do a > > > sys.path.append(directoryPath). This basically makes whatever modules > > > in that path available at run time. If you need a beginners reference > > > book, I recommend "Beginning Python" by Hetland. "Python Programming > > > for the Absolute Beginner" by Dawson was a lot of fun, but he doesn't > > > get into the internals of the language like Hetland does. Once you're > > > a snake charmer too, you can "graduate" to the "Programming Python" > > > book by Lutz. > > > > Mike > > > Something else going on then, does the directory path need to be the > > full path or will it search sub-directories? > > > Traceback (most recent call last): > > File "C:\maxq-0.98\bin\testScripts\compactLogin.py", line 2, in > > > > from CompactTest import CompactTest > > File "c:\maxq-0.98\jython\CompactTest.py", line 2, in > > from java.lang import * > > ImportError: No module named java.lang > > > Thanks for the book recommendations. > > > gtb > > Usually, the sys.path.append will allow Python to search the > subfolders too, but I have noticed that sometimes it doesn't if you > use UNC paths. I don't use jython, so maybe there's another way to fix > this that is more specific to that implementation of Python? > > Mike Thanks for the sys.path.append info. Turns out maxq cranks thing up with java ( I should have seen it). The sys.path.append does everything it supposed to do. gtb From tjgolden at gmail.com Tue Mar 6 08:48:26 2007 From: tjgolden at gmail.com (Tim Golden) Date: 6 Mar 2007 05:48:26 -0800 Subject: askstring Window to the top under Windows In-Reply-To: <1173186819.622405.121170@30g2000cwc.googlegroups.com> References: <1173186819.622405.121170@30g2000cwc.googlegroups.com> Message-ID: <1173188906.327302.291650@s48g2000cws.googlegroups.com> On Mar 6, 1:13 pm, "iwl" wrote: > Hi, > > I tryed askstring to input some text in my script, > but some ugly empty Window appears with the > Input-Window behind and all together behind my > Console showing my script. So all have to brought > to the top first by the user - very unconfortable It's not clear whether you're talking about the usual "Why do I get a DOS window when I run my python script?" question -- to which the answer is, in essence, change your script's extension to .pyw or use the pythonw.exe executable -- or "Why _when I use askstring_ do I get an empty window?". If it's the latter, then I don't know, but can you provide a small example script which exhibits the behaviour. TJG From istvan.albert at gmail.com Tue Mar 6 15:18:39 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 6 Mar 2007 12:18:39 -0800 Subject: Graphviz Python Binding for Python 2.5 on Windows? In-Reply-To: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> References: <1173132974.311859.273130@c51g2000cwc.googlegroups.com> Message-ID: <1173212319.214424.320090@64g2000cwx.googlegroups.com> On Mar 5, 5:16 pm, "Alex Li" wrote: > I tried to avoid. Any suggestions? try the networkx package, it includes the pygraphviz module that can generate dot files: https://networkx.lanl.gov/wiki Istvan From steve at REMOVE.THIS.cybersource.com.au Fri Mar 23 23:22:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 24 Mar 2007 14:22:09 +1100 Subject: Join strings - very simple Q. References: <1174675011.244339@jubilee.claranet.pt> <1174680929.492601.140270@o5g2000hsb.googlegroups.com> Message-ID: On Fri, 23 Mar 2007 13:15:29 -0700, John Machin wrote: > OK, I'll bite: This was "new" in late 2000 when Python 2.0 was > released. Where have you been in the last ~6.5 years? Western civilization is 6,000 years old. Anything after 1850 is "new". *wink* -- Steven. From albmont at centroin.com.br Sun Mar 11 22:02:07 2007 From: albmont at centroin.com.br (Alberto Vieira Ferreira Monteiro) Date: Mon, 12 Mar 2007 02:02:07 +0000 Subject: New to Python Message-ID: <200703120202.07810.albmont@centroin.com.br> Hi, I am new to Python, how stupid can be the questions I ask? For example, how can I add (mathematically) two tuples? x = (1,2) y = (3,4) How can I get z = (1 + 3, 2 + 4) ? Alberto Monteiro From deets at nospam.web.de Tue Mar 13 17:35:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Mar 2007 22:35:20 +0100 Subject: help!! *extra* tricky web page to extract data from... In-Reply-To: <1173819262.288501.66350@n76g2000hsh.googlegroups.com> References: <1173819262.288501.66350@n76g2000hsh.googlegroups.com> Message-ID: <55ojorF26c25jU1@mid.uni-berlin.de> seberino at spawar.navy.mil schrieb: > How extract the visible numerical data from this Microsoft financial > web site? > > http://tinyurl.com/yw2w4h > > If you simply download the HTML file you'll see the data is *not* > embedded in it but loaded from some other file. > > Surely if I can see the data in my browser I can grab it somehow right > in a Python script? > > Any help greatly appreciated. It's an AJAX-site. You have to carefully analyze it and see what actually happens in the javascript, then use that. Maybe something like the http header plugin for firefox helps you there. Diez From nagle at animats.com Sat Mar 10 12:23:57 2007 From: nagle at animats.com (John Nagle) Date: Sat, 10 Mar 2007 17:23:57 GMT Subject: [python-advocacy] A Pythonic Way to Measure and Improve Your Programming Skills? In-Reply-To: References: <45F14D7E.3060707@taupro.com> Message-ID: Michael Bernstein wrote: > On Sat, 2007-03-10 at 10:01 -0600, Brad Allen wrote: > > >>When I discussed this problem with Michael Bernstein at PyCon he suggested >>the idea of creating a "chroot jail" for each web session which could run >>the Python interpreter in a secure sandbox. That might be easier than giving >>each session a whole virtual server. > > > Note that this wasn't an original idea of mine, I got it from brief > mentions associated with two existing interactive python-in-a-web-page > implementations: > > Try Python: http://www.mired.org/home/mwm/try_python/ > > TryPy: http://trac.pocoo.org/wiki/TryPy That's a fun toy. Of course, your server has to have enough memory to keep a Python instance open for each connected user, so there's a scaling issue if you have hundreds or thousands of people using it. And you have to have some good way to decide when the user has disconnected and release the Python instance. John Nagle From starGaming at gmail.com Thu Mar 22 14:45:20 2007 From: starGaming at gmail.com (starGaming at gmail.com) Date: 22 Mar 2007 11:45:20 -0700 Subject: #!/usr/bin/env python > 2.4? In-Reply-To: References: <1174407745.208492.264020@l75g2000hse.googlegroups.com> <1174415242.455972.51400@d57g2000hsg.googlegroups.com> <1174506107.863399.7970@l75g2000hse.googlegroups.com> <1174580529.081658.326800@b75g2000hsg.googlegroups.com> Message-ID: <1174589120.474725.11780@n59g2000hsh.googlegroups.com> On Mar 22, 5:23 pm, Jon Ribbens wrote: > In article <1174580529.081658.326... at b75g2000hsg.googlegroups.com>, starGam... at gmail.com wrote: > > I don't see any problem with:: > > > if version_info[0] <= 2 and version_info[1] < 4: > > raise RuntimeError() > > What if the version number is 1.5? Ah, now I get your problem. OK. From mail at timgolden.me.uk Mon Mar 26 04:59:51 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 26 Mar 2007 09:59:51 +0100 Subject: Create new processes over telnet in XP In-Reply-To: <4607873D.5050107@timgolden.me.uk> References: <1174646834.183920.293420@e1g2000hsg.googlegroups.com> <46043ad8$0$27402$ba4acef3@news.orange.fr> <4607873D.5050107@timgolden.me.uk> Message-ID: <46078B87.9040703@timgolden.me.uk> Tim Golden wrote: > Laurent Pointal wrote: >> Shane Geiger a ?crit : >>> This reminds me of something I once wanted to do: How can I install >>> Python in a totally non-gui way on Windows (without the use of VNC)? I >>> think I was telnetted into a computer (or something like that) and I was >>> unable to run the usual Python installer because it uses a GUI. > > While I don't remember if I've actually tried it you should > be able to do this with WMI. Example here... > > http://timgolden.me.uk/python/wmi_cookbook.html#install-a-product > > If I have time to do it (and then undo whatever damage it > does ;) I'll give it a go later. > > TJG Or, indeed, just run it in quiet mode, according to the docs: http://www.python.org/download/releases/2.5/msi/ TJG From ptmcg at austin.rr.com Thu Mar 29 10:06:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Mar 2007 07:06:17 -0700 Subject: BeautifulSoup vs. Microsoft In-Reply-To: References: Message-ID: <1175177177.239473.69860@n59g2000hsh.googlegroups.com> On Mar 29, 1:50 am, John Nagle wrote: > Here's a construct with which BeautifulSoup has problems. It's > from "http://support.microsoft.com/contactussupport/?ws=support". > > This is the original: > > id="L_75998" > title="". So all that following stuff is from what > follows the next "-->" which terminates a comment. > No, that comment is inside a quoted string, so it should be ok. If you are just trying to extract tags, this pyparsing scraper gets them, including this problematic one: import urllib from pyparsing import makeHTMLTags pg = urllib.urlopen("http://support.microsoft.com/contactussupport/? ws=support") htmlSrc = pg.read() pg.close() # only take first tag returned from makeHTMLTags, not interested in # closing tags anchorTag = makeHTMLTags("A")[0] for a in anchorTag.searchString(htmlSrc): if "title" in a: print "Title:", a.title print "HREF:", a.href # or use this statement to dump the complete tag contents # print a.dump() print Prints: Title: risk of more pain with C extensions. John From tiedon_jano at hotmail.com Sat Mar 3 12:53:01 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 03 Mar 2007 17:53:01 GMT Subject: Perl and Python, a practical side-by-side example. In-Reply-To: References: Message-ID: <1CiGh.254$Dg7.71@read3.inet.fi> Shawn Milo kirjoitti: > > I am not looking for the smallest number of lines, or anything else > that would make the code more difficult to read in six months. Just > any instances where I'm doing something inefficiently or in a "bad" > way. > > I'm attaching both the Perl and Python versions, and I'm open to > comments on either. The script reads a file from standard input and > finds the best record for each unique ID (piid). The best is defined > as follows: The newest expiration date (field 5) for the record with > the state (field 1) which matches the desired state (field 6). If > there is no record matching the desired state, then just take the > newest expiration date. > I don't know if this attempt satisfies your criteria but here goes! This is not a rewrite of your program but was created using your problem description above. I've not included the reading of the data because it has not much to do with the problem per se. #============================================================ input = [ "aaa\tAAA\t...\t...\t...\t20071212\tBBB\n", "aaa\tAAA\t...\t...\t...\t20070120\tAAA\n", "aaa\tAAA\t...\t...\t...\t20070101\tAAA\n", "aaa\tAAA\t...\t...\t...\t20071010\tBBB\n", "aaa\tAAA\t...\t...\t...\t20071111\tBBB\n", "ccc\tAAA\t...\t...\t...\t20071201\tBBB\n", "ccc\tAAA\t...\t...\t...\t20070101\tAAA\n", "ccc\tAAA\t...\t...\t...\t20071212\tBBB\n", "ccc\tAAA\t...\t...\t...\t20071212\tAAA\n", "bbb\tAAA\t...\t...\t...\t20070101\tAAA\n", "bbb\tAAA\t...\t...\t...\t20070101\tAAA\n", "bbb\tAAA\t...\t...\t...\t20071212\tAAA\n", "bbb\tAAA\t...\t...\t...\t20070612\tAAA\n", "bbb\tAAA\t...\t...\t...\t20071212\tBBB\n", ] input = [x[:-1].split('\t') for x in input] recs = {} for row in input: recs.setdefault(row[0], []).append(row) for key in recs: rows = recs[key] rows.sort(key=lambda x:x[5], reverse=True) for current in rows: if current[1] == current[6]: break else: current = rows[0] print '\t'.join(current) #============================================================ The output is: aaa AAA ... ... ... 20070120 AAA bbb AAA ... ... ... 20071212 AAA ccc AAA ... ... ... 20071212 AAA and it is the same as the output of your original code on this data. Further testing would naturally be beneficial. Cheers, Jussi From claird at lairds.us Sun Mar 25 12:43:57 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 25 Mar 2007 16:43:57 +0000 Subject: Tkinter Toplevel geometry References: <1174803181.656189.303200@l77g2000hsb.googlegroups.com> <0dtNh.9164$JZ3.2879@newssvr13.news.prodigy.net> <1174824649.683426.78990@d57g2000hsg.googlegroups.com> Message-ID: In article <1174824649.683426.78990 at d57g2000hsg.googlegroups.com>, Chris wrote: > >> After playing with this an inordinate amount of time, I found that one >> does need to supply parameters, namely the null parameter of an empty >> string. Try: >> >> sometop.geometry('') >> >> This repacks according to the widgets. Not quite clear from the >> miserable docs, is it? > > >Wow, that does work. Thank you very much for figuring it out! > A TRULY good way to show your thanks for help like this is to write up what you learned at the Tkinter Wiki . Note: A. You have to log in to edit pages on this particular Wiki. If you decide to join us, then, you'll first need to create an account. Read-only visitors can be anony- mous, of course. B. Major thanks to Jeff Epler for maintaining the site, and, in particular, for fighting off recent vandalism. From bj_666 at gmx.net Sun Mar 4 06:29:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 04 Mar 2007 12:29:39 +0100 Subject: multiple content-types break cgi.py References: <1173002603.690853.250090@p10g2000cwp.googlegroups.com> Message-ID: In , Jon Ribbens wrote: > It's not a bug - sending multiple content-types is just totally broken. > What would such a header even be supposed to mean? It's like saying > "this is an apple orange". And the correct header for such a beast would be "this is an iOrange" of course. ;-) SCNR, Marc 'BlackJack' Rintsch From aleax at mac.com Sun Mar 4 10:54:23 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 4 Mar 2007 07:54:23 -0800 Subject: class attrdict References: <1hud4hf.r52pr7wyx0adN%aleax@mac.com> <1173009806.383478.50230@i80g2000cwc.googlegroups.com> Message-ID: <1hufw45.os60h3bkuqh9N%aleax@mac.com> goodwolf wrote: ... > Then you will prefer something like this: > > class Namespace(object): > def __init__(self, __ns={}, **kwargs): > if kwargs: __ns.update(kwargs) > self.__dict__ = __ns I might, if it weren't for the redundant "if" and the horribly buggy interference between separate instances -- which is why I wrote it, almost six years ago and without the bugs, as . Not much later, in the printed Cookbook, I also gave some other good ways and explained (as I did in the current thread) why confusing attributes and items, as proposed in most of this thread, is really a bad idea. Alex From mscottschilling at hotmail.com Fri Mar 30 13:19:14 2007 From: mscottschilling at hotmail.com (Mike Schilling) Date: Fri, 30 Mar 2007 17:19:14 GMT Subject: What are OOP's Jargons and Complexities References: <1175180497.362830.285710@y80g2000hsf.googlegroups.com> <460cc83a.2652073@news.readfreenews.net> Message-ID: Timofei Shatrov wrote: > On Fri, 30 Mar 2007 06:48:05 GMT, "Mike Schilling" > tried to confuse everyone with this > message: > >> Xah Lee wrote: >> >>> So, a simple code like this in normal languages: > >>> becomes in Java: >>> >>> >> >> Only when written by someone almost entirely ignorant of Java. >> > > Which is the state most people want to be in... Most of them have the brains not to display their ignorance so widely. From steve at holdenweb.com Thu Mar 22 05:48:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 22 Mar 2007 05:48:57 -0400 Subject: [JOB] Sr. Python Developer, Northern VA In-Reply-To: References: Message-ID: Anton Vredegoor wrote: > Steven D. Arnold wrote: > [...] > /rant > Feel better now? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com From laurent.pointal at limsi.fr Wed Mar 28 07:01:18 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 28 Mar 2007 13:01:18 +0200 Subject: XML Parsing In-Reply-To: <1175067518.919256.243090@n59g2000hsh.googlegroups.com> References: <1175067518.919256.243090@n59g2000hsh.googlegroups.com> Message-ID: pyapplico at gmail.com a ?crit : > I want to parse this XML file: > As you might have guessed, I want to create files from this XML file > contents, so how can I do this? > What modules should I use? What options do I have? Where can I find > tutorials? Will I be able to put > this on the internet (on a googlepages server)? See urllib2 module and its "missing guide". > Thanks in advance to everyone who helps me. > And yes I have used Google but I am unsure what to use. > About XML, to complete Amit link to ElementsTree, you may take a look at: http://www.diveintopython.org/xml_processing/index.html (learn by example) And look at: http://pyxml.sourceforge.net/ http://www.rexx.com/~dkuhlman/pyxmlfaq.html http://shellsage.com/?q=node/12 http://www.python.org/community/sigs/current/xml-sig/ http://docs.python.org/lib/markup.html From george.trojan at noaa.gov Thu Mar 1 12:54:44 2007 From: george.trojan at noaa.gov (George Trojan) Date: Thu, 01 Mar 2007 12:54:44 -0500 Subject: Dialog with a process via subprocess.Popen blocks forever In-Reply-To: <1172770920.052040.33990@h3g2000cwc.googlegroups.com> References: <1172698063.670659.318340@k78g2000cwa.googlegroups.com> <1172770920.052040.33990@h3g2000cwc.googlegroups.com> Message-ID: bayer.justin at googlemail.com wrote: > Okay, here is what I want to do: > > I have a C Program that I have the source for and want to hook with > python into that. What I want to do is: run the C program as a > subprocess. > The C programm gets its "commands" from its stdin and sends its state > to stdout. Thus I have some kind of dialog over stdin. > > So, once I start the C Program from the shell, I immediately get its > output in my terminal. If I start it from a subprocess in python and > use python's sys.stdin/sys.stdout as the subprocess' stdout/stdin I > also get it immediately. > > BUT If I use PIPE for both (so I can .write() on the stdin and .read() > from the subprocess' stdout stream (better: file descriptor)) reading > from the subprocess stdout blocks forever. If I write something onto > the subprocess' stdin that causes it to somehow proceed, I can read > from its stdout. > > Thus a useful dialogue is not possible. > > Regards, > -Justin > > > Have you considered using pexpect: http://pexpect.sourceforge.net/ ? George From steve at REMOVE.THIS.cybersource.com.au Sat Mar 10 08:38:31 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Mar 2007 00:38:31 +1100 Subject: number generator References: <1173451441.077648.321270@c51g2000cwc.googlegroups.com> <7x7itqqxlh.fsf@ruckus.brouhaha.com> <1173453432.893222.308610@j27g2000cwj.googlegroups.com> Message-ID: On Sat, 10 Mar 2007 02:32:21 -0800, Dick Moores wrote: > So why not just repeatedly call a function to generate lists of > length N of random integers within the appropriate range (the closed > interval [1,M-N-1]), and return the first list the sum of which is M? > I don't understand what all the discussion is about. Time is not one > of the constraints. Time is always a constraint. The sun will expand and destroy the Earth in a couple of billion years, it would be nice to have a solutions before then... *wink* Seriously, almost all programming problems have two implicit constraints: it must run as fast as practical, using as little computer resources (e.g. memory) as practical. Naturally those two constraints are usually in opposition, which leads to compromise algorithms that run "fast enough" without using "too much" memory. -- Steven. From gtcopeland at gmail.com Thu Mar 8 16:19:45 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 8 Mar 2007 13:19:45 -0800 Subject: SQLAlchemy and Oracle Functions? Message-ID: <1173388785.133560.146300@p10g2000cwp.googlegroups.com> I'm using SQLAlchemy and have a need to call an Oracle function; which is not the same as a stored procedure. Can this be done directory or indirectly with SQLAlchemy? If so, can someone please provide an example? If not, how do I obtain the raw cx_Oracle cursor so I can use callfunc directly on that? Thanks, Greg From mahs at telcopartners.com Wed Mar 28 18:01:00 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 28 Mar 2007 15:01:00 -0700 Subject: manually implementing staticmethod()? References: <1175115664.288706.183390@p77g2000hsh.googlegroups.com> Message-ID: "7stud" wrote in message news:1175115664.288706.183390 at p77g2000hsh.googlegroups.com... > Hi, > > Can someone show me how to manually implement staticmethod()? Here is > my latest attempt: > ---------------- Raymond Hettinger can: http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods From Graham.Dumpleton at gmail.com Sat Mar 10 21:45:25 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 10 Mar 2007 18:45:25 -0800 Subject: merits of Lisp vs Python In-Reply-To: <878xe4zhud.fsf@pobox.com> References: <1165576029.316969.24690@j72g2000cwa.googlegroups.com> <1165613280.584178.36470@16g2000cwy.googlegroups.com> <1165627684.709241.86340@16g2000cwy.googlegroups.com> <1165685950.758858.18960@n67g2000cwd.googlegroups.com> <1165732072.056289.274460@79g2000cws.googlegroups.com> <1173329966.266070.283130@8g2000cwh.googlegroups.com> <56NHh.1217$FG1.248@newssvr27.news.prodigy.net> <7xhcsws35x.fsf@ruckus.brouhaha.com> <%PNHh.1221$FG1.642@newssvr27.news.prodigy.net> <87zm6kzodq.fsf@pobox.com> <878xe4zhud.fsf@pobox.com> Message-ID: <1173581125.663707.5810@s48g2000cws.googlegroups.com> On Mar 11, 12:31 pm, j... at pobox.com (John J. Lee) wrote: > John Nagle writes: > > John J. Lee wrote: > > > John Nagle writes: > > > [...] > > > >> Python, on the other hand, is uphill all the way. Constant trouble > > >>with version issues, especially with C components called from Python. > > >>MySQLdb, M2Crypto, SSL - they all have platform/version > > >>incompatibility problems. I just spent three days making M2Crypto > > >>work on a new Linux server with a different Red Hat version. > > >>Neither Python's packaging tools nor the platform's packaging > > >>tools deal adequately with these issues. > > > [...] > > > You haven't been usingmod_python, by any chance? > > > John > > > No, haven't started to deal with that yet. Still using > > CGI. Not sure whether to usemod_pythonor fastcgi for the > > small requests where the Python load time swamps the time > > to do one SQL select and reply. Comments? > > mod_pythonrelies on an unsupported feature of Python, namedly > multiple interpreters --> risk of more pain with C extensions. As usual, those bashing up on mod_python tend not to really know what they are talking about. :-( Although multiple Python interpreters cannot be manipulated directly from within a Python script, they can from the Python C API and it is very much a feature of Python and has been for a long time. The only issue with multiple sub interpreters in respect of C extension modules is that implementers of those C extension modules take the easy path and use the simplified thread API for GIL locking. The consequence of them doing that is that their C extension module may not work when used in anything but the first interpreter created by Python. If instead of using the simplified thread API for GIL locking they used other parts of the Python threading API as appropriate and did thread lock handling properly for multiple interpreters, there would not be an issue. Even so, to get such a C extension module working in the context of mod_python simply means telling mod_python to run that particular application in the first interpreter instance by specifying the mod_python directive: PythonInterpreter main_interpreter Thus, the problem is not mod_python at all, but that the C extension modules implementer didn't bother to implement their module so as to be usable within a system such as mod_python where multiple interpreters are used. Further, mod_python even provides a way to work around the problems with such third party C extension modules. If you feel that this is not the case and mod_python is still broken in some way, please properly explain what the problem is. PS. Yes I do know that forcing using of main interpreter in mod_python only helps solve this problem in mod_python 3.2 and later and did not help with older versions. Graham From gagsl-py2 at yahoo.com.ar Mon Mar 19 19:25:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Mar 2007 20:25:05 -0300 Subject: struct.pack returns nothing [3] References: <1174331199.134156.105430@n59g2000hsh.googlegroups.com> <20070319223241.GA21961@mail.lacordilleraandina.com.ar> Message-ID: En Mon, 19 Mar 2007 19:32:41 -0300, Andr?s Martinelli escribi?: > I'm using the example of the site > http://docs.python.org/lib/module-struct.html : > > import struct > pack('hhl', 1, 2, 3) That code should raise a NameError. Either you are using *another* pack function, or that is not what you actually typed. This is what I get: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import struct py> struct.pack('hhl', 1, 2, 3) '\x01\x00\x02\x00\x03\x00\x00\x00' > I should get: >>>> '\x00\x01\x00\x02\x00\x00\x00\x03' Maybe on another platform - on i386 I get the byte ordering as above. -- Gabriel Genellina From aleax at mac.com Mon Mar 19 01:11:44 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 18 Mar 2007 22:11:44 -0700 Subject: list comprehension help References: <1174269687.497013.249480@o5g2000hsb.googlegroups.com> <1hv6v32.17ahray13d45puN%aleax@mac.com> Message-ID: <1hv6ysz.1eicq7etgq7ysN%aleax@mac.com> rkmr.em at gmail.com wrote: ... > > > files (you see "huge" is really relative ;-)) on 2-4GB RAM boxes and > > > setting a big buffer (1GB or more) reduces the wall time by 30 to 50% > > > compared to the default value. BerkeleyDB should have a buffering > > Out of curiosity, what OS and FS are you using? On a well-tuned FS and > > Fedora Core 4 and ext 3. Is there something I should do to the FS? In theory, nothing. In practice, this is strange. > Which should I do? How much buffer should I allocate? I have a box > with 2GB memory. I'd be curious to see a read-only loop on the file, opened with (say) 1MB of buffer vs 30MB vs 1GB -- just loop on the lines, do a .split() on each, and do nothing with the results. What elapsed times do you measure with each buffersize...? If the huge buffers confirm their worth, it's time to take a nice critical look at what other processes you're running and what all are they doing to your disk -- maybe some daemon (or frequently-run cron entry, etc) is out of control...? You could try running the benchmark again in single-user mode (with essentially nothing else running) and see how the elapsed-time measurements change... Alex From dd55 at cornell.edu Wed Mar 14 18:03:22 2007 From: dd55 at cornell.edu (Darren Dale) Date: Wed, 14 Mar 2007 18:03:22 -0400 Subject: string formatting: engineering notation References: <1173908915.676706.176140@l75g2000hse.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > On Mar 14, 1:14 pm, Darren Dale wrote: >> Does anyone know if it is possible to represent a number as a string with >> engineering notation (like scientific notation, but with 10 raised to >> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the >> decimal.Decimal class, but repeatedly instantiating Decimals is >> inefficient for my application (matplotlib plotting library). If it is >> not currently possible, do you think the python devs would be receptive >> to including support for engineering notation in future releases? > > > Do you also consider this to be too inefficient? > > > import math > > for exponent in xrange(-10, 11): > flt = 1.23 * math.pow(10, exponent) > l = math.log10(flt) > if l < 0: > l = l - 3 > p3 = int(l / 3) * 3 > multiplier = flt / pow(10, p3) > print '%e => %fe%d' % (flt, multiplier, p3) > That's a good suggestion. It's probably fast enough. I was hoping that something like '%n'%my_number already existed. From MonkeeSage at gmail.com Mon Mar 5 18:23:30 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Mar 2007 15:23:30 -0800 Subject: Squisher -- a lightweight, self-contained alternative to eggs? In-Reply-To: <9018$45ec9619$d443bb3a$19973@news.speedlinq.nl> References: <1173076302.035996.118480@n33g2000cwc.googlegroups.com> <45ec89a4$0$2349$426a74cc@news.free.fr> <1173131863.216300.109120@s48g2000cws.googlegroups.com> <9018$45ec9619$d443bb3a$19973@news.speedlinq.nl> Message-ID: <1173137010.498117.259470@j27g2000cwj.googlegroups.com> Stef, What Adam is talking about has nothing to do with windows or *nix. He's talking about packing one or more .py files into a single archive, which can be imported just like the regular .py files. This means you can distribute a whole bunch of module files/dirs as a single .pyc file. It just makes it easier to have a single file to distribute rather than a whole bunch, or a zip that one has to unzip into a certain directory, &c. So you can have myscript.py + myscriptfiles.pyc vs. myscript.py + somedepdir/ + someotherdepdir/ + somedepfile.py...&c. If you still don't get it, you don't need it. Regards, Jordan From nagle at animats.com Tue Mar 20 13:32:33 2007 From: nagle at animats.com (John Nagle) Date: Tue, 20 Mar 2007 17:32:33 GMT Subject: difference between urllib2.urlopen and firefox view 'page source'? In-Reply-To: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> References: <1174357838.255108.141880@o5g2000hsb.googlegroups.com> Message-ID: Here's a useful online tool that might help you see what's happening: http://www.sitetruth.com/experimental/viewer.html We use this to help webmasters see what our web crawler is seeing. This reads a page, using Python and FancyURLOpener, with a USER-AGENT string of "SiteTruth.com site rating system." Then it parses the page with BeautifulSoup, removes all